diff --git a/.dockerignore b/.dockerignore index b6687c95fa7a..51d4ec61a457 100644 --- a/.dockerignore +++ b/.dockerignore @@ -28,3 +28,4 @@ _isaac_sim? docker/.isaac-lab-docker-history # ignore uv environment env_isaaclab +tools/wheel_builder/build/ diff --git a/.gitattributes b/.gitattributes index 683729991542..99e35795611a 100644 --- a/.gitattributes +++ b/.gitattributes @@ -11,5 +11,7 @@ *.jit filter=lfs diff=lfs merge=lfs -text *.hdf5 filter=lfs diff=lfs merge=lfs -text +source/isaaclab_tasks/test/golden_images/**/*.png filter=lfs diff=lfs merge=lfs -text + *.bat text eol=crlf *.sh text eol=lf diff --git a/.github/actions/run-package-tests/action.yml b/.github/actions/run-package-tests/action.yml index cb32d46d4c6b..9d7e7200e875 100644 --- a/.github/actions/run-package-tests/action.yml +++ b/.github/actions/run-package-tests/action.yml @@ -55,12 +55,47 @@ inputs: description: 'Additional pytest options' default: '' required: false + extra-pip-packages: + description: 'Space-separated pip packages to install inside the Docker container before pytest starts' + default: '' + required: false container-name: description: 'Docker container name prefix (run-id is appended automatically)' required: true runs: using: composite steps: + # Display some details on AWS instance we're running on + - name: AWS Instance Info + shell: bash + run: | + # get instance ID for debugging purposes (if running on EC2) + IMDS_TOKEN=$(curl -sf -X PUT "http://169.254.169.254/latest/api/token" \ + -H "X-aws-ec2-metadata-token-ttl-seconds: 21600") || true + if [ -n "$IMDS_TOKEN" ]; then + INSTANCE_ID=$(curl -sf -H "X-aws-ec2-metadata-token: ${IMDS_TOKEN}" \ + "http://169.254.169.254/latest/meta-data/instance-id") || true + INSTANCE_REGION=$(curl -sf -H "X-aws-ec2-metadata-token: ${IMDS_TOKEN}" \ + "http://169.254.169.254/latest/meta-data/placement/region") || true + INSTANCE_TYPE=$(curl -sf -H "X-aws-ec2-metadata-token: ${IMDS_TOKEN}" \ + "http://169.254.169.254/latest/meta-data/instance-type") || true + echo "⚪ Instance ID: ${INSTANCE_ID:-Not running on EC2}" + echo "⚪ Instance Region: ${INSTANCE_REGION:-Not running on EC2}" + echo "⚪ Instance Type: ${INSTANCE_TYPE:-Not running on EC2}" + echo "⚪ Connect: https://${INSTANCE_REGION}.console.aws.amazon.com/ec2-instance-connect/ssh/home?region=${INSTANCE_REGION}&connType=standard&instanceId=${INSTANCE_ID}&osUser=ubuntu&sshPort=22&addressFamily=ipv4" + else + echo "🟠 Could not obtain IMDS token, probably not running on EC2" + fi + + - name: Prepare Docker disk space + shell: bash + run: | + bash .github/actions/run-package-tests/cleanup_docker_storage.sh \ + "${{ inputs.isaacsim-base-image }}:${{ inputs.isaacsim-version }}" \ + "isaacsim-pin-${{ inputs.container-name }}-${{ github.run_id }}-${{ github.run_attempt }}-pre" \ + "pre-test-cleanup" \ + "true" + - name: Record pull start time id: pull-start shell: bash @@ -103,6 +138,7 @@ runs: quarantined-only: ${{ inputs.quarantined-only }} include-files: ${{ inputs.include-files }} volume-mount-source: ${{ github.workspace }} + extra-pip-packages: ${{ inputs.extra-pip-packages }} - name: Check Test Results if: always() @@ -126,3 +162,13 @@ runs: echo "🟠 Workflow cancelled, force-killing container ${CONTAINER}..." docker kill "${CONTAINER}" 2>/dev/null || true docker rm -f "${CONTAINER}" 2>/dev/null || true + + - name: Cleanup old Docker images + if: always() + shell: bash + run: | + bash .github/actions/run-package-tests/cleanup_docker_storage.sh \ + "${{ inputs.isaacsim-base-image }}:${{ inputs.isaacsim-version }}" \ + "isaacsim-pin-${{ inputs.container-name }}-${{ github.run_id }}-${{ github.run_attempt }}-post" \ + "post-job-cleanup" \ + "false" diff --git a/.github/actions/run-package-tests/cleanup_docker_storage.sh b/.github/actions/run-package-tests/cleanup_docker_storage.sh new file mode 100755 index 000000000000..097dfeefb8e7 --- /dev/null +++ b/.github/actions/run-package-tests/cleanup_docker_storage.sh @@ -0,0 +1,128 @@ +#!/usr/bin/env bash + +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +set -u + +ISAACSIM_IMAGE="${1:-}" +ISAACSIM_IMAGE_PIN_CONTAINER="${2:-isaacsim-pin-run-package-tests}" +CLEANUP_CONTEXT="${3:-docker-cleanup}" +FAIL_IF_STILL_HIGH="${4:-false}" + +DOCKER_STORAGE_PATH="${DOCKER_STORAGE_PATH:-/var/lib/docker}" +DOCKER_CLEANUP_THRESHOLD_PERCENT="${DOCKER_CLEANUP_THRESHOLD_PERCENT:-85}" +DOCKER_AGGRESSIVE_PRUNE_UNTIL="${DOCKER_AGGRESSIVE_PRUNE_UNTIL:-24h}" +DOCKER_CONSERVATIVE_PRUNE_UNTIL="${DOCKER_CONSERVATIVE_PRUNE_UNTIL:-72h}" + +get_docker_storage_usage_percent() { + df -P "${DOCKER_STORAGE_PATH}" 2>/dev/null | awk 'NR == 2 { gsub("%", "", $5); print $5 }' +} + +resolve_docker_storage_path() { + local docker_root_dir + docker_root_dir="$(docker info --format '{{.DockerRootDir}}' 2>/dev/null || true)" + if [ -n "${docker_root_dir}" ]; then + DOCKER_STORAGE_PATH="${docker_root_dir}" + echo "[${CLEANUP_CONTEXT}] Using Docker root from docker info: ${DOCKER_STORAGE_PATH}" + return 0 + fi + + echo "[${CLEANUP_CONTEXT}] Could not determine Docker storage path from ${DOCKER_STORAGE_PATH} or docker info." >&2 + return 1 +} + +print_docker_storage_usage() { + echo "[${CLEANUP_CONTEXT}] Docker storage usage:" + df -h "${DOCKER_STORAGE_PATH}" || true + docker system df || true +} + +pin_isaacsim_image_if_present() { + if [ -z "${ISAACSIM_IMAGE}" ]; then + echo "[${CLEANUP_CONTEXT}] No IsaacSim base image provided; skipping image pin." + return + fi + + if docker image inspect "${ISAACSIM_IMAGE}" >/dev/null 2>&1; then + echo "[${CLEANUP_CONTEXT}] Pinning IsaacSim base image: ${ISAACSIM_IMAGE}" + docker create --name "${ISAACSIM_IMAGE_PIN_CONTAINER}" "${ISAACSIM_IMAGE}" true >/dev/null 2>&1 || true + else + echo "[${CLEANUP_CONTEXT}] IsaacSim base image is not present locally; skipping image pin." + fi +} + +remove_isaacsim_image_pin() { + docker rm "${ISAACSIM_IMAGE_PIN_CONTAINER}" >/dev/null 2>&1 || true +} + +run_conservative_cleanup() { + echo "[${CLEANUP_CONTEXT}] Running conservative Docker cleanup." + echo "[${CLEANUP_CONTEXT}] Removing Docker images older than ${DOCKER_CONSERVATIVE_PRUNE_UNTIL}." + docker image prune -a -f --filter "until=${DOCKER_CONSERVATIVE_PRUNE_UNTIL}" || true +} + +run_aggressive_cleanup() { + echo "[${CLEANUP_CONTEXT}] Running aggressive Docker cleanup." + echo "[${CLEANUP_CONTEXT}] Removing stopped Docker containers." + docker container prune -f --filter "until=${DOCKER_AGGRESSIVE_PRUNE_UNTIL}" || true + + echo "[${CLEANUP_CONTEXT}] Removing unused Docker builder cache older than ${DOCKER_AGGRESSIVE_PRUNE_UNTIL}." + docker builder prune -a -f --filter "until=${DOCKER_AGGRESSIVE_PRUNE_UNTIL}" || true + + echo "[${CLEANUP_CONTEXT}] Removing Docker images older than ${DOCKER_AGGRESSIVE_PRUNE_UNTIL}." + docker image prune -a -f --filter "until=${DOCKER_AGGRESSIVE_PRUNE_UNTIL}" || true +} + +main() { + echo "[${CLEANUP_CONTEXT}] Checking Docker storage before cleanup." + + local usage_percent + usage_percent="$(get_docker_storage_usage_percent)" + if [ -z "${usage_percent}" ]; then + resolve_docker_storage_path || true + usage_percent="$(get_docker_storage_usage_percent)" + fi + + print_docker_storage_usage + + if [ -z "${usage_percent}" ]; then + echo "[${CLEANUP_CONTEXT}] Could not determine Docker storage usage; running conservative cleanup." + pin_isaacsim_image_if_present + trap remove_isaacsim_image_pin EXIT + run_conservative_cleanup + print_docker_storage_usage + if [ "${FAIL_IF_STILL_HIGH}" = "true" ]; then + echo "::error::Could not determine Docker storage usage after cleanup. The self-hosted runner needs a measurable Docker storage path before tests can run." >&2 + return 1 + fi + return 0 + fi + + pin_isaacsim_image_if_present + trap remove_isaacsim_image_pin EXIT + + if [ "${usage_percent}" -ge "${DOCKER_CLEANUP_THRESHOLD_PERCENT}" ]; then + echo "[${CLEANUP_CONTEXT}] Docker storage is at ${usage_percent}%, meeting the ${DOCKER_CLEANUP_THRESHOLD_PERCENT}% threshold." + run_aggressive_cleanup + else + echo "[${CLEANUP_CONTEXT}] Docker storage is at ${usage_percent}%, below the ${DOCKER_CLEANUP_THRESHOLD_PERCENT}% threshold." + run_conservative_cleanup + fi + + echo "[${CLEANUP_CONTEXT}] Docker storage after cleanup." + print_docker_storage_usage + + local final_usage_percent + final_usage_percent="$(get_docker_storage_usage_percent)" + if [ "${FAIL_IF_STILL_HIGH}" = "true" ] \ + && [ -n "${final_usage_percent}" ] \ + && [ "${final_usage_percent}" -ge "${DOCKER_CLEANUP_THRESHOLD_PERCENT}" ]; then + echo "::error::Docker storage remains at ${final_usage_percent}% after cleanup. The self-hosted runner needs more free Docker storage before tests can run." >&2 + return 1 + fi +} + +main "$@" diff --git a/.github/actions/run-package-tests/test_cleanup_docker_storage.py b/.github/actions/run-package-tests/test_cleanup_docker_storage.py new file mode 100644 index 000000000000..dd49216c1cd9 --- /dev/null +++ b/.github/actions/run-package-tests/test_cleanup_docker_storage.py @@ -0,0 +1,181 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Tests for CI Docker storage cleanup helpers.""" + +from __future__ import annotations + +import os +import subprocess +from pathlib import Path + +_ACTION_DIR = Path(__file__).resolve().parent +_REPO_ROOT = _ACTION_DIR.parents[2] +_ACTION_PATH = _ACTION_DIR / "action.yml" +_SCRIPT_PATH = _ACTION_DIR / "cleanup_docker_storage.sh" + + +def _write_fake_df( + bin_dir: Path, first_usage: int, final_usage: int, failed_path: str | None = None, fallback_path: str | None = None +) -> None: + count_file = bin_dir / "df-count" + count_file.write_text("0", encoding="utf-8") + script = bin_dir / "df" + script.write_text( + f"""#!/usr/bin/env bash +set -euo pipefail + +path="${{2:-}}" +if [ -n "{failed_path or ""}" ] && [ "$path" = "{failed_path or ""}" ]; then + exit 1 +fi +if [ -n "{fallback_path or ""}" ] && [ "$path" = "{fallback_path or ""}" ]; then + : +elif [ -n "{fallback_path or ""}" ]; then + exit 1 +fi + +if [ "${{1:-}}" = "-P" ]; then + count=$(cat "{count_file}") + if [ "$count" -eq 0 ]; then + usage="{first_usage}" + else + usage="{final_usage}" + fi + echo "$((count + 1))" > "{count_file}" + echo "Filesystem 1024-blocks Used Available Capacity Mounted on" + echo "/dev/test 100 90 10 ${{usage}}% /var/lib/docker" +else + echo "Filesystem Size Used Avail Use% Mounted on" + echo "/dev/test 100G 90G 10G {first_usage}% /var/lib/docker" +fi +""", + encoding="utf-8", + ) + script.chmod(0o755) + + +def _write_fake_docker(bin_dir: Path, docker_root_dir: str = "/var/lib/docker") -> Path: + log_path = bin_dir / "docker.log" + script = bin_dir / "docker" + script.write_text( + f"""#!/usr/bin/env bash +set -euo pipefail + +printf '%s\\n' "$*" >> "{log_path}" +if [ "${{1:-}}" = "info" ] && [ "${{2:-}}" = "--format" ]; then + if [ -z "{docker_root_dir}" ]; then + exit 1 + fi + echo "{docker_root_dir}" + exit 0 +fi +if [ "${{1:-}}" = "image" ] && [ "${{2:-}}" = "inspect" ]; then + exit 0 +fi +exit 0 +""", + encoding="utf-8", + ) + script.chmod(0o755) + return log_path + + +def _run_cleanup( + tmp_path: Path, + first_usage: int, + final_usage: int, + failed_path: str | None = None, + docker_root_dir: str = "/var/lib/docker", +) -> subprocess.CompletedProcess[str]: + bin_dir = tmp_path / "bin" + bin_dir.mkdir() + _write_fake_df(bin_dir, first_usage, final_usage, failed_path=failed_path, fallback_path=docker_root_dir) + _write_fake_docker(bin_dir, docker_root_dir=docker_root_dir) + + env = os.environ.copy() + env["PATH"] = f"{bin_dir}{os.pathsep}{env['PATH']}" + env["DOCKER_STORAGE_PATH"] = "/var/lib/docker" + env["DOCKER_CLEANUP_THRESHOLD_PERCENT"] = "85" + + return subprocess.run( + [ + "bash", + str(_SCRIPT_PATH), + "nvcr.io/nvidian/isaac-sim:latest-develop", + "isaacsim-pin-test", + "test-cleanup", + "true", + ], + cwd=_REPO_ROOT, + env=env, + check=False, + capture_output=True, + text=True, + ) + + +def test_cleanup_uses_aggressive_pruning_when_docker_storage_exceeds_threshold(tmp_path: Path): + result = _run_cleanup(tmp_path, first_usage=91, final_usage=70) + + assert result.returncode == 0, result.stderr + docker_log = (tmp_path / "bin" / "docker.log").read_text(encoding="utf-8") + assert "container prune -f --filter until=24h" in docker_log + assert "builder prune -a -f --filter until=24h" in docker_log + assert "image prune -a -f --filter until=24h" in docker_log + + +def test_cleanup_keeps_conservative_image_pruning_below_threshold(tmp_path: Path): + result = _run_cleanup(tmp_path, first_usage=70, final_usage=70) + + assert result.returncode == 0, result.stderr + docker_log = (tmp_path / "bin" / "docker.log").read_text(encoding="utf-8") + assert "image prune -a -f --filter until=72h" in docker_log + assert "builder prune" not in docker_log + + +def test_cleanup_fails_early_when_aggressive_pruning_cannot_recover_space(tmp_path: Path): + result = _run_cleanup(tmp_path, first_usage=91, final_usage=89) + + assert result.returncode == 1 + assert "Docker storage remains at 89%" in result.stderr + + +def test_cleanup_uses_docker_root_dir_when_default_storage_path_is_unavailable(tmp_path: Path): + result = _run_cleanup( + tmp_path, + first_usage=91, + final_usage=89, + failed_path="/var/lib/docker", + docker_root_dir="/mnt/docker-root", + ) + + assert result.returncode == 1 + assert "Using Docker root from docker info: /mnt/docker-root" in result.stdout + assert "Docker storage remains at 89%" in result.stderr + + +def test_cleanup_fails_early_when_docker_storage_usage_cannot_be_measured(tmp_path: Path): + result = _run_cleanup( + tmp_path, + first_usage=91, + final_usage=89, + failed_path="/var/lib/docker", + docker_root_dir="", + ) + + assert result.returncode == 1 + assert "Could not determine Docker storage usage after cleanup" in result.stderr + + +def test_run_package_tests_prepares_docker_space_before_image_pull(): + action_text = _ACTION_PATH.read_text(encoding="utf-8") + + cleanup_index = action_text.index("name: Prepare Docker disk space") + pull_start_index = action_text.index("name: Record pull start time") + pull_index = action_text.index("name: Pull image from ECR") + + assert cleanup_index < pull_start_index < pull_index + assert "cleanup_docker_storage.sh" in action_text diff --git a/.github/actions/run-tests/action.yml b/.github/actions/run-tests/action.yml index dc95acda7a5c..ab8a6c5e1caa 100644 --- a/.github/actions/run-tests/action.yml +++ b/.github/actions/run-tests/action.yml @@ -55,6 +55,10 @@ inputs: description: 'Host path to bind-mount at /workspace/isaaclab (for deps-cache-hit mode)' default: '' required: false + extra-pip-packages: + description: 'Space-separated pip packages to install inside the Docker container before pytest starts' + default: '' + required: false runs: using: composite @@ -77,11 +81,30 @@ runs: local shard_index="${11}" local shard_count="${12}" local volume_mount_source="${13}" + local extra_pip_packages="${14}" + local logs_pid="" + local wait_pid="" + local docker_wait_file="/tmp/.docker_exit_${container_name}" + + # Kill the container immediately if the runner is cancelled. + # The GitHub Actions runner can deliver HUP, INT, or TERM on cancellation + # (see actions/runner#1309). Trap all three so the cleanup always fires. + # shellcheck disable=SC2064 + trap "echo '::warning::Cancellation signal - killing container ${container_name}'; \ + docker kill '${container_name}' 2>/dev/null || true; \ + docker rm -f '${container_name}' 2>/dev/null || true; \ + rm -f '${docker_wait_file}'; \ + if [ -n \"\$logs_pid\" ]; then kill \"\$logs_pid\" 2>/dev/null || true; fi; \ + if [ -n \"\$wait_pid\" ]; then kill \"\$wait_pid\" 2>/dev/null || true; fi; \ + exit 130" HUP INT TERM echo "Running tests in: $test_path" if [ -n "$pytest_options" ]; then echo "With pytest options: $pytest_options" fi + if [ -n "$extra_pip_packages" ]; then + echo "With extra pip packages: $extra_pip_packages" + fi if [ -n "$filter_pattern" ]; then echo "With filter pattern: $filter_pattern" fi @@ -110,6 +133,7 @@ runs: -e ISAAC_SIM_LOW_MEMORY=1 \ -e PYTHONUNBUFFERED=1 \ -e PYTHONIOENCODING=utf-8 \ + -e GITHUB_ACTIONS=${GITHUB_ACTIONS:-} \ -e TEST_RESULT_FILE=$result_file" if [ "$curobo_only" = "true" ]; then @@ -151,6 +175,11 @@ runs: echo "No filter pattern provided" fi + if [ -n "$extra_pip_packages" ]; then + export TEST_EXTRA_PIP_PACKAGES="$extra_pip_packages" + docker_env_vars="$docker_env_vars -e TEST_EXTRA_PIP_PACKAGES" + fi + echo "Docker environment variables: '$docker_env_vars'" # Volume mount for deps-cache-hit mode: bind-mount the checked-out @@ -183,20 +212,40 @@ runs: set -e cd /workspace/isaaclab mkdir -p tests + rm _isaac_sim || true + ln -s /isaac-sim _isaac_sim + if [ -n \"\${TEST_EXTRA_PIP_PACKAGES:-}\" ]; then + echo \"Installing extra pip packages: \${TEST_EXTRA_PIP_PACKAGES}\" + ./isaaclab.sh -p -m pip install \${TEST_EXTRA_PIP_PACKAGES} + fi echo 'Starting pytest with path: $test_path' - /isaac-sim/python.sh -m pytest --ignore=tools/conftest.py $test_path $pytest_options -v --junitxml=tests/$result_file + ./isaaclab.sh -p -m pytest --ignore=tools/conftest.py --ignore=source/isaaclab/test/install_ci $test_path $pytest_options -v --junitxml=tests/$result_file " - # Stream container logs to CI output (this is the killable foreground process). - docker logs -f $container_name & - local logs_pid=$! + # Stream container logs in background. + docker logs -f "$container_name" & + logs_pid=$! + + # Background `docker wait` + bash `wait` (interruptible by signals). + docker wait "$container_name" > "$docker_wait_file" & + wait_pid=$! + wait $wait_pid 2>/dev/null + local wait_status=$? + wait_pid="" - # Wait for the container to exit and capture its exit code. - DOCKER_EXIT=$(docker wait $container_name) || DOCKER_EXIT=1 + # If interrupted by signal, trap already handled cleanup. + if [ $wait_status -gt 128 ]; then + kill $logs_pid 2>/dev/null || true + exit 130 + fi + + DOCKER_EXIT=$(cat "$docker_wait_file" 2>/dev/null) || DOCKER_EXIT=1 + rm -f "$docker_wait_file" # Stop following logs. kill $logs_pid 2>/dev/null || true wait $logs_pid 2>/dev/null || true + logs_pid="" if [ $DOCKER_EXIT -eq 0 ]; then echo "🟢 Docker container completed successfully" @@ -247,7 +296,7 @@ runs: fi fi - # Copy comparison images (saved by test_rendering_correctness.py). + # Copy comparison images (saved by source/isaaclab_tasks/test/test_rendering_*.py). local img_dir="$reports_dir/comparison-images" if [ -n "$volume_mount_source" ] && [ -d "${volume_mount_source}/tests/comparison-images" ]; then cp -r "${volume_mount_source}/tests/comparison-images" "$img_dir" @@ -264,7 +313,15 @@ runs: } # Call the function with provided parameters - run_tests "${{ inputs.test-path }}" "${{ inputs.result-file }}" "${{ inputs.container-name }}" "${{ inputs.image-tag }}" "${{ inputs.reports-dir }}" "${{ inputs.pytest-options }}" "${{ inputs.filter-pattern }}" "${{ inputs.curobo-only }}" "${{ inputs.include-files }}" "${{ inputs.quarantined-only }}" "${{ inputs.shard-index }}" "${{ inputs.shard-count }}" "${{ inputs.volume-mount-source }}" + run_tests "${{ inputs.test-path }}" "${{ inputs.result-file }}" "${{ inputs.container-name }}" "${{ inputs.image-tag }}" "${{ inputs.reports-dir }}" "${{ inputs.pytest-options }}" "${{ inputs.filter-pattern }}" "${{ inputs.curobo-only }}" "${{ inputs.include-files }}" "${{ inputs.quarantined-only }}" "${{ inputs.shard-index }}" "${{ inputs.shard-count }}" "${{ inputs.volume-mount-source }}" "${{ inputs.extra-pip-packages }}" + + - name: Kill container on cancellation + if: cancelled() + shell: bash + run: | + echo "::warning::Job cancelled - force-killing container" + docker kill "${{ inputs.container-name }}" 2>/dev/null || true + docker rm -f "${{ inputs.container-name }}" 2>/dev/null || true - name: Write job summary if: always() @@ -293,7 +350,7 @@ runs: retention-days: 7 - name: Clean up Docker container - if: always() + if: always() && !cancelled() shell: bash run: | echo "🔵 Cleaning up Docker container..." diff --git a/.github/workflows/build.yaml b/.github/workflows/build.yaml index 07e054ba8a15..b971940fe00b 100644 --- a/.github/workflows/build.yaml +++ b/.github/workflows/build.yaml @@ -3,30 +3,8 @@ # # SPDX-License-Identifier: BSD-3-Clause -# Test job gating summary -# -# +------------------------------------+-----------------------------------------------------+ -# | Job | Gate (any match triggers the job) | -# +------------------------------------+-----------------------------------------------------+ -# | test-isaaclab-tasks (x3 shards) | isaaclab-tasks | isaaclab-core | infra | -# | test-isaaclab-core (x3 shards) | isaaclab-core | infra | -# | test-isaaclab-rl | isaaclab-rl | isaaclab-core | infra | -# | test-isaaclab-mimic | isaaclab-mimic | isaaclab-core | infra | -# | test-isaaclab-contrib | isaaclab-contrib | isaaclab-core | infra | -# | test-isaaclab-teleop | isaaclab-teleop | isaaclab-core | infra | -# | test-isaaclab-visualizers | isaaclab-visualizers | isaaclab-core | infra | -# | test-isaaclab-assets | isaaclab-assets | isaaclab-core | infra | -# | test-isaaclab-newton | isaaclab-newton | isaaclab-core | infra | -# | test-isaaclab-physx | isaaclab-physx | isaaclab-core | infra | -# | test-isaaclab-ov | isaaclab-ov | isaaclab-core | infra | -# | test-environments-training | isaaclab-tasks | isaaclab-core | infra | -# | test-curobo (needs build-curobo) | isaaclab-mimic | isaaclab-core | infra | -# | test-skillgen (needs build-curobo) | isaaclab-mimic | isaaclab-tasks | isaaclab-core | -# | | | infra | -# | test-quarantined | vars.RUN_QUARANTINED_TESTS == "true" | -# | build-curobo | isaaclab-mimic | isaaclab-tasks | isaaclab-core | -# | | | infra | -# +------------------------------------+-----------------------------------------------------+ +# region help +# Every test job runs on every PR. # # ============================================================================= # CI DEBUGGING TIPS @@ -63,19 +41,13 @@ # # Remember to REVERT all temporary changes before merging! # ============================================================================= +#endregion name: Docker + Tests on: pull_request: types: [opened, synchronize, reopened] - paths: - - 'source/**' - - 'docker/**' - - 'tools/**' - - 'apps/**' - - '.github/workflows/build.yaml' - - '.github/actions/**' branches: - main - develop @@ -84,7 +56,7 @@ on: # Concurrency control to prevent parallel runs on the same PR concurrency: - group: ${{ github.workflow }}-${{ github.ref }} + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} cancel-in-progress: true permissions: @@ -95,157 +67,138 @@ permissions: env: NGC_API_KEY: ${{ secrets.NGC_API_KEY }} - # On merge to main defaults will point to "nvcr.io/nvidia/isaac-sim:6.0.0" - ISAACSIM_BASE_IMAGE: 'nvcr.io/nvidian/isaac-sim' # ${{ vars.ISAACSIM_BASE_IMAGE || 'nvcr.io/nvidia/isaac-sim' }} - ISAACSIM_BASE_VERSION: 'latest-develop' # ${{ vars.ISAACSIM_BASE_VERSION || '6.0.0' }} - DOCKER_IMAGE_TAG: isaac-lab-dev:${{ github.event_name == 'pull_request' && format('pr-{0}', github.event.pull_request.number) || github.ref_name }}-${{ github.sha }} - # To run quarantined tests, create a GitHub repo variable named - # RUN_QUARANTINED_TESTS and set it to 'true'. The test-quarantined - # job is skipped when the variable is absent or not 'true'. + CI_IMAGE_TAG: isaac-lab-ci:${{ github.event_name == 'pull_request' && format('pr-{0}', github.event.pull_request.number) || github.ref_name }}-${{ github.sha }} jobs: - detect-changes: + changes: name: Detect Changes runs-on: ubuntu-latest outputs: - isaaclab-core: ${{ steps.check.outputs.isaaclab-core }} - isaaclab-physx: ${{ steps.check.outputs.isaaclab-physx }} - isaaclab-newton: ${{ steps.check.outputs.isaaclab-newton }} - isaaclab-tasks: ${{ steps.check.outputs.isaaclab-tasks }} - isaaclab-rl: ${{ steps.check.outputs.isaaclab-rl }} - isaaclab-mimic: ${{ steps.check.outputs.isaaclab-mimic }} - isaaclab-contrib: ${{ steps.check.outputs.isaaclab-contrib }} - isaaclab-teleop: ${{ steps.check.outputs.isaaclab-teleop }} - isaaclab-visualizers: ${{ steps.check.outputs.isaaclab-visualizers }} - isaaclab-assets: ${{ steps.check.outputs.isaaclab-assets }} - isaaclab-ov: ${{ steps.check.outputs.isaaclab-ov }} - infra: ${{ steps.check.outputs.infra }} + run_docker_tests: ${{ steps.detect.outputs.run_docker_tests }} steps: - - name: Checkout Code - uses: actions/checkout@v6 - with: - fetch-depth: 1 - - - name: Detect changed files and packages - id: check + - id: detect + env: + GH_TOKEN: ${{ github.token }} + PR_NUMBER: ${{ github.event.pull_request.number }} + EVENT_NAME: ${{ github.event_name }} + REPO: ${{ github.repository }} run: | set -euo pipefail - # For non-PR events, run all tests - if [ "${{ github.event_name }}" != "pull_request" ]; then - for pkg in isaaclab-core isaaclab-physx isaaclab-newton isaaclab-tasks \ - isaaclab-rl isaaclab-mimic isaaclab-contrib isaaclab-teleop \ - isaaclab-visualizers isaaclab-assets isaaclab-ov infra; do - echo "$pkg=true" >> "$GITHUB_OUTPUT" + # Docker test jobs run only when paths in the patterns table change. + # Otherwise they skip via `if:` and report green to branch protection, + # which is why we don't use a workflow-level `paths:` filter (a + # not-triggered required check would block the PR forever). + # config.yaml is included because it controls the base image names and + # tags consumed by the Docker build jobs. + patterns=( + $'^source/\tLibrary source code' + $'^docker/\tContainer build inputs' + $'^tools/\tBuild tooling' + $'^apps/\tStandalone apps' + $'^scripts/\tStandalone scripts' + $'^\\.github/workflows/build\\.yaml$\tThis workflow file' + $'^\\.github/workflows/config\\.yaml$\tBase image config' + $'^\\.github/actions/\tCI actions' + ) + triggered_jobs="Docker build + all test-* matrix jobs" + + render_table() { + local files="$1" entry regex desc count sample + echo "| Pattern | What it covers | Matched files |" + echo "|---|---|---|" + for entry in "${patterns[@]}"; do + IFS=$'\t' read -r regex desc <<< "$entry" + count=$(printf '%s\n' "$files" | grep -cE "$regex" || true) + if [ "$count" -gt 0 ]; then + sample=$(printf '%s\n' "$files" | grep -E "$regex" | head -3 | paste -sd ', ' -) + [ "$count" -gt 3 ] && sample="$sample (and $((count - 3)) more)" + echo "| \`$regex\` | $desc | $sample |" + else + echo "| \`$regex\` | $desc | - |" + fi done + } + + any_match() { + local files="$1" entry regex + for entry in "${patterns[@]}"; do + IFS=$'\t' read -r regex _ <<< "$entry" + if printf '%s\n' "$files" | grep -qE "$regex"; then + return 0 + fi + done + return 1 + } + + decide() { + local decision="$1" reason="$2" files="${3:-}" + echo "Decision: run_docker_tests=$decision ($reason)" + echo "run_docker_tests=$decision" >> "$GITHUB_OUTPUT" + { + echo "## Docker test gating" + echo "" + if [ "$decision" = "true" ]; then + echo "Docker tests will **run**: $reason." + else + echo "Docker tests will be **skipped**: $reason." + fi + echo "" + echo "Triggered jobs: $triggered_jobs." + if [ -n "$files" ]; then + echo "" + render_table "$files" + fi + } >> "$GITHUB_STEP_SUMMARY" + } + + if [ "$EVENT_NAME" != "pull_request" ]; then + decide true "non-PR event ($EVENT_NAME)" exit 0 fi - # Fetch the PR base branch tip to diff against - git fetch --depth=1 origin "${{ github.event.pull_request.base.ref }}" - changed=$(git diff --name-only FETCH_HEAD HEAD) - - if [ -z "$changed" ]; then - echo "::warning::No changed files detected between FETCH_HEAD and HEAD - running all tests as a safety measure" - for pkg in isaaclab-core isaaclab-physx isaaclab-newton isaaclab-tasks \ - isaaclab-rl isaaclab-mimic isaaclab-contrib isaaclab-teleop \ - isaaclab-visualizers isaaclab-assets isaaclab-ov infra; do - echo "$pkg=true" >> "$GITHUB_OUTPUT" - done + if ! changed_files="$(gh api --paginate "repos/$REPO/pulls/$PR_NUMBER/files" --jq '.[].filename')"; then + # Fail-safe: a transient API error must not block merge. Default to running. + echo "::warning::Could not list changed files; defaulting to running tests" + decide true "fail-safe (could not list changed files)" exit 0 fi - has() { - echo "$changed" | grep -qE "$1" - local rc=$? - if [ $rc -eq 0 ]; then echo true - elif [ $rc -eq 1 ]; then echo false - else - echo "::error::grep failed with exit $rc for pattern: $1" - exit 1 - fi - } + printf '%s\n' "$changed_files" - # Detect per-package changes - core=$(has '^source/isaaclab/') - physx=$(has '^source/isaaclab_physx/') - newton=$(has '^source/isaaclab_newton/') - tasks=$(has '^source/isaaclab_tasks/') - - # Changes in apps/ trigger: core, physx, newton, tasks - apps=$(has '^apps/') - if [ "$apps" = "true" ]; then - core=true - physx=true - newton=true - tasks=true + if any_match "$changed_files"; then + decide true "relevant paths changed" "$changed_files" + else + decide false "no relevant paths changed" "$changed_files" fi - echo "isaaclab-core=$core" >> "$GITHUB_OUTPUT" - echo "isaaclab-physx=$physx" >> "$GITHUB_OUTPUT" - echo "isaaclab-newton=$newton" >> "$GITHUB_OUTPUT" - echo "isaaclab-tasks=$tasks" >> "$GITHUB_OUTPUT" - echo "isaaclab-rl=$(has '^source/isaaclab_rl/')" >> "$GITHUB_OUTPUT" - echo "isaaclab-mimic=$(has '^source/isaaclab_mimic/')" >> "$GITHUB_OUTPUT" - echo "isaaclab-contrib=$(has '^source/isaaclab_contrib/')" >> "$GITHUB_OUTPUT" - echo "isaaclab-teleop=$(has '^source/isaaclab_teleop/')" >> "$GITHUB_OUTPUT" - echo "isaaclab-visualizers=$(has '^source/isaaclab_visualizers/')" >> "$GITHUB_OUTPUT" - echo "isaaclab-assets=$(has '^source/isaaclab_assets/')" >> "$GITHUB_OUTPUT" - echo "isaaclab-ov=$(has '^source/isaaclab_ov/')" >> "$GITHUB_OUTPUT" - echo "infra=$(has '^(\.github/|docker/|tools/|scripts/)')" >> "$GITHUB_OUTPUT" - - echo "" - echo "CHANGED FILES:" - echo "$changed" | while IFS= read -r f; do - case "$f" in - source/isaaclab/*) echo "$f (isaaclab-core)" ;; - source/isaaclab_physx/*) echo "$f (isaaclab-physx)" ;; - source/isaaclab_newton/*) echo "$f (isaaclab-newton)" ;; - source/isaaclab_tasks/*) echo "$f (isaaclab-tasks)" ;; - source/isaaclab_rl/*) echo "$f (isaaclab-rl)" ;; - source/isaaclab_mimic/*) echo "$f (isaaclab-mimic)" ;; - source/isaaclab_contrib/*) echo "$f (isaaclab-contrib)" ;; - source/isaaclab_teleop/*) echo "$f (isaaclab-teleop)" ;; - source/isaaclab_visualizers/*) echo "$f (isaaclab-visualizers)" ;; - source/isaaclab_assets/*) echo "$f (isaaclab-assets)" ;; - source/isaaclab_ov/*) echo "$f (isaaclab-ov)" ;; - .github/*|docker/*|tools/*|scripts/*) echo "$f (infra)" ;; - apps/*) echo "$f (apps - core/physx/newton/tasks)" ;; - *) echo "$f" ;; - esac - done - echo "" - echo "CHANGED PACKAGES:" - cat "$GITHUB_OUTPUT" - - # Write job summary visible on the GH Actions UI - { - echo "| File | Package |" - echo "|------|---------|" - echo "$changed" | while IFS= read -r f; do - case "$f" in - source/isaaclab/*) echo "| \`$f\` | isaaclab-core |" ;; - source/isaaclab_physx/*) echo "| \`$f\` | isaaclab-physx |" ;; - source/isaaclab_newton/*) echo "| \`$f\` | isaaclab-newton |" ;; - source/isaaclab_tasks/*) echo "| \`$f\` | isaaclab-tasks |" ;; - source/isaaclab_rl/*) echo "| \`$f\` | isaaclab-rl |" ;; - source/isaaclab_mimic/*) echo "| \`$f\` | isaaclab-mimic |" ;; - source/isaaclab_contrib/*) echo "| \`$f\` | isaaclab-contrib |" ;; - source/isaaclab_teleop/*) echo "| \`$f\` | isaaclab-teleop |" ;; - source/isaaclab_visualizers/*) echo "| \`$f\` | isaaclab-visualizers |" ;; - source/isaaclab_assets/*) echo "| \`$f\` | isaaclab-assets |" ;; - source/isaaclab_ov/*) echo "| \`$f\` | isaaclab-ov |" ;; - .github/*|docker/*|tools/*|scripts/*) echo "| \`$f\` | infra |" ;; - apps/*) echo "| \`$f\` | apps - core/physx/newton/tasks |" ;; - *) echo "| \`$f\` | - |" ;; - esac - done - } >> "$GITHUB_STEP_SUMMARY" + config: + name: Load Config + runs-on: ubuntu-latest + outputs: + isaacsim_image_name: ${{ steps.load.outputs.isaacsim_image_name }} + isaacsim_image_tag: ${{ steps.load.outputs.isaacsim_image_tag }} + isaaclab_image_name: ${{ steps.load.outputs.isaaclab_image_name }} + steps: + - uses: actions/checkout@v6 + with: + fetch-depth: 1 + sparse-checkout: .github/workflows/config.yaml + sparse-checkout-cone-mode: false + - id: load + run: | + set -euo pipefail + f=.github/workflows/config.yaml + echo "isaacsim_image_name=$(yq -r .isaacsim_image_name "$f")" >> "$GITHUB_OUTPUT" + echo "isaacsim_image_tag=$(yq -r .isaacsim_image_tag "$f")" >> "$GITHUB_OUTPUT" + echo "isaaclab_image_name=$(yq -r .isaaclab_image_name "$f")" >> "$GITHUB_OUTPUT" + #region build jobs build: name: Build Base Docker Image runs-on: [self-hosted, gpu] - needs: [detect-changes] + needs: [changes, config] + if: needs.changes.outputs.run_docker_tests == 'true' steps: - name: Checkout Code uses: actions/checkout@v6 @@ -256,22 +209,17 @@ jobs: - name: Build and push to ECR uses: ./.github/actions/ecr-build-push-pull with: - image-tag: ${{ env.DOCKER_IMAGE_TAG }} - isaacsim-base-image: ${{ env.ISAACSIM_BASE_IMAGE }} - isaacsim-version: ${{ env.ISAACSIM_BASE_VERSION }} + image-tag: ${{ env.CI_IMAGE_TAG }} + isaacsim-base-image: ${{ needs.config.outputs.isaacsim_image_name }} + isaacsim-version: ${{ needs.config.outputs.isaacsim_image_tag }} dockerfile-path: docker/Dockerfile.base cache-tag: cache-base - build-curobo: name: Build cuRobo Docker Image runs-on: [self-hosted, gpu] - needs: [detect-changes] - if: >- - needs.detect-changes.outputs.isaaclab-mimic == 'true' || - needs.detect-changes.outputs.isaaclab-tasks == 'true' || - needs.detect-changes.outputs.isaaclab-core == 'true' || - needs.detect-changes.outputs.infra == 'true' + needs: [changes, config] + if: needs.changes.outputs.run_docker_tests == 'true' steps: - name: Checkout Code uses: actions/checkout@v6 @@ -282,29 +230,21 @@ jobs: - name: Build and push to ECR uses: ./.github/actions/ecr-build-push-pull with: - image-tag: ${{ env.DOCKER_IMAGE_TAG }}-curobo - isaacsim-base-image: ${{ env.ISAACSIM_BASE_IMAGE }} - isaacsim-version: ${{ env.ISAACSIM_BASE_VERSION }} + image-tag: ${{ env.CI_IMAGE_TAG }}-curobo + isaacsim-base-image: ${{ needs.config.outputs.isaacsim_image_name }} + isaacsim-version: ${{ needs.config.outputs.isaacsim_image_tag }} dockerfile-path: docker/Dockerfile.curobo cache-tag: cache-curobo + #endregion - - - # Each test job checks out code, then calls run-package-tests which handles - # ECR pull, pytest in Docker, artifact upload, and fork-PR checks. - + #region test jobs test-isaaclab-tasks: name: isaaclab_tasks [1/3] runs-on: [self-hosted, gpu] timeout-minutes: 180 continue-on-error: true - needs: [build, detect-changes] - if: >- - always() && needs.build.result == 'success' && ( - needs.detect-changes.outputs.isaaclab-tasks == 'true' || - needs.detect-changes.outputs.isaaclab-core == 'true' || - needs.detect-changes.outputs.infra == 'true' - ) + needs: [build, config] + if: needs.build.result == 'success' steps: - uses: actions/checkout@v6 with: @@ -312,27 +252,21 @@ jobs: lfs: true - uses: ./.github/actions/run-package-tests with: - image-tag: ${{ env.DOCKER_IMAGE_TAG }} - isaacsim-base-image: ${{ env.ISAACSIM_BASE_IMAGE }} - isaacsim-version: ${{ env.ISAACSIM_BASE_VERSION }} + image-tag: ${{ env.CI_IMAGE_TAG }} + isaacsim-base-image: ${{ needs.config.outputs.isaacsim_image_name }} + isaacsim-version: ${{ needs.config.outputs.isaacsim_image_tag }} filter-pattern: "isaaclab_tasks" shard-index: "0" shard-count: "3" container-name: isaac-lab-tasks-1-test - test-isaaclab-tasks-2: name: isaaclab_tasks [2/3] runs-on: [self-hosted, gpu] timeout-minutes: 180 continue-on-error: true - needs: [build, detect-changes] - if: >- - always() && needs.build.result == 'success' && ( - needs.detect-changes.outputs.isaaclab-tasks == 'true' || - needs.detect-changes.outputs.isaaclab-core == 'true' || - needs.detect-changes.outputs.infra == 'true' - ) + needs: [build, config] + if: needs.build.result == 'success' steps: - uses: actions/checkout@v6 with: @@ -340,27 +274,21 @@ jobs: lfs: true - uses: ./.github/actions/run-package-tests with: - image-tag: ${{ env.DOCKER_IMAGE_TAG }} - isaacsim-base-image: ${{ env.ISAACSIM_BASE_IMAGE }} - isaacsim-version: ${{ env.ISAACSIM_BASE_VERSION }} + image-tag: ${{ env.CI_IMAGE_TAG }} + isaacsim-base-image: ${{ needs.config.outputs.isaacsim_image_name }} + isaacsim-version: ${{ needs.config.outputs.isaacsim_image_tag }} filter-pattern: "isaaclab_tasks" shard-index: "1" shard-count: "3" container-name: isaac-lab-tasks-2-test - test-isaaclab-tasks-3: name: isaaclab_tasks [3/3] runs-on: [self-hosted, gpu] timeout-minutes: 180 continue-on-error: true - needs: [build, detect-changes] - if: >- - always() && needs.build.result == 'success' && ( - needs.detect-changes.outputs.isaaclab-tasks == 'true' || - needs.detect-changes.outputs.isaaclab-core == 'true' || - needs.detect-changes.outputs.infra == 'true' - ) + needs: [build, config] + if: needs.build.result == 'success' steps: - uses: actions/checkout@v6 with: @@ -368,25 +296,20 @@ jobs: lfs: true - uses: ./.github/actions/run-package-tests with: - image-tag: ${{ env.DOCKER_IMAGE_TAG }} - isaacsim-base-image: ${{ env.ISAACSIM_BASE_IMAGE }} - isaacsim-version: ${{ env.ISAACSIM_BASE_VERSION }} + image-tag: ${{ env.CI_IMAGE_TAG }} + isaacsim-base-image: ${{ needs.config.outputs.isaacsim_image_name }} + isaacsim-version: ${{ needs.config.outputs.isaacsim_image_tag }} filter-pattern: "isaaclab_tasks" shard-index: "2" shard-count: "3" container-name: isaac-lab-tasks-3-test - test-isaaclab-core: name: isaaclab (core) [1/3] runs-on: [self-hosted, gpu] timeout-minutes: 180 - needs: [build, detect-changes] - if: >- - always() && needs.build.result == 'success' && ( - needs.detect-changes.outputs.isaaclab-core == 'true' || - needs.detect-changes.outputs.infra == 'true' - ) + needs: [build, config] + if: needs.build.result == 'success' steps: - uses: actions/checkout@v6 with: @@ -394,25 +317,20 @@ jobs: lfs: true - uses: ./.github/actions/run-package-tests with: - image-tag: ${{ env.DOCKER_IMAGE_TAG }} - isaacsim-base-image: ${{ env.ISAACSIM_BASE_IMAGE }} - isaacsim-version: ${{ env.ISAACSIM_BASE_VERSION }} + image-tag: ${{ env.CI_IMAGE_TAG }} + isaacsim-base-image: ${{ needs.config.outputs.isaacsim_image_name }} + isaacsim-version: ${{ needs.config.outputs.isaacsim_image_tag }} filter-pattern: "not isaaclab_" shard-index: "0" shard-count: "3" container-name: isaac-lab-core-1-test - test-isaaclab-core-2: name: isaaclab (core) [2/3] runs-on: [self-hosted, gpu] timeout-minutes: 180 - needs: [build, detect-changes] - if: >- - always() && needs.build.result == 'success' && ( - needs.detect-changes.outputs.isaaclab-core == 'true' || - needs.detect-changes.outputs.infra == 'true' - ) + needs: [build, config] + if: needs.build.result == 'success' steps: - uses: actions/checkout@v6 with: @@ -420,25 +338,20 @@ jobs: lfs: true - uses: ./.github/actions/run-package-tests with: - image-tag: ${{ env.DOCKER_IMAGE_TAG }} - isaacsim-base-image: ${{ env.ISAACSIM_BASE_IMAGE }} - isaacsim-version: ${{ env.ISAACSIM_BASE_VERSION }} + image-tag: ${{ env.CI_IMAGE_TAG }} + isaacsim-base-image: ${{ needs.config.outputs.isaacsim_image_name }} + isaacsim-version: ${{ needs.config.outputs.isaacsim_image_tag }} filter-pattern: "not isaaclab_" shard-index: "1" shard-count: "3" container-name: isaac-lab-core-2-test - test-isaaclab-core-3: name: isaaclab (core) [3/3] runs-on: [self-hosted, gpu] timeout-minutes: 180 - needs: [build, detect-changes] - if: >- - always() && needs.build.result == 'success' && ( - needs.detect-changes.outputs.isaaclab-core == 'true' || - needs.detect-changes.outputs.infra == 'true' - ) + needs: [build, config] + if: needs.build.result == 'success' steps: - uses: actions/checkout@v6 with: @@ -446,26 +359,20 @@ jobs: lfs: true - uses: ./.github/actions/run-package-tests with: - image-tag: ${{ env.DOCKER_IMAGE_TAG }} - isaacsim-base-image: ${{ env.ISAACSIM_BASE_IMAGE }} - isaacsim-version: ${{ env.ISAACSIM_BASE_VERSION }} + image-tag: ${{ env.CI_IMAGE_TAG }} + isaacsim-base-image: ${{ needs.config.outputs.isaacsim_image_name }} + isaacsim-version: ${{ needs.config.outputs.isaacsim_image_tag }} filter-pattern: "not isaaclab_" shard-index: "2" shard-count: "3" container-name: isaac-lab-core-3-test - test-isaaclab-rl: name: isaaclab_rl runs-on: [self-hosted, gpu] timeout-minutes: 180 - needs: [build, detect-changes] - if: >- - always() && needs.build.result == 'success' && ( - needs.detect-changes.outputs.isaaclab-rl == 'true' || - needs.detect-changes.outputs.isaaclab-core == 'true' || - needs.detect-changes.outputs.infra == 'true' - ) + needs: [build, config] + if: needs.build.result == 'success' steps: - uses: actions/checkout@v6 with: @@ -473,24 +380,19 @@ jobs: lfs: true - uses: ./.github/actions/run-package-tests with: - image-tag: ${{ env.DOCKER_IMAGE_TAG }} - isaacsim-base-image: ${{ env.ISAACSIM_BASE_IMAGE }} - isaacsim-version: ${{ env.ISAACSIM_BASE_VERSION }} + image-tag: ${{ env.CI_IMAGE_TAG }} + isaacsim-base-image: ${{ needs.config.outputs.isaacsim_image_name }} + isaacsim-version: ${{ needs.config.outputs.isaacsim_image_tag }} filter-pattern: "isaaclab_rl" + extra-pip-packages: "leapp" container-name: isaac-lab-rl-test - test-isaaclab-mimic: name: isaaclab_mimic runs-on: [self-hosted, gpu] timeout-minutes: 180 - needs: [build, detect-changes] - if: >- - always() && needs.build.result == 'success' && ( - needs.detect-changes.outputs.isaaclab-mimic == 'true' || - needs.detect-changes.outputs.isaaclab-core == 'true' || - needs.detect-changes.outputs.infra == 'true' - ) + needs: [build, config] + if: needs.build.result == 'success' steps: - uses: actions/checkout@v6 with: @@ -498,24 +400,18 @@ jobs: lfs: true - uses: ./.github/actions/run-package-tests with: - image-tag: ${{ env.DOCKER_IMAGE_TAG }} - isaacsim-base-image: ${{ env.ISAACSIM_BASE_IMAGE }} - isaacsim-version: ${{ env.ISAACSIM_BASE_VERSION }} + image-tag: ${{ env.CI_IMAGE_TAG }} + isaacsim-base-image: ${{ needs.config.outputs.isaacsim_image_name }} + isaacsim-version: ${{ needs.config.outputs.isaacsim_image_tag }} filter-pattern: "isaaclab_mimic" container-name: isaac-lab-mimic-test - test-isaaclab-contrib: name: isaaclab_contrib runs-on: [self-hosted, gpu] timeout-minutes: 180 - needs: [build, detect-changes] - if: >- - always() && needs.build.result == 'success' && ( - needs.detect-changes.outputs.isaaclab-contrib == 'true' || - needs.detect-changes.outputs.isaaclab-core == 'true' || - needs.detect-changes.outputs.infra == 'true' - ) + needs: [build, config] + if: needs.build.result == 'success' steps: - uses: actions/checkout@v6 with: @@ -523,24 +419,18 @@ jobs: lfs: true - uses: ./.github/actions/run-package-tests with: - image-tag: ${{ env.DOCKER_IMAGE_TAG }} - isaacsim-base-image: ${{ env.ISAACSIM_BASE_IMAGE }} - isaacsim-version: ${{ env.ISAACSIM_BASE_VERSION }} + image-tag: ${{ env.CI_IMAGE_TAG }} + isaacsim-base-image: ${{ needs.config.outputs.isaacsim_image_name }} + isaacsim-version: ${{ needs.config.outputs.isaacsim_image_tag }} filter-pattern: "isaaclab_contrib" container-name: isaac-lab-contrib-test - test-isaaclab-teleop: name: isaaclab_teleop runs-on: [self-hosted, gpu] timeout-minutes: 180 - needs: [build, detect-changes] - if: >- - always() && needs.build.result == 'success' && ( - needs.detect-changes.outputs.isaaclab-teleop == 'true' || - needs.detect-changes.outputs.isaaclab-core == 'true' || - needs.detect-changes.outputs.infra == 'true' - ) + needs: [build, config] + if: needs.build.result == 'success' steps: - uses: actions/checkout@v6 with: @@ -548,24 +438,18 @@ jobs: lfs: true - uses: ./.github/actions/run-package-tests with: - image-tag: ${{ env.DOCKER_IMAGE_TAG }} - isaacsim-base-image: ${{ env.ISAACSIM_BASE_IMAGE }} - isaacsim-version: ${{ env.ISAACSIM_BASE_VERSION }} + image-tag: ${{ env.CI_IMAGE_TAG }} + isaacsim-base-image: ${{ needs.config.outputs.isaacsim_image_name }} + isaacsim-version: ${{ needs.config.outputs.isaacsim_image_tag }} filter-pattern: "isaaclab_teleop" container-name: isaac-lab-teleop-test - test-isaaclab-visualizers: name: isaaclab_visualizers runs-on: [self-hosted, gpu] timeout-minutes: 180 - needs: [build, detect-changes] - if: >- - always() && needs.build.result == 'success' && ( - needs.detect-changes.outputs.isaaclab-visualizers == 'true' || - needs.detect-changes.outputs.isaaclab-core == 'true' || - needs.detect-changes.outputs.infra == 'true' - ) + needs: [build, config] + if: needs.build.result == 'success' steps: - uses: actions/checkout@v6 with: @@ -573,24 +457,18 @@ jobs: lfs: true - uses: ./.github/actions/run-package-tests with: - image-tag: ${{ env.DOCKER_IMAGE_TAG }} - isaacsim-base-image: ${{ env.ISAACSIM_BASE_IMAGE }} - isaacsim-version: ${{ env.ISAACSIM_BASE_VERSION }} + image-tag: ${{ env.CI_IMAGE_TAG }} + isaacsim-base-image: ${{ needs.config.outputs.isaacsim_image_name }} + isaacsim-version: ${{ needs.config.outputs.isaacsim_image_tag }} filter-pattern: "isaaclab_visualizers" container-name: isaac-lab-visualizers-test - test-isaaclab-assets: name: isaaclab_assets runs-on: [self-hosted, gpu] timeout-minutes: 180 - needs: [build, detect-changes] - if: >- - always() && needs.build.result == 'success' && ( - needs.detect-changes.outputs.isaaclab-assets == 'true' || - needs.detect-changes.outputs.isaaclab-core == 'true' || - needs.detect-changes.outputs.infra == 'true' - ) + needs: [build, config] + if: needs.build.result == 'success' steps: - uses: actions/checkout@v6 with: @@ -598,24 +476,18 @@ jobs: lfs: true - uses: ./.github/actions/run-package-tests with: - image-tag: ${{ env.DOCKER_IMAGE_TAG }} - isaacsim-base-image: ${{ env.ISAACSIM_BASE_IMAGE }} - isaacsim-version: ${{ env.ISAACSIM_BASE_VERSION }} + image-tag: ${{ env.CI_IMAGE_TAG }} + isaacsim-base-image: ${{ needs.config.outputs.isaacsim_image_name }} + isaacsim-version: ${{ needs.config.outputs.isaacsim_image_tag }} filter-pattern: "isaaclab_assets" container-name: isaac-lab-assets-test - test-isaaclab-newton: name: isaaclab_newton runs-on: [self-hosted, gpu] timeout-minutes: 180 - needs: [build, detect-changes] - if: >- - always() && needs.build.result == 'success' && ( - needs.detect-changes.outputs.isaaclab-newton == 'true' || - needs.detect-changes.outputs.isaaclab-core == 'true' || - needs.detect-changes.outputs.infra == 'true' - ) + needs: [build, config] + if: needs.build.result == 'success' steps: - uses: actions/checkout@v6 with: @@ -623,24 +495,18 @@ jobs: lfs: true - uses: ./.github/actions/run-package-tests with: - image-tag: ${{ env.DOCKER_IMAGE_TAG }} - isaacsim-base-image: ${{ env.ISAACSIM_BASE_IMAGE }} - isaacsim-version: ${{ env.ISAACSIM_BASE_VERSION }} + image-tag: ${{ env.CI_IMAGE_TAG }} + isaacsim-base-image: ${{ needs.config.outputs.isaacsim_image_name }} + isaacsim-version: ${{ needs.config.outputs.isaacsim_image_tag }} filter-pattern: "isaaclab_newton" container-name: isaac-lab-newton-test - test-isaaclab-physx: name: isaaclab_physx runs-on: [self-hosted, gpu] timeout-minutes: 180 - needs: [build, detect-changes] - if: >- - always() && needs.build.result == 'success' && ( - needs.detect-changes.outputs.isaaclab-physx == 'true' || - needs.detect-changes.outputs.isaaclab-core == 'true' || - needs.detect-changes.outputs.infra == 'true' - ) + needs: [build, config] + if: needs.build.result == 'success' steps: - uses: actions/checkout@v6 with: @@ -648,24 +514,18 @@ jobs: lfs: true - uses: ./.github/actions/run-package-tests with: - image-tag: ${{ env.DOCKER_IMAGE_TAG }} - isaacsim-base-image: ${{ env.ISAACSIM_BASE_IMAGE }} - isaacsim-version: ${{ env.ISAACSIM_BASE_VERSION }} + image-tag: ${{ env.CI_IMAGE_TAG }} + isaacsim-base-image: ${{ needs.config.outputs.isaacsim_image_name }} + isaacsim-version: ${{ needs.config.outputs.isaacsim_image_tag }} filter-pattern: "isaaclab_physx" container-name: isaac-lab-physx-test - test-isaaclab-ov: name: isaaclab_ov runs-on: [self-hosted, gpu] timeout-minutes: 180 - needs: [build, detect-changes] - if: >- - always() && needs.build.result == 'success' && ( - needs.detect-changes.outputs.isaaclab-ov == 'true' || - needs.detect-changes.outputs.isaaclab-core == 'true' || - needs.detect-changes.outputs.infra == 'true' - ) + needs: [build, config] + if: needs.build.result == 'success' steps: - uses: actions/checkout@v6 with: @@ -673,25 +533,19 @@ jobs: lfs: true - uses: ./.github/actions/run-package-tests with: - image-tag: ${{ env.DOCKER_IMAGE_TAG }} - isaacsim-base-image: ${{ env.ISAACSIM_BASE_IMAGE }} - isaacsim-version: ${{ env.ISAACSIM_BASE_VERSION }} + image-tag: ${{ env.CI_IMAGE_TAG }} + isaacsim-base-image: ${{ needs.config.outputs.isaacsim_image_name }} + isaacsim-version: ${{ needs.config.outputs.isaacsim_image_tag }} filter-pattern: "isaaclab_ov" container-name: isaac-lab-ov-test - test-curobo: name: test-curobo runs-on: [self-hosted, gpu] timeout-minutes: 120 continue-on-error: true - needs: [build-curobo, detect-changes] - if: >- - always() && needs.build-curobo.result == 'success' && ( - needs.detect-changes.outputs.isaaclab-mimic == 'true' || - needs.detect-changes.outputs.isaaclab-core == 'true' || - needs.detect-changes.outputs.infra == 'true' - ) + needs: [build-curobo, config] + if: needs.build-curobo.result == 'success' steps: - uses: actions/checkout@v6 with: @@ -699,28 +553,21 @@ jobs: lfs: true - uses: ./.github/actions/run-package-tests with: - image-tag: ${{ env.DOCKER_IMAGE_TAG }}-curobo - isaacsim-base-image: ${{ env.ISAACSIM_BASE_IMAGE }} - isaacsim-version: ${{ env.ISAACSIM_BASE_VERSION }} + image-tag: ${{ env.CI_IMAGE_TAG }}-curobo + isaacsim-base-image: ${{ needs.config.outputs.isaacsim_image_name }} + isaacsim-version: ${{ needs.config.outputs.isaacsim_image_tag }} dockerfile-path: docker/Dockerfile.curobo cache-tag: cache-curobo include-files: "test_curobo_planner_franka.py,test_curobo_planner_cube_stack.py,test_pink_ik.py" container-name: isaac-lab-curobo-test - test-skillgen: name: test-skillgen runs-on: [self-hosted, gpu] timeout-minutes: 120 continue-on-error: true - needs: [build-curobo, detect-changes] - if: >- - always() && needs.build-curobo.result == 'success' && ( - needs.detect-changes.outputs.isaaclab-mimic == 'true' || - needs.detect-changes.outputs.isaaclab-tasks == 'true' || - needs.detect-changes.outputs.isaaclab-core == 'true' || - needs.detect-changes.outputs.infra == 'true' - ) + needs: [build-curobo, config] + if: needs.build-curobo.result == 'success' steps: - uses: actions/checkout@v6 with: @@ -728,49 +575,21 @@ jobs: lfs: true - uses: ./.github/actions/run-package-tests with: - image-tag: ${{ env.DOCKER_IMAGE_TAG }}-curobo - isaacsim-base-image: ${{ env.ISAACSIM_BASE_IMAGE }} - isaacsim-version: ${{ env.ISAACSIM_BASE_VERSION }} + image-tag: ${{ env.CI_IMAGE_TAG }}-curobo + isaacsim-base-image: ${{ needs.config.outputs.isaacsim_image_name }} + isaacsim-version: ${{ needs.config.outputs.isaacsim_image_tag }} dockerfile-path: docker/Dockerfile.curobo cache-tag: cache-curobo include-files: "test_generate_dataset_skillgen.py,test_environments_skillgen.py,test_environments_automate.py" container-name: isaac-lab-skillgen-test - - # test-quarantined: - # name: "Quarantined Tests" - # runs-on: [self-hosted, gpu] - # timeout-minutes: 180 - # continue-on-error: true - # needs: [build, detect-changes] - # if: >- - # always() && needs.build.result == 'success' && - # vars.RUN_QUARANTINED_TESTS == 'true' - # steps: - # - uses: actions/checkout@v6 - # with: - # fetch-depth: 1 - # lfs: true - # - uses: ./.github/actions/run-package-tests - # with: - # image-tag: ${{ env.DOCKER_IMAGE_TAG }} - # isaacsim-base-image: ${{ env.ISAACSIM_BASE_IMAGE }} - # isaacsim-version: ${{ env.ISAACSIM_BASE_VERSION }} - # quarantined-only: "true" - # container-name: isaac-lab-quarantined-test - test-environments-training: name: "environments_training" runs-on: [self-hosted, gpu] timeout-minutes: 300 continue-on-error: true - needs: [build, detect-changes] - if: >- - always() && needs.build.result == 'success' && ( - needs.detect-changes.outputs.isaaclab-tasks == 'true' || - needs.detect-changes.outputs.isaaclab-core == 'true' || - needs.detect-changes.outputs.infra == 'true' - ) + needs: [build, config] + if: needs.build.result == 'success' steps: - uses: actions/checkout@v6 with: @@ -778,9 +597,34 @@ jobs: lfs: true - uses: ./.github/actions/run-package-tests with: - image-tag: ${{ env.DOCKER_IMAGE_TAG }} - isaacsim-base-image: ${{ env.ISAACSIM_BASE_IMAGE }} - isaacsim-version: ${{ env.ISAACSIM_BASE_VERSION }} + image-tag: ${{ env.CI_IMAGE_TAG }} + isaacsim-base-image: ${{ needs.config.outputs.isaacsim_image_name }} + isaacsim-version: ${{ needs.config.outputs.isaacsim_image_tag }} filter-pattern: "isaaclab_tasks" include-files: "test_environments_training.py" container-name: isaac-lab-environments-training-test + #endregion + +#region disabled quarantined tests +# test-quarantined: +# name: "Quarantined Tests" +# runs-on: [self-hosted, gpu] +# timeout-minutes: 180 +# continue-on-error: true +# needs: [build, config] +# if: >- +# needs.build.result == 'success' && +# vars.RUN_QUARANTINED_TESTS == 'true' +# steps: +# - uses: actions/checkout@v6 +# with: +# fetch-depth: 1 +# lfs: true +# - uses: ./.github/actions/run-package-tests +# with: +# image-tag: ${{ env.CI_IMAGE_TAG }} +# isaacsim-base-image: ${{ needs.config.outputs.isaacsim_image_name }} +# isaacsim-version: ${{ needs.config.outputs.isaacsim_image_tag }} +# quarantined-only: "true" +# container-name: isaac-lab-quarantined-test +#endregion diff --git a/.github/workflows/changelog-check.yml b/.github/workflows/changelog-check.yml new file mode 100644 index 000000000000..945d6139f43b --- /dev/null +++ b/.github/workflows/changelog-check.yml @@ -0,0 +1,48 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +name: Changelog Fragment Check + +on: + pull_request: + types: [opened, synchronize, reopened] + workflow_dispatch: + inputs: + base_ref: + description: 'Base branch to diff against' + required: true + default: 'develop' + +concurrency: + group: changelog-check-${{ github.ref }} + cancel-in-progress: true + +permissions: + contents: read + +jobs: + check-fragments: + name: Check changelog fragments + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 + with: + # Full history needed to diff against the base branch + fetch-depth: 0 + + - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5 + with: + python-version: "3.12" + + - name: Resolve base ref + id: base + run: echo "ref=${{ github.event.inputs.base_ref || github.base_ref }}" >> "$GITHUB_OUTPUT" + + - name: Fetch base branch + run: git fetch origin ${{ steps.base.outputs.ref }} + + - name: Verify changelog fragments + run: python3 tools/changelog/cli.py check ${{ steps.base.outputs.ref }} diff --git a/.github/workflows/check-links.yml b/.github/workflows/check-links.yml index 2251222a569b..edec5899aa3e 100644 --- a/.github/workflows/check-links.yml +++ b/.github/workflows/check-links.yml @@ -100,6 +100,10 @@ jobs: --exclude 'huggingface\.co/nvidia/COMPASS' --exclude 'huggingface\.co/nvidia/X-Mobility' --exclude 'openusd\.org' + --exclude 'ubuntu\.com/server/docs' + --exclude 'docs\.ray\.io' + --exclude 'docs\.conda\.io' + --exclude 'stackoverflow\.com' --max-retries 5 --retry-wait-time 10 --timeout 20 diff --git a/.github/workflows/config.yaml b/.github/workflows/config.yaml new file mode 100644 index 000000000000..aa3c1888b240 --- /dev/null +++ b/.github/workflows/config.yaml @@ -0,0 +1,10 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +# Shared image config for CI workflows. Loaded by the `config` job in each +# workflow via yq and exposed as job outputs (see e.g. .github/workflows/build.yaml). +isaacsim_image_name: nvcr.io/nvidian/isaac-sim +isaacsim_image_tag: latest-develop +isaaclab_image_name: nvcr.io/nvidian/isaac-lab diff --git a/.github/workflows/daily-compatibility.yml b/.github/workflows/daily-compatibility.yml index 8e9dcba23a81..2e307bd1a4ad 100644 --- a/.github/workflows/daily-compatibility.yml +++ b/.github/workflows/daily-compatibility.yml @@ -29,9 +29,29 @@ permissions: env: NGC_API_KEY: ${{ secrets.NGC_API_KEY }} - ISAACSIM_BASE_IMAGE: ${{ vars.ISAACSIM_BASE_IMAGE || 'nvcr.io/nvidia/isaac-sim' }} jobs: + config: + name: Load Config + runs-on: ubuntu-latest + outputs: + isaacsim_image_name: ${{ steps.load.outputs.isaacsim_image_name }} + isaacsim_image_tag: ${{ steps.load.outputs.isaacsim_image_tag }} + isaaclab_image_name: ${{ steps.load.outputs.isaaclab_image_name }} + steps: + - uses: actions/checkout@v6 + with: + fetch-depth: 1 + sparse-checkout: .github/workflows/config.yaml + sparse-checkout-cone-mode: false + - id: load + run: | + set -euo pipefail + f=.github/workflows/config.yaml + echo "isaacsim_image_name=$(yq -r .isaacsim_image_name "$f")" >> "$GITHUB_OUTPUT" + echo "isaacsim_image_tag=$(yq -r .isaacsim_image_tag "$f")" >> "$GITHUB_OUTPUT" + echo "isaaclab_image_name=$(yq -r .isaaclab_image_name "$f")" >> "$GITHUB_OUTPUT" + setup-versions: runs-on: ubuntu-latest outputs: @@ -52,7 +72,7 @@ jobs: fi test-isaaclab-tasks-compat: - needs: setup-versions + needs: [setup-versions, config] runs-on: [self-hosted, gpu] timeout-minutes: 180 continue-on-error: true @@ -79,7 +99,7 @@ jobs: uses: ./.github/actions/docker-build with: image-tag: ${{ env.DOCKER_IMAGE_TAG }} - isaacsim-base-image: ${{ env.ISAACSIM_BASE_IMAGE }} + isaacsim-base-image: ${{ needs.config.outputs.isaacsim_image_name }} isaacsim-version: ${{ matrix.isaacsim_version }} - name: Run IsaacLab Tasks Tests @@ -110,7 +130,7 @@ jobs: compression-level: 9 test-general-compat: - needs: setup-versions + needs: [setup-versions, config] runs-on: [self-hosted, gpu] timeout-minutes: 180 strategy: @@ -136,7 +156,7 @@ jobs: uses: ./.github/actions/docker-build with: image-tag: ${{ env.DOCKER_IMAGE_TAG }} - isaacsim-base-image: ${{ env.ISAACSIM_BASE_IMAGE }} + isaacsim-base-image: ${{ needs.config.outputs.isaacsim_image_name }} isaacsim-version: ${{ matrix.isaacsim_version }} - name: Run General Tests diff --git a/.github/workflows/docs.yaml b/.github/workflows/docs.yaml index 2469a838eea5..593956e0bcb1 100644 --- a/.github/workflows/docs.yaml +++ b/.github/workflows/docs.yaml @@ -28,9 +28,13 @@ jobs: outputs: trigger-deploy: ${{ steps.trigger-deploy.outputs.defined }} steps: + - id: info + run: echo "repo=github.repository=${{ github.repository }}, ref=github.ref=${{ github.ref }}" - id: trigger-deploy env: REPO_NAME: ${{ secrets.REPO_NAME }} + # develop, main, release/ trigger multi-version build, then deployment to gh-pages + # all others - just the current docs without deployment if: "${{ github.repository == env.REPO_NAME && (github.ref == 'refs/heads/main' || github.ref == 'refs/heads/develop' || startsWith(github.ref, 'refs/heads/release/')) }}" run: echo "defined=true" >> "$GITHUB_OUTPUT"; echo "Docs will be built multi-version and deployed" @@ -89,12 +93,12 @@ jobs: - name: Generate multi-version docs working-directory: ./docs env: - # When triggered from develop, build only the develop branch, no tags or main. - # Branches main and release/* will build main + release/* + tags. - # This way each main branch does not overwrite develop content, - # provided keep_files is true for gh-pages action. - SMV_BRANCH_WHITELIST: ${{ github.ref == 'refs/heads/develop' && '^develop$' || '^(main|release/.*)$' }} - SMV_TAG_WHITELIST: ${{ github.ref == 'refs/heads/develop' && '^$' || '^v[1-9]\d*\.\d+\.\d+$' }} + # "deploy" branches build the full set of versions so every page + # has a complete version dropdown: main, develop, tags >= v2.0.0 + # (including pre-release suffixes like -beta or -rc1). v1.x tags and + # release/ branches are excluded. + SMV_BRANCH_WHITELIST: '^(main|develop)$' + SMV_TAG_WHITELIST: '^v[2-9]\d*\.\d+\.\d+(-[A-Za-z0-9.]+)?$' run: | git fetch --prune --unshallow --tags git checkout --detach HEAD @@ -126,4 +130,4 @@ jobs: with: github_token: ${{ secrets.GITHUB_TOKEN }} publish_dir: ./docs/_build - keep_files: true + keep_files: false diff --git a/.github/workflows/install-ci.yml b/.github/workflows/install-ci.yml new file mode 100644 index 000000000000..c66e1bf4fce5 --- /dev/null +++ b/.github/workflows/install-ci.yml @@ -0,0 +1,157 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +name: Installation Tests +on: + pull_request: + types: [opened, synchronize, reopened] + push: + branches: + - main + - develop + - release/** + workflow_dispatch: + inputs: + base_image: + description: 'Docker base image for the test container' + required: false + default: 'ubuntu:24.04' + type: string + test_filter: + description: 'pytest -k filter expression (e.g. "uv" or "bugs")' + default: '' + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +permissions: + contents: read + pull-requests: read +jobs: + changes: + name: Detect Installation Test Changes + runs-on: ubuntu-latest + outputs: + run_install_tests: ${{ steps.detect.outputs.run_install_tests }} + steps: + - id: detect + env: + GH_TOKEN: ${{ github.token }} + PR_NUMBER: ${{ github.event.pull_request.number }} + EVENT_NAME: ${{ github.event_name }} + REPO: ${{ github.repository }} + run: | + set -euo pipefail + + # Installation tests run only when paths in the patterns table change. + # Otherwise the test job skips via `if:` and reports green to branch + # protection, which is why we don't use a workflow-level `paths:` + # filter (a not-triggered required check would block the PR forever). + patterns=( + $'^apps/\tStandalone apps' + $'^tools/\tBuild tooling' + $'^source/\tLibrary source code' + $'^\\.github/actions/run-package-tests/\tTest action' + $'^\\.github/workflows/install-ci\\.yml$\tThis workflow file' + $'^VERSION$\tVersion file' + $'(^|/)pyproject\\.toml$\tPython project metadata' + $'(^|/)environment\\.ya?ml$\tConda environment file' + ) + triggered_jobs="Installation Tests" + + render_table() { + local files="$1" entry regex desc count sample + echo "| Pattern | What it covers | Matched files |" + echo "|---|---|---|" + for entry in "${patterns[@]}"; do + IFS=$'\t' read -r regex desc <<< "$entry" + count=$(printf '%s\n' "$files" | grep -cE "$regex" || true) + if [ "$count" -gt 0 ]; then + sample=$(printf '%s\n' "$files" | grep -E "$regex" | head -3 | paste -sd ', ' -) + [ "$count" -gt 3 ] && sample="$sample (and $((count - 3)) more)" + echo "| \`$regex\` | $desc | $sample |" + else + echo "| \`$regex\` | $desc | - |" + fi + done + } + + any_match() { + local files="$1" entry regex + for entry in "${patterns[@]}"; do + IFS=$'\t' read -r regex _ <<< "$entry" + if printf '%s\n' "$files" | grep -qE "$regex"; then + return 0 + fi + done + return 1 + } + + decide() { + local decision="$1" reason="$2" files="${3:-}" + echo "Decision: run_install_tests=$decision ($reason)" + echo "run_install_tests=$decision" >> "$GITHUB_OUTPUT" + { + echo "## Installation test gating" + echo "" + if [ "$decision" = "true" ]; then + echo "Installation tests will **run**: $reason." + else + echo "Installation tests will be **skipped**: $reason." + fi + echo "" + echo "Triggered jobs: $triggered_jobs." + if [ -n "$files" ]; then + echo "" + render_table "$files" + fi + } >> "$GITHUB_STEP_SUMMARY" + } + + if [ "$EVENT_NAME" != "pull_request" ]; then + decide true "non-PR event ($EVENT_NAME)" + exit 0 + fi + + if ! changed_files="$(gh api --paginate "repos/$REPO/pulls/$PR_NUMBER/files" --jq '.[].filename')"; then + # Fail-safe: a transient API error must not block merge. Default to running. + echo "::warning::Could not list changed files; defaulting to running tests" + decide true "fail-safe (could not list changed files)" + exit 0 + fi + + printf '%s\n' "$changed_files" + + if any_match "$changed_files"; then + decide true "relevant paths changed" "$changed_files" + else + decide false "no relevant paths changed" "$changed_files" + fi + + install-tests: + name: Installation Tests + needs: [changes] + if: needs.changes.outputs.run_install_tests == 'true' + runs-on: [self-hosted, gpu] + timeout-minutes: 90 + steps: + - name: Checkout + uses: actions/checkout@v6 # v6 + - name: Run installation tests + env: + BASE_IMAGE: ${{ github.event_name == 'workflow_dispatch' && inputs.base_image || 'ubuntu:24.04' }} + TEST_FILTER: ${{ github.event_name == 'workflow_dispatch' && inputs.test_filter || '' }} + run: | + RUNNER_ARGS="--base-image $BASE_IMAGE" + RUNNER_ARGS="$RUNNER_ARGS --results-dir ${{ github.workspace }}/results" + RUNNER_ARGS="$RUNNER_ARGS --gpu" + + PYTEST_EXTRA_ARGS=(-sv) + if [ -n "$TEST_FILTER" ]; then + PYTEST_EXTRA_ARGS+=(-k "$TEST_FILTER") + fi + + tools/run_install_ci.py docker $RUNNER_ARGS -- --tb=short "${PYTEST_EXTRA_ARGS[@]}" diff --git a/.github/workflows/license-check.yaml b/.github/workflows/license-check.yaml index 4a27eb9b1493..0b296f9e74eb 100644 --- a/.github/workflows/license-check.yaml +++ b/.github/workflows/license-check.yaml @@ -52,7 +52,7 @@ jobs: - name: Set up Python uses: actions/setup-python@v5 with: - python-version: '3.11' # Adjust as needed + python-version: '3.12' - name: Install dependencies using ./isaaclab.sh -i env: @@ -63,7 +63,7 @@ jobs: run: | # first install isaac sim pip install --upgrade pip - pip install 'isaacsim[all,extscache]==${{ vars.ISAACSIM_BASE_VERSION || '5.1.0' }}' --extra-index-url https://pypi.nvidia.com + pip install 'isaacsim[all,extscache]==${{ vars.ISAACSIM_BASE_VERSION || '6.0.0' }}' --extra-index-url https://pypi.nvidia.com chmod +x ./isaaclab.sh # Make sure the script is executable # install all lab dependencies ./isaaclab.sh -i diff --git a/.github/workflows/license-exceptions.json b/.github/workflows/license-exceptions.json index b63def1fc252..8ac605547dcf 100644 --- a/.github/workflows/license-exceptions.json +++ b/.github/workflows/license-exceptions.json @@ -23,6 +23,10 @@ "package": "isaaclab_tasks", "license": null }, + { + "package": "isaaclab_tasks_experimental", + "license": null + }, { "package": "isaaclab_teleop", "license": null @@ -187,6 +191,11 @@ "package": "omniverse-kit", "license": null }, + { + "package": "osqp", + "license": "UNKNOWN", + "comment": "Apache 2.0" + }, { "package": "warp-lang", "license": null @@ -321,7 +330,7 @@ }, { "package": "usd-core", - "license": "Other/Proprietary License", + "license": "LicenseRef-TOST-1.0", "comment": "TOST / OSRB" }, { @@ -421,7 +430,7 @@ }, { "package": "aiohappyeyeballs", - "license": "Other/Proprietary License; Python Software Foundation License", + "license": "Python Software Foundation License", "comment": "PSFL / OSRB" }, { @@ -461,7 +470,7 @@ }, { "package": "typing_extensions", - "license": "Python Software Foundation License", + "license": "PSF-2.0", "comment": "PSF-2.0 / OSRB" }, { @@ -483,5 +492,10 @@ "package": "omniverseclient", "license": "NVIDIA Proprietary Software, https://www.nvidia.com/en-us/agreements/enterprise-software/nvidia-software-license-agreement/", "comment": "NVIDIA" + }, + { + "package": "ovphysx", + "license": "LicenseRef-NVIDIA-Omniverse", + "comment": "NVIDIA" } ] diff --git a/.github/workflows/nightly-changelog.yml b/.github/workflows/nightly-changelog.yml new file mode 100644 index 000000000000..7e55ad7450c6 --- /dev/null +++ b/.github/workflows/nightly-changelog.yml @@ -0,0 +1,119 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +# Nightly auto-compile: rolls accumulated fragments under +# ``source//changelog.d/`` into per-package ``CHANGELOG.rst`` entries, +# bumps each ``extension.toml``, deletes consumed fragments, and pushes the +# result back to ``develop``. Keeps the develop branch's changelog current +# without requiring a maintainer to run ``compile`` by hand. +# +# The push uses ``CHANGELOG_PAT`` (a personal access token / fine-grained +# GitHub App token with ``contents:write`` on this repo) when it's +# available so downstream CI runs on the auto-commit. Falls back to +# ``GITHUB_TOKEN`` — sufficient for the push itself, but pushes signed +# with ``GITHUB_TOKEN`` do not trigger workflow runs on the resulting +# commit, which is by design (avoids infinite loops) but means the +# Docker / docs rebuild won't re-trigger off the nightly's auto-commit. + +name: Nightly Changelog Compilation + +on: + schedule: + # Run nightly at 5 AM UTC (one hour after daily-compatibility, so we + # don't compete for runner capacity). + - cron: '0 5 * * *' + workflow_dispatch: + inputs: + dry_run: + description: 'Preview only — do not commit / push' + required: false + type: boolean + default: false + +concurrency: + # Only one nightly compile may be in flight at a time. ``cancel-in-progress`` + # is intentionally false: if a previous run is still finishing its push, we + # queue rather than abort it mid-commit. + group: nightly-changelog + cancel-in-progress: false + +permissions: + contents: write + +jobs: + compile-changelog: + name: Compile changelog fragments + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 + with: + # Operate on develop, not the repo's default branch. Scheduled + # workflows fire from the default branch's workflow file by + # default, but we want the *checkout* to be develop so the + # compile sees develop's accumulated fragments and the push + # writes back to develop. + ref: develop + # Use a PAT so the auto-commit triggers downstream CI; falls back + # to GITHUB_TOKEN which is sufficient for the push itself. + token: ${{ secrets.CHANGELOG_PAT || secrets.GITHUB_TOKEN }} + # Full history so the compiler can resolve each fragment's merge + # time via ``git log --diff-filter=A --first-parent``. + fetch-depth: 0 + + - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5 + with: + python-version: "3.12" + + - name: Compile fragments + run: | + ARGS="--all" + if [ "${{ inputs.dry_run }}" = "true" ]; then + ARGS="$ARGS --dry-run" + fi + echo "Running: python3 tools/changelog/cli.py compile $ARGS" + python3 tools/changelog/cli.py compile $ARGS + + - name: Commit and push if fragments were compiled + if: inputs.dry_run != 'true' + run: | + git config user.name "github-actions[bot]" + git config user.email "41898282+github-actions[bot]@users.noreply.github.com" + git add source/*/changelog.d/ \ + source/*/docs/CHANGELOG.rst \ + source/*/config/extension.toml + if git diff --staged --quiet; then + echo "No changelog fragments found — nothing to commit." + else + # Convention for CI-driven auto-commits on this repo: + # [CI][] + # The leading ``[CI]`` tag groups every machine-driven commit + # (so future automations — auto image rebuilds, auto publish, + # etc. — all share the prefix and are easy to find/filter in + # ``git log --grep``). The second tag names the specific + # action. The trigger event suffix (``schedule`` vs + # ``workflow_dispatch``) is preserved for traceability. + # + # The body lists every package that bumped, derived from the + # staged ``extension.toml`` diff so the entries are accurate + # regardless of which packages happen to have pending + # fragments this run. + MSG_FILE=$(mktemp) + { + echo "[CI][Auto Version Bump] Compile changelog fragments (${{ github.event_name }})" + echo + echo "Bumped packages:" + for tom in $(git diff --staged --name-only -- 'source/*/config/extension.toml'); do + pkg=$(echo "$tom" | sed -E 's|source/([^/]+)/config/extension.toml|\1|') + old=$(git diff --staged "$tom" | awk -F'"' '/^-version/{print $2; exit}') + new=$(git diff --staged "$tom" | awk -F'"' '/^\+version/{print $2; exit}') + echo "- $pkg: $old → $new" + done + } > "$MSG_FILE" + git commit -F "$MSG_FILE" + # Push explicitly to develop so we don't accidentally write + # to the source ref of a workflow_dispatch run. + git push origin HEAD:develop + fi diff --git a/.github/workflows/postmerge-ci.yml b/.github/workflows/postmerge-ci.yml deleted file mode 100644 index ef3ea68a545b..000000000000 --- a/.github/workflows/postmerge-ci.yml +++ /dev/null @@ -1,178 +0,0 @@ -# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). -# All rights reserved. -# -# SPDX-License-Identifier: BSD-3-Clause - -name: Post-Merge CI - -on: - push: - branches: - - main - - develop - - release/** - - feature/isaacsim-6-0 - -# Concurrency control to prevent parallel runs -concurrency: - group: postmerge-ci-${{ github.ref }} - cancel-in-progress: true - -permissions: - contents: read - -env: - NGC_API_KEY: ${{ secrets.NGC_API_KEY }} - # On merge to main defaults will point to "nvcr.io/nvidia/isaac-sim:6.0.0" - ISAACSIM_BASE_IMAGE: 'nvcr.io/nvidian/isaac-sim' # ${{ vars.ISAACSIM_BASE_IMAGE || 'nvcr.io/nvidia/isaac-sim' }} - ISAACSIM_BASE_VERSIONS_STRING: 'latest-release-6-0' # ${{ vars.ISAACSIM_BASE_VERSIONS_STRING || '6.0.0' }} - ISAACLAB_IMAGE_NAME: ${{ vars.ISAACLAB_IMAGE_NAME || 'isaac-lab-base' }} - -jobs: - build-and-push-images: - runs-on: [self-hosted, gpu] - timeout-minutes: 180 - environment: - name: postmerge-production - url: https://github.com/${{ github.repository }} - env: - DOCKER_HOST: unix:///var/run/docker.sock - DOCKER_TLS_CERTDIR: "" - - steps: - - name: Checkout Code - uses: actions/checkout@v6 - with: - fetch-depth: 1 - lfs: true - - - name: Set up QEMU - uses: docker/setup-qemu-action@v3 - with: - platforms: linux/arm64 - - - name: Set up Docker Buildx - uses: docker/setup-buildx-action@v3 - with: - platforms: linux/amd64,linux/arm64 - driver-opts: | - image=moby/buildkit:buildx-stable-1 - - - name: Login to NGC - run: | - # Only attempt NGC login if API key is available - if [ -n "${{ env.NGC_API_KEY }}" ]; then - echo "Logging into NGC registry..." - docker login -u \$oauthtoken -p ${{ env.NGC_API_KEY }} nvcr.io - echo "✅ Successfully logged into NGC registry" - else - echo "⚠️ NGC_API_KEY not available - skipping NGC login" - echo "This is normal when secrets are not configured" - fi - - - name: Build and Push Docker Images - run: | - # Determine branch name - BRANCH_NAME="${{ github.ref_name }}" - - # Replace '/' with '-' and remove any invalid characters for Docker tag - SAFE_BRANCH_NAME=$(echo $BRANCH_NAME | sed 's/[^a-zA-Z0-9._-]/-/g') - - # Use "latest" if branch name is empty or only contains invalid characters - if [ -z "$SAFE_BRANCH_NAME" ]; then - SAFE_BRANCH_NAME="latest" - fi - - # Get the git repository short name - REPO_SHORT_NAME="${{ github.event.repository.name }}" - if [ -z "$REPO_SHORT_NAME" ]; then - REPO_SHORT_NAME="verification" - fi - - echo "Building images for branch: $BRANCH_NAME" - echo "Safe branch name: $SAFE_BRANCH_NAME" - echo "Repository name: $REPO_SHORT_NAME" - echo "IsaacSim versions: ${{ env.ISAACSIM_BASE_VERSIONS_STRING }}" - - # Parse the env variable string into an array - IMAGE_BASE_VERSIONS_STRING="${{ env.ISAACSIM_BASE_VERSIONS_STRING }}" - # Use set to split the string into positional parameters, then convert to array - set -- $IMAGE_BASE_VERSIONS_STRING - IMAGE_BASE_VERSIONS=("$@") - - for IMAGE_BASE_VERSION in "${IMAGE_BASE_VERSIONS[@]}"; do - IMAGE_BASE_VERSION=$(echo "$IMAGE_BASE_VERSION" | tr -d '[:space:]') - - # Skip empty versions - if [ -z "$IMAGE_BASE_VERSION" ]; then - continue - fi - - # Combine repo short name and branch name for the tag - COMBINED_TAG="${REPO_SHORT_NAME}-${SAFE_BRANCH_NAME}-${IMAGE_BASE_VERSION}" - BUILD_TAG="${COMBINED_TAG}-b${{ github.run_number }}" - COMMIT_TAG="${COMBINED_TAG}-${{ github.sha }}" - SHORT_COMMIT_TAG="${COMBINED_TAG}-${GITHUB_SHA::7}" - - # Determine if multiarch is supported by inspecting the base image manifest - echo "Checking if base image supports multiarch..." - BASE_IMAGE_FULL="${{ env.ISAACSIM_BASE_IMAGE }}:${IMAGE_BASE_VERSION}" - - # Get architectures from the base image manifest - ARCHITECTURES=$(docker manifest inspect "$BASE_IMAGE_FULL" 2>/dev/null | grep -o '"architecture": "[^"]*"' | cut -d'"' -f4 | sort -u) - - if [ -z "$ARCHITECTURES" ]; then - echo "Could not inspect base image manifest: $BASE_IMAGE_FULL" - echo "Defaulting to AMD64 only for safety" - BUILD_PLATFORMS="linux/amd64" - else - echo "Base image architectures found:" - echo "$ARCHITECTURES" | sed 's/^/ - /' - - # Check if both amd64 and arm64 are present - HAS_AMD64=$(echo "$ARCHITECTURES" | grep -c "amd64" || true) - HAS_ARM64=$(echo "$ARCHITECTURES" | grep -c "arm64" || true) - - if [ "$HAS_AMD64" -gt 0 ] && [ "$HAS_ARM64" -gt 0 ]; then - echo "Base image supports multiarch (amd64 + arm64)" - BUILD_PLATFORMS="linux/amd64,linux/arm64" - elif [ "$HAS_AMD64" -gt 0 ]; then - echo "Base image only supports amd64" - BUILD_PLATFORMS="linux/amd64" - elif [ "$HAS_ARM64" -gt 0 ]; then - echo "Base image only supports arm64" - BUILD_PLATFORMS="linux/arm64" - else - echo "Unknown architecture support, defaulting to amd64" - BUILD_PLATFORMS="linux/amd64" - fi - fi - - echo "Building image: ${{ env.ISAACLAB_IMAGE_NAME }}:$COMBINED_TAG" - echo "IsaacSim version: $IMAGE_BASE_VERSION" - echo "Base image: $BASE_IMAGE_FULL" - echo "Target platforms: $BUILD_PLATFORMS" - - # Build Docker image once with all tags for multiple architectures - docker buildx build \ - --platform $BUILD_PLATFORMS \ - --progress=plain \ - -t ${{ env.ISAACLAB_IMAGE_NAME }}:$COMBINED_TAG \ - -t ${{ env.ISAACLAB_IMAGE_NAME }}:$BUILD_TAG \ - -t ${{ env.ISAACLAB_IMAGE_NAME }}:$COMMIT_TAG \ - -t ${{ env.ISAACLAB_IMAGE_NAME }}:$SHORT_COMMIT_TAG \ - --build-arg ISAACSIM_BASE_IMAGE_ARG=${{ env.ISAACSIM_BASE_IMAGE }} \ - --build-arg ISAACSIM_VERSION_ARG=$IMAGE_BASE_VERSION \ - --build-arg ISAACSIM_ROOT_PATH_ARG=/isaac-sim \ - --build-arg ISAACLAB_PATH_ARG=/workspace/isaaclab \ - --build-arg DOCKER_USER_HOME_ARG=/root \ - --cache-from type=gha \ - --cache-to type=gha,mode=max \ - -f docker/Dockerfile.base \ - --push . - - echo "✅ Successfully built and pushed: ${{ env.ISAACLAB_IMAGE_NAME }}:$COMBINED_TAG (platforms: $BUILD_PLATFORMS)" - echo "✅ Successfully built and pushed: ${{ env.ISAACLAB_IMAGE_NAME }}:$BUILD_TAG (platforms: $BUILD_PLATFORMS)" - echo "✅ Successfully built and pushed: ${{ env.ISAACLAB_IMAGE_NAME }}:$COMMIT_TAG (platforms: $BUILD_PLATFORMS)" - echo "✅ Successfully built and pushed: ${{ env.ISAACLAB_IMAGE_NAME }}:$SHORT_COMMIT_TAG (platforms: $BUILD_PLATFORMS)" - done diff --git a/.github/workflows/pre-commit.yaml b/.github/workflows/pre-commit.yaml index aa3a38daffff..ef7e5a820512 100644 --- a/.github/workflows/pre-commit.yaml +++ b/.github/workflows/pre-commit.yaml @@ -9,6 +9,10 @@ on: pull_request: types: [opened, synchronize, reopened] +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + jobs: pre-commit: runs-on: ubuntu-latest diff --git a/.github/workflows/publish-images.yaml b/.github/workflows/publish-images.yaml new file mode 100644 index 000000000000..d986142ac8b3 --- /dev/null +++ b/.github/workflows/publish-images.yaml @@ -0,0 +1,203 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +name: Publish Docker Images + +on: + push: + branches: + - main + - develop + - release/** + +# Concurrency control to prevent parallel runs +concurrency: + group: publish-images-${{ github.ref }} + cancel-in-progress: true + +permissions: + contents: read + +env: + NGC_API_KEY: ${{ secrets.NGC_API_KEY }} + +jobs: + config: + name: Load Config + runs-on: ubuntu-latest + outputs: + isaacsim_image_name: ${{ steps.load.outputs.isaacsim_image_name }} + isaacsim_image_tag: ${{ steps.load.outputs.isaacsim_image_tag }} + isaaclab_image_name: ${{ steps.load.outputs.isaaclab_image_name }} + steps: + - uses: actions/checkout@v6 + with: + fetch-depth: 1 + sparse-checkout: .github/workflows/config.yaml + sparse-checkout-cone-mode: false + - id: load + run: | + set -euo pipefail + f=.github/workflows/config.yaml + echo "isaacsim_image_name=$(yq -r .isaacsim_image_name "$f")" >> "$GITHUB_OUTPUT" + echo "isaacsim_image_tag=$(yq -r .isaacsim_image_tag "$f")" >> "$GITHUB_OUTPUT" + echo "isaaclab_image_name=$(yq -r .isaaclab_image_name "$f")" >> "$GITHUB_OUTPUT" + + build-and-push-images: + needs: [config] + runs-on: [self-hosted, gpu] + timeout-minutes: 180 + environment: + name: postmerge-production + url: https://github.com/${{ github.repository }} + env: + DOCKER_HOST: unix:///var/run/docker.sock + DOCKER_TLS_CERTDIR: "" + + steps: + - name: Checkout Code + uses: actions/checkout@v6 + with: + fetch-depth: 1 + lfs: true + + - name: Set up QEMU + uses: docker/setup-qemu-action@v3 + with: + platforms: linux/arm64 + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + with: + platforms: linux/amd64,linux/arm64 + driver-opts: | + image=moby/buildkit:buildx-stable-1 + + - name: Login to NGC + run: | + # Only attempt NGC login if API key is available + if [ -n "${{ env.NGC_API_KEY }}" ]; then + echo "🔵 Logging into NGC registry..." + if ! docker login -u \$oauthtoken -p ${{ env.NGC_API_KEY }} nvcr.io; then + echo "🔴 Failed to log into NGC registry" + exit 1 + fi + echo "🟢 Successfully logged into NGC registry" + else + echo "🟠 NGC_API_KEY not set - skipping NGC login (normal when secrets are not configured)" + fi + + - name: Build and Push Docker Images + run: | + BRANCH_NAME="${{ github.ref_name }}" + IMAGE_BASE_VERSION="${{ needs.config.outputs.isaacsim_image_tag }}" + SHA="${{ github.sha }}" + IMAGE="${{ needs.config.outputs.isaaclab_image_name }}" + + echo "Branch: $BRANCH_NAME" + echo "Commit: $SHA" + echo "IsaacSim base image: ${{ needs.config.outputs.isaacsim_image_name }}:$IMAGE_BASE_VERSION" + echo "Target Isaac Lab image: $IMAGE" + + # Build the list of tags based on the branch. + # + # Tagging scheme: + # - Push to develop: $IMAGE:latest-develop (moves to newest develop build) + # $IMAGE:latest-develop-- (immutable per-build) + # - Push to release/X: $IMAGE:latest-release-X (moves to newest build on that release branch) + # $IMAGE:latest-release-X-- (immutable per-build) + # - Push to main: $IMAGE:latest (moves to newest main build) + # $IMAGE:v (from the VERSION file, e.g. v3.0.0) + TAGS=() + + case "$BRANCH_NAME" in + develop) + TAGS+=("$IMAGE:latest-develop") + TAGS+=("$IMAGE:latest-develop-${{ github.run_number }}-${SHA:0:8}") + ;; + main) + TAGS+=("$IMAGE:latest") + VERSION="$(tr -d '[:space:]' < VERSION)" + if [ -n "$VERSION" ]; then + TAGS+=("$IMAGE:v$VERSION") + else + echo "🛑 ERROR: VERSION file is empty or missing. Cannot tag build with version tag." + exit 1 + fi + ;; + release/*) + # Sanitize the part after release/ for use as a Docker tag suffix. + RELEASE_SUFFIX=$(echo "${BRANCH_NAME#release/}" | sed 's/[^a-zA-Z0-9._-]/-/g') + TAGS+=("$IMAGE:latest-release-$RELEASE_SUFFIX") + TAGS+=("$IMAGE:latest-release-$RELEASE_SUFFIX-${{ github.run_number }}-${SHA:0:8}") + ;; + *) + echo "Branch '$BRANCH_NAME' is not configured for publishing; skipping." + exit 0 + ;; + esac + + # Determine if multiarch is supported by inspecting the base image manifest + echo "🔵 Checking if base image supports multiarch..." + BASE_IMAGE_FULL="${{ needs.config.outputs.isaacsim_image_name }}:${IMAGE_BASE_VERSION}" + ARCHITECTURES=$(docker manifest inspect "$BASE_IMAGE_FULL" 2>/dev/null | grep -o '"architecture": "[^"]*"' | cut -d'"' -f4 | sort -u) + + if [ -z "$ARCHITECTURES" ]; then + echo "🟠 Could not inspect base image manifest: $BASE_IMAGE_FULL - defaulting to linux/amd64 only" + BUILD_PLATFORMS="linux/amd64" + else + echo "Base image architectures found:" + echo "$ARCHITECTURES" | sed 's/^/ - /' + + HAS_AMD64=$(echo "$ARCHITECTURES" | grep -c "amd64" || true) + HAS_ARM64=$(echo "$ARCHITECTURES" | grep -c "arm64" || true) + + if [ "$HAS_AMD64" -gt 0 ] && [ "$HAS_ARM64" -gt 0 ]; then + echo "🟢 Base image supports multiarch (amd64 + arm64)" + BUILD_PLATFORMS="linux/amd64,linux/arm64" + elif [ "$HAS_AMD64" -gt 0 ]; then + echo "Base image only supports amd64" + BUILD_PLATFORMS="linux/amd64" + elif [ "$HAS_ARM64" -gt 0 ]; then + echo "Base image only supports arm64" + BUILD_PLATFORMS="linux/arm64" + else + echo "🟠 Unknown architecture support for $BASE_IMAGE_FULL - defaulting to linux/amd64" + BUILD_PLATFORMS="linux/amd64" + fi + fi + + echo "Target platforms: $BUILD_PLATFORMS" + echo "Tags to publish:" + printf ' - %s\n' "${TAGS[@]}" + + # Compose -t flags for buildx + TAG_ARGS=() + for t in "${TAGS[@]}"; do + TAG_ARGS+=("-t" "$t") + done + + echo "🔵 Building and pushing image with tags listed above..." + if ! docker buildx build \ + --platform "$BUILD_PLATFORMS" \ + --progress=plain \ + "${TAG_ARGS[@]}" \ + --build-arg ISAACSIM_BASE_IMAGE_ARG=${{ needs.config.outputs.isaacsim_image_name }} \ + --build-arg ISAACSIM_VERSION_ARG="$IMAGE_BASE_VERSION" \ + --build-arg ISAACSIM_ROOT_PATH_ARG=/isaac-sim \ + --build-arg ISAACLAB_PATH_ARG=/workspace/isaaclab \ + --build-arg DOCKER_USER_HOME_ARG=/root \ + --cache-from type=gha \ + --cache-to type=gha,mode=max \ + -f docker/Dockerfile.base \ + --push .; then + echo "🔴 docker buildx build/push failed for tags:" + printf ' - %s\n' "${TAGS[@]}" + exit 1 + fi + + for t in "${TAGS[@]}"; do + echo "🟢 Successfully built and pushed: $t (platforms: $BUILD_PLATFORMS)" + done diff --git a/.github/workflows/test-multi-gpu.yaml b/.github/workflows/test-multi-gpu.yaml new file mode 100644 index 000000000000..e9bee1c4ed2d --- /dev/null +++ b/.github/workflows/test-multi-gpu.yaml @@ -0,0 +1,153 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +# Multi-GPU distributed training validation +# +# This workflow validates that multi-GPU training works correctly across: +# - Physics backends: PhysX, Newton +# - Rendering backends: none (physics-only), Isaac RTX, Newton Warp +# +# Runs on a dedicated multi-GPU runner (separate from standard CI) to minimize costs. +# Only triggered on PRs that touch distributed training code paths. + +name: Multi-GPU Training Tests + +on: + pull_request: + paths: + - "source/isaaclab/isaaclab/app/app_launcher.py" + - "source/isaaclab_tasks/isaaclab_tasks/utils/sim_launcher.py" + - "scripts/reinforcement_learning/**/train.py" + - ".github/workflows/test-multi-gpu.yaml" + workflow_dispatch: + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + test-multi-gpu: + name: Multi-GPU (${{ matrix.physics }}, ${{ matrix.renderer }}) + # Use dedicated multi-GPU runner to avoid blocking standard CI resources + # Configure this label on a runner with 2+ GPUs (e.g., g5.12xlarge with 4x A10G) + runs-on: [self-hosted, linux, x64, gpu, multi-gpu] + timeout-minutes: 30 + strategy: + fail-fast: false + matrix: + include: + # PhysX physics-only + - physics: physx + renderer: none + task: Isaac-Cartpole-Direct-v0 + extra_args: "" + + # PhysX + Isaac RTX renderer + - physics: physx + renderer: isaac-rtx + task: Isaac-Cartpole-Camera-Presets-Direct-v0 + extra_args: "" + trainer: skrl + + # PhysX + Newton Warp renderer (hybrid) + - physics: physx + renderer: newton-warp + task: Isaac-Cartpole-Camera-Presets-Direct-v0 + extra_args: "env.tiled_camera.renderer_cfg=newton_renderer" + trainer: skrl + + # Newton physics-only + - physics: newton + renderer: none + task: Isaac-Cartpole-Direct-v0 + extra_args: "+sim=newton" + + # Newton + Newton Warp renderer + - physics: newton + renderer: newton-warp + task: Isaac-Cartpole-Camera-Presets-Direct-v0 + extra_args: "+sim=newton env.tiled_camera.renderer_cfg=newton_renderer" + trainer: skrl + + # Newton + Isaac RTX renderer (hybrid) + - physics: newton + renderer: isaac-rtx + task: Isaac-Cartpole-Camera-Presets-Direct-v0 + extra_args: "+sim=newton" + trainer: skrl + + steps: + - name: Checkout repository + uses: actions/checkout@v4 + + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: "3.10" + + - name: Install Isaac Lab + run: | + ./isaaclab.sh --install + + - name: Verify multi-GPU availability + run: | + echo "=== GPU Info ===" + nvidia-smi --query-gpu=index,name,memory.total --format=csv + + GPU_COUNT=$(python -c "import torch; print(torch.cuda.device_count())") + echo "Detected $GPU_COUNT GPU(s)" + + if [ "$GPU_COUNT" -lt 2 ]; then + echo "::error::At least 2 GPUs required for multi-GPU tests, found $GPU_COUNT" + exit 1 + fi + + - name: Run multi-GPU training (${{ matrix.physics }}, ${{ matrix.renderer }}) + env: + NCCL_DEBUG: WARN + run: | + TRAINER="${{ matrix.trainer || 'rsl_rl' }}" + + echo "==========================================" + echo "Physics: ${{ matrix.physics }}" + echo "Renderer: ${{ matrix.renderer }}" + echo "Task: ${{ matrix.task }}" + echo "Trainer: $TRAINER" + echo "Extra args: ${{ matrix.extra_args }}" + echo "==========================================" + + # Run 2-GPU distributed training for 3 iterations + ./isaaclab.sh -p -m torch.distributed.run --nproc_per_node=2 \ + scripts/reinforcement_learning/${TRAINER}/train.py \ + --task=${{ matrix.task }} \ + --headless \ + --distributed \ + --max_iterations=3 \ + --num_envs=16 \ + ${{ matrix.extra_args }} + + - name: Verify training completed + run: | + # Find the most recent log directory + LATEST_LOG=$(ls -td logs/*/*/*/ 2>/dev/null | head -1) + + if [ -z "$LATEST_LOG" ]; then + echo "::error::No training log directory found" + exit 1 + fi + + echo "Log directory: $LATEST_LOG" + ls -la "$LATEST_LOG" + + # Check for model checkpoints + MODELS=$(find "$LATEST_LOG" -name "*.pt" | wc -l) + echo "Model checkpoints found: $MODELS" + + if [ "$MODELS" -lt 1 ]; then + echo "::error::No model checkpoints found - training may have failed" + exit 1 + fi + + echo "✅ Multi-GPU training completed successfully (${{ matrix.physics }}, ${{ matrix.renderer }})" diff --git a/.github/workflows/wheel.yml b/.github/workflows/wheel.yml new file mode 100644 index 000000000000..0cad2933e949 --- /dev/null +++ b/.github/workflows/wheel.yml @@ -0,0 +1,73 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +name: Build PIP Wheel + +on: + pull_request: + types: [opened, synchronize, reopened] + paths: + - 'apps/**' + - 'VERSION' + - 'source/**' + - 'tools/wheel_builder/**' + - '.github/workflows/wheel.yml' + push: + branches: + - main + - develop + - 'release/**' + +concurrency: + group: ${{ github.workflow }}-${{ github.event_name }}-${{ github.ref }} + cancel-in-progress: true + +permissions: + contents: read + +jobs: + build-wheel: + name: Build Wheel + runs-on: ubuntu-latest + timeout-minutes: 5 + + steps: + - name: Checkout code + uses: actions/checkout@v6 + with: + fetch-depth: 1 + lfs: true + + - name: Setup Python + uses: actions/setup-python@v5 + with: + python-version: "3.12" + architecture: x64 + + # Compose Docker-image-style metadata for the artifact. The artifact + # name is what QA sees in `gh run download`, so we make it scannable: + # isaaclab--build-. The wheel inside follows + # PEP 440 (VERSION+buildN.SHA7) since pip requires that format. + - name: Compute wheel metadata + id: meta + run: | + set -euo pipefail + version=$(cat VERSION) + sha_slug="${GITHUB_SHA:0:7}" + echo "artifact_name=isaaclab-${version}-build${{ github.run_number }}-${sha_slug}" >> "$GITHUB_OUTPUT" + + - name: Build wheel + env: + WHEEL_BUILD_NUMBER: ${{ github.run_number }} + WHEEL_SHA: ${{ github.sha }} + run: bash tools/wheel_builder/build.sh + + - name: Upload wheel artifact + uses: actions/upload-artifact@v7 + with: + name: ${{ steps.meta.outputs.artifact_name }} + path: tools/wheel_builder/build/dist/isaaclab-*.whl + if-no-files-found: error + retention-days: 30 diff --git a/.gitignore b/.gitignore index 21d82c9e7349..60989ad5dd1b 100644 --- a/.gitignore +++ b/.gitignore @@ -65,7 +65,7 @@ _build /datasets/ # Tests -tests/ +/tests/ # Docker history .isaac-lab-docker-history @@ -79,3 +79,12 @@ tests/ # Ruff cache **/.ruff_cache/ + +# Dev-time files, generated stuff +**/__* + +# Isaac Lab CI environments in native mode +**/_isaaclab_install_ci_* + +# Superpowers (Claude Code plugin artifacts) +docs/superpowers/ diff --git a/AGENTS.md b/AGENTS.md index 70c1d15158ab..f331c3c10988 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -64,7 +64,7 @@ We use a wrapped python call within `./isaaclab.sh`. ### Pre-commit (lint/format hooks) -**CRITICAL: Always run pre-commit hooks BEFORE committing, not after.** +**CRITICAL: Always run pre-commit hooks BEFORE committing and BEFORE pushing.** Proper workflow: 1. Make your code changes @@ -73,37 +73,43 @@ Proper workflow: 4. Stage the modified files with `git add` 5. Run `./isaaclab.sh -f` again to ensure all checks pass 6. Only then create your commit with `git commit` +7. Verify pre-commit still passes before pushing — never push commits that haven't been checked ```bash # Run pre-commit checks on all files ./isaaclab.sh -f ``` -**Common mistake to avoid:** +**Common mistakes to avoid:** - Don't commit first and then run pre-commit (requires amending commits) -- Do run pre-commit before committing (clean workflow) +- Don't push before running pre-commit (pushes broken code to the remote) +- Do run pre-commit before committing and before pushing (clean workflow) **When reviewing code** (e.g. via a code-reviewer agent), always run `./isaaclab.sh -f` as part of the review to catch formatting or lint issues early. ## Changelog -- **Update `CHANGELOG.rst` for every change** targeting the source directory. Each extension has its own changelog at `source//docs/CHANGELOG.rst` (e.g. `source/isaaclab/docs/CHANGELOG.rst`, `source/isaaclab_physx/docs/CHANGELOG.rst`). -- **Always create a new version heading.** Never add entries to an existing version — they are released and immutable. Bump the patch version (e.g. `1.5.0` → `1.5.1`) and use today's date. -- **Bump `config/extension.toml` to match.** When creating a new changelog version, update the `version` field in `source//config/extension.toml` to the same version string. -- **Determine which changelog(s) to update** by looking at which `source//` directories your changes touch. A single PR may require entries in multiple changelogs. +- **Do not edit `CHANGELOG.rst` or `config/extension.toml` directly.** Each PR adds a fragment file under `source//changelog.d/`; the changelog and version are compiled by the nightly CI workflow. +- **Add one fragment per touched package.** Pick any short, unique slug for the filename — your branch name (with `/` replaced by `-`) is a good default. The filename suffix declares the bump tier; within a batch the highest tier wins for the package. + + | Filename | Effect | + |---|---| + | `source//changelog.d/.rst` | patch bump | + | `source//changelog.d/.minor.rst` | minor bump | + | `source//changelog.d/.major.rst` | major bump | + | `source//changelog.d/.skip` | no entry, no bump (CI / docs / test-only) | + - Use **past tense** matching the section header: "Added X", "Fixed Y", "Changed Z". - Place entries under the correct category: `Added`, `Changed`, `Deprecated`, `Removed`, or `Fixed`. - Avoid internal implementation details users wouldn't understand. - **For `Deprecated`, `Changed`, and `Removed` entries, include migration guidance.** - Example: "Deprecated `Articulation.A` in favor of `Articulation.B`." +- **Breaking changes** belong in `Changed`, prefixed with `**Breaking:**`. - Use Sphinx cross-reference roles for class/method/module names. ### RST formatting reference ``` -X.Y.Z (YYYY-MM-DD) -~~~~~~~~~~~~~~~~~~ - Added ^^^^^ @@ -117,10 +123,10 @@ Fixed ``` Key formatting rules: -- Version heading: underline with `~` (tildes), must be at least as long as the heading text. -- Category heading: underline with `^` (carets). +- Category heading: underline with `^` (carets), at least as long as the heading text. - Entries: `* ` prefix, continuation lines indented by 2 spaces. -- Blank line between the last entry and the next version heading. + +See `tools/changelog/test/integration/` for worked examples that double as integration-test fixtures. ## Commit and Pull Request Guidelines @@ -152,6 +158,7 @@ Follow conventional commit message practices. ## Sandbox & Networking - Network access (e.g., `git push`) is blocked by the sandbox. Use `dangerouslyDisableSandbox: true` so the user gets an approval prompt — don't ask them to run it manually. +- **Never push to `origin` (`isaac-sim/IsaacLab`).** The `origin` remote is the public upstream repository. Push to your own fork remote (e.g., `antoine`, `alex`) or to the remote of the PR you are working on. If the correct remote is unclear, ask the user before pushing. ## GitHub Actions and CI/CD diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 318e1106c688..82c5eb49ba92 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -34,6 +34,8 @@ Guidelines for modifications: * Kelly (Yunrong) Guo * Matthew Trepte * Mayank Mittal +* Mike Yan Michelis +* Mikhail Yurasov * Nikita Rudin * Octi (Zhengyu) Zhang * Ossama Ahmed @@ -55,8 +57,10 @@ Guidelines for modifications: * Ashwin Varghese Kuruttukulam * Bikram Pandit * Bingjie Tang +* Bocheng Zou * Brayden Zhang * Brian Bingham +* Brian Dilinila * Brian McCann * Caelan Garrett * Calvin Yu @@ -69,13 +73,16 @@ Guidelines for modifications: * David Leon * David Yang * Dhananjay Shendre +* Dhyan Thakkar * Dongxuan Fan * Dorsa Rohani +* Ege Sekkin * Emily Sturman * Emmanuel Ferdman * Fabian Jenelten * Felipe Mohr * Felix Yu +* Frank Lai * Gary Lvov * Giulio Romualdi * Grzegorz Malczyk @@ -122,7 +129,6 @@ Guidelines for modifications: * Michael Noseworthy * Miguel Alonso Jr * Mihir Kulkarni -* Mikhail Yurasov * Mingxue Gu * Mingyu Lee * Muhong Guo @@ -147,6 +153,7 @@ Guidelines for modifications: * Rafael Wiltz * Renaud Poncelet * René Zurbrügg +* Richard Schmitt * RinZ27 * Ritvik Singh * Rosario Scalise diff --git a/README.md b/README.md index a2f2cfd766ac..7c9b9f751e23 100644 --- a/README.md +++ b/README.md @@ -18,6 +18,11 @@ This branch is a development branch for Isaac Sim 6.0, which is currently only a For installation, please refer to the Isaac Sim GitHub repo to build the latest Isaac Sim branch, and follow the binary installation method in the Isaac Lab documentation for Isaac Lab installation. +> [!WARNING] +> A recent breaking change on the Isaac Lab `develop` branch is not compatible with the `develop` branch of Isaac Sim on GitHub. +> To run Isaac Lab with Isaac Sim's GitHub `develop` branch, use Isaac Lab commit [`f0234a82e432e2a0b0f0a26ca3c5b59e527ddaaa`](https://github.com/isaac-sim/IsaacLab/commit/f0234a82e432e2a0b0f0a26ca3c5b59e527ddaaa) or an earlier commit. +> Alternatively, use the Isaac Lab [`v3.0.0-beta`](https://github.com/isaac-sim/IsaacLab/tree/v3.0.0-beta) tag. + Note that this branch is currently under active development and may experience breaking changes or error messages. Performance issues and regressions may also be observed in some use cases. diff --git a/apps/isaaclab.python.headless.kit b/apps/isaaclab.python.headless.kit index 1d28f7b9018c..e4a8b0a7dde0 100644 --- a/apps/isaaclab.python.headless.kit +++ b/apps/isaaclab.python.headless.kit @@ -26,7 +26,6 @@ log.outputStreamLevel = "Warn" "omni.physx" = {} "omni.physx.tensors" = {} "omni.physx.fabric" = {} -"omni.warp.core" = {} "usdrt.scenegraph" = {} "omni.kit.telemetry" = {} "omni.kit.loop" = {} @@ -107,7 +106,7 @@ isaac.startup.ros_bridge_extension = "" metricsAssembler.changeListenerEnabled = false # explicitly disable omni.kit.pip_archive to prevent conflicting dependencies -app.extensions.excluded = ["omni.kit.pip_archive"] +app.extensions.excluded = ["omni.kit.pip_archive", "omni.isaac.ml_archive", "isaacsim.pip.newton", "omni.warp.core"] # Extensions ############################### @@ -174,11 +173,9 @@ folders = [ "${exe-path}/exts", # kit extensions "${exe-path}/extscore", # kit core extensions "${exe-path}/../exts", # isaac extensions - "${exe-path}/../extsDeprecated", # deprecated isaac extensions "${exe-path}/../extscache", # isaac cache extensions "${exe-path}/../extsPhysics", # isaac physics extensions "${exe-path}/../isaacsim/exts", # isaac extensions for pip - "${exe-path}/../isaacsim/extsDeprecated", # deprecated isaac extensions "${exe-path}/../isaacsim/extscache", # isaac cache extensions for pip "${exe-path}/../isaacsim/extsPhysics", # isaac physics extensions for pip "${app}", # needed to find other app files @@ -193,9 +190,7 @@ enabled=true # Enable this for DLSS ######################## [dependencies] "isaacsim.simulation_app" = {} -"isaacsim.core.api" = {} -"isaacsim.core.cloner" = {} -"isaacsim.core.utils" = {} +"isaacsim.core.simulation_manager" = {} "isaacsim.core.version" = {} ######################## diff --git a/apps/isaaclab.python.headless.rendering.kit b/apps/isaaclab.python.headless.rendering.kit index 12229aca0eca..4c387ddb3425 100644 --- a/apps/isaaclab.python.headless.rendering.kit +++ b/apps/isaaclab.python.headless.rendering.kit @@ -17,11 +17,14 @@ keywords = ["experience", "app", "isaaclab", "python", "camera", "minimal"] [dependencies] # Isaac Lab minimal app "isaaclab.python.headless" = {} +"isaacsim.core.rendering_manager" = {} "omni.replicator.core" = {} # Rendering "omni.kit.material.library" = {} "omni.kit.viewport.rtx" = {} +"omni.kit.hydra_texture" = {} # required for headless rendering and rtx instantiation + [settings.isaaclab] # This is used to check that this experience file is loaded when using cameras @@ -107,7 +110,7 @@ exts."omni.replicator.core".Orchestrator.enabled = false metricsAssembler.changeListenerEnabled = false # explicitly disable omni.kit.pip_archive to prevent conflicting dependencies -app.extensions.excluded = ["omni.kit.pip_archive"] +app.extensions.excluded = ["omni.kit.pip_archive", "omni.isaac.ml_archive", "isaacsim.pip.newton", "omni.warp.core"] [settings.app.python] # These disable the kit app from also printing out python output, which gets confusing @@ -140,11 +143,9 @@ folders = [ "${exe-path}/exts", # kit extensions "${exe-path}/extscore", # kit core extensions "${exe-path}/../exts", # isaac extensions - "${exe-path}/../extsDeprecated", # deprecated isaac extensions "${exe-path}/../extscache", # isaac cache extensions "${exe-path}/../extsPhysics", # isaac physics extensions "${exe-path}/../isaacsim/exts", # isaac extensions for pip - "${exe-path}/../isaacsim/extsDeprecated", # deprecated isaac extensions "${exe-path}/../isaacsim/extscache", # isaac cache extensions for pip "${exe-path}/../isaacsim/extsPhysics", # isaac physics extensions for pip "${app}", # needed to find other app files diff --git a/apps/isaaclab.python.kit b/apps/isaaclab.python.kit index cc54d43a4da3..dad8a1e72808 100644 --- a/apps/isaaclab.python.kit +++ b/apps/isaaclab.python.kit @@ -14,23 +14,26 @@ keywords = ["experience", "app", "usd"] # Isaac Sim extensions "isaacsim.app.about" = {} "isaacsim.examples.browser" = {} -"isaacsim.core.api" = {} "isaacsim.core.cloner" = {} +"isaacsim.core.deprecation_manager" = { order = -100 } +"isaacsim.core.experimental.materials" = {} +"isaacsim.core.experimental.objects" = {} +"isaacsim.core.experimental.primdata" = {} +"isaacsim.core.experimental.prims" = {} +"isaacsim.core.experimental.utils" = {} "isaacsim.core.nodes" = {} +"isaacsim.core.rendering_manager" = {} +"isaacsim.core.simulation_manager" = {} "isaacsim.core.throttling" = {} -"isaacsim.core.utils" = {} "isaacsim.core.version" = {} -"isaacsim.gui.menu" = {} "isaacsim.gui.property" = {} "isaacsim.replicator.behavior" = {} -"isaacsim.robot.manipulators" = {} "isaacsim.robot.policy.examples" = {} "isaacsim.robot.schema" = {} -"isaacsim.robot.wheeled_robots" = {} -"isaacsim.sensors.camera" = {} -"isaacsim.sensors.physics" = {} -"isaacsim.sensors.physx" = {} -"isaacsim.sensors.rtx" = {} +"isaacsim.robot.experimental.wheeled_robots" = {} +"isaacsim.robot.wheeled_robots.nodes" = {} +"isaacsim.sensors.experimental.physics" = {} +"isaacsim.sensors.experimental.rtx" = {} "isaacsim.simulation_app" = {} "isaacsim.storage.native" = {} "isaacsim.util.debug_draw" = {} @@ -92,7 +95,6 @@ keywords = ["experience", "app", "usd"] "omni.uiaudio" = {} "omni.usd.metrics.assembler.ui" = {} "omni.usd.schema.metrics.assembler" = {} -"omni.warp.core" = {} ######################## # Isaac Lab Extensions # @@ -257,7 +259,7 @@ exts."omni.replicator.core".Orchestrator.enabled = false omni.rtx.nre.compositing.rendererHints = 3 # explicitly disable omni.kit.pip_archive to prevent conflicting dependencies -app.extensions.excluded = ["omni.kit.pip_archive"] +app.extensions.excluded = ["omni.kit.pip_archive", "omni.isaac.ml_archive", "isaacsim.pip.newton", "omni.warp.core"] [settings.app.livestream] outDirectory = "${data}" @@ -274,11 +276,9 @@ folders = [ "${exe-path}/exts", # kit extensions "${exe-path}/extscore", # kit core extensions "${exe-path}/../exts", # isaac extensions - "${exe-path}/../extsDeprecated", # deprecated isaac extensions "${exe-path}/../extscache", # isaac cache extensions "${exe-path}/../extsPhysics", # isaac physics extensions "${exe-path}/../isaacsim/exts", # isaac extensions for pip - "${exe-path}/../isaacsim/extsDeprecated", # deprecated isaac extensions "${exe-path}/../isaacsim/extscache", # isaac cache extensions for pip "${exe-path}/../isaacsim/extsPhysics", # isaac physics extensions for pip "${app}", # needed to find other app files diff --git a/apps/isaaclab.python.rendering.kit b/apps/isaaclab.python.rendering.kit index ad58b159186a..9094bcad4b9f 100644 --- a/apps/isaaclab.python.rendering.kit +++ b/apps/isaaclab.python.rendering.kit @@ -93,7 +93,7 @@ exts."omni.replicator.core".Orchestrator.enabled = false metricsAssembler.changeListenerEnabled = false # explicitly disable omni.kit.pip_archive to prevent conflicting dependencies -app.extensions.excluded = ["omni.kit.pip_archive"] +app.extensions.excluded = ["omni.kit.pip_archive", "omni.isaac.ml_archive", "isaacsim.pip.newton", "omni.warp.core"] [settings.physics] updateToUsd = false @@ -126,11 +126,9 @@ folders = [ "${exe-path}/exts", # kit extensions "${exe-path}/extscore", # kit core extensions "${exe-path}/../exts", # isaac extensions - "${exe-path}/../extsDeprecated", # deprecated isaac extensions "${exe-path}/../extscache", # isaac cache extensions "${exe-path}/../extsPhysics", # isaac physics extensions "${exe-path}/../isaacsim/exts", # isaac extensions for pip - "${exe-path}/../isaacsim/extsDeprecated", # deprecated isaac extensions "${exe-path}/../isaacsim/extscache", # isaac cache extensions for pip "${exe-path}/../isaacsim/extsPhysics", # isaac physics extensions for pip "${app}", # needed to find other app files diff --git a/apps/isaaclab.python.xr.openxr.headless.kit b/apps/isaaclab.python.xr.openxr.headless.kit index 6bf1bb7c43d6..b3516dda71f4 100644 --- a/apps/isaaclab.python.xr.openxr.headless.kit +++ b/apps/isaaclab.python.xr.openxr.headless.kit @@ -42,7 +42,7 @@ cameras_enabled = true [settings] # explicitly disable omni.kit.pip_archive to prevent conflicting dependencies -app.extensions.excluded = ["omni.kit.pip_archive"] +app.extensions.excluded = ["omni.kit.pip_archive", "omni.isaac.ml_archive", "isaacsim.pip.newton", "omni.warp.core"] [settings.app.python] # These disable the kit app from also printing out python output, which gets confusing @@ -56,11 +56,9 @@ folders = [ "${exe-path}/extscore", # kit core extensions "${exe-path}/../exts", # isaac extensions "${exe-path}/../extsInternal", # isaac internal extensions - "${exe-path}/../extsDeprecated", # deprecated isaac extensions "${exe-path}/../extscache", # isaac cache extensions "${exe-path}/../extsPhysics", # isaac physics extensions "${exe-path}/../isaacsim/exts", # isaac extensions for pip - "${exe-path}/../isaacsim/extsDeprecated", # deprecated isaac extensions "${exe-path}/../isaacsim/extscache", # isaac cache extensions for pip "${exe-path}/../isaacsim/extsPhysics", # isaac physics extensions for pip "${app}", # needed to find other app files diff --git a/apps/isaaclab.python.xr.openxr.kit b/apps/isaaclab.python.xr.openxr.kit index 3b730f0eab64..7ff3f9861c7a 100644 --- a/apps/isaaclab.python.xr.openxr.kit +++ b/apps/isaaclab.python.xr.openxr.kit @@ -66,7 +66,7 @@ xr.openxr.components."isaacsim.xr.openxr.hand_tracking".enabled = true xr.openxr.components."isaacsim.kit.xr.teleop.bridge".enabled = true # explicitly disable omni.kit.pip_archive to prevent conflicting dependencies -app.extensions.excluded = ["omni.kit.pip_archive"] +app.extensions.excluded = ["omni.kit.pip_archive", "omni.isaac.ml_archive", "isaacsim.pip.newton", "omni.warp.core"] [settings.app.python] # These disable the kit app from also printing out python output, which gets confusing @@ -80,11 +80,9 @@ folders = [ "${exe-path}/extscore", # kit core extensions "${exe-path}/../exts", # isaac extensions "${exe-path}/../extsInternal", # isaac internal extensions - "${exe-path}/../extsDeprecated", # deprecated isaac extensions "${exe-path}/../extscache", # isaac cache extensions "${exe-path}/../extsPhysics", # isaac physics extensions "${exe-path}/../isaacsim/exts", # isaac extensions for pip - "${exe-path}/../isaacsim/extsDeprecated", # deprecated isaac extensions "${exe-path}/../isaacsim/extscache", # isaac cache extensions for pip "${exe-path}/../isaacsim/extsPhysics", # isaac physics extensions for pip "${app}", # needed to find other app files diff --git a/docker/.env.base b/docker/.env.base index 6fdf46e12e90..c2b7bbc14c61 100644 --- a/docker/.env.base +++ b/docker/.env.base @@ -6,8 +6,9 @@ ACCEPT_EULA=Y # NVIDIA Isaac Sim base image ISAACSIM_BASE_IMAGE=nvcr.io/nvidia/isaac-sim -# NVIDIA Isaac Sim version to use (e.g. 6.0.0) -ISAACSIM_VERSION=6.0.0 +# NVIDIA Isaac Sim version to use (e.g. 6.0.0-dev2) +# TODO(AntoineRichard): Revert to stable 6.0.0 tag once it ships on NGC +ISAACSIM_VERSION=6.0.0-dev2 # Derived from the default path in the NVIDIA provided Isaac Sim container DOCKER_ISAACSIM_ROOT_PATH=/isaac-sim # The Isaac Lab path in the container diff --git a/docker/Dockerfile.base b/docker/Dockerfile.base index f13d7918c9a6..c10c036ce0a6 100644 --- a/docker/Dockerfile.base +++ b/docker/Dockerfile.base @@ -46,12 +46,15 @@ RUN apt-get update && \ git \ wget -# Install packages needed to build imgui-bundle on arm64 as no prebuilt pip wheel is provided +# arm64-only build deps: +# - imgui-bundle has no prebuilt arm64 wheel; needs GL/X11 dev headers. +# - swig is required for the nlopt source build (see arm64 nlopt step below). RUN if [ "$(dpkg --print-architecture)" = "arm64" ]; then \ apt-get update && \ apt-get install -y --no-install-recommends \ libgl1-mesa-dev libopengl-dev libglx-dev \ - libx11-dev libxcursor-dev libxi-dev libxinerama-dev libxrandr-dev; \ + libx11-dev libxcursor-dev libxi-dev libxinerama-dev libxrandr-dev \ + swig; \ fi # copy files necessary for installing Isaac Lab and its dependencies @@ -97,6 +100,18 @@ RUN touch /bin/nvidia-smi && \ mkdir -p /var/run/nvidia-persistenced && \ touch /var/run/nvidia-persistenced/socket +# On arm64, pre-install nlopt 2.6.2 (transitively pinned by isaacteleop[retargeters]). +# There is no aarch64 wheel for this version, and pip's isolated build env hides the +# system numpy from nlopt's cmake-based build, so we install it manually with +# --no-build-isolation. setuptools+wheel+numpy must be importable in the host Python +# for that mode (PEP 517 backend lookup). The subsequent isaaclab.sh --install then +# sees nlopt as already satisfied and skips the from-source rebuild that would fail. +RUN --mount=type=cache,target=${DOCKER_USER_HOME}/.cache/pip \ + if [ "$(dpkg --print-architecture)" = "arm64" ]; then \ + ${ISAACLAB_PATH}/isaaclab.sh -p -m pip install setuptools wheel numpy && \ + ${ISAACLAB_PATH}/isaaclab.sh -p -m pip install --no-build-isolation nlopt==2.6.2; \ + fi + # installing Isaac Lab dependencies # use pip caching to avoid reinstalling large packages RUN --mount=type=cache,target=${DOCKER_USER_HOME}/.cache/pip \ diff --git a/docker/Dockerfile.curobo b/docker/Dockerfile.curobo index 36072612f576..8a9f09547077 100644 --- a/docker/Dockerfile.curobo +++ b/docker/Dockerfile.curobo @@ -46,12 +46,15 @@ RUN apt-get update && \ git \ wget -# Install packages needed to build imgui-bundle on arm64 as no prebuilt pip wheel is provided +# arm64-only build deps: +# - imgui-bundle has no prebuilt arm64 wheel; needs GL/X11 dev headers. +# - swig is required for the nlopt source build (see arm64 nlopt step below). RUN if [ "$(dpkg --print-architecture)" = "arm64" ]; then \ apt-get update && \ apt-get install -y --no-install-recommends \ libgl1-mesa-dev libopengl-dev libglx-dev \ - libx11-dev libxcursor-dev libxi-dev libxinerama-dev libxrandr-dev; \ + libx11-dev libxcursor-dev libxi-dev libxinerama-dev libxrandr-dev \ + swig; \ fi # Detect Ubuntu version and install CUDA 12.8 via NVIDIA network repo (cuda-keyring) @@ -145,6 +148,18 @@ RUN rm -rf ${ISAACSIM_ROOT_PATH}/kit/python/lib/python3.12/site-packages/pip* && ${ISAACLAB_PATH}/_isaac_sim/kit/python/bin/python3 get-pip.py && \ rm get-pip.py +# On arm64, pre-install nlopt 2.6.2 (transitively pinned by isaacteleop[retargeters]). +# There is no aarch64 wheel for this version, and pip's isolated build env hides the +# system numpy from nlopt's cmake-based build, so we install it manually with +# --no-build-isolation. setuptools+wheel+numpy must be importable in the host Python +# for that mode (PEP 517 backend lookup). The subsequent isaaclab.sh --install then +# sees nlopt as already satisfied and skips the from-source rebuild that would fail. +RUN --mount=type=cache,target=${DOCKER_USER_HOME}/.cache/pip \ + if [ "$(dpkg --print-architecture)" = "arm64" ]; then \ + ${ISAACLAB_PATH}/isaaclab.sh -p -m pip install setuptools wheel numpy && \ + ${ISAACLAB_PATH}/isaaclab.sh -p -m pip install --no-build-isolation nlopt==2.6.2; \ + fi + # installing Isaac Lab dependencies # use pip caching to avoid reinstalling large packages RUN --mount=type=cache,target=${DOCKER_USER_HOME}/.cache/pip \ diff --git a/docker/Dockerfile.installci b/docker/Dockerfile.installci new file mode 100644 index 000000000000..30da2b55b82a --- /dev/null +++ b/docker/Dockerfile.installci @@ -0,0 +1,67 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +# Minimal container for testing Isaac Lab installation scenarios. +# +# Usage: +# docker build --build-arg BASE_IMAGE=ubuntu:24.04 -t isaaclab-install-ci . +# docker run --rm isaaclab-install-ci -v -k "test_pip" + +ARG BASE_IMAGE=ubuntu:24.04 +FROM ${BASE_IMAGE} + +SHELL ["/bin/bash", "-c"] + +LABEL description="Container for installation CI tests." + +ENV LANG=C.UTF-8 +ENV DEBIAN_FRONTEND=noninteractive +ENV PYTHONDONTWRITEBYTECODE=1 +ENV PYTHONUNBUFFERED=1 + +# Install system dependencies needed for building Py packages +RUN apt-get update && \ + apt-get install -y --no-install-recommends \ + git \ + curl \ + cmake \ + python3 \ + python3-dev \ + python3-pip \ + libglib2.0-0 \ + python3-venv \ + build-essential \ + && rm -rf /var/lib/apt/lists/* + +# Make python3 the default python +RUN ln -sf /usr/bin/python3 /usr/bin/python + +# Install test runner dependencies +RUN pip install --break-system-packages \ + pytest>=8.0 \ + pytest-timeout>=2.0 + +# Install uv +RUN curl -LsSf https://astral.sh/uv/install.sh | sh +ENV PATH="/root/.local/bin:${PATH}" + +# Copy the repo +ARG ISAACLAB_PATH=/workspace/isaaclab +ENV ISAACLAB_PATH=${ISAACLAB_PATH} +COPY . ${ISAACLAB_PATH} + +# Fix line endings in .sh files (Win git may add \r) +# This hack need to be in the main Dockerfiles too +RUN find ${ISAACLAB_PATH} -type f -name "*.sh" -exec sed -i 's/\r$//' {} + +RUN chmod +x ${ISAACLAB_PATH}/isaaclab.sh + +WORKDIR ${ISAACLAB_PATH} + +# isaaclab.x debug mode +ENV DEBUG=1 + +# Run all installation CI tests by default +ENTRYPOINT ["python", "-m", "pytest", "-c", "source/isaaclab/test/install_ci/pytest.ini", "source/isaaclab/test/install_ci"] +CMD ["-v", "--tb=short"] diff --git a/docs/conf.py b/docs/conf.py index fae8e4937088..792ee6eeecbc 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -136,7 +136,8 @@ "python": ("https://docs.python.org/3", None), "numpy": ("https://numpy.org/doc/stable/", None), "trimesh": ("https://trimesh.org/", None), - "torch": ("https://docs.pytorch.org/docs/stable/", None), + # NOTE: pinned to /docs/2.11/ because /docs/stable/objects.inv currently 404s + "torch": ("https://docs.pytorch.org/docs/2.11/", None), "isaacsim": ("https://docs.isaacsim.omniverse.nvidia.com/6.0.0/py/", None), "gymnasium": ("https://gymnasium.farama.org/", None), "warp": ("https://nvidia.github.io/warp/", None), @@ -173,11 +174,11 @@ "pxr.PhysxSchema", "pxr.PhysicsSchemaTools", "omni.replicator", - "isaacsim", - "isaacsim.core.api", "isaacsim.core.cloner", "isaacsim.core.version", - "isaacsim.core.utils", + "isaacsim.core.experimental.prims", + "isaacsim.core.experimental.utils", + "isaacsim.core.rendering_manager", "isaacsim.robot_motion.motion_generation", "isaacsim.gui.components", "isaacsim.asset.importer.urdf", @@ -186,6 +187,7 @@ "omni.timeline", "omni.ui", "gym", + "gymnasium", "skrl", "stable_baselines3", "rsl_rl", @@ -209,6 +211,10 @@ "mpl_toolkits", "isaacteleop", "scipy", + "hydra", + "hydra.core", + "hydra.core.config_store", + "omegaconf", ] # List of zero or more Sphinx-specific warning categories to be squelched (i.e., @@ -300,8 +306,10 @@ smv_remote_whitelist = r"^.*$" # Whitelist pattern for branches (set to None to ignore all branches) smv_branch_whitelist = os.getenv("SMV_BRANCH_WHITELIST", r"^(main|develop|release/.*)$") -# Whitelist pattern for tags (set to None to ignore all tags) -smv_tag_whitelist = os.getenv("SMV_TAG_WHITELIST", r"^v[1-9]\d*\.\d+\.\d+$") +# Whitelist pattern for tags (set to None to ignore all tags). +# Matches vMAJOR.MINOR.PATCH with an optional pre-release suffix like -beta or -rc1, +# so tags like v3.0.0-beta show up in the version selector. +smv_tag_whitelist = os.getenv("SMV_TAG_WHITELIST", r"^v[1-9]\d*\.\d+\.\d+(-[A-Za-z0-9.]+)?$") html_sidebars = { "**": ["navbar-logo.html", "versioning.html", "icon-links.html", "search-field.html", "sbt-sidebar-nav.html"] } diff --git a/docs/index.rst b/docs/index.rst index 820351b314d5..6c8e6ba9ac41 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -52,7 +52,7 @@ For more information about the framework, please refer to the `technical report License -======= +======== The Isaac Lab framework is open-sourced under the BSD-3-Clause license, with certain parts under Apache-2.0 license. Please refer to :ref:`license` for more details. @@ -157,6 +157,7 @@ Table of Contents :titlesonly: source/migration/migrating_to_isaaclab_3-0 + source/migration/migrating_deformables source/migration/migrating_from_isaacgymenvs source/migration/migrating_from_omniisaacgymenvs source/migration/migrating_from_orbit diff --git a/docs/requirements.txt b/docs/requirements.txt index 9ada473005e4..392951b0a8ee 100644 --- a/docs/requirements.txt +++ b/docs/requirements.txt @@ -1,5 +1,5 @@ # for building the docs -sphinx>=7.0 +sphinx>=7.0,<9 sphinx-book-theme>=1.1 myst-parser sphinxcontrib-bibtex==2.5.0 diff --git a/docs/source/_static/demos/deformables.jpg b/docs/source/_static/demos/deformables.jpg index 6645e821d8bf..3bc3cbd799e7 100644 Binary files a/docs/source/_static/demos/deformables.jpg and b/docs/source/_static/demos/deformables.jpg differ diff --git a/docs/source/_static/how-to/howto_profile_nsys_example.png b/docs/source/_static/how-to/howto_profile_nsys_example.png new file mode 100644 index 000000000000..6590f967018c Binary files /dev/null and b/docs/source/_static/how-to/howto_profile_nsys_example.png differ diff --git a/docs/source/_static/mimic/franka_cube_stacking_env.jpg b/docs/source/_static/mimic/franka_cube_stacking_env.jpg new file mode 100644 index 000000000000..f0bb187b5e7f Binary files /dev/null and b/docs/source/_static/mimic/franka_cube_stacking_env.jpg differ diff --git a/docs/source/_static/mimic/franka_datagen.jpg b/docs/source/_static/mimic/franka_datagen.jpg index fa0a0c8203f1..e578f321731f 100644 Binary files a/docs/source/_static/mimic/franka_datagen.jpg and b/docs/source/_static/mimic/franka_datagen.jpg differ diff --git a/docs/source/_static/mimic/mimic_env_architecture.jpg b/docs/source/_static/mimic/mimic_env_architecture.jpg new file mode 100644 index 000000000000..c0fb241de309 Binary files /dev/null and b/docs/source/_static/mimic/mimic_env_architecture.jpg differ diff --git a/docs/source/_static/policy_deployment/04_reach/reach_train.png b/docs/source/_static/policy_deployment/04_reach/reach_train.png new file mode 100644 index 000000000000..850c733729ad Binary files /dev/null and b/docs/source/_static/policy_deployment/04_reach/reach_train.png differ diff --git a/docs/source/api/index.rst b/docs/source/api/index.rst index 46343eb6419a..cea73de6802d 100644 --- a/docs/source/api/index.rst +++ b/docs/source/api/index.rst @@ -129,6 +129,8 @@ The following modules are available in the ``isaaclab_physx`` extension: renderers scene_data_providers sensors + sim.schemas + sim.spawners .. toctree:: :hidden: @@ -139,6 +141,8 @@ The following modules are available in the ``isaaclab_physx`` extension: lab_physx/isaaclab_physx.renderers lab_physx/isaaclab_physx.scene_data_providers lab_physx/isaaclab_physx.sensors + lab_physx/isaaclab_physx.sim.schemas + lab_physx/isaaclab_physx.sim.spawners isaaclab_newton extension ------------------------- diff --git a/docs/source/api/lab/isaaclab.app.rst b/docs/source/api/lab/isaaclab.app.rst index c1440dd631a0..f1b040f1770e 100644 --- a/docs/source/api/lab/isaaclab.app.rst +++ b/docs/source/api/lab/isaaclab.app.rst @@ -77,7 +77,7 @@ The following snippet shows how use the :class:`AppLauncher` in different ways: .. code:: python - import argparser + import argparse from isaaclab.app import AppLauncher diff --git a/docs/source/api/lab/isaaclab.sensors.rst b/docs/source/api/lab/isaaclab.sensors.rst index 52dfd9bba5d1..1beccd5481f1 100644 --- a/docs/source/api/lab/isaaclab.sensors.rst +++ b/docs/source/api/lab/isaaclab.sensors.rst @@ -18,8 +18,6 @@ Camera CameraData CameraCfg - TiledCamera - TiledCameraCfg ContactSensor ContactSensorData ContactSensorCfg @@ -38,6 +36,9 @@ MultiMeshRayCasterCameraCfg Imu ImuCfg + JointWrenchSensor + JointWrenchSensorData + JointWrenchSensorCfg Sensor Base ----------- @@ -68,19 +69,6 @@ USD Camera :show-inheritance: :exclude-members: __init__, class_type, OffsetCfg -Tile-Rendered USD Camera ------------------------- - -.. autoclass:: TiledCamera - :members: - :inherited-members: - :show-inheritance: - -.. autoclass:: TiledCameraCfg - :members: - :inherited-members: - :show-inheritance: - :exclude-members: __init__, class_type Contact Sensor -------------- @@ -204,3 +192,22 @@ Inertia Measurement Unit :inherited-members: :show-inheritance: :exclude-members: __init__, class_type + +Joint Wrench Sensor +------------------- + +.. autoclass:: JointWrenchSensor + :members: + :inherited-members: + :show-inheritance: + +.. autoclass:: JointWrenchSensorData + :members: + :inherited-members: + :exclude-members: __init__ + +.. autoclass:: JointWrenchSensorCfg + :members: + :inherited-members: + :show-inheritance: + :exclude-members: __init__, class_type diff --git a/docs/source/api/lab/isaaclab.sim.schemas.rst b/docs/source/api/lab/isaaclab.sim.schemas.rst index 77ac6512dbce..263e3152e596 100644 --- a/docs/source/api/lab/isaaclab.sim.schemas.rst +++ b/docs/source/api/lab/isaaclab.sim.schemas.rst @@ -13,7 +13,6 @@ MassPropertiesCfg JointDrivePropertiesCfg FixedTendonPropertiesCfg - DeformableBodyPropertiesCfg .. rubric:: Functions @@ -30,8 +29,6 @@ modify_mass_properties modify_joint_drive_properties modify_fixed_tendon_properties - define_deformable_body_properties - modify_deformable_body_properties Articulation Root ----------------- @@ -95,9 +92,11 @@ Fixed Tendon Deformable Body --------------- -.. autoclass:: DeformableBodyPropertiesCfg - :members: - :exclude-members: __init__ +.. note:: + + Deformable body schemas have moved to the PhysX backend extension. See + :class:`isaaclab_physx.sim.schemas.DeformableBodyPropertiesCfg`, + :func:`isaaclab_physx.sim.schemas.define_deformable_body_properties`, and + :func:`isaaclab_physx.sim.schemas.modify_deformable_body_properties`. -.. autofunction:: define_deformable_body_properties -.. autofunction:: modify_deformable_body_properties + For migration details, see :ref:`migrating-deformables`. diff --git a/docs/source/api/lab/isaaclab.sim.spawners.rst b/docs/source/api/lab/isaaclab.sim.spawners.rst index 701efda84e18..a31968edfe07 100644 --- a/docs/source/api/lab/isaaclab.sim.spawners.rst +++ b/docs/source/api/lab/isaaclab.sim.spawners.rst @@ -21,7 +21,6 @@ SpawnerCfg RigidObjectSpawnerCfg - DeformableObjectSpawnerCfg Spawners -------- @@ -35,10 +34,12 @@ Spawners :show-inheritance: :exclude-members: __init__ -.. autoclass:: DeformableObjectSpawnerCfg - :members: - :show-inheritance: - :exclude-members: __init__ +.. note:: + + ``DeformableObjectSpawnerCfg`` has moved to the PhysX backend extension. See + :class:`isaaclab_physx.sim.spawners.DeformableObjectSpawnerCfg`. + + For migration details, see :ref:`migrating-deformables`. Shapes ------ @@ -260,7 +261,6 @@ Materials GlassMdlCfg PhysicsMaterialCfg RigidBodyMaterialCfg - DeformableBodyMaterialCfg Visual Materials ~~~~~~~~~~~~~~~~ @@ -298,11 +298,15 @@ Physical Materials :members: :exclude-members: __init__, func -.. autofunction:: spawn_deformable_body_material +.. note:: -.. autoclass:: DeformableBodyMaterialCfg - :members: - :exclude-members: __init__, func + ``DeformableBodyMaterialCfg``, ``SurfaceDeformableBodyMaterialCfg``, and + ``spawn_deformable_body_material`` have moved to the PhysX backend extension. See + :class:`isaaclab_physx.sim.spawners.materials.DeformableBodyMaterialCfg`, + :class:`isaaclab_physx.sim.spawners.materials.SurfaceDeformableBodyMaterialCfg`, and + :func:`isaaclab_physx.sim.spawners.materials.spawn_deformable_body_material`. + + For migration details, see :ref:`migrating-deformables`. Wrappers -------- diff --git a/docs/source/api/lab/isaaclab.sim.views.rst b/docs/source/api/lab/isaaclab.sim.views.rst index 3a5f9bdecfe9..e06c4e54a246 100644 --- a/docs/source/api/lab/isaaclab.sim.views.rst +++ b/docs/source/api/lab/isaaclab.sim.views.rst @@ -7,11 +7,27 @@ .. autosummary:: - XformPrimView + BaseFrameView + UsdFrameView + FrameView -XForm Prim View +Base Frame View --------------- -.. autoclass:: XformPrimView +.. autoclass:: BaseFrameView + :members: + :show-inheritance: + +USD Frame View +-------------- + +.. autoclass:: UsdFrameView + :members: + :show-inheritance: + +Frame View +---------- + +.. autoclass:: FrameView :members: :show-inheritance: diff --git a/docs/source/api/lab_physx/isaaclab_physx.sim.schemas.rst b/docs/source/api/lab_physx/isaaclab_physx.sim.schemas.rst new file mode 100644 index 000000000000..40fb3addb275 --- /dev/null +++ b/docs/source/api/lab_physx/isaaclab_physx.sim.schemas.rst @@ -0,0 +1,30 @@ +isaaclab_physx.sim.schemas +========================== + +.. automodule:: isaaclab_physx.sim.schemas + + .. rubric:: Classes + + .. autosummary:: + + DeformableBodyPropertiesCfg + + .. rubric:: Functions + + .. autosummary:: + + define_deformable_body_properties + modify_deformable_body_properties + +.. currentmodule:: isaaclab_physx.sim.schemas + +Deformable Body +--------------- + +.. autoclass:: DeformableBodyPropertiesCfg + :members: + :show-inheritance: + :exclude-members: __init__ + +.. autofunction:: define_deformable_body_properties +.. autofunction:: modify_deformable_body_properties diff --git a/docs/source/api/lab_physx/isaaclab_physx.sim.spawners.rst b/docs/source/api/lab_physx/isaaclab_physx.sim.spawners.rst new file mode 100644 index 000000000000..27463a44425d --- /dev/null +++ b/docs/source/api/lab_physx/isaaclab_physx.sim.spawners.rst @@ -0,0 +1,52 @@ +isaaclab_physx.sim.spawners +=========================== + +.. automodule:: isaaclab_physx.sim.spawners + + .. rubric:: Submodules + + .. autosummary:: + + materials + + .. rubric:: Classes + + .. autosummary:: + + DeformableObjectSpawnerCfg + +.. currentmodule:: isaaclab_physx.sim.spawners + +Spawners +-------- + +.. autoclass:: DeformableObjectSpawnerCfg + :members: + :show-inheritance: + :exclude-members: __init__ + +Materials +--------- + +.. automodule:: isaaclab_physx.sim.spawners.materials + + .. rubric:: Classes + + .. autosummary:: + + DeformableBodyMaterialCfg + SurfaceDeformableBodyMaterialCfg + +.. currentmodule:: isaaclab_physx.sim.spawners.materials + +.. autofunction:: spawn_deformable_body_material + +.. autoclass:: DeformableBodyMaterialCfg + :members: + :show-inheritance: + :exclude-members: __init__, func + +.. autoclass:: SurfaceDeformableBodyMaterialCfg + :members: + :show-inheritance: + :exclude-members: __init__, func diff --git a/docs/source/experimental-features/newton-physics-integration/installation.rst b/docs/source/experimental-features/newton-physics-integration/installation.rst index 7ac2fa12bb70..330ade886c3e 100644 --- a/docs/source/experimental-features/newton-physics-integration/installation.rst +++ b/docs/source/experimental-features/newton-physics-integration/installation.rst @@ -75,4 +75,4 @@ To verify that the installation was successful, run the following command from t .. code-block:: bash - ./isaaclab.sh -p scripts/environments/zero_agent.py --task Isaac-Cartpole-Direct-v0 --num_envs 128 --viz newton presets=newton + ./isaaclab.sh -p scripts/environments/zero_agent.py --task Isaac-Cartpole-Direct-v0 --num_envs 128 --viz newton presets=newton_mjwarp diff --git a/docs/source/experimental-features/newton-physics-integration/solver-transitioning.rst b/docs/source/experimental-features/newton-physics-integration/solver-transitioning.rst index db85df0f991f..0c480bfec73d 100644 --- a/docs/source/experimental-features/newton-physics-integration/solver-transitioning.rst +++ b/docs/source/experimental-features/newton-physics-integration/solver-transitioning.rst @@ -2,7 +2,16 @@ Solver Transitioning ==================== Transitioning to the Newton physics engine introduces new physics solvers that handle simulation using different numerical approaches. -While Newton supports several different solvers, our initial focus for Isaac Lab is on using the MuJoCo-Warp solver from Google DeepMind. +While Newton supports several different solvers, our initial focus for Isaac Lab is on using the +MuJoCo-Warp solver from Google DeepMind. Isaac Lab also includes beta support for the Kamino +solver on selected classic tasks. Kamino is selected through a physics preset rather than as a +separate backend; see :ref:`hydra-backend-solver-presets`. + +.. note:: + + Kamino support is experimental and currently depends on assets being structured + in a way that Kamino can consume. Assets that work with MuJoCo-Warp or PhysX + may still require model-structure updates before they work with Kamino. The way the physics scene itself is defined does not change - we continue to use USD as the primary way to set basic parameters of objects and robots in the scene, and for current environments, the exact same USD files used for the PhysX-based Isaac Lab are used. @@ -12,15 +21,18 @@ What does require change is the way that some solver-specific settings are confi Tuning these parameters can have a significant impact on both simulation performance and behaviour. For now, we will show an example of setting these parameters to help provide a feel for these changes. -Note that the :class:`~isaaclab.sim.NewtonCfg` replaces the :class:`~isaaclab.sim.PhysxCfg` and is used to set everything related to the physical simulation parameters except for the ``dt``: +Note that the :class:`~isaaclab_newton.physics.NewtonCfg` replaces +:class:`~isaaclab_physx.physics.PhysxCfg` and is used to set everything related to the physical +simulation parameters except for the ``dt``: .. code-block:: python - from isaaclab.sim._impl.newton_manager_cfg import NewtonCfg - from isaaclab.sim._impl.solvers_cfg import MJWarpSolverCfg + from isaaclab.sim import SimulationCfg + from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg solver_cfg = MJWarpSolverCfg( - nefc_per_env=35, + njmax=35, + nconmax=20, ls_iterations=10, cone="pyramidal", ls_parallel=True, @@ -31,14 +43,17 @@ Note that the :class:`~isaaclab.sim.NewtonCfg` replaces the :class:`~isaaclab.si num_substeps=1, debug_mode=False, ) - sim: SimulationCfg = SimulationCfg(dt=1 / 120, render_interval=decimation, newton_cfg=newton_cfg) + sim: SimulationCfg = SimulationCfg(dt=1 / 120, render_interval=decimation, physics=newton_cfg) Here is a very brief explanation of some of the key parameters above: -* ``nefc_per_env``: This is the size of the buffer constraints we want MuJoCo warp to - pre-allocate for a given environment. A large value will slow down the simulation, - while a too small value may lead to some contacts being missed. +* ``njmax``: This is the number of constraint rows MuJoCo-Warp pre-allocates for a + given environment. A large value will slow down the simulation, while a too small + value may lead to missing constraints. + +* ``nconmax``: This is the maximum number of contact points MuJoCo-Warp pre-allocates + for a given environment. Set it high enough for the expected contact count. * ``ls_iterations``: The number of line searches performed by the MuJoCo Warp solver. Line searches are used to find an optimal step size, and for each solver step, diff --git a/docs/source/features/hydra.rst b/docs/source/features/hydra.rst index 0e3ddc341815..25b5d4b8bdf1 100644 --- a/docs/source/features/hydra.rst +++ b/docs/source/features/hydra.rst @@ -188,8 +188,8 @@ Override Order Overrides are applied in sequence: 1. **Auto-default**: Configs with a ``"default"`` field auto-apply without CLI args -2. **Global presets**: ``presets=newton,inference`` applies to ALL matching configs -3. **Path presets**: ``env.backend=newton`` replaces a specific section +2. **Global presets**: ``presets=newton_mjwarp,inference`` applies to ALL matching configs +3. **Path presets**: ``env.backend=newton_mjwarp`` replaces a specific section 4. **Scalar overrides**: ``env.sim.dt=0.001`` modifies individual fields @@ -207,7 +207,7 @@ override is given: @configclass class PhysicsCfg(PresetCfg): default: PhysxCfg = PhysxCfg() - newton: NewtonCfg = NewtonCfg() + newton_mjwarp: NewtonCfg = NewtonCfg() @configclass class MyEnvCfg: @@ -216,7 +216,7 @@ override is given: .. code-block:: bash # Use Newton physics backend - python train.py --task=Isaac-Reach-Franka-v0 env.physics=newton + python train.py --task=Isaac-Reach-Franka-v0 env.physics=newton_mjwarp The ``default`` field can be set to ``None`` to make an optional feature that is disabled unless explicitly selected: @@ -242,6 +242,74 @@ disabled unless explicitly selected: python train.py --task=Isaac-Reach-Franka-v0 env.scene.camera=large +.. _hydra-backend-solver-presets: + +Backend and Solver Presets +^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Physics backend selection uses the same preset system. A task can define a +``PresetCfg`` whose entries replace the complete physics config: + +.. code-block:: python + + from isaaclab.utils import configclass + from isaaclab_newton.physics import KaminoSolverCfg, MJWarpSolverCfg, NewtonCfg + from isaaclab_physx.physics import PhysxCfg + from isaaclab_tasks.utils import PresetCfg + + @configclass + class CartpolePhysicsCfg(PresetCfg): + default: PhysxCfg = PhysxCfg() + physx: PhysxCfg = PhysxCfg() + newton_mjwarp: NewtonCfg = NewtonCfg( + solver_cfg=MJWarpSolverCfg(njmax=5, nconmax=3), + num_substeps=1, + ) + newton_kamino: NewtonCfg = NewtonCfg( + solver_cfg=KaminoSolverCfg( + integrator="moreau", + use_collision_detector=True, + sparse_jacobian=True, + padmm_max_iterations=100, + ), + num_substeps=1, + debug_mode=False, + use_cuda_graph=True, + ) + +The ``newton_mjwarp`` and ``newton_kamino`` entries both select the Newton physics backend because +both entries are :class:`~isaaclab_newton.physics.NewtonCfg` objects. The difference +is the solver configuration: ``newton_mjwarp`` uses +:class:`~isaaclab_newton.physics.MJWarpSolverCfg`, while ``newton_kamino`` uses +:class:`~isaaclab_newton.physics.KaminoSolverCfg`. + +Kamino is therefore a solver preset, not a separate Isaac Lab backend. The same +Newton assets, sensors, renderers, and visualizers are used after the preset is +resolved. It is a Proximal Alternating Direction Method of Multipliers (P-ADMM) +based solver for constrained rigid multi-body dynamics, and its Isaac Lab support +is currently beta. + +.. note:: + + Kamino support is experimental and currently depends on the asset being + structured in a way that Kamino can consume. Assets that work with the + MuJoCo-Warp or PhysX presets may still require model-structure updates before + they work with ``presets=newton_kamino``. + +.. code-block:: bash + + # Select the Kamino solver preset everywhere it is defined + python train.py --task=Isaac-Cartpole-v0 presets=newton_kamino + + # Select the Kamino solver preset for a specific physics config path + python train.py --task=Isaac-Cartpole-v0 env.sim.physics=newton_kamino + +The ``newton_kamino`` preset is currently defined for ``Isaac-Cartpole-Direct-v0``, +``Isaac-Ant-Direct-v0``, ``Isaac-Cartpole-v0``, and ``Isaac-Ant-v0``. Passing +``presets=newton_kamino`` to a task without a ``newton_kamino`` preset does not enable Kamino; +add and validate a task-specific preset first. + + Inline Presets with preset() ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -254,7 +322,7 @@ For simple values (scalars, lists) that don't warrant a full subclass, use the from isaaclab_tasks.utils.hydra import preset # Scalar preset -- one line, no boilerplate class - self.scene.robot.actuators["legs"].armature = preset(default=0.0, newton=0.01, physx=0.0) + self.scene.robot.actuators["legs"].armature = preset(default=0.0, newton_mjwarp=0.01, physx=0.0) This is equivalent to defining a ``PresetCfg`` subclass with three ``float`` fields, but without the ceremony. The ``default`` keyword is required. @@ -283,8 +351,8 @@ including inside dict-valued fields such as ``actuators``: .. code-block:: bash - # Select newton preset globally -- sets armature to 0.01 - python train.py --task=Isaac-Velocity-Rough-Anymal-C-v0 presets=newton + # Select MJWarp preset globally -- sets armature to 0.01 + python train.py --task=Isaac-Velocity-Rough-Anymal-C-v0 presets=newton_mjwarp Using Presets @@ -295,29 +363,29 @@ Using Presets .. code-block:: bash python train.py --task=Isaac-Velocity-Rough-Anymal-C-v0 \ - env.events=newton + env.events=newton_mjwarp **Global presets** -- apply the same preset name everywhere it exists: .. code-block:: bash - # Apply "newton" preset to all configs that define it + # Apply "newton_mjwarp" preset to all configs that define it python train.py --task=Isaac-Velocity-Rough-Anymal-C-v0 \ - presets=newton + presets=newton_mjwarp **Multiple global presets** -- apply several non-conflicting presets: .. code-block:: bash python train.py --task=Isaac-Velocity-Rough-Anymal-C-v0 \ - presets=newton,inference + presets=newton_mjwarp,inference **Combined** -- global presets + scalar overrides: .. code-block:: bash python train.py --task=Isaac-Velocity-Rough-Anymal-C-v0 \ - presets=newton \ + presets=newton_mjwarp \ env.sim.dt=0.002 @@ -343,8 +411,8 @@ working together: :language: python :lines: 21-42 -A single ``presets=newton`` on the command line resolves every ``PresetCfg`` -and ``preset()`` that defines a ``newton`` field: the physics engine is swapped +A single ``presets=newton_mjwarp`` on the command line resolves every ``PresetCfg`` +and ``preset()`` that defines a ``newton_mjwarp`` field: the physics engine is swapped to Newton, ``AnymalCEventsCfg`` selects Newton-compatible events, and the actuator armature is set to ``0.01``. @@ -353,8 +421,8 @@ actuator armature is set to ``0.01``. # Default (PhysX events, armature=0.0) python train.py --task=Isaac-Velocity-Rough-Anymal-C-v0 - # Newton (Newton events, armature=0.01) - python train.py --task=Isaac-Velocity-Rough-Anymal-C-v0 presets=newton + # MJWarp (Newton events, armature=0.01) + python train.py --task=Isaac-Velocity-Rough-Anymal-C-v0 presets=newton_mjwarp Summary @@ -371,11 +439,11 @@ Summary - ``env.sim.dt=0.001`` - Modify single field * - Path preset - - ``env.events=newton`` + - ``env.events=newton_mjwarp`` - Replace entire section * - Global preset - - ``presets=newton`` + - ``presets=newton_mjwarp`` - Apply everywhere matching * - Combined - - ``presets=newton env.sim.dt=0.001`` + - ``presets=newton_mjwarp env.sim.dt=0.001`` - Global + scalar overrides diff --git a/docs/source/features/isaac_teleop.rst b/docs/source/features/isaac_teleop.rst index 4e881b90236c..733150259586 100644 --- a/docs/source/features/isaac_teleop.rst +++ b/docs/source/features/isaac_teleop.rst @@ -115,8 +115,10 @@ and Isaac Lab. It composes three collaborators: Isaac Sim's XR bridge, creates the ``TeleopSession``, and steps it each frame to produce an action tensor. -* **CommandHandler** -- registers and dispatches START / STOP / RESET callbacks triggered by XR UI - buttons or the message bus. +* **CommandHandler** -- lightweight callback registry for START / STOP / RESET commands. Scripts + can register callbacks via :meth:`~isaaclab_teleop.IsaacTeleopDevice.add_callback`, but the + primary control path uses :func:`~isaaclab_teleop.poll_control_events` (see + :ref:`isaac-teleop-control-states`). .. dropdown:: Session lifecycle details @@ -127,6 +129,104 @@ and Isaac Lab. It composes three collaborators: the session is not yet ready or has been torn down. +.. _isaac-teleop-control-states: + +Teleop Control States (Start / Stop / Reset) +--------------------------------------------- + +Isaac Lab supports remote teleop control commands -- **start**, **stop**, and **reset** -- sent +from the XR headset to the simulation. These are used to begin and end demonstration recording, +pause the robot, or reset the environment without touching the simulation host. + +How it works +~~~~~~~~~~~~ + +By default, every :class:`~isaaclab_teleop.IsaacTeleopCfg` enables a control message channel +using the well-known UUID ``uuid5(NAMESPACE_DNS, "teleop_command")``. The channel is created as +a ``teleop_control_pipeline`` inside TeleopCore's :class:`TeleopSession`, which means: + +1. A :class:`~isaacteleop.retargeting_engine.deviceio_source_nodes.MessageChannelSource` opens an + OpenXR opaque data channel (``XR_NV_opaque_data_channel``) with the agreed-upon UUID. +2. The CloudXR JS client (or any other client) discovers the channel by UUID and sends UTF-8 + JSON commands:: + + {"type": "teleop_command", "message": {"command": "start teleop"}} + {"type": "teleop_command", "message": {"command": "stop teleop"}} + {"type": "teleop_command", "message": {"command": "reset teleop"}} + +3. A :class:`~isaaclab_teleop.teleop_message_processor.TeleopMessageProcessor` parses these + payloads and produces boolean pulse signals (``run_toggle``, ``kill``, ``reset``). +4. :class:`~isaacteleop.teleop_session_manager.DefaultTeleopStateManager` consumes the + boolean signals, runs its state machine (edge detection, fail-safe), and produces + ``teleop_state`` (one-hot) and ``reset_event`` (bool pulse) outputs. +5. TeleopCore decodes these outputs into ``ExecutionEvents`` and injects them into every + retargeter's ``ComputeContext``, so stateful retargeters can react to state changes + (e.g. reinitializing cross-step state on reset). + +Polling control events in your script +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Use :func:`~isaaclab_teleop.poll_control_events` to read the latest control state each frame: + +.. code-block:: python + + from isaaclab_teleop import poll_control_events + + with IsaacTeleopDevice(cfg) as device: + running = False + while sim_app.is_running(): + action = device.advance() + + ctrl = poll_control_events(device) + if ctrl.is_active is not None: + running = ctrl.is_active # True after "start", False after "stop" + if ctrl.should_reset: + env.reset() # "reset" command received this frame + + if action is not None and running: + env.step(action.repeat(num_envs, 1)) + else: + env.sim.render() + +:class:`~isaaclab_teleop.ControlEvents` has two fields: + +* ``is_active`` -- ``True`` after a "start" command, ``False`` after "stop", ``None`` when no + command has been received yet (callers should leave their own flag unchanged). +* ``should_reset`` -- ``True`` for exactly one frame after a "reset" command. + +Disabling the control channel +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +If you do not need headset-driven start/stop/reset (e.g. keyboard-only workflows), set +``control_channel_uuid=None`` in your config: + +.. code-block:: python + + IsaacTeleopCfg( + pipeline_builder=_build_my_pipeline, + control_channel_uuid=None, # no opaque data channel created + ) + +Using a custom channel UUID +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +To use a different channel UUID (e.g. for a separate control protocol), pass any 16-byte +``bytes`` value: + +.. code-block:: python + + import uuid + + MY_UUID = uuid.uuid5(uuid.NAMESPACE_DNS, "my_custom_control").bytes + + IsaacTeleopCfg( + pipeline_builder=_build_my_pipeline, + control_channel_uuid=MY_UUID, + ) + +The CloudXR JS client must be updated to discover this UUID when sending commands. + + .. _isaac-teleop-retargeting: Retargeting Framework @@ -593,6 +693,87 @@ Key ``IsaacTeleopCfg`` fields: would break pre-built pipeline graphs. +.. _isaac-teleop-cloudxr-profiles: + +CloudXR Environment Profiles +----------------------------- + +Isaac Lab ships two ``.env`` profiles that configure the CloudXR runtime for different XR devices. +These are bundled inside the ``isaaclab_teleop`` package and can be referenced via constants: + +.. list-table:: + :header-rows: 1 + :widths: 30 25 25 20 + + * - Constant + - File + - ``NV_DEVICE_PROFILE`` + - ``NV_CXR_ENABLE_PUSH_DEVICES`` + * - :data:`~isaaclab_teleop.CLOUDXR_JS_ENV` + - ``cloudxrjs-cloudxr.env`` + - ``auto-webrtc`` + - ``0`` + * - :data:`~isaaclab_teleop.CLOUDXR_AVP_ENV` + - ``avp-cloudxr.env`` + - ``auto-native`` + - ``0`` + +Both profiles set ``NV_CXR_ENABLE_PUSH_DEVICES=0``, which is correct for headset optical hand +tracking (the most common setup). For external push-device peripherals such as Manus gloves, set +this to ``1`` in a custom profile (see below). + +Override at launch time +~~~~~~~~~~~~~~~~~~~~~~~ + +The ``--cloudxr_env`` flag on ``teleop_se3_agent.py`` and ``record_demos.py`` selects which +``.env`` profile to use. The default is ``cloudxrjs`` (Quest/Pico). Use the ``avp`` shorthand +for Apple Vision Pro, or pass a full file path for a custom profile: + +.. code-block:: bash + + # Use the AVP profile + ./isaaclab.sh -p scripts/environments/teleoperation/teleop_se3_agent.py \ + --task Isaac-PickPlace-GR1T2-WaistEnabled-Abs-v0 \ + --visualizer kit --xr \ + --cloudxr_env avp + +Create a custom profile +~~~~~~~~~~~~~~~~~~~~~~~ + +Copy a shipped profile and edit it: + +.. code-block:: bash + + # Start from the Quest/Pico profile + cp $(python -c "from isaaclab_teleop import CLOUDXR_JS_ENV; print(CLOUDXR_JS_ENV)") ~/my-cloudxr.env + +Edit ``~/my-cloudxr.env`` to change any values (e.g. ``NV_CXR_ENABLE_PUSH_DEVICES=1`` for +Manus gloves), then pass it via ``--cloudxr_env ~/my-cloudxr.env``. + +Disable auto-launch +~~~~~~~~~~~~~~~~~~~ + +If you prefer to run the CloudXR runtime manually in a separate terminal +(``python -m isaacteleop.cloudxr``), you can disable auto-launch in several ways: + +* **CLI flag**: ``--no-auto_launch_cloudxr`` on the teleop script. +* **Disable CloudXR entirely**: ``--cloudxr_env none``. +* **Environment variable**: ``ISAACLAB_CXR_SKIP_AUTOLAUNCH=1`` overrides the CLI flag at runtime. + +.. code-block:: bash + + # Disable via CLI flag + ./isaaclab.sh -p scripts/environments/teleoperation/teleop_se3_agent.py \ + --task Isaac-PickPlace-GR1T2-WaistEnabled-Abs-v0 \ + --visualizer kit --xr \ + --no-auto_launch_cloudxr + + # Or disable via environment variable + ISAACLAB_CXR_SKIP_AUTOLAUNCH=1 ./isaaclab.sh -p scripts/environments/teleoperation/teleop_se3_agent.py \ + --task Isaac-PickPlace-GR1T2-WaistEnabled-Abs-v0 \ + --visualizer kit --xr + + .. _isaac-teleop-xr-anchor: Configure the XR Anchor @@ -827,6 +1008,10 @@ See the :ref:`isaaclab_teleop-api` for full class and function documentation: * :class:`~isaaclab_teleop.IsaacTeleopCfg` * :class:`~isaaclab_teleop.IsaacTeleopDevice` * :func:`~isaaclab_teleop.create_isaac_teleop_device` +* :class:`~isaaclab_teleop.ControlEvents` +* :class:`~isaaclab_teleop.SupportsControlEvents` +* :func:`~isaaclab_teleop.poll_control_events` +* :data:`~isaaclab_teleop.TELEOP_CONTROL_CHANNEL_UUID` * :class:`~isaaclab_teleop.XrCfg` * :class:`~isaaclab_teleop.XrAnchorRotationMode` diff --git a/docs/source/features/multi_gpu.rst b/docs/source/features/multi_gpu.rst index 2537e5eff25b..03277d26e6e1 100644 --- a/docs/source/features/multi_gpu.rst +++ b/docs/source/features/multi_gpu.rst @@ -124,6 +124,36 @@ To train with multiple GPUs, use the following command, where ``--nproc_per_node python -m skrl.utils.distributed.jax --nnodes=1 --nproc_per_node=2 scripts/reinforcement_learning/skrl/train.py --task=Isaac-Cartpole-v0 --headless --distributed --ml_framework jax +.. _multi-gpu-nccl-troubleshooting: + +Troubleshooting NCCL Errors +^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +On some Linux multi-GPU systems, distributed training may fail with +``CUDA error: an illegal memory access was encountered`` reported by ``ProcessGroupNCCL`` +during or shortly after communicator initialization. + +If this occurs, try disabling the NCCL shared-memory transport before launching training: + +.. code-block:: shell + + export NCCL_SHM_DISABLE=1 + +If the issue persists, additional NCCL fallbacks that may help are: + +.. code-block:: shell + + export NCCL_IB_DISABLE=1 + export NCCL_ALGO=Ring + +Then relaunch the distributed training command as usual. + +.. note:: + + These variables are NCCL-level workarounds intended for affected systems. They are not + required on all machines, and may change communication behavior or performance depending + on the hardware topology. + Multi-Node Training ------------------- diff --git a/docs/source/features/population_based_training.rst b/docs/source/features/population_based_training.rst index 1de85bb57c57..906eaf516437 100644 --- a/docs/source/features/population_based_training.rst +++ b/docs/source/features/population_based_training.rst @@ -122,12 +122,12 @@ Launch *N* workers, where *n* indicates each worker index: --track \ --wandb-name=idx \ --wandb-entity=<**entity**> \ - --wandb-project-name=<**project**> + --wandb-project-name=<**project**> \ agent.pbt.enabled=True \ agent.pbt.num_policies= \ agent.pbt.policy_idx= \ agent.pbt.workspace=<**pbt_workspace_name**> \ - agent.pbt.directory=<**/path/to/shared_folder**> \ + agent.pbt.directory=<**/path/to/shared_folder**> References diff --git a/docs/source/features/ray.rst b/docs/source/features/ray.rst index 0edf935e8389..dbf88d682a24 100644 --- a/docs/source/features/ray.rst +++ b/docs/source/features/ray.rst @@ -224,7 +224,7 @@ the following dependencies are also needed. .. code-block:: bash - python3 -p -m pip install kubernetes Jinja2 + python3 -m pip install kubernetes Jinja2 For use on Kubernetes clusters with KubeRay, such as Google Kubernetes Engine or Amazon Elastic Kubernetes Service, ``kubectl`` is required, and can @@ -276,7 +276,7 @@ Shared Steps Between KubeRay and Pure Ray Part I .. code-block:: bash - python3 -p -m pip install ray[default]==2.31.0 + python3 -m pip install "ray[default]==2.31.0" 2.) Build the Isaac Ray image, and upload it to your container registry of choice. diff --git a/docs/source/features/visualization.rst b/docs/source/features/visualization.rst index 13d573308efb..4efbf2470698 100644 --- a/docs/source/features/visualization.rst +++ b/docs/source/features/visualization.rst @@ -104,17 +104,14 @@ You can also configure custom visualizers in the code by defining ``VisualizerCf sim_cfg = SimulationCfg( visualizer_cfgs=[ KitVisualizerCfg( - viewport_name="Visualizer Viewport", - create_viewport=True, - dock_position="SAME", - window_width=1280, - window_height=720, - camera_position=(0.0, 0.0, 20.0), # high top down view - camera_target=(0.0, 0.0, 0.0), + # Omit create_viewport (default False) to use the active viewport; set + # create_viewport=True and optionally viewport_name to add a dedicated window. + eye=(0.0, 0.0, 20.0), # high top down view + lookat=(0.0, 0.0, 0.0), ), NewtonVisualizerCfg( - camera_position=(5.0, 5.0, 5.0), # closer quarter view - camera_target=(0.0, 0.0, 0.0), + eye=(5.0, 5.0, 5.0), # closer quarter view + lookat=(0.0, 0.0, 0.0), show_joints=True, ), RerunVisualizerCfg( @@ -142,6 +139,21 @@ The effective visualizer mode is resolved from both CLI and ``SimulationCfg.visu For the migration-focused summary and deprecation context, see :doc:`/source/migration/migrating_to_isaaclab_3-0`. +Partial Visualization +~~~~~~~~~~~~~~~~~~~~~ + +Visualizers can be configured to visualize just a subset of environments. +This is called partial visualization. + +There are 3 fields exposed in the ``VisualizerCfg`` for selecting environments for partial visualization: + +- ``max_visible_envs`` caps how many envs are shown. +- ``visible_env_indices`` explicitly selects the envs to visualize. +- ``randomly_sample_visible_envs`` (default ``True``): when ``visible_env_indices`` is unset and ``max_visible_envs`` is set, + enables randomly sampling the selected envs. If disabled, the first ``max_visible_envs`` envs are selected. + +Also, there is a CLI arg ``--max_visible_envs`` that overrides ``VisualizerCfg.max_visible_envs`` for the run. + .. _visualization-common-modes: .. list-table:: Common modes @@ -173,6 +185,96 @@ For the migration-focused summary and deprecation context, see - any - Run headless; ``--headless`` takes precedence. +Video Recording +--------------- + +Video recording is enabled with the ``--video`` flag. When combined with ``--visualizer``, +the visualizer selection also determines which backend captures the video frames: + +- ``--visualizer kit`` enables ``--video`` capture through the Isaac RTX renderer (Omniverse Replicator). +- ``--visualizer newton`` enables ``--video`` capture through the Newton OpenGL renderer. +- ``--visualizer rerun`` does not produce ``--video`` clips; it records Rerun ``.rrd`` data for replay + through the Rerun visualizer. +- ``--visualizer viser`` does not currently provide a ``--video`` recording backend. + +When both Kit and Newton visualizers are active, Isaac Lab records a single ``--video`` stream and +Kit takes precedence. To record from the renderer/physics stack instead of the active visualizer, +set ``VideoRecorderCfg.backend_source = "renderer"`` in the task configuration. + +.. list-table:: ``--video`` compatibility: visualizer × renderer preset + :header-rows: 1 + :widths: 28 36 36 + + * - Renderer preset + - ``--visualizer kit --video`` + - ``--visualizer newton --video`` + * - ``isaacsim_rtx_renderer`` + - ✅ Kit RTX captures video *(default, no change)* + - ✅ Newton GL captures video *(overrides RTX backend)* + * - ``newton_renderer`` + - ✅ Kit RTX captures video *(overrides Newton backend)* + - ✅ Newton GL captures video *(default, no change)* + * - ``ovrtx_renderer`` + - ❌ **Raises an error** — see note below + - ✅ Newton GL captures video; ovrtx provides camera sensor data + +.. note:: + + ``--visualizer kit`` combined with ``ovrtx_renderer`` raises a ``ValueError`` at startup. + Both Kit (Isaac Sim) and ovrtx ship conflicting RTX hydra libraries compiled against + different USD namespaces (``pxrInternal_v0_25_11`` vs ``ovInternal_v0_25_11``), which + causes a dynamic-linker crash when loaded into the same process. + Use ``--visualizer newton`` instead — it is compatible with all renderer presets. + +**Record video with the ovrtx renderer preset** + +.. code-block:: bash + + ./isaaclab.sh -p scripts/benchmarks/benchmark_rsl_rl.py \ + --task=Isaac-Repose-Cube-Shadow-Vision-Direct-v0 \ + --enable_cameras \ + --visualizer newton \ + --video \ + --video_length=300 \ + --video_interval=2000 \ + --max_iterations=5 \ + --num_envs=1024 \ + --benchmark_backend=summary \ + "presets=newton_mjwarp,ovrtx_renderer,rgb" + +**Record video with the Isaac RTX renderer preset using the Newton video backend** + +.. code-block:: bash + + ./isaaclab.sh -p scripts/benchmarks/benchmark_rsl_rl.py \ + --task=Isaac-Repose-Cube-Shadow-Vision-Direct-v0 \ + --enable_cameras \ + --visualizer newton \ + --video \ + --video_length=300 \ + --video_interval=2000 \ + --max_iterations=5 \ + --num_envs=1024 \ + --benchmark_backend=summary \ + "presets=physx,isaacsim_rtx_renderer,rgb" + +**Record video with the Isaac RTX renderer preset using the Kit video backend** + +.. code-block:: bash + + ./isaaclab.sh -p scripts/benchmarks/benchmark_rsl_rl.py \ + --task=Isaac-Repose-Cube-Shadow-Vision-Direct-v0 \ + --enable_cameras \ + --visualizer kit \ + --video \ + --video_length=300 \ + --video_interval=2000 \ + --max_iterations=5 \ + --num_envs=1024 \ + --benchmark_backend=summary \ + "presets=physx,isaacsim_rtx_renderer,rgb" + + Visualizer Backends ------------------- @@ -193,20 +295,18 @@ Omniverse Visualizer from isaaclab_visualizers.kit import KitVisualizerCfg visualizer_cfg = KitVisualizerCfg( - # Viewport settings - viewport_name="Visualizer Viewport", # Viewport window name - create_viewport=True, # Create new viewport vs. use existing - dock_position="SAME", # Docking: 'LEFT', 'RIGHT', 'BOTTOM', 'SAME' - window_width=1280, # Viewport width in pixels - window_height=720, # Viewport height in pixels - - # Camera settings - camera_position=(8.0, 8.0, 3.0), # Initial camera position (x, y, z) - camera_target=(0.0, 0.0, 0.0), # Camera look-at target - - # Feature toggles - enable_markers=True, # Enable visualization markers - enable_live_plots=True, # Enable live plots (auto-expands frames) + # Viewport: default is create_viewport=False (use active viewport). + # Set create_viewport=True to create a docked window; viewport_name=None uses the default name. + create_viewport=False, + dock_position="SAME", + window_width=1280, + window_height=720, + + eye=(8.0, 8.0, 3.0), + lookat=(0.0, 0.0, 0.0), + + enable_markers=True, + enable_live_plots=True, ) @@ -217,7 +317,7 @@ Newton Visualizer - Lightweight OpenGL rendering with low overhead - Visualization markers (joints, contacts, springs, COM) -- Training and rendering pause controls +- Simulation and rendering pause controls - Adjustable update frequency for performance tuning - Some customizable rendering options (shadows, sky, wireframe) @@ -255,8 +355,8 @@ Newton Visualizer window_height=1080, # Window height in pixels # Camera settings - camera_position=(8.0, 8.0, 3.0), # Initial camera position (x, y, z) - camera_target=(0.0, 0.0, 0.0), # Camera look-at target + eye=(8.0, 8.0, 3.0), # Initial camera position (x, y, z) + lookat=(0.0, 0.0, 0.0), # Camera look-at target # Performance tuning update_frequency=1, # Update every N frames (1=every frame) @@ -303,8 +403,8 @@ Rerun Visualizer bind_address="0.0.0.0", # Endpoint host formatting/reuse checks # Camera settings - camera_position=(8.0, 8.0, 3.0), # Initial camera position (x, y, z) - camera_target=(0.0, 0.0, 0.0), # Camera look-at target + eye=(8.0, 8.0, 3.0), # Initial camera position (x, y, z) + lookat=(0.0, 0.0, 0.0), # Camera look-at target # History settings keep_historical_data=False, # Keep transforms for time scrubbing @@ -350,7 +450,7 @@ server, allowing you to view and interact with the scene from any browser. open_browser=True, label="Isaac Lab Simulation", share=False, - max_worlds=64, + max_visible_envs=16, ) **Configuration options:** @@ -361,7 +461,6 @@ server, allowing you to view and interact with the scene from any browser. - ``share`` (bool, default ``False``): Request a public share URL from Viser for remote viewing. - ``record_to_viser`` (str or None, default ``None``): Path to save a ``.viser`` recording file. - ``verbose`` (bool, default ``True``): Print viewer server startup information. -- ``max_worlds`` (int or None, default ``None``): Maximum number of environments rendered. .. note:: @@ -371,7 +470,7 @@ server, allowing you to view and interact with the scene from any browser. Performance Note ---------------- -To reduce overhead when visualizing large-scale environments, consider: +When visualizing large-scale environments, consider: - Using Newton instead of Omniverse or Rerun - Reducing window sizes @@ -393,12 +492,6 @@ the num of environments can be overwritten and decreased using ``--num_envs``: python scripts/reinforcement_learning/rsl_rl/train.py --task Isaac-Cartpole-v0 --viz rerun --num_envs 512 -.. note:: - - A future feature will support visualizing only a subset of environments, which will improve visualization performance - and reduce resource usage while maintaining full-scale training in the background. - - **Rerun Visualizer FPS Control** The FPS control in the Rerun visualizer UI may not affect the visualization frame rate in all configurations. diff --git a/docs/source/how-to/cloudxr_teleoperation.rst b/docs/source/how-to/cloudxr_teleoperation.rst index 10474d390c0d..3613228d5b7f 100644 --- a/docs/source/how-to/cloudxr_teleoperation.rst +++ b/docs/source/how-to/cloudxr_teleoperation.rst @@ -9,10 +9,9 @@ Setting up Isaac Teleop with CloudXR teleoperation in Isaac Lab. It provides standardized device interfaces, a flexible retargeting pipeline, and bundled `NVIDIA CloudXR`_ streaming for immersive XR-based teleoperation. -This guide walks you through installing Isaac Teleop, starting the CloudXR runtime, connecting an -XR device, and running your first teleoperation session. For the canonical step-by-step flow (install -package, run CloudXR server, connect headset, run teleop example), refer to the `Isaac Teleop Quick -Start `_. +This guide walks you through setting up CloudXR, connecting an XR device, and running your first +teleoperation session. For additional details see the `Isaac Teleop Quick Start +`_. .. tip:: @@ -68,28 +67,9 @@ Install Isaac Teleop The CloudXR runtime links against Vulkan at runtime. If your system already has the NVIDIA driver installed, ``libvulkan1`` may already be present. -#. Activate the **same** virtual environment you use for Isaac Lab, then install the - ``isaacteleop`` package with the extras you need: - - .. code-block:: bash - - pip install "isaacteleop[retargeters,ui,cloudxr]~=1.0.0" --extra-index-url https://pypi.nvidia.com - - The extras provide the following functionality: - - * ``retargeters`` -- hand retargeting libraries (dex-retargeting, scipy, torch, etc.) - * ``ui`` -- retargeter tuning UI (imgui) - * ``cloudxr`` -- CloudXR runtime and WSS proxy (websockets) - - .. tip:: - - The pip package includes the CloudXR runtime, the WSS proxy, and all bundled native - libraries -- no separate clone or build step is needed. For advanced configuration, - building from source, or plugin development, see the - `Isaac Teleop GitHub `_. - - For version and compatibility details, see the - `Isaac Teleop releases `_. +#. ``isaacteleop`` is installed automatically as a dependency of ``isaaclab_teleop``. + No separate pip install step is required. For building from source or plugin + development, see the `Isaac Teleop GitHub `_. #. Configure the firewall to allow CloudXR traffic. The required ports depend on the client type. @@ -125,115 +105,42 @@ Install Isaac Teleop documentation. -.. _start-cloudxr-runtime: - -Start the CloudXR Runtime -------------------------- - -In a dedicated terminal, activate the Isaac Lab virtual environment and start the CloudXR -runtime: - -.. code-block:: bash - - python -m isaacteleop.cloudxr - -This single command performs the following: - -* **EULA acceptance** -- on first run you will be prompted to accept the NVIDIA CloudXR - EULA. The acceptance is stored in ``~/.cloudxr/run/eula_accepted`` and is not requested - again. -* **CloudXR runtime** -- loads the bundled CloudXR native libraries and starts the - runtime service. -* **WSS proxy** -- starts a WebSocket Secure (WSS) proxy on port **48322** that terminates - TLS for CloudXR.js web clients. A self-signed certificate is generated automatically in - ``~/.cloudxr/certs/`` if one does not already exist. - -Keep this terminal running for the duration of your teleoperation session. - -.. _cloudxr-runtime-configuration: - -.. rubric:: Runtime Configuration - -**Install directory** -- by default the runtime stores its OpenXR libraries, IPC socket, -logs, certificates, and a generated ``cloudxr.env`` file under ``~/.cloudxr/run/``. To use a -different location, pass the ``--cloudxr-install-dir`` flag: - -.. code-block:: bash - - python -m isaacteleop.cloudxr --cloudxr-install-dir=~/my_cloudxr - -**CloudXR environment config** -- runtime behavior can be customized by passing a -``.env``-style configuration file with the ``--cloudxr-env-config`` flag: - -.. code-block:: bash - - python -m isaacteleop.cloudxr --cloudxr-env-config=~/custom.env - -Common configuration options: - -.. important:: - - **Using optical hand tracking from the XR headset?** By default the runtime expects - hand tracking data from an external push device (e.g. Manus gloves). If you are using - the headset's built-in optical hand tracking (the most common setup for Quest 3 and - Pico 4 Ultra, and Apple Vision Pro), you **must** set the following in your ``.env`` config file: - - .. code-block:: text - - NV_CXR_ENABLE_PUSH_DEVICES=0 - - Without this, the runtime will not process hand tracking data from the headset and your - hands will not appear in the simulation. - -* **Apple Vision Pro** -- the Vision Pro uses the CloudXR native framework rather than - WebXR. To connect with an Apple Vision Pro, set: - - .. code-block:: text - - NV_DEVICE_PROFILE=auto-native - -Multiple options can be combined in the same file, one per line. Both flags can be used -together. - -.. note:: - - The previous Docker Compose workflow (used with Isaac Lab 2.3 and CloudXR 5.0.1) is - still supported for legacy environments but is deprecated in favor of the pip-based - Isaac Teleop workflow described here. See the ``docker/`` directory in the Isaac Lab - repository for the legacy Docker Compose files. - - .. _run-isaac-lab-with-the-cloudxr-runtime: Run Isaac Lab with CloudXR -------------------------- -Open a **new** terminal and source the environment file generated by the CloudXR runtime on -its first start. This sets the ``XR_RUNTIME_JSON`` and ``NV_CXR_RUNTIME_DIR`` variables that -Isaac Sim needs to locate the OpenXR runtime: +The CloudXR runtime launches automatically when a teleop script is started. No separate +terminal or ``source`` step is needed. Launch a teleoperation script directly: .. code-block:: bash - # Activate the Isaac Lab virtual environment (conda or uv) - source ~/.cloudxr/run/cloudxr.env - -If you specified a custom install directory with ``--cloudxr-install-dir``, source -``cloudxr.env`` from that directory instead. + ./isaaclab.sh -p scripts/environments/teleoperation/teleop_se3_agent.py \ + --task Isaac-PickPlace-GR1T2-WaistEnabled-Abs-v0 \ + --visualizer kit \ + --xr .. tip:: - You can add the ``source`` line to your shell profile (e.g. ``~/.bashrc``) so the - CloudXR environment is configured automatically in every new terminal. + The ``Isaac-PickPlace-GR1T2-WaistEnabled-Abs-v0`` task above uses **hand tracking** as its + input mode. Make sure your XR device has hand tracking enabled (optical hand tracking on + Quest 3, or the built-in hand tracking on Apple Vision Pro). Different tasks require + different input modes (motion controllers vs hand tracking) -- see the + :ref:`isaac-teleop-control-schemes` table for the full list. -With the CloudXR runtime running in a separate terminal (see :ref:`start-cloudxr-runtime`), -launch an Isaac Lab teleoperation script: +To switch the CloudXR device profile at launch time (e.g. from Quest to Apple Vision Pro), +use the ``--cloudxr_env`` flag: .. code-block:: bash ./isaaclab.sh -p scripts/environments/teleoperation/teleop_se3_agent.py \ --task Isaac-PickPlace-GR1T2-WaistEnabled-Abs-v0 \ --visualizer kit \ - --xr + --xr \ + --cloudxr_env avp + +For details on the shipped ``.env`` profiles and how to customise them, see +:ref:`isaac-teleop-cloudxr-profiles` in the feature guide. Then in the Isaac Sim UI: @@ -276,22 +183,16 @@ choose the tab that matches your hardware. Meta Quest 3 and Pico 4 Ultra connect to Isaac Lab via the `CloudXR.js `_ - WebXR client. The built-in WSS proxy started by ``python -m isaacteleop.cloudxr`` - provides the HTTPS connection that the web client requires. - - .. important:: - - If you are using the headset's built-in optical hand tracking (instead of - Manus gloves), make sure you started the CloudXR runtime with - ``NV_CXR_ENABLE_PUSH_DEVICES=0`` in your env config. See - :ref:`cloudxr-runtime-configuration` for details. + WebXR client. The built-in environments default to the ``cloudxrjs-cloudxr.env`` profile + (``auto-webrtc``), which is the correct setting for these devices. .. note:: Pico 4 Ultra requires Pico OS 15.4.4U or later and must use HTTPS mode. - #. Ensure the CloudXR runtime and WSS proxy are running - (see :ref:`start-cloudxr-runtime`). + #. Launch the teleop script as shown in + :ref:`run-isaac-lab-with-the-cloudxr-runtime`. The CloudXR runtime and WSS proxy + start automatically. #. Open the browser on your headset and navigate to the hosted CloudXR.js client: ``_. @@ -342,16 +243,17 @@ choose the tab that matches your hardware. .. important:: - The CloudXR runtime must be started with ``NV_DEVICE_PROFILE=auto-native`` to - accept connections from the Apple Vision Pro. Create a ``.env`` file containing - ``NV_DEVICE_PROFILE=auto-native`` and pass it when starting the runtime: + Apple Vision Pro requires the ``auto-native`` device profile. Pass the ``avp`` + shorthand when launching the teleop script: .. code-block:: bash - echo "NV_DEVICE_PROFILE=auto-native" > ~/custom.env - python -m isaacteleop.cloudxr --cloudxr-env-config=~/custom.env + ./isaaclab.sh -p scripts/environments/teleoperation/teleop_se3_agent.py \ + --task Isaac-PickPlace-GR1T2-WaistEnabled-Abs-v0 \ + --visualizer kit --xr \ + --cloudxr_env avp - See :ref:`cloudxr-runtime-configuration` for details. + See :ref:`isaac-teleop-cloudxr-profiles` for details on the shipped profiles. .. _build-apple-vision-pro: @@ -466,6 +368,26 @@ Manus Gloves Manus gloves provide high-fidelity finger tracking via the Manus SDK. This is useful when optical hand tracking from the headset is occluded or when higher-precision finger data is needed. +.. important:: + + Manus gloves and other external push-device peripherals require + ``NV_CXR_ENABLE_PUSH_DEVICES=1``. The shipped ``.env`` profiles set this to ``0`` + (optimised for headset optical hand tracking). To use Manus gloves, create a custom + ``.env`` file with the value set to ``1`` and pass it via ``--cloudxr_env``: + + .. code-block:: bash + + # Copy a shipped profile and enable push devices + cp $(python -c "from isaaclab_teleop import CLOUDXR_JS_ENV; print(CLOUDXR_JS_ENV)") ~/manus.env + sed -i 's/NV_CXR_ENABLE_PUSH_DEVICES=0/NV_CXR_ENABLE_PUSH_DEVICES=1/' ~/manus.env + + ./isaaclab.sh -p scripts/environments/teleoperation/teleop_se3_agent.py \ + --task Isaac-PickPlace-GR1T2-WaistEnabled-Abs-v0 \ + --visualizer kit --xr \ + --cloudxr_env ~/manus.env + + See :ref:`isaac-teleop-cloudxr-profiles` for full details on customising profiles. + .. note:: Manus glove support has been migrated into Isaac Teleop as a native plugin. The previous @@ -498,32 +420,23 @@ Teleoperation runs in a **single container**. Build the image yourself and run a Do **not** use Docker Compose, which is a multi-container setup as we had in Isaac Lab 2.x. All components run inside one container with Isaac Lab in this release. -Inside the container, install Isaac Teleop (once per container or image), then start the CloudXR -runtime and the teleop script. You must accept the NVIDIA CloudXR EULA; pass ``--accept-eula`` -when starting the runtime so there is no interactive prompt. - -#. Install Isaac Teleop with CloudXR and retargeters support: - - .. code-block:: bash - - ./isaaclab.sh -p -m pip install 'isaacteleop[retargeters,cloudxr]~=1.0.0' --extra-index-url https://pypi.nvidia.com +The CloudXR runtime auto-launches when a teleop script is started, so no separate +runtime command is needed. -#. Start the CloudXR runtime in the background, load the environment, and run the teleop script - (e.g. ``record_demos.py`` to record demonstrations): +Run the teleop script (e.g. ``record_demos.py`` to record demonstrations): - .. code-block:: bash +.. code-block:: bash - ./isaaclab.sh -p -m isaacteleop.cloudxr --accept-eula & - source ~/.cloudxr/run/cloudxr.env - ./isaaclab.sh -p scripts/tools/record_demos.py \ - --task Isaac-PickPlace-Locomanipulation-G1-Abs-v0 \ - --num_demos 5 \ - --dataset_file ./datasets/dataset.hdf5 \ - --xr --visualizer kit + ./isaaclab.sh -p scripts/tools/record_demos.py \ + --task Isaac-PickPlace-Locomanipulation-G1-Abs-v0 \ + --num_demos 5 \ + --dataset_file ./datasets/dataset.hdf5 \ + --xr --visualizer kit Then in the Isaac Sim UI, set the AR panel to **System OpenXR Runtime** and click **Start XR**. -For a fully headless experience, replace ``--visualizer kit`` with ``--headless`` when running docker and XR teleop session will run automatically. +For a fully headless experience, replace ``--visualizer kit`` with ``--headless`` and the XR +teleop session will run automatically. .. admonition:: Next Steps diff --git a/docs/source/how-to/haply_teleoperation.rst b/docs/source/how-to/haply_teleoperation.rst index 1f8d1d6e2522..46651077e338 100644 --- a/docs/source/how-to/haply_teleoperation.rst +++ b/docs/source/how-to/haply_teleoperation.rst @@ -70,7 +70,7 @@ Software Requirements * Isaac Lab (follow the :ref:`installation guide `) * Haply SDK (provided by Haply Robotics) -* Python 3.10+ +* Python 3.12+ * ``websockets`` Python package (automatically installed with Isaac Lab) diff --git a/docs/source/how-to/index.rst b/docs/source/how-to/index.rst index 278e88c4b6c6..25ae4fbee85d 100644 --- a/docs/source/how-to/index.rst +++ b/docs/source/how-to/index.rst @@ -101,6 +101,18 @@ Isaac Lab. draw_markers +Working with Simulation Data +---------------------------- + +This guide explains how to read and write simulation state using the :class:`~isaaclab.utils.warp.ProxyArray` +dual-access wrapper that all data classes return. + +.. toctree:: + :maxdepth: 1 + + proxy_array + + Interfacing with Environments ----------------------------- @@ -195,3 +207,14 @@ This guide explains 2 features that can speed up stage initialization, **fabric :maxdepth: 1 optimize_stage_creation + + +Profiling Isaac Lab with Nsight Systems +--------------------------------------- + +This guide explains how to profile Isaac Lab tasks with NVIDIA Nsight Systems for runtime performance analysis. + +.. toctree:: + :maxdepth: 1 + + profile_with_nsys diff --git a/docs/source/how-to/profile_with_nsys.rst b/docs/source/how-to/profile_with_nsys.rst new file mode 100644 index 000000000000..6ef17f55c555 --- /dev/null +++ b/docs/source/how-to/profile_with_nsys.rst @@ -0,0 +1,114 @@ +Profiling Isaac Lab with Nsight Systems +======================================= + +.. currentmodule:: isaaclab + +Isaac Lab supports CPU and GPU profiling via **NVIDIA Nsight Systems (nsys)** for runtime performance analysis. This can help identify GPU/CPU bottlenecks and determine the best configuration for your environments and tasks. Profiling adds modest runtime overhead and produces large output files, so it's best suited to targeted investigations rather than long unattended training runs. + +Common Use Cases +---------------- + +- **My training iteration is slow** - capture 3-5 iterations to see whether time is mostly spent on physics, rendering, env reset, observation, etc. +- **Env init takes 40 seconds** - profile a single launch to see the import times for each module, kernel compilation, etc. +- **Which physics/renderer backend should I use?** - profile your task with different backend combinations to find the best fit. +- **Are my GPU kernels efficient?** - dive into the CUDA rows in nsys to identify when the GPU is idle (optimization opportunity). +- **Did my code changes make things slower?** - A/B profile comparison before and after your change. + + +Quick Start +----------- + +This section walks you through everything needed to capture your first nsys profile. + +Prerequisites +~~~~~~~~~~~~~ + +- `Nsight Systems `_ - install for your platform. +- ``nvtx`` Python package for source code instrumentation, installed into your Isaac Lab environment: + + .. code-block:: bash + + ./isaaclab.sh -p -m pip install nvtx + + +Running a Profile +~~~~~~~~~~~~~~~~~ + +The following command shows how to capture a profile for the ``Isaac-Cartpole-v0`` task via the ``rsl_rl`` training framework with 3 iterations: + +.. code-block:: bash + + nsys profile \ + -t nvtx,cuda \ + --python-functions-trace=scripts/benchmarks/nsys_trace.json \ + -o my_profile \ + ./isaaclab.sh -p scripts/reinforcement_learning/rsl_rl/train.py \ + --task=Isaac-Cartpole-v0 \ + --headless \ + --max_iterations=3 + +Flags: + +- ``-t nvtx,cuda`` - capture NVTX ranges (CPU swim-lanes) and CUDA activity (GPU row). +- ``--python-functions-trace=...`` - the function annotations file; ships with Isaac Lab. +- ``-o my_profile`` - output path; nsys appends ``.nsys-rep``. + +Reading the Resulting Profile +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Launch the Nsight Systems UI, go to **File > Open**, and select your ``.nsys-rep`` file that you generated in the previous step. Expand the **Threads** section and the domain swim-lanes will appear as separate rows. Clicking on a function will highlight related functions in other lanes. Expand the **CUDA HW** row to cross-reference with GPU kernels fired during that CPU range. + +.. image:: ../_static/how-to/howto_profile_nsys_example.png + :alt: Domain swim-lanes in nsys-ui + + +The Trace JSON +-------------- + +The trace definition file lives at ``scripts/benchmarks/nsys_trace.json`` and defines metadata for the Python functions of interest in Isaac Lab. nsys monkey-patches these functions to automatically emit NVTX ranges at runtime. + +Schema: + +.. code-block:: json + + [ + { + "domain": "MyDomain", + "color": "0x9C27B0", + "module": "isaaclab.envs.manager_based_env", + "functions": [ + "ManagerBasedEnv.step", + {"function": "ManagerBasedEnv.reset", "color": "0xAB47BC"} + ] + } + ] + + +After editing the JSON, run the sync test to confirm every entry resolves: + +.. code-block:: bash + + ./isaaclab.sh -p -m pytest scripts/benchmarks/test/test_nsys_trace.py + + +Troubleshooting +--------------- + +- **An expected domain doesn't appear in the timeline:** + + - Confirm ``nvtx`` is installed in your Isaac Lab environment (``./isaaclab.sh -p -m pip show nvtx``). + - Make sure the function is actually called during the profiled run. + - Verify the JSON entry by running the sync test (above). + +- **Sync test fails with an** ``AttributeError`` - a function listed in the JSON no longer exists at the given path. + + - Fix the path to point at the renamed function, or + - Remove the entry if the function was deleted. + + +See Also +-------- + +- :doc:`simulation_performance` - broader simulation performance tuning tips. +- `Nsight Systems User Guide `_ - official ``nsys`` documentation. +- `NVTX Python package `_ - the package nsys uses to emit NVTX ranges from Python. diff --git a/docs/source/how-to/proxy_array.rst b/docs/source/how-to/proxy_array.rst new file mode 100644 index 000000000000..7bf0a90374f3 --- /dev/null +++ b/docs/source/how-to/proxy_array.rst @@ -0,0 +1,134 @@ +.. _how-to-torch-array: + +Working with ProxyArray +======================= + +.. currentmodule:: isaaclab.utils.warp + +Isaac Lab data classes return :class:`ProxyArray` — a lightweight, warp-first wrapper that +provides zero-copy access to simulation data as either a :class:`warp.array` or a +:class:`torch.Tensor`. + +.. note:: + + ``ProxyArray`` is inspired by the ``ProxyArray`` class from + `mujocolab/mjlab `_ (BSD-3-Clause). + The design adapts the same dual-accessor pattern to Isaac Lab's warp-based data pipeline. + + +Quick Start +~~~~~~~~~~~ + +Every property on asset and sensor data classes (e.g., ``robot.data.joint_pos``, +``sensor.data.net_forces_w``) returns a ``ProxyArray``: + +.. code-block:: python + + robot = env.scene["robot"] + + # Explicit torch access (preferred) + joint_positions = robot.data.joint_pos.torch # torch.Tensor, cached zero-copy view + gravity_proj = robot.data.projected_gravity_b.torch # torch.Tensor + + # Explicit warp access (for kernel interop) + wp_array = robot.data.joint_pos.warp # warp.array, the original buffer + + # Pass directly to warp kernels — no unwrapping needed + wp.launch(my_kernel, inputs=[robot.data.joint_pos], ...) # works via __cuda_array_interface__ + + +The ``.torch`` and ``.warp`` Accessors +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +- ``.torch`` returns a cached, zero-copy :class:`torch.Tensor` view of the underlying warp array + (via :func:`warp.to_torch`). The tensor is created on first access and reused on subsequent + calls. Since it is a zero-copy view, writes to the tensor are visible through the warp array + and vice versa. + +- ``.warp`` returns the original :class:`warp.array`. Use this when you need to pass data to + warp kernels explicitly or access warp-specific attributes (``ptr``, ``strides``, etc.). + + +Deprecation Bridge +~~~~~~~~~~~~~~~~~~ + +To ease migration, ``ProxyArray`` includes a deprecation bridge that allows existing code to +treat it as a ``torch.Tensor`` temporarily: + +.. code-block:: python + + # These still work but emit a one-time DeprecationWarning: + result = torch.sum(robot.data.joint_pos) # via __torch_function__ + value = robot.data.joint_pos[0, 3] # via __getitem__ + result = robot.data.joint_pos + 1.0 # via __add__ + legacy = wp.to_torch(robot.data.joint_pos) # temporary shim + + # Preferred (no warning): + result = torch.sum(robot.data.joint_pos.torch) + value = robot.data.joint_pos.torch[0, 3] + result = robot.data.joint_pos.torch + 1.0 + tensor = robot.data.joint_pos.torch + +The ``wp.to_torch()`` compatibility path is a temporary shim for code that was migrated +before ``ProxyArray`` exposed explicit accessors. It returns the same zero-copy tensor as +``.torch`` and emits a one-time ``DeprecationWarning``. The shim and the other deprecation +bridges will be removed in a future release. Migrate to explicit ``.torch`` access now. + + +Migrating from Isaac Lab 2.x +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +In Isaac Lab 2.x, data properties returned ``torch.Tensor`` directly. In 3.0, they return +``ProxyArray``. Append ``.torch`` to get the tensor: + +.. code-block:: python + + # BEFORE (Isaac Lab 2.x) — properties returned torch.Tensor directly + joint_pos = robot.data.joint_pos + first_contact = sensor.compute_first_contact(dt) + + # AFTER (Isaac Lab 3.0) — properties return ProxyArray + joint_pos = robot.data.joint_pos.torch + first_contact = sensor.compute_first_contact(dt).torch + +.. note:: + + Passing a ``ProxyArray`` to ``wp.to_torch()`` is temporarily supported by a compatibility + shim and returns the same cached zero-copy tensor as ``.torch``. This path emits a + one-time ``DeprecationWarning`` and will be removed in a future release. Use ``.torch`` + in new code. + + +Backend Differences +~~~~~~~~~~~~~~~~~~~ + +While the ``ProxyArray`` interface is identical across backends, the underlying data refresh +model differs: + +**PhysX (pull-to-refresh):** + Properties pull fresh data from the PhysX tensor API on first access per simulation step, + then cache the result. The underlying GPU buffers are stable and pre-allocated — the + ``ProxyArray`` wrapper is created once and reused safely across steps. + +**Newton (auto-refresh with wrapper replacement):** + The simulation automatically refreshes GPU buffers each step. On full simulation resets, + buffers may be re-created. The Newton backend creates new ``ProxyArray`` wrappers for the + new warp arrays, invalidating any previously cached torch tensors. + +In both cases, ``.torch`` always returns a view of the current simulation state for the +current step. + +.. warning:: + + Do not cache ``.torch`` results across simulation resets. After a reset (especially on + Newton), previously obtained tensors may point to stale or freed GPU memory. Always + re-access the property after a reset. + + +API Reference +~~~~~~~~~~~~~ + +.. autoclass:: ProxyArray + :members: + :undoc-members: + :no-index: diff --git a/docs/source/how-to/record_video.rst b/docs/source/how-to/record_video.rst index aba743631295..335ba7192557 100644 --- a/docs/source/how-to/record_video.rst +++ b/docs/source/how-to/record_video.rst @@ -3,6 +3,10 @@ Recording video clips during training Isaac Lab supports recording video clips during training using the `gymnasium.wrappers.RecordVideo `_ class. +When the ``--video`` flag is enabled, Isaac Lab captures a perspective view of the scene. If a Kit or +Newton visualizer is active, that visualizer selects the video backend by default. Otherwise, the +backend is chosen automatically from the active physics and renderer stack: an Isaac Sim Kit camera or +a Newton GL headless viewer. This feature can be enabled by installing ``ffmpeg`` and using the following command line arguments with the training script: @@ -11,7 +15,6 @@ script: * ``--video_length``: length of each recorded video (in steps) * ``--video_interval``: interval between each video recording (in steps) -Make sure to also add the ``--enable_cameras`` argument when running headless. Note that enabling recording is equivalent to enabling rendering during training, which will slow down both startup and runtime performance. Example usage: @@ -23,3 +26,144 @@ Example usage: The recorded videos will be saved in the same directory as the training checkpoints, under ``IsaacLab/logs////videos/train``. + + +Overview +-------- + +The video recording feature is implemented using the ``VideoRecorder`` class. This class is responsible for resolving the video backend from the scene, capturing the video frames, and saving them to a file. + +* ``VideoRecorderCfg`` (``isaaclab.envs.utils.video_recorder_cfg``) holds resolution, backend source, + and world-space perspective parameters ``eye`` and ``lookat`` (defaults to a diagonal view of the + scene). +* ``VideoRecorder`` (``isaaclab.envs.utils.video_recorder``) picks a video backend from the scene + (Kit vs Newton GL), builds the matching low-level capture object, and returns RGB frames via + ``render_rgb_array()``. +* Direct RL, Direct MARL and manager-based RL environments copy the task's + :class:`~isaaclab.envs.common.ViewerCfg` ``eye`` and ``lookat`` into those fields before the + recorder is constructed, so training clips align with the task's intended viewport when + ``origin_type`` is ``"world"``. + + +Configuration: ``VideoRecorderCfg`` +------------------------------------ + +The dataclass lives in ``isaaclab.envs.utils.video_recorder_cfg``. Fields ``eye`` and ``lookat`` are +the perspective camera position and target in meters. + +.. literalinclude:: ../../../source/isaaclab/isaaclab/envs/utils/video_recorder_cfg.py + :language: python + :lines: 20-58 + + +Task framing: ``ViewerCfg`` +---------------------------- + +Tasks define the interactive viewer with :class:`~isaaclab.envs.common.ViewerCfg`. The ``eye`` and +``lookat`` tuples are the same values the RL base classes copy into ``VideoRecorderCfg`` (see below). +If your task uses ``origin_type="world"``, those tuples are world-space positions and match what the +perspective recorder expects. + +.. literalinclude:: ../../../source/isaaclab/isaaclab/envs/common.py + :language: python + :lines: 20-28 + + +Backend selection: Kit vs Newton GL +------------------------------------- + +``VideoRecorder`` resolves the implementation from the live :class:`~isaaclab.scene.InteractiveScene`. +With the default ``VideoRecorderCfg.backend_source = "visualizer"``, an active ``--visualizer kit`` +selects the Kit path (``omni.replicator`` on ``/OmniverseKit_Persp``), and an active +``--visualizer newton`` selects the Newton GL path. If both visualizers are active, Kit takes +precedence and only one ``--video`` stream is recorded. Rerun records ``.rrd`` replay data through +the Rerun visualizer rather than producing ``--video`` clips, and Viser does not currently provide a +``--video`` recording backend. + +Set ``VideoRecorderCfg.backend_source = "renderer"`` to ignore active visualizers and choose from the +physics/renderer stack instead. In that mode, PhysX physics (``presets=physx,...``) or Isaac RTX +(``presets=isaac_rtx_renderer,...``) selects the Kit path. Newton physics (``presets=newton_mjwarp,...``) or +the Newton Warp renderer (``presets=newton_renderer,...``) selects the Newton GL path when no Kit +signal is present. OVRTX (``presets=ovrtx_renderer,...`` from ``isaaclab_ov``) can pair with IsaacSim +or Newton physics; in that case the video backend is selected via the physics preset. If both Kit and +Newton GL signals are present, the Kit path is chosen. + +.. literalinclude:: ../../../source/isaaclab/isaaclab/envs/utils/video_recorder.py + :language: python + :lines: 38-59 + + +Construction and dispatch +-------------------------- + +When ``env_render_mode`` is ``"rgb_array"`` (as when wrappers or scripts request RGB frames for +video), the recorder instantiates the backend-specific helper and passes through ``eye``, ``lookat``, +and window size. + +.. literalinclude:: ../../../source/isaaclab/isaaclab/envs/utils/video_recorder.py + :language: python + :lines: 70-114 + + +Customising the camera view +---------------------------- + +When ``--video`` is passed, the recording camera uses the same configured +position and look-at target as the active Kit or Newton visualizer when that visualizer drives backend +selection. Otherwise, the defaults come from +:class:`~isaaclab.envs.common.ViewerCfg`: + +* ``eye = (7.5, 7.5, 7.5)`` — camera position in world space (metres) +* ``lookat = (0.0, 0.0, 0.0)`` — camera look-at target in world space (metres) +* Resolution ``1280x720`` + +To change the recording angle without a visualizer, override the ``viewer`` field in your task's +environment config. The RL base classes automatically copy ``eye`` and ``lookat`` into +``VideoRecorderCfg`` before recording starts (when ``origin_type`` is ``"world"``), so the video clip +uses the same configured viewpoint as the interactive viewport: + +.. code-block:: python + + from isaaclab.envs import ManagerBasedRLEnvCfg + from isaaclab.envs.common import ViewerCfg + from isaaclab.utils import configclass + + @configclass + class MyTaskCfg(ManagerBasedRLEnvCfg): + viewer: ViewerCfg = ViewerCfg( + eye=(5.0, 5.0, 5.0), + lookat=(0.0, 0.0, 1.0), + ) + + +Summary +------- + +.. list-table:: + :widths: 40 22 38 + :header-rows: 1 + + * - Stack example (``presets=...``) + - Video backend + - Capture mechanism + * - ``physx,...`` or ``isaac_rtx_renderer,...`` + - Kit (``"kit"``) + - ``/OmniverseKit_Persp`` + Replicator RGB + * - ``newton_mjwarp,...`` or ``newton_renderer,...`` (no Kit signals) + - Newton GL (``"newton_gl"``) + - ``newton.viewer.ViewerGL`` on the SDP Newton model + * - ``newton_mjwarp,...,ovrtx_renderer,...`` (OVRTX + Newton physics) + - Newton GL (``"newton_gl"``) + - ``newton.viewer.ViewerGL`` on the SDP Newton model + * - ``--visualizer kit`` with default ``backend_source`` + - Kit (``"kit"``) + - Visualizer ``eye`` / ``lookat`` copied to ``/OmniverseKit_Persp`` + Replicator RGB + * - ``--visualizer newton`` with default ``backend_source`` + - Newton GL (``"newton_gl"``) + - Visualizer ``eye`` / ``lookat`` initially, then live Newton viewer camera sync per frame + + +See also +-------- + +* :doc:`/source/features/visualization` - interactive visualizers diff --git a/docs/source/how-to/save_camera_output.rst b/docs/source/how-to/save_camera_output.rst index f92f9bcc93d5..01b404efc0d8 100644 --- a/docs/source/how-to/save_camera_output.rst +++ b/docs/source/how-to/save_camera_output.rst @@ -14,13 +14,23 @@ directory. .. literalinclude:: ../../../scripts/tutorials/04_sensors/run_usd_camera.py :language: python - :emphasize-lines: 171-179, 229-247, 251-264 + :emphasize-lines: 174-182, 232-250, 254-267 :linenos: Saving using Replicator Basic Writer ------------------------------------ +.. note:: + The BasicWriter is part of the Omniverse Replicator ecosystem and is specific to the default + Isaac RTX renderer backend. Other renderer backends may require different save workflows. + +.. note:: + The ``colorize_*`` arguments below are set on + :attr:`~isaaclab.sensors.camera.CameraCfg.renderer_cfg` (an + :class:`~isaaclab_physx.renderers.IsaacRtxRendererCfg`); the same-named + fields on :class:`~isaaclab.sensors.camera.CameraCfg` are deprecated. + To save camera outputs, we use the basic write class from Omniverse Replicator. This class allows us to save the images in a numpy format. For more information on the basic writer, please check the `documentation `_. @@ -32,18 +42,11 @@ images in a numpy format. For more information on the basic writer, please check While stepping the simulator, the images can be saved to the defined folder. Since the BasicWriter only supports saving data using NumPy format, we first need to convert the PyTorch sensors to NumPy arrays before packing -them in a dictionary. +them in a dictionary and writing with the BasicWriter. .. literalinclude:: ../../../scripts/tutorials/04_sensors/run_usd_camera.py :language: python :start-at: # Save images from camera at camera_index - :end-at: single_cam_info = camera.data.info[camera_index] - -After this step, we can save the images using the BasicWriter. - -.. literalinclude:: ../../../scripts/tutorials/04_sensors/run_usd_camera.py - :language: python - :start-at: # Pack data back into replicator format to save them using its writer :end-at: rep_writer.write(rep_output) diff --git a/docs/source/migration/migrating_deformables.rst b/docs/source/migration/migrating_deformables.rst new file mode 100644 index 000000000000..efb7f7da689e --- /dev/null +++ b/docs/source/migration/migrating_deformables.rst @@ -0,0 +1,224 @@ +.. _migrating-deformables: + +Migration of Deformables +======================== + +.. currentmodule:: isaaclab + +In the newer versions of Omni Physics (107.0 and later), the old deformable body functionality has become deprecated. +The following sections describe the changes to migrate to the new Omni Physics API, specifically moving away from +Soft Bodies and towards Surface and Volume Deformables. We currently only support deformable bodies in the PhysX +backend, hence these features are implemented in ``isaaclab_physx``. + +.. note:: + + The following changes are with respect to Isaac Lab v3.0.0 and Omni Physics v110.0. Please refer to the + `release notes`_ for any changes in the future releases. + + +Surface and Volume Deformables +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +With the new Omni Physics API, deformable bodies are split into two distinct types, as described in the +`Omni Physics documentation`_: + +- **Volume deformables**: 3D objects simulated with a tetrahedral FEM mesh (e.g., soft cubes, spheres, capsules). + These support kinematic targets on individual vertices. The simulation operates on a tetrahedral mesh internally, + while a separate triangle surface mesh handles rendering. +- **Surface deformables**: 2D surfaces simulated directly on a triangle mesh (e.g., cloth, fabric, membranes). + These have additional material properties for controlling stretch, shear, and bend stiffness, but do not support + kinematic vertex targets. + +The type of deformable is determined by the **physics material** assigned to the object: + +- :class:`~isaaclab_physx.sim.DeformableBodyMaterialCfg` creates a **volume** deformable. +- :class:`~isaaclab_physx.sim.SurfaceDeformableBodyMaterialCfg` creates a **surface** deformable. + + +Migration from the Old API +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Import Changes +^^^^^^^^^^^^^^ + +All deformable-related classes have moved from ``isaaclab`` to ``isaaclab_physx``. The table below summarizes the +import changes: + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Old Import + - New Import + * - ``from isaaclab.sim import DeformableBodyPropertiesCfg`` + - ``from isaaclab_physx.sim import DeformableBodyPropertiesCfg`` + * - ``from isaaclab.sim import DeformableBodyMaterialCfg`` + - ``from isaaclab_physx.sim import DeformableBodyMaterialCfg`` + + +Removed Properties +^^^^^^^^^^^^^^^^^^ + +The following properties have been **removed** from :class:`~isaaclab_physx.sim.DeformableBodyPropertiesCfg`: + +- ``collision_simplification`` and related parameters (``collision_simplification_remeshing``, + ``collision_simplification_target_triangle_count``, ``collision_simplification_force_conforming``, + ``collision_simplification_remove_open_edges``) — collision mesh generation is now handled automatically by + PhysX through ``deformableUtils.create_auto_volume_deformable_hierarchy()`` and + ``deformableUtils.create_auto_surface_deformable_hierarchy()``. +- ``simulation_hexahedral_resolution`` — the simulation mesh resolution is no longer user-configurable; + PhysX determines it automatically. +- ``vertex_velocity_damping`` — replaced by the more general ``linear_damping`` property from the + `PhysX deformable schema`_. +- ``sleep_damping`` — replaced by ``settling_damping`` in the `PhysX deformable schema`_. + +Added Properties +^^^^^^^^^^^^^^^^ + +The following properties have been **added** to :class:`~isaaclab_physx.sim.DeformableBodyPropertiesCfg`: + +- ``linear_damping`` — linear damping coefficient [1/s]. +- ``max_linear_velocity`` — maximum allowable linear velocity [m/s]. A negative value lets the simulation choose + a per-vertex value dynamically (currently only supported for surface deformables). +- ``settling_damping`` — additional damping applied when vertex velocity falls below ``settling_threshold`` [1/s]. +- ``enable_speculative_c_c_d`` — enables speculative continuous collision detection. +- ``disable_gravity`` — per-deformable gravity control. +- ``collision_pair_update_frequency`` — how often surface-to-surface collision pairs are updated per time step + (surface deformables only). +- ``collision_iteration_multiplier`` — collision subiterations per solver iteration (surface deformables only). + +For a full description of all available properties, refer to the `PhysX deformable schema`_ and +`OmniPhysics deformable schema`_ documentation. + +Material Changes +^^^^^^^^^^^^^^^^ + +The old :class:`DeformableBodyMaterialCfg` (from ``isaaclab.sim``) has been replaced by a new hierarchy in +``isaaclab_physx``: + +- :class:`~isaaclab_physx.sim.DeformableBodyMaterialCfg` — for volume deformables. Contains ``density``, + ``static_friction``, ``dynamic_friction``, ``youngs_modulus``, ``poissons_ratio``, and ``elasticity_damping``. +- :class:`~isaaclab_physx.sim.SurfaceDeformableBodyMaterialCfg` — extends the volume material config with + surface-specific properties: ``surface_thickness``, ``surface_stretch_stiffness``, ``surface_shear_stiffness``, + ``surface_bend_stiffness``, and ``bend_damping``. + +The old ``damping_scale`` property has been removed. Use ``elasticity_damping`` directly instead. + +DeformableObject View Change +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The internal PhysX view type has changed from ``physx.SoftBodyView`` to ``physx.DeformableBodyView``. +The property ``root_physx_view`` has been deprecated in favor of ``root_view``. + + +Code Examples +~~~~~~~~~~~~~ + +Volume Deformable (Before and After) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +**Before**: + +.. code-block:: python + :emphasize-lines: 1,2 + + import isaaclab.sim as sim_utils + from isaaclab.assets import DeformableObject, DeformableObjectCfg + + cfg = DeformableObjectCfg( + prim_path="/World/Origin.*/Cube", + spawn=sim_utils.MeshCuboidCfg( + size=(0.2, 0.2, 0.2), + deformable_props=sim_utils.DeformableBodyPropertiesCfg(), + visual_material=sim_utils.PreviewSurfaceCfg(), + physics_material=sim_utils.DeformableBodyMaterialCfg(poissons_ratio=0.4, youngs_modulus=1e5), + ), + ) + cube_object = DeformableObject(cfg=cfg) + +**After**: + +.. code-block:: python + :emphasize-lines: 1,2,3 + + import isaaclab.sim as sim_utils + from isaaclab_physx.assets import DeformableObject, DeformableObjectCfg + from isaaclab_physx.sim import DeformableBodyPropertiesCfg, DeformableBodyMaterialCfg + + cfg = DeformableObjectCfg( + prim_path="/World/Origin.*/Cube", + spawn=sim_utils.MeshCuboidCfg( + size=(0.2, 0.2, 0.2), + deformable_props=DeformableBodyPropertiesCfg(), + visual_material=sim_utils.PreviewSurfaceCfg(), + physics_material=DeformableBodyMaterialCfg(poissons_ratio=0.4, youngs_modulus=1e5), + ), + ) + cube_object = DeformableObject(cfg=cfg) + +Surface Deformable (New) +^^^^^^^^^^^^^^^^^^^^^^^^ + +Surface deformables use :class:`~isaaclab.sim.spawners.meshes.MeshSquareCfg` for 2D meshes, combined with +:class:`~isaaclab_physx.sim.SurfaceDeformableBodyMaterialCfg`: + +.. code-block:: python + + import isaaclab.sim as sim_utils + from isaaclab_physx.assets import DeformableObject, DeformableObjectCfg + from isaaclab_physx.sim import DeformableBodyPropertiesCfg, SurfaceDeformableBodyMaterialCfg + + cfg = DeformableObjectCfg( + prim_path="/World/Origin.*/Cloth", + spawn=sim_utils.MeshSquareCfg( + size=1.5, + resolution=(21, 21), + deformable_props=DeformableBodyPropertiesCfg(), + visual_material=sim_utils.PreviewSurfaceCfg(), + physics_material=SurfaceDeformableBodyMaterialCfg(poissons_ratio=0.4, youngs_modulus=1e5), + ), + ) + cloth_object = DeformableObject(cfg=cfg) + +USD File Deformable +^^^^^^^^^^^^^^^^^^^ + +Deformable properties can also be applied to imported USD assets using +:class:`~isaaclab.sim.spawners.from_files.UsdFileCfg`: + +.. code-block:: python + + import isaaclab.sim as sim_utils + from isaaclab_physx.assets import DeformableObject, DeformableObjectCfg + from isaaclab_physx.sim import DeformableBodyPropertiesCfg, DeformableBodyMaterialCfg + + from isaaclab.utils.assets import ISAACLAB_NUCLEUS_DIR + + cfg = DeformableObjectCfg( + prim_path="/World/Origin.*/Teddy", + spawn=sim_utils.UsdFileCfg( + usd_path=f"{ISAACLAB_NUCLEUS_DIR}/Objects/Teddy_Bear/teddy_bear.usd", + deformable_props=DeformableBodyPropertiesCfg(), + physics_material=DeformableBodyMaterialCfg(poissons_ratio=0.4, youngs_modulus=1e5), + scale=[0.05, 0.05, 0.05], + ), + ) + teddy_object = DeformableObject(cfg=cfg) + + +Limitations +~~~~~~~~~~~ + +- **Kinematic targets are volume-only.** Calling + :meth:`~isaaclab_physx.assets.DeformableObject.write_nodal_kinematic_target_to_sim_index` on a surface + deformable will raise a ``ValueError``. +- **Surface-specific solver properties** (``collision_pair_update_frequency``, + ``collision_iteration_multiplier``) have no effect on volume deformables. +- **Deformables are PhysX-only.** The ``isaaclab_physx`` extension is required; other physics backends + do not support deformable bodies through Isaac Lab yet. + + +.. _Omni Physics documentation: https://docs.omniverse.nvidia.com/kit/docs/omni_physics/110.0/dev_guide/deformables/deformable_bodies.html +.. _PhysX deformable schema: https://docs.omniverse.nvidia.com/kit/docs/omni_physics/110.0/dev_guide/deformables/physx_deformable_schema.html#physxbasedeformablebodyapi +.. _OmniPhysics deformable schema: https://docs.omniverse.nvidia.com/kit/docs/omni_physics/110.0/dev_guide/deformables/omniphysics_deformable_schema.html +.. _release notes: https://github.com/isaac-sim/IsaacLab/releases diff --git a/docs/source/migration/migrating_to_isaaclab_3-0.rst b/docs/source/migration/migrating_to_isaaclab_3-0.rst index f1a057d9738d..4d29d5f4c8fe 100644 --- a/docs/source/migration/migrating_to_isaaclab_3-0.rst +++ b/docs/source/migration/migrating_to_isaaclab_3-0.rst @@ -98,6 +98,49 @@ The following classes have been moved to ``isaaclab_physx``: installation steps are required. +Renaming of ``XformPrimView`` to ``FrameView`` +----------------------------------------------- + +Isaac Lab's ``XformPrimView`` and related classes have been renamed to ``FrameView`` to +better reflect their purpose and avoid confusion with Isaac Sim's ``XFormPrim`` class +hierarchy. The old ``XformPrimView`` name is kept as a deprecated alias. + +The rename applies across all backends: + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Isaac Lab 2.x + - Isaac Lab 3.0 + * - ``BaseXformPrimView`` + - :class:`~isaaclab.sim.views.BaseFrameView` + * - ``UsdXformPrimView`` + - :class:`~isaaclab.sim.views.UsdFrameView` + * - ``XformPrimView`` + - :class:`~isaaclab.sim.views.FrameView` + * - ``FabricXformPrimView`` + - :class:`~isaaclab_physx.sim.views.FabricFrameView` + * - ``NewtonSiteXformPrimView`` + - :class:`~isaaclab_newton.sim.views.NewtonSiteFrameView` + +For most users, the only change needed is updating imports: + +.. code-block:: python + + # Before + from isaaclab.sim.views import XformPrimView + + # After + from isaaclab.sim.views import FrameView + +The :class:`~isaaclab.sim.views.FrameView` factory automatically dispatches to the correct +backend (:class:`~isaaclab_physx.sim.views.FabricFrameView` for PhysX, +:class:`~isaaclab_newton.sim.views.NewtonSiteFrameView` for Newton) based on the active +physics backend. The deprecated ``XformPrimView`` alias continues to work but will be +removed in a future release. + + Unchanged Imports ----------------- @@ -113,11 +156,21 @@ The following sensor classes also remain in the ``isaaclab`` package with unchan - :class:`~isaaclab.sensors.ContactSensor`, :class:`~isaaclab.sensors.ContactSensorCfg`, :class:`~isaaclab.sensors.ContactSensorData` - :class:`~isaaclab.sensors.Imu`, :class:`~isaaclab.sensors.ImuCfg`, :class:`~isaaclab.sensors.ImuData` +- :class:`~isaaclab.sensors.Pva`, :class:`~isaaclab.sensors.PvaCfg`, :class:`~isaaclab.sensors.PvaData` - :class:`~isaaclab.sensors.FrameTransformer`, :class:`~isaaclab.sensors.FrameTransformerCfg`, :class:`~isaaclab.sensors.FrameTransformerData` +- :class:`~isaaclab.sensors.JointWrenchSensor`, :class:`~isaaclab.sensors.JointWrenchSensorCfg`, + :class:`~isaaclab.sensors.JointWrenchSensorData` These sensor classes now use factory patterns that automatically instantiate the appropriate backend implementation (PhysX by default), maintaining full backward compatibility. +.. note:: + + The ``Imu`` sensor in Isaac Lab 3.0 is **not** the same as the ``Imu`` sensor in 2.x. + The old ``Imu`` (full state sensor) has been renamed to :class:`~isaaclab.sensors.Pva`. + The new :class:`~isaaclab.sensors.Imu` is a lightweight sensor that only provides angular velocity + and linear acceleration. See :ref:`imu-to-pva-migration` below for details. + If you need to import the PhysX sensor implementations directly (e.g., for type hints or subclassing), you can import from ``isaaclab_physx.sensors``: @@ -126,7 +179,9 @@ you can import from ``isaaclab_physx.sensors``: # Direct PhysX implementation imports from isaaclab_physx.sensors import ContactSensor, ContactSensorData from isaaclab_physx.sensors import Imu, ImuData + from isaaclab_physx.sensors import Pva, PvaData from isaaclab_physx.sensors import FrameTransformer, FrameTransformerData + from isaaclab_physx.sensors import JointWrenchSensor, JointWrenchSensorData New ``isaaclab_newton`` Extension @@ -136,6 +191,8 @@ A new extension ``isaaclab_newton`` provides Newton physics backend implementati - :class:`~isaaclab_newton.assets.Articulation` and :class:`~isaaclab_newton.assets.ArticulationData` - :class:`~isaaclab_newton.assets.RigidObject` and :class:`~isaaclab_newton.assets.RigidObjectData` +- :class:`~isaaclab_newton.sensors.JointWrenchSensor` and + :class:`~isaaclab_newton.sensors.JointWrenchSensorData` These classes implement the same base interfaces as their PhysX counterparts (:class:`~isaaclab.assets.BaseArticulation`, :class:`~isaaclab.assets.BaseRigidObject`), @@ -156,11 +213,102 @@ If you need to import Newton implementations directly (e.g., for type hints or s from isaaclab_newton.assets import RigidObject as NewtonRigidObject +Deformable Object API Changes +------------------------------ + +Isaac Lab 3.0 updates the deformable body API to align with the current Omni Physics 110.0 +release. The old soft body API has been deprecated and replaced by two distinct deformable +types: **volume deformables** (3D FEM tetrahedral meshes) and **surface deformables** (2D +triangle cloth meshes). The deformable type is determined by the physics material assigned: + +- :class:`~isaaclab_physx.sim.DeformableBodyMaterialCfg` for volume deformables. +- :class:`~isaaclab_physx.sim.SurfaceDeformableBodyMaterialCfg` for surface deformables. + +All deformable-related classes have moved from ``isaaclab`` to ``isaaclab_physx``, as shown +in the import table above. Several properties on +:class:`~isaaclab_physx.sim.DeformableBodyPropertiesCfg` have been removed or added to match +the new Omni Physics schema. + +For a comprehensive guide covering the full deformable API migration — including removed and +added properties, material changes, code examples for both volume and surface deformables, and +current limitations — see :ref:`migrating-deformables`. + + +.. _imu-to-pva-migration: + +IMU Sensor Renamed to PVA; New Lightweight IMU Sensor +----------------------------------------------------- + +The old ``Imu`` sensor has been renamed to **PVA** (Pose Velocity Acceleration) because it provided +full pose, velocity, and acceleration data — far more than a real inertial measurement unit measures. +A new lightweight **IMU** sensor has been introduced that only provides the two physical quantities +a real IMU measures: angular velocity (gyroscope) and linear acceleration (accelerometer). + +If you were using the old ``Imu`` sensor, you need to decide which new sensor to use: + +- Use :class:`~isaaclab.sensors.Pva` / :class:`~isaaclab.sensors.PvaCfg` if you need full state + data (pose, linear velocity, angular velocity, linear and angular acceleration, projected gravity). +- Use :class:`~isaaclab.sensors.Imu` / :class:`~isaaclab.sensors.ImuCfg` if you only need angular + velocity and linear acceleration (as a real IMU provides). + +**Import changes:** + +.. code-block:: python + + # Before (Isaac Lab 2.x) — the old IMU provided full state + from isaaclab.sensors import Imu, ImuCfg, ImuData + + # After (Isaac Lab 3.x) — use PVA for the same full-state sensor + from isaaclab.sensors import Pva, PvaCfg, PvaData + + # Or use the new lightweight IMU for angular velocity + linear acceleration only + from isaaclab.sensors import Imu, ImuCfg, ImuData + +**Configuration changes:** + +The ``gravity_bias`` configuration parameter has been removed from both sensors: + +- **PVA** reports raw kinematic acceleration (no gravity contribution), as the acceleration + is derived from finite differencing of velocities which do not include gravity. +- **IMU** unconditionally includes gravity in its accelerometer readings, matching the behavior + of a real accelerometer. The gravity vector is automatically queried from the simulation. + +.. code-block:: python + + # Before (Isaac Lab 2.x) + imu_cfg = ImuCfg( + prim_path="{ENV_REGEX_NS}/Robot/base", + gravity_bias=(0.0, 0.0, 9.81), # had to be configured manually + ) + + # After (Isaac Lab 3.x) — PVA (no gravity in acceleration) + pva_cfg = PvaCfg(prim_path="{ENV_REGEX_NS}/Robot/base") + + # After (Isaac Lab 3.x) — IMU (gravity always included automatically) + imu_cfg = ImuCfg(prim_path="{ENV_REGEX_NS}/Robot/base") + +**Observation function changes:** + +.. code-block:: python + + # Before (Isaac Lab 2.x) + from isaaclab.envs.mdp import imu_orientation, imu_projected_gravity + + # After (Isaac Lab 3.x) + from isaaclab.envs.mdp import pva_orientation, pva_projected_gravity + +**Data property changes:** + +The new ``ImuData`` only provides ``ang_vel_b`` and ``lin_acc_b``. If you were accessing other +properties (``pos_w``, ``quat_w``, ``lin_vel_b``, ``ang_acc_b``, ``projected_gravity_b``), switch +to :class:`~isaaclab.sensors.PvaData` which provides all of them. + + Sensor Pose Properties Deprecation ---------------------------------- The ``pose_w``, ``pos_w``, and ``quat_w`` properties on :class:`~isaaclab.sensors.ContactSensorData` -and :class:`~isaaclab.sensors.ImuData` are deprecated and will be removed in a future release. +are deprecated and will be removed in a future release. If you need to track sensor poses in world frame, please use a dedicated sensor such as :class:`~isaaclab.sensors.FrameTransformer` instead. @@ -188,6 +336,75 @@ If you need to track sensor poses in world frame, please use a dedicated sensor sensor_quat = frame_transformer.data.target_quat_w +Articulation Joint Wrench Data Moved to ``JointWrenchSensor`` +------------------------------------------------------------- + +The ``ArticulationData.body_incoming_joint_wrench_b`` property has been removed. In +Isaac Lab 3.0, incoming joint reaction wrenches are exposed through +:class:`~isaaclab.sensors.JointWrenchSensor`, which has PhysX and Newton backend +implementations and returns separate force [N] and torque [N·m] buffers. +The sensor reports wrenches in the child-side incoming joint frame, with torque +referenced at the child-side joint anchor. + +**Before (Isaac Lab 2.x):** + +.. code-block:: python + + wrench_b = robot.data.body_incoming_joint_wrench_b.torch[:, body_ids] + +**After (Isaac Lab 3.x):** + +.. code-block:: python + + import torch + from isaaclab.scene import InteractiveSceneCfg + from isaaclab.sensors import JointWrenchSensorCfg + + class MySceneCfg(InteractiveSceneCfg): + robot = ROBOT_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") + joint_wrench = JointWrenchSensorCfg(prim_path="{ENV_REGEX_NS}/Robot") + + sensor = env.scene.sensors["joint_wrench"] + data = sensor.data + wrench_j = torch.cat( + ( + data.force.torch[:, body_ids], + data.torque.torch[:, body_ids], + ), + dim=-1, + ) + +Use :attr:`~isaaclab.sensors.BaseJointWrenchSensor.body_names` or +:meth:`~isaaclab.sensors.BaseJointWrenchSensor.find_bodies` to map sensor entries to +articulation body names. PhysX reports one entry for every link, including the articulation +root link. Newton reports the child bodies of reportable incoming joints. + +For manager-based environments, update observations that used the articulation data property to +depend on the joint-wrench sensor instead: + +.. code-block:: python + + import isaaclab.envs.mdp as mdp + from isaaclab.managers import SceneEntityCfg + from isaaclab.managers import ObservationTermCfg as ObsTerm + from isaaclab.scene import InteractiveSceneCfg + from isaaclab.sensors import JointWrenchSensorCfg + + class MySceneCfg(InteractiveSceneCfg): + robot = ROBOT_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") + joint_wrench = JointWrenchSensorCfg(prim_path="{ENV_REGEX_NS}/Robot") + + feet_body_forces = ObsTerm( + func=mdp.body_incoming_wrench, + params={ + "sensor_cfg": SceneEntityCfg( + "joint_wrench", + body_names=["left_foot", "right_foot"], + ) + }, + ) + + Multi-Backend Support: PresetCfg Pattern ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -213,17 +430,17 @@ when no CLI override is given. Other fields are named presets selectable with class MyPhysicsCfg(PresetCfg): default: PhysxCfg = PhysxCfg(...) # used when no override is given physx: PhysxCfg = PhysxCfg(...) # selected by presets=physx - newton: NewtonCfg = NewtonCfg(...) # selected by presets=newton + newton_mjwarp: NewtonCfg = NewtonCfg(...) # selected by presets=newton_mjwarp Selecting a preset at launch ----------------------------- -Pass ``presets=newton`` (or ``presets=physx``) on the CLI to swap the entire config section: +Pass ``presets=newton_mjwarp`` (or ``presets=physx``) on the CLI to swap the entire config section: .. code-block:: bash # Run with Newton backend - python train.py task=Isaac-Franka-Cabinet-v0 presets=newton + python train.py task=Isaac-Franka-Cabinet-v0 presets=newton_mjwarp # Run with default (PhysX) backend python train.py task=Isaac-Franka-Cabinet-v0 @@ -256,7 +473,7 @@ subclass that carries both a PhysX and a Newton variant. class ReachPhysicsCfg(PresetCfg): default: PhysxCfg = PhysxCfg(bounce_threshold_velocity=0.2) physx: PhysxCfg = PhysxCfg(bounce_threshold_velocity=0.2) - newton: NewtonCfg = NewtonCfg( + newton_mjwarp: NewtonCfg = NewtonCfg( solver_cfg=MJWarpSolverCfg( njmax=20, nconmax=20, ls_iterations=20, cone="pyramidal", ls_parallel=True, @@ -328,7 +545,7 @@ We can provide a Newton-specific config such as: class EnvEventCfg(PresetCfg): default: EventCfg = EventCfg() physx: EventCfg = EventCfg() - newton: _EnvNewtonEventCfg = _EnvNewtonEventCfg() + newton_mjwarp: _EnvNewtonEventCfg = _EnvNewtonEventCfg() Then change the ``events`` field in your env cfg from ``EventCfg`` to ``EnvEventCfg``: @@ -746,6 +963,56 @@ Best Practices for Migration 6. **Check documentation** - Update any docs or comments that mention quaternion format. + +Using the Runtime Quaternion Access Detector +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The quaternion finder tool above covers hard-coded values in source files, +but it cannot see quaternions that are *read* from asset/sensor data at +runtime. For those, Isaac Lab ships a +runtime detector hook on :class:`~isaaclab.utils.warp.ProxyArray` that flags +every ``.torch`` access on a ``wp.quatf``-typed property and points at the +exact call site. Use it after the source-level migration to catch the cases +the finder tool can't reach. + +Enable it by setting an environment variable before launching your script: + +.. code-block:: bash + + export WARN_ON_TORCH_QUATF_ACCESS=1 + ./isaaclab.sh -p my_script.py + +Every read of ``.torch`` on a ``ProxyArray`` whose underlying ``wp.array`` has +dtype ``wp.quatf`` then emits a :class:`UserWarning` with the message: + +.. code-block:: text + + Reading .torch on a wp.quatf-typed ProxyArray. The Isaac Lab quaternion + convention changed from (w, x, y, z) in 2.x to (x, y, z, w) in 3.x. If + your code assumes the old order, this is likely the source of incorrect + rotations. Unset WARN_ON_TORCH_QUATF_ACCESS to silence this warning. + +The warning's traceback points at the exact line that performed the access +(via ``stacklevel=2``), so you can walk through the matches in your code and +confirm each one uses the new ``(x, y, z, w)`` order. + +Typical workflow: + +1. Run a representative scene or task with the env var set. +2. Triage every warning location — check whether the call site assumes + ``(w, x, y, z)`` (Lab 2.x) or ``(x, y, z, w)`` (Lab 3.x). +3. Migrate the call sites that still expect the old order. +4. Re-run with the env var still set; the warnings should be gone (or only + come from intentionally-handled call sites). +5. Unset the env var for production runs — the detector adds an + ``os.environ`` lookup per ``.torch`` access, which is cheap but not free. + +The detector covers only ``ProxyArray.torch`` reads. Direct accesses on the +underlying ``wp.array`` (via ``ProxyArray.warp``) are not flagged, because +warp uses ``(x, y, z, w)`` natively and so a warp-side read is unaffected +by the convention change. + + API Changes ~~~~~~~~~~~ @@ -779,37 +1046,36 @@ quaternions in XYZW format: - And all other quaternion utilities -Warp Backend for Asset and Sensor Data -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +ProxyArray Backend for Asset and Sensor Data +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -All ``.data.*`` properties on asset and sensor classes now return ``wp.array`` instead of -``torch.Tensor``. This change applies to all asset classes (:class:`~isaaclab.assets.Articulation`, +All ``.data.*`` properties on asset and sensor classes now return +:class:`~isaaclab.utils.warp.ProxyArray` instead of ``torch.Tensor``. ``ProxyArray`` wraps +the underlying ``wp.array`` and exposes explicit ``.torch`` and ``.warp`` accessors. This +change applies to all asset classes (:class:`~isaaclab.assets.Articulation`, :class:`~isaaclab.assets.RigidObject`, :class:`~isaaclab.assets.RigidObjectCollection`, :class:`~isaaclab_physx.assets.DeformableObject`) and all sensor classes (:class:`~isaaclab_physx.sensors.ContactSensor`, :class:`~isaaclab_physx.sensors.Imu`, -:class:`~isaaclab_physx.sensors.FrameTransformer`). +:class:`~isaaclab_physx.sensors.Pva`, :class:`~isaaclab_physx.sensors.FrameTransformer`). -To convert back to ``torch.Tensor`` for use with PyTorch operations, wrap the property -access with ``wp.to_torch()``: +To use a data property as a ``torch.Tensor``, append ``.torch``: .. code-block:: python - import warp as wp - # Before (Isaac Lab 2.x) root_pos = robot.data.root_pos_w # torch.Tensor joint_pos = robot.data.joint_pos # torch.Tensor contact_forces = sensor.data.net_forces_w # torch.Tensor # After (Isaac Lab 3.x) - root_pos = robot.data.root_pos_w # wp.array - joint_pos = robot.data.joint_pos # wp.array - contact_forces = sensor.data.net_forces_w # wp.array + root_pos = robot.data.root_pos_w # ProxyArray + joint_pos = robot.data.joint_pos # ProxyArray + contact_forces = sensor.data.net_forces_w # ProxyArray - # To use with torch operations, wrap with wp.to_torch() - root_pos_torch = wp.to_torch(robot.data.root_pos_w) # torch.Tensor - joint_pos_torch = wp.to_torch(robot.data.joint_pos) # torch.Tensor - contact_torch = wp.to_torch(sensor.data.net_forces_w) # torch.Tensor + # To use with torch operations, access .torch + root_pos_torch = robot.data.root_pos_w.torch # torch.Tensor + joint_pos_torch = robot.data.joint_pos.torch # torch.Tensor + contact_torch = sensor.data.net_forces_w.torch # torch.Tensor Common patterns that need updating: @@ -819,19 +1085,19 @@ Common patterns that need updating: # Before: pos = robot.data.root_pos_w.clone() # After: - pos = wp.to_torch(robot.data.root_pos_w).clone() + pos = robot.data.root_pos_w.torch.clone() # Creating zero tensors with matching shape # Before: zeros = torch.zeros_like(robot.data.root_pos_w) # After: - zeros = torch.zeros_like(wp.to_torch(robot.data.root_pos_w)) + zeros = torch.zeros_like(robot.data.root_pos_w.torch) # Assertions in tests # Before: torch.testing.assert_close(robot.data.root_pos_w, expected) # After: - torch.testing.assert_close(wp.to_torch(robot.data.root_pos_w), expected) + torch.testing.assert_close(robot.data.root_pos_w.torch, expected) .. list-table:: Affected classes :header-rows: 1 @@ -851,25 +1117,146 @@ Common patterns that need updating: - ``isaaclab_physx`` * - :class:`~isaaclab_physx.sensors.Imu` - ``isaaclab_physx`` + * - :class:`~isaaclab_physx.sensors.Pva` + - ``isaaclab_physx`` * - :class:`~isaaclab_physx.sensors.FrameTransformer` - ``isaaclab_physx`` + * - :class:`~isaaclab.sensors.RayCaster` + - ``isaaclab`` + * - :class:`~isaaclab.sensors.RayCasterCamera` + - ``isaaclab`` + * - :class:`~isaaclab.sensors.MultiMeshRayCaster` + - ``isaaclab`` + * - :class:`~isaaclab.sensors.MultiMeshRayCasterCamera` + - ``isaaclab`` .. note:: - An automated migration tool is provided at ``scripts/tools/wrap_warp_to_torch.py``. - It scans Python files for ``.data.`` accesses and wraps them with - ``wp.to_torch()``. Usage: + ``wp.to_torch(proxy_array)`` is temporarily supported by a compatibility shim. It returns + the same zero-copy tensor as ``proxy_array.torch`` and emits a one-time + ``DeprecationWarning``. This shim exists for older migration code and will be removed in a + future release; prefer ``.torch`` in new code. - .. code-block:: bash - # Dry run (preview changes) - python scripts/tools/wrap_warp_to_torch.py path/to/your/code --dry-run +Ray Caster Warp Backend +~~~~~~~~~~~~~~~~~~~~~~~ + +The :class:`~isaaclab.sensors.RayCaster`, :class:`~isaaclab.sensors.RayCasterCamera`, +:class:`~isaaclab.sensors.MultiMeshRayCaster`, and +:class:`~isaaclab.sensors.MultiMeshRayCasterCamera` sensors have been transitioned from a +PyTorch/USD-based backend to a native Warp kernel pipeline. This improves performance by +eliminating per-step tensor allocations and torch-to-warp conversions, but introduces several +breaking changes. - # Apply changes in-place - python scripts/tools/wrap_warp_to_torch.py path/to/your/code - Always review the changes after running the tool, as some accesses (e.g., those - already passed to warp-native functions) should not be wrapped. +RayCasterData Return Types +-------------------------- + +The :attr:`~isaaclab.sensors.RayCasterData.pos_w`, +:attr:`~isaaclab.sensors.RayCasterData.quat_w`, and +:attr:`~isaaclab.sensors.RayCasterData.ray_hits_w` properties now return +:class:`~isaaclab.utils.warp.ProxyArray` instead of ``torch.Tensor``. This follows the same +pattern as the general ProxyArray backend migration described above. + +.. code-block:: python + + # Before (Isaac Lab 2.x) + ray_hits = ray_caster.data.ray_hits_w # torch.Tensor + sensor_pos = ray_caster.data.pos_w # torch.Tensor + + # After (Isaac Lab 3.x) + ray_hits = ray_caster.data.ray_hits_w # ProxyArray + sensor_pos = ray_caster.data.pos_w # ProxyArray + + # To use with torch operations, access .torch + ray_hits_torch = ray_caster.data.ray_hits_w.torch + sensor_pos_torch = ray_caster.data.pos_w.torch + + +Ray Alignment Configuration +---------------------------- + +The ``attach_yaw_only`` boolean parameter on :class:`~isaaclab.sensors.RayCasterCfg` has been +deprecated in favor of the new ``ray_alignment`` parameter, which accepts one of three string +values: + +.. list-table:: + :header-rows: 1 + :widths: 30 30 40 + + * - Old (2.x) + - New (3.0) + - Behavior + * - ``attach_yaw_only=False`` + - ``ray_alignment="base"`` + - Rays follow the full sensor orientation. + * - ``attach_yaw_only=True`` + - ``ray_alignment="yaw"`` + - Rays follow only the yaw component of the sensor orientation. + * - *(not available)* + - ``ray_alignment="world"`` + - Rays are always cast in the world frame (no rotation applied). + +.. code-block:: python + + # Before (Isaac Lab 2.x) + cfg = RayCasterCfg(attach_yaw_only=True, ...) + + # After (Isaac Lab 3.x) + cfg = RayCasterCfg(ray_alignment="yaw", ...) + + +Raycasting Kernel Signature Change +----------------------------------- + +The :func:`~isaaclab.utils.warp.kernels.raycast_dynamic_meshes_kernel` Warp kernel now requires +an ``env_mask`` parameter as its first argument. This is a ``wp.array(dtype=wp.bool)`` that +controls which environments are updated. The public Python wrapper +:func:`~isaaclab.utils.warp.ops.raycast_dynamic_meshes` has been updated to inject an all-True +mask automatically, so code using the wrapper is unaffected. + +If you call the kernel directly, update your launch call: + +.. code-block:: python + + import warp as wp + + # Before (Isaac Lab 2.x) + wp.launch( + raycast_dynamic_meshes_kernel, + dim=(num_meshes, num_envs, num_rays), + inputs=[ray_starts, ray_directions, mesh_ids, ...], + ) + + # After (Isaac Lab 3.x) -- env_mask is now the first input + env_mask = wp.ones(num_envs, dtype=wp.bool, device=device) + wp.launch( + raycast_dynamic_meshes_kernel, + dim=(num_meshes, num_envs, num_rays), + inputs=[env_mask, ray_starts, ray_directions, mesh_ids, ...], + ) + + +RayCaster.meshes Cache Key +-------------------------- + +The :attr:`~isaaclab.sensors.RayCaster.meshes` class variable, which caches warp meshes across +all :class:`~isaaclab.sensors.RayCaster` instances, is now keyed by ``(prim_path, device)`` tuples +instead of by ``prim_path`` alone. This prevents a mesh that was built on one device (e.g. CPU) +from being reused by a sensor running on a different device (e.g. CUDA), which caused illegal +memory accesses on systems without unified memory. + +Code that reads or writes this cache directly must update both the type annotation and the key: + +.. code-block:: python + + # Before (Isaac Lab 2.x) + meshes: ClassVar[dict[str, wp.Mesh]] = {} + wp_mesh = RayCaster.meshes[prim_path] + + # After (Isaac Lab 3.x) + meshes: ClassVar[dict[tuple[str, str], wp.Mesh]] = {} + wp_mesh = RayCaster.meshes[(prim_path, device)] Write Method Index/Mask Split @@ -1396,6 +1783,204 @@ Deprecated retargeters have been moved to ``isaaclab_teleop.deprecated.openxr.re compatibility. These will be removed in a future release. +.. _torcharray-migration: + +ProxyArray Interop and Temporary Compatibility +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Asset and sensor data class properties return :class:`~isaaclab.utils.warp.ProxyArray`, a +lightweight wrapper with explicit ``.torch`` and ``.warp`` accessors: + +.. code-block:: python + + # BEFORE (2.x) — properties returned torch.Tensor directly + joint_pos = robot.data.joint_pos # torch.Tensor + root_pos = robot.data.root_pos_w # torch.Tensor + + # AFTER (3.0) — properties return ProxyArray, use .torch for the tensor + joint_pos = robot.data.joint_pos.torch # cached zero-copy torch.Tensor + root_pos = robot.data.root_pos_w.torch # cached zero-copy torch.Tensor + joint_pos_warp = robot.data.joint_pos.warp # the underlying warp.array + +**Automatic interop — in many cases, no changes are needed:** + +- **Warp kernels:** ``ProxyArray`` implements ``__cuda_array_interface__``, so it can be passed + directly to ``wp.launch()`` without calling ``.warp``: + + .. code-block:: python + + # Just works — no .warp needed + wp.launch(my_kernel, inputs=[robot.data.joint_pos], ...) + +- **Torch functions:** ``ProxyArray`` implements ``__torch_function__``, so ``torch.*`` operations + accept it directly. During the deprecation period this emits a one-time warning, but works: + + .. code-block:: python + + # Works (emits DeprecationWarning once, then silent) + mean_pos = torch.mean(robot.data.joint_pos, dim=1) + clipped = torch.clamp(robot.data.joint_pos, -3.14, 3.14) + +**What to change:** + +1. Append ``.torch`` where you need an explicit ``torch.Tensor`` (e.g., for indexing, slicing, + or passing to non-torch libraries). +2. Warp kernel calls need no changes — ``ProxyArray`` works transparently. +3. If you need the underlying ``warp.array`` (e.g., for ``ptr``, ``strides``), use ``.warp``. +4. Replace legacy ``wp.to_torch(proxy_array)`` calls with ``proxy_array.torch``. + +.. note:: + + The ``__torch_function__`` bridge and the temporary ``wp.to_torch(proxy_array)`` shim will + be removed in a future release. We recommend migrating to explicit ``.torch`` access now. + +For a complete guide, see :doc:`/source/how-to/proxy_array`. + + +Migration off Deprecated Isaac Sim APIs +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +In Isaac Sim 6.0, the legacy ``isaacsim.core.*``, ``isaacsim.sensors.*``, and +``isaacsim.robot.wheeled_robots`` Python module paths are **deprecated** in favor of their +``isaacsim.core.experimental.*`` (and ``*.experimental.*``) equivalents. Isaac Lab 3.0 has +been migrated off the deprecated paths so that Isaac Lab continues to load and run when +those modules are removed in a future Isaac Sim release. + +This is mostly a transparent change for users — Isaac Lab's own public Python API +(:mod:`isaaclab`, :mod:`isaaclab_physx`, :mod:`isaaclab_tasks`, :mod:`isaaclab_teleop`, +:mod:`isaaclab_mimic`) is unchanged. The migration is only user-visible if you: + +1. Import Isaac Sim symbols **directly** in your project, or +2. Maintain a custom Kit experience (``.kit`` file) that lists Isaac Sim extension + dependencies, or +3. Imported ``SimulationManager`` from ``isaacsim.core.simulation_manager`` in your own + PhysX-backed code. + + +Python module renames +--------------------- + +Update direct imports in your own code as follows. **Where Isaac Lab provides an in-tree +replacement, prefer the Isaac Lab API** over the ``isaacsim.core.experimental.*`` fallback: + +.. list-table:: + :header-rows: 1 + :widths: 45 55 + + * - Deprecated Isaac Sim path + - Recommended replacement + * - ``isaacsim.core.utils.stage`` + - :mod:`isaaclab.sim.utils.stage` (e.g. ``get_current_stage``, + ``create_new_stage``, ``open_stage``, ``save_stage``, ``close_stage``, + ``clear_stage``, ``update_stage``, ``use_stage``) + * - ``isaacsim.core.utils.prims`` + - :mod:`isaaclab.sim.utils.prims` (e.g. ``create_prim``, ``delete_prim``, + ``change_prim_property``, ``bind_visual_material``, + ``bind_physics_material``, ``add_usd_reference``) + * - ``isaacsim.core.utils.queries`` + - :mod:`isaaclab.sim.utils.queries` (e.g. ``find_matching_prims``, + ``find_matching_prim_paths``, ``get_first_matching_child_prim``) + * - ``isaacsim.core.utils.transforms`` + - :mod:`isaaclab.sim.utils.transforms` + * - ``isaacsim.core.utils.semantics`` + - :mod:`isaaclab.sim.utils.semantics` + * - ``isaacsim.core.utils.extensions.enable_extension`` + - ``isaacsim.core.experimental.utils.app.enable_extension`` (no Isaac Lab equivalent) + * - ``isaacsim.core.utils.viewports.set_camera_view`` + - ``isaacsim.core.rendering_manager.ViewportManager.set_camera_view`` (or + ``omni.kit.viewport.utility.camera_state.ViewportCameraState`` for lower-level control) + * - ``isaacsim.core.prims.XFormPrim`` / ``XFormPrimView`` + - :class:`~isaaclab.sim.views.FrameView` (Isaac Lab in-tree view; see + :ref:`migrating-to-isaaclab-3-0` ``Renaming of XformPrimView to FrameView`` above). + For ``Articulation`` / ``RigidPrim`` use ``isaacsim.core.experimental.prims``. + * - ``isaacsim.core.simulation_manager.SimulationManager`` + - :class:`isaaclab_physx.physics.PhysxManager` (PhysX backend) or + ``isaaclab_newton.physics.NewtonManager`` (Newton backend); see local-alias + pattern below. + * - ``isaacsim.core.cloner`` + - :mod:`isaaclab.cloner` (Isaac Lab in-tree cloner) + * - ``isaacsim.replicator.mobility_gen`` + - ``isaacsim.replicator.experimental.mobility_gen`` + * - ``isaacsim.sensors.`` + - ``isaacsim.sensors.experimental.`` + * - ``isaacsim.robot.wheeled_robots`` + - ``isaacsim.robot.experimental.wheeled_robots`` (and + ``isaacsim.robot.wheeled_robots.nodes`` for OmniGraph nodes) + +To keep call-site code symmetric across backends when migrating off +``isaacsim.core.simulation_manager.SimulationManager``, use the local-alias pattern: + +.. code-block:: python + + from isaaclab_physx.physics import PhysxManager as SimulationManager + # or, for the Newton backend + from isaaclab_newton.physics import NewtonManager as SimulationManager + + +Kit experience (``.kit``) updates +--------------------------------- + +If you maintain a custom Kit experience derived from one of the Isaac Lab apps under +``apps/``: + +* **Stop registering deprecated extension search paths.** The ``extsDeprecated`` search + path entry has been removed from all stock Isaac Lab Kit experiences (headless, + rendering, XR variants). Mirror that change in your own experience. +* **Switch explicit Isaac Sim extension dependencies** to the non-deprecated equivalents + listed above (``isaacsim.core.experimental.*``, ``isaacsim.sensors.experimental.*``, + ``isaacsim.robot.experimental.wheeled_robots``). +* **Remove unused Isaac Sim extensions that pull in** ``isaacsim.core.api`` — Isaac Lab + no longer depends on those, and keeping them resurrects the deprecated stack. + + +``SimulationManager`` is no longer re-exported +---------------------------------------------- + +Earlier internal previews of this migration briefly exposed +``isaaclab_physx.physics.SimulationManager`` as a public alias of +:class:`~isaaclab_physx.physics.PhysxManager`. **That alias has been removed**; use +:class:`~isaaclab_physx.physics.PhysxManager` directly (with ``as SimulationManager`` at +the import site if you want backend-agnostic call-site code, as shown above). + + +Retired standalone reproducers +------------------------------ + +A handful of legacy reproducers under ``source/isaaclab/test/deps/isaacsim`` that +depended on the deprecated Isaac Sim core extensions have been retired: +``check_camera.py``, ``check_floating_base_made_fixed.py``, +``check_legged_robot_clone.py``, ``check_rep_texture_randomizer.py``, and +``check_ref_count.py``. Use :mod:`isaaclab.sim` together with the new +``isaacsim.core.experimental.*`` APIs for the same debugging workflows. + + +PhysX Tensors API Module Path +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Recent Isaac Sim releases removed the internal ``impl`` submodule of +``omni.physics.tensors`` and now expose the PhysX Tensor API types +(``ArticulationView``, ``RigidBodyView``, ``SimulationView``, etc.) directly +under ``omni.physics.tensors.api``. Importing from the old path raises +``ModuleNotFoundError: No module named 'omni.physics.tensors.impl'`` at import +time. + +Isaac Lab has been updated to import from the new path. Downstream code +(custom assets, sensors, or scripts) that imported from the old path must be +updated: + +.. code-block:: python + + # Before (Isaac Lab 2.x / older Isaac Sim) + import omni.physics.tensors.impl.api as physx + + # After (Isaac Lab 3.x / current Isaac Sim) + import omni.physics.tensors.api as physx + +The class identities are unchanged — only the module path moved. Type hints +referencing the old path (``omni.physics.tensors.impl.api.ArticulationView``) +should be similarly updated to ``omni.physics.tensors.api.ArticulationView``. + + Need Help? ~~~~~~~~~~ diff --git a/docs/source/overview/core-concepts/multi_backend_architecture.rst b/docs/source/overview/core-concepts/multi_backend_architecture.rst index c9821ebf4a64..8fd0e326437f 100644 --- a/docs/source/overview/core-concepts/multi_backend_architecture.rst +++ b/docs/source/overview/core-concepts/multi_backend_architecture.rst @@ -148,7 +148,7 @@ Environments can support multiple backends simultaneously using the :doc:`preset class CartpolePhysicsCfg(PresetCfg): default: PhysxCfg = PhysxCfg() physx: PhysxCfg = PhysxCfg() - newton: NewtonCfg = NewtonCfg( + newton_mjwarp: NewtonCfg = NewtonCfg( solver_cfg=MJWarpSolverCfg(njmax=5, nconmax=3) ) @@ -156,15 +156,15 @@ Environments can support multiple backends simultaneously using the :doc:`preset class CartpoleEnvCfg(ManagerBasedRLEnvCfg): sim: SimulationCfg = SimulationCfg(physics=CartpolePhysicsCfg()) -Users then select a backend at the command line: +Users then select the MJWarp Newton preset at the command line: .. code-block:: bash # Default (PhysX) python train.py --task Isaac-Cartpole-v0 - # Newton - python train.py --task Isaac-Cartpole-v0 presets=newton + # MJWarp (Newton backend) + python train.py --task Isaac-Cartpole-v0 presets=newton_mjwarp The Physics Manager ------------------- diff --git a/docs/source/overview/core-concepts/renderers.rst b/docs/source/overview/core-concepts/renderers.rst index 4971e7a1d0cf..2ae8bae28af3 100644 --- a/docs/source/overview/core-concepts/renderers.rst +++ b/docs/source/overview/core-concepts/renderers.rst @@ -39,25 +39,35 @@ The renderer system consists of: 2. **Renderer** — Factory that instantiates the appropriate backend based on renderer configuration class 3. **RendererCfg** — Base configuration; each backend extends it with backend-specific options 4. **Concrete implementations** — Backend-specific renderers in extension packages +5. **RenderContext** — A management class for instantiating and accessing renderer instances using a **RendererCfg**. + After instantiation, a config can then be used to acquire the instance of the renderer as needed. .. code-block:: python - from isaaclab.renderers import BaseRenderer, Renderer + import isaaclab.sim as sim_utils + from isaaclab.renderers import BaseRenderer from isaaclab_newton.renderers import NewtonWarpRendererCfg # Create a Newton Warp renderer (no Isaac Sim required) - renderer: BaseRenderer = Renderer(NewtonWarpRendererCfg()) + sim_ctx = sim_utils.SimulationContext.instance() + # RenderContext.get_renderer will instantiate the renderer backend + # or return an existing renderer with a matching config + renderer: BaseRenderer = sim_ctx.render_context.get_renderer(NewtonWarpRendererCfg()) assert isinstance(renderer, BaseRenderer) For the RTX renderer (requires Isaac Sim): .. code-block:: python - from isaaclab.renderers import Renderer - from isaaclab.renderers import IsaacRtxRendererCfg # or OVRTXRendererCfg + import isaaclab.sim as sim_utils + from isaaclab.renderers import BaseRenderer + from isaaclab_physx.renderers import IsaacRtxRendererCfg # Create an RTX renderer - renderer: BaseRenderer = Renderer(IsaacRtxRendererCfg()) + sim_ctx = sim_utils.SimulationContext.instance() + # RenderContext.get_renderer will instantiate the renderer backend + # or return an existing renderer with a matching config + renderer: BaseRenderer = sim_ctx.render_context.get_renderer(IsaacRtxRendererCfg()) For RTX renderer settings and presets (quality, balanced, performance), see :doc:`/source/how-to/configure_rendering`. @@ -65,8 +75,8 @@ For RTX renderer settings and presets (quality, balanced, performance), see Core concepts ------------- -- **Use the factory**: Always instantiate renderers via the factory with a renderer-specific config class - (e.g. ``Renderer(IsaacRtxRendererCfg())``). Do not import or instantiate concrete backend classes +- **Use the RenderContext**: Always instantiate renderers via the RenderContext with a renderer-specific config class + (e.g. ``sim_ctx.render_context.get_renderer(IsaacRtxRendererCfg())``). Do not import or instantiate concrete backend classes (e.g. ``IsaacRtxRenderer``, ``OVRTXRenderer``) directly—their names and package locations are implementation details and may change without notice. @@ -76,11 +86,14 @@ Core concepts .. code-block:: python + import isaaclab.sim as sim_utils + from isaaclab.renderers import BaseRenderer # Lightweight: does not import OVRTX backend dependencies from isaaclab_ov.renderers import OVRTXRendererCfg # Lazily loads ovrtx when instantiated; may fail if isaaclab_ov / ovrtx is not installed - renderer: BaseRenderer = Renderer(OVRTXRendererCfg()) + sim_ctx = sim_utils.SimulationContext.instance() + renderer: BaseRenderer = sim_ctx.render_context.get_renderer(OVRTXRendererCfg()) Installing the OVRTX renderer ------------------------------ diff --git a/docs/source/overview/core-concepts/scene_data_providers.rst b/docs/source/overview/core-concepts/scene_data_providers.rst index 684dfcefcbef..527c59a03c12 100644 --- a/docs/source/overview/core-concepts/scene_data_providers.rst +++ b/docs/source/overview/core-concepts/scene_data_providers.rst @@ -27,9 +27,9 @@ The system has three layers: 1. **BaseSceneDataProvider** — abstract interface defining the contract: - - ``update(env_ids)`` — refresh cached scene data + - ``update()`` — refresh cached scene data (full Newton model/state sync when applicable) - ``get_newton_model()`` — return Newton model handle (if available) - - ``get_newton_state(env_ids)`` — return Newton state handle (if available) + - ``get_newton_state()`` — return Newton state handle (if available) - ``get_usd_stage()`` — return USD stage handle (if available) - ``get_transforms()`` — return body transforms - ``get_velocities()`` — return body velocities @@ -55,7 +55,7 @@ Newton-based visualizers (Newton, Rerun, Viser) require a Newton model/state to The sync pipeline: 1. Reads transforms from PhysX ``RigidBodyView`` (fast tensor API) -2. Falls back to ``XformPrimView`` for bodies not covered by the rigid body view +2. Falls back to :class:`~isaaclab.sim.views.FrameView` for bodies not covered by the rigid body view 3. Converts and writes merged poses into the Newton state via Warp kernels Newton Scene Data Provider diff --git a/docs/source/overview/core-concepts/sensors/camera.rst b/docs/source/overview/core-concepts/sensors/camera.rst index 917022b6cb46..29673f2bf465 100644 --- a/docs/source/overview/core-concepts/sensors/camera.rst +++ b/docs/source/overview/core-concepts/sensors/camera.rst @@ -5,8 +5,9 @@ Camera ====== -Camera sensors in Isaac Lab are renderer-backed sensors: each :class:`~sensors.TiledCamera` instance -is coupled to a **renderer** that produces the image data. The renderer and camera are intentionally +Camera sensors in Isaac Lab are renderer-backed sensors: each :class:`~sensors.Camera` instance +is coupled to a **renderer** that produces the image data. If multiple cameras use the same renderer +type, only one renderer is instantiated and shared between them. The renderer and camera are intentionally isolated from each other — the camera defines *what* to capture (pose, resolution, field of view, data types), while the renderer defines *how* to render it (RTX ray-tracing, Newton Warp rasterizer, etc.). This separation allows the same camera configuration to run across different physics and @@ -25,7 +26,7 @@ Renderer Backends ----------------- The renderer used by a camera is configured via the ``renderer_cfg`` field on -:class:`~sensors.TiledCameraCfg`. The default is :class:`~isaaclab_physx.renderers.IsaacRtxRendererCfg` +:class:`~sensors.CameraCfg`. The default is :class:`~isaaclab_physx.renderers.IsaacRtxRendererCfg` (NVIDIA RTX, requires Isaac Sim). .. list-table:: @@ -68,14 +69,14 @@ The Tiled Rendering API provides a vectorized interface for collecting image dat clones in a single batched render pass. Instead of one render call per camera, all copies of a camera are composited into a single large tiled image, dramatically reducing host-device transfer overhead. -Isaac Lab provides tiled rendering through :class:`~sensors.TiledCamera`, configured via -:class:`~sensors.TiledCameraCfg`. The ``renderer_cfg`` field selects the rendering backend. +Isaac Lab provides tiled rendering through :class:`~sensors.Camera`, configured via +:class:`~sensors.CameraCfg`. The ``renderer_cfg`` field selects the rendering backend. -TiledCameraCfg with renderer_cfg +CameraCfg with renderer_cfg ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -The renderer is specified via ``renderer_cfg`` on :class:`~sensors.TiledCameraCfg`. The camera and +The renderer is specified via ``renderer_cfg`` on :class:`~sensors.CameraCfg`. The camera and renderer configurations are fully decoupled: you can swap renderers without changing any other camera parameters. @@ -83,13 +84,13 @@ parameters. .. code-block:: python - from isaaclab.sensors import TiledCameraCfg + from isaaclab.sensors import CameraCfg import isaaclab.sim as sim_utils # IsaacRtxRendererCfg is the default, no explicit import needed - tiled_camera: TiledCameraCfg = TiledCameraCfg( + tiled_camera: CameraCfg = CameraCfg( prim_path="/World/envs/env_.*/Camera", - offset=TiledCameraCfg.OffsetCfg(pos=(-7.0, 0.0, 3.0), rot=(0.9945, 0.0, 0.1045, 0.0), convention="world"), + offset=CameraCfg.OffsetCfg(pos=(-7.0, 0.0, 3.0), rot=(0.9945, 0.0, 0.1045, 0.0), convention="world"), data_types=["rgb"], spawn=sim_utils.PinholeCameraCfg( focal_length=24.0, focus_distance=400.0, horizontal_aperture=20.955, clipping_range=(0.1, 20.0) @@ -103,13 +104,13 @@ parameters. .. code-block:: python - from isaaclab.sensors import TiledCameraCfg + from isaaclab.sensors import CameraCfg from isaaclab_newton.renderers import NewtonWarpRendererCfg import isaaclab.sim as sim_utils - tiled_camera: TiledCameraCfg = TiledCameraCfg( + tiled_camera: CameraCfg = CameraCfg( prim_path="/World/envs/env_.*/Camera", - offset=TiledCameraCfg.OffsetCfg(pos=(-7.0, 0.0, 3.0), rot=(0.9945, 0.0, 0.1045, 0.0), convention="world"), + offset=CameraCfg.OffsetCfg(pos=(-7.0, 0.0, 3.0), rot=(0.9945, 0.0, 0.1045, 0.0), convention="world"), data_types=["rgb", "depth"], # only rgb and depth supported with Newton renderer spawn=sim_utils.PinholeCameraCfg( focal_length=24.0, focus_distance=400.0, horizontal_aperture=20.955, clipping_range=(0.1, 20.0) @@ -127,13 +128,13 @@ For environments that need to support both backends, use .. code-block:: python - from isaaclab.sensors import TiledCameraCfg + from isaaclab.sensors import CameraCfg from isaaclab_tasks.utils.presets import MultiBackendRendererCfg import isaaclab.sim as sim_utils - tiled_camera: TiledCameraCfg = TiledCameraCfg( + tiled_camera: CameraCfg = CameraCfg( prim_path="/World/envs/env_.*/Camera", - offset=TiledCameraCfg.OffsetCfg(pos=(-7.0, 0.0, 3.0), rot=(0.9945, 0.0, 0.1045, 0.0), convention="world"), + offset=CameraCfg.OffsetCfg(pos=(-7.0, 0.0, 3.0), rot=(0.9945, 0.0, 0.1045, 0.0), convention="world"), data_types=["rgb"], spawn=sim_utils.PinholeCameraCfg( focal_length=24.0, focus_distance=400.0, horizontal_aperture=20.955, clipping_range=(0.1, 20.0) @@ -162,7 +163,7 @@ Accessing camera data .. code-block:: python - tiled_camera = TiledCamera(cfg.tiled_camera) + tiled_camera = Camera(cfg.tiled_camera) data = tiled_camera.data.output["rgb"] # shape: (num_cameras, H, W, 3), torch.uint8 The returned data has shape ``(num_cameras, height, width, num_channels)``, ready to use directly @@ -185,7 +186,7 @@ Annotators (RTX only) They are **not** available with the Newton Warp renderer or ovrtx, which support only ``rgb`` and ``depth``. -:class:`~sensors.TiledCamera` exposes the following annotator +:class:`~sensors.Camera` exposes the following annotator data types when using the RTX renderer: * ``"rgb"``: A 3-channel rendered color image. diff --git a/docs/source/overview/core-concepts/sensors/contact_sensor.rst b/docs/source/overview/core-concepts/sensors/contact_sensor.rst index 4ddd2d10c077..ebd81e60a54d 100644 --- a/docs/source/overview/core-concepts/sensors/contact_sensor.rst +++ b/docs/source/overview/core-concepts/sensors/contact_sensor.rst @@ -55,7 +55,7 @@ Here, we print both the net contact force and the filtered force matrix for each ------------------------------- Contact sensor @ '/World/envs/env_.*/Robot/LF_FOOT': - view type : + view type : update period (s) : 0.0 number of bodies : 1 body names : ['LF_FOOT'] @@ -64,7 +64,7 @@ Here, we print both the net contact force and the filtered force matrix for each Received contact force of: tensor([[[-1.3923e-05, 1.5727e-04, 1.1032e+02]]], device='cuda:0') ------------------------------- Contact sensor @ '/World/envs/env_.*/Robot/RF_FOOT': - view type : + view type : update period (s) : 0.0 number of bodies : 1 body names : ['RF_FOOT'] @@ -85,7 +85,7 @@ Notice that even with filtering, both sensors report the net contact force actin ------------------------------- Contact sensor @ '/World/envs/env_.*/Robot/.*H_FOOT': - view type : + view type : update period (s) : 0.0 number of bodies : 2 body names : ['LH_FOOT', 'RH_FOOT'] diff --git a/docs/source/overview/core-concepts/sensors/imu.rst b/docs/source/overview/core-concepts/sensors/imu.rst index fe429f77a2b3..5435bf227f5d 100644 --- a/docs/source/overview/core-concepts/sensors/imu.rst +++ b/docs/source/overview/core-concepts/sensors/imu.rst @@ -61,7 +61,7 @@ The oscillations in the values reported by the sensor are a direct result of of .. code-block:: bash Imu sensor @ '/World/envs/env_.*/Robot/LF_FOOT': - view type : + view type : update period (s) : 0.0 number of sensors : 1 @@ -71,7 +71,7 @@ The oscillations in the values reported by the sensor are a direct result of of Received angular acceleration: tensor([[-0.0389, -0.0262, -0.0045]], device='cuda:0') ------------------------------- Imu sensor @ '/World/envs/env_.*/Robot/RF_FOOT': - view type : + view type : update period (s) : 0.0 number of sensors : 1 diff --git a/docs/source/overview/core-concepts/sensors/ray_caster.rst b/docs/source/overview/core-concepts/sensors/ray_caster.rst index 8b2f12020b3f..9b6ce1a31373 100644 --- a/docs/source/overview/core-concepts/sensors/ray_caster.rst +++ b/docs/source/overview/core-concepts/sensors/ray_caster.rst @@ -50,7 +50,7 @@ Querying the sensor for data can be done at simulation run time like any other s ------------------------------- Ray-caster @ '/World/envs/env_.*/Robot/base/lidar_cage': - view type : + view type : update period (s) : 0.016666666666666666 number of meshes : 1 number of sensors : 1 diff --git a/docs/source/overview/core-concepts/sensors/visuo_tactile_sensor.rst b/docs/source/overview/core-concepts/sensors/visuo_tactile_sensor.rst index d761c4a2e8a8..e1b389e45c1c 100644 --- a/docs/source/overview/core-concepts/sensors/visuo_tactile_sensor.rst +++ b/docs/source/overview/core-concepts/sensors/visuo_tactile_sensor.rst @@ -22,7 +22,7 @@ Tactile sensors require specific configuration parameters to define their behavi .. code-block:: python - from isaaclab.sensors import TiledCameraCfg + from isaaclab.sensors import CameraCfg from isaaclab_assets.sensors import GELSIGHT_R15_CFG import isaaclab.sim as sim_utils @@ -45,7 +45,7 @@ Tactile sensors require specific configuration parameters to define their behavi friction_coefficient=2.0, tangential_stiffness=0.1, ## Camera configuration - camera_cfg=TiledCameraCfg( + camera_cfg=CameraCfg( prim_path="{ENV_REGEX_NS}/Robot/elastomer_tip/cam", update_period=1 / 60, # 60 Hz height=320, @@ -66,7 +66,7 @@ The configuration supports customization of: * **Contact Object Configuration**: Define properties of interacting objects using prim path expressions to locate objects with SDF collision meshes * **Physics Parameters**: Control the sensor's force field computation: * ``normal_contact_stiffness``, ``friction_coefficient``, ``tangential_stiffness`` - Normal stiffness, friction coefficient, and tangential stiffness -* **Camera Settings**: Configure resolution, update rates, and data types, currently only ``distance_to_image_plane`` (alias for ``depth``) is supported. +* **Camera Settings**: Configure resolution, update rates, and data types using :class:`~sensors.CameraCfg`. Currently only ``distance_to_image_plane`` (alias for ``depth``) is supported. ``spawn`` is set to ``None`` by default, which means that the camera is already spawned in the USD file. If you want to spawn the camera yourself and set focal length, etc., you can set the spawn configuration to a valid spawn configuration. @@ -77,7 +77,7 @@ Configuration Requirements The following requirements must be satisfied for proper sensor operation: **Camera Tactile Imaging** - If ``enable_camera_tactile=True``, a valid ``camera_cfg`` (TiledCameraCfg) must be provided with appropriate camera parameters. + If ``enable_camera_tactile=True``, a valid ``camera_cfg`` (CameraCfg) must be provided with appropriate camera parameters. **Force Field Computation** If ``enable_force_field=True``, the following parameters are required: diff --git a/docs/source/overview/developer-guide/repo_structure.rst b/docs/source/overview/developer-guide/repo_structure.rst index a201886c0f8d..d8a5a1b200a5 100644 --- a/docs/source/overview/developer-guide/repo_structure.rst +++ b/docs/source/overview/developer-guide/repo_structure.rst @@ -61,8 +61,10 @@ They are structured as follows: * **demos**: Contains various demo applications that showcase the core framework :mod:`isaaclab`. * **environments**: Contains applications for running environments defined in :mod:`isaaclab_tasks` with different agents. These include a random policy, zero-action policy, teleoperation or scripted state machines. +* **imitation_learning**: Contains applications for training and evaluating policies with various + imitation learning libraries (e.g. robomimic). +* **reinforcement_learning**: Contains applications for training and evaluating policies with various + reinforcement learning libraries (e.g. rsl_rl, rl_games, sb3, skrl). * **tools**: Contains applications for using the tools provided by the framework. These include converting assets, generating datasets, etc. * **tutorials**: Contains step-by-step tutorials for using the APIs provided by the framework. -* **workflows**: Contains applications for using environments with various learning-based frameworks. These include different - reinforcement learning or imitation learning libraries. diff --git a/docs/source/overview/environments.rst b/docs/source/overview/environments.rst index 95c29a33e8ea..c1bce52597e4 100644 --- a/docs/source/overview/environments.rst +++ b/docs/source/overview/environments.rst @@ -43,54 +43,52 @@ Classic Classic environments that are based on IsaacGymEnvs implementation of MuJoCo-style environments. .. table:: - :widths: 33 37 30 - - +------------------+-----------------------------+-------------------------------------------------------------------------+ - | World | Environment ID | Description | - +==================+=============================+=========================================================================+ - | |humanoid| | |humanoid-link| | Move towards a direction with the MuJoCo humanoid robot | - | | | | - | | |humanoid-direct-link| | | - +------------------+-----------------------------+-------------------------------------------------------------------------+ - | |ant| | |ant-link| | Move towards a direction with the MuJoCo ant robot | - | | | | - | | |ant-direct-link| | | - +------------------+-----------------------------+-------------------------------------------------------------------------+ - | |cartpole| | |cartpole-link| | Move the cart to keep the pole upwards in the classic cartpole control | - | | | | - | | |cartpole-direct-link| | | - +------------------+-----------------------------+-------------------------------------------------------------------------+ - | |cartpole| | |cartpole-rgb-link| | Move the cart to keep the pole upwards in the classic cartpole control | - | | | and perceptive inputs. Requires running with ``--enable_cameras``. | - | | |cartpole-depth-link| | | - | | | | - | | |cartpole-rgb-direct-link| | | - | | | | - | | |cartpole-depth-direct-link|| | - +------------------+-----------------------------+-------------------------------------------------------------------------+ - | |cartpole| | |cartpole-resnet-link| | Move the cart to keep the pole upwards in the classic cartpole control | - | | | based off of features extracted from perceptive inputs with pre-trained | - | | |cartpole-theia-link| | frozen vision encoders. Requires running with ``--enable_cameras``. | - +------------------+-----------------------------+-------------------------------------------------------------------------+ + :widths: 25 30 25 20 + + +------------------+-----------------------------+-------------------------------------------------------------------------+------------------------------+ + | World | Environment ID | Description | Presets | + +==================+=============================+=========================================================================+==============================+ + | |humanoid| | |humanoid-link| | Move towards a direction with the MuJoCo humanoid robot | ``newton_mjwarp``, ``physx`` | + | | | | ``ovphysx`` | + | | |humanoid-direct-link| | | | + +------------------+-----------------------------+-------------------------------------------------------------------------+------------------------------+ + | |ant| | |ant-link| | Move towards a direction with the MuJoCo ant robot | ``newton_mjwarp``, ``physx`` | + | | | | ``ovphysx`` | + | | |ant-direct-link| | | | + +------------------+-----------------------------+-------------------------------------------------------------------------+------------------------------+ + | |cartpole| | |cartpole-link| | Move the cart to keep the pole upwards in the classic cartpole control | ``newton_mjwarp``, ``physx`` | + | | | | ``ovphysx`` | + | | |cartpole-direct-link| | | | + +------------------+-----------------------------+-------------------------------------------------------------------------+------------------------------+ + | |cartpole| | |cartpole-camera-presets| | Move the cart to keep the pole upwards in the classic cartpole control | ``newton_mjwarp``, ``physx`` | + | | | and perceptive inputs. Select data type via ``presets=``. Requires | ``newton_renderer``, | + | | | running with ``--enable_cameras``. | ``ovrtx_renderer``, | + | | | | ``rgb``, ``depth``, | + | | | | ``albedo``, | + | | | | ``semantic_`` | + | | | | ``segmentation``, | + | | | | ``simple_shading_*`` | + +------------------+-----------------------------+-------------------------------------------------------------------------+------------------------------+ + | |cartpole| | |cartpole-resnet-link| | Move the cart to keep the pole upwards in the classic cartpole control | ``newton_mjwarp``, ``physx`` | + | | | based off of features extracted from perceptive inputs with pre-trained | | + | | |cartpole-theia-link| | frozen vision encoders. Requires running with ``--enable_cameras``. | | + +------------------+-----------------------------+-------------------------------------------------------------------------+------------------------------+ .. |humanoid| image:: ../_static/tasks/classic/humanoid.jpg .. |ant| image:: ../_static/tasks/classic/ant.jpg .. |cartpole| image:: ../_static/tasks/classic/cartpole.jpg -.. |humanoid-link| replace:: `Isaac-Humanoid-v0 `__ -.. |ant-link| replace:: `Isaac-Ant-v0 `__ -.. |cartpole-link| replace:: `Isaac-Cartpole-v0 `__ -.. |cartpole-rgb-link| replace:: `Isaac-Cartpole-RGB-v0 `__ -.. |cartpole-depth-link| replace:: `Isaac-Cartpole-Depth-v0 `__ -.. |cartpole-resnet-link| replace:: `Isaac-Cartpole-RGB-ResNet18-v0 `__ -.. |cartpole-theia-link| replace:: `Isaac-Cartpole-RGB-TheiaTiny-v0 `__ +.. |humanoid-link| replace:: `Isaac-Humanoid-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/classic/humanoid/humanoid_env_cfg.py>`__ +.. |ant-link| replace:: `Isaac-Ant-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/classic/ant/ant_env_cfg.py>`__ +.. |cartpole-link| replace:: `Isaac-Cartpole-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/classic/cartpole/cartpole_env_cfg.py>`__ +.. |cartpole-camera-presets| replace:: `Isaac-Cartpole-Camera-Presets-Direct-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/direct/cartpole/cartpole_camera_presets_env_cfg.py>`__ +.. |cartpole-resnet-link| replace:: `Isaac-Cartpole-RGB-ResNet18-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/classic/cartpole/cartpole_camera_env_cfg.py>`__ +.. |cartpole-theia-link| replace:: `Isaac-Cartpole-RGB-TheiaTiny-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/classic/cartpole/cartpole_camera_env_cfg.py>`__ -.. |humanoid-direct-link| replace:: `Isaac-Humanoid-Direct-v0 `__ -.. |ant-direct-link| replace:: `Isaac-Ant-Direct-v0 `__ -.. |cartpole-direct-link| replace:: `Isaac-Cartpole-Direct-v0 `__ -.. |cartpole-rgb-direct-link| replace:: `Isaac-Cartpole-RGB-Camera-Direct-v0 `__ -.. |cartpole-depth-direct-link| replace:: `Isaac-Cartpole-Depth-Camera-Direct-v0 `__ +.. |humanoid-direct-link| replace:: `Isaac-Humanoid-Direct-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/direct/humanoid/humanoid_env.py>`__ +.. |ant-direct-link| replace:: `Isaac-Ant-Direct-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/direct/ant/ant_env.py>`__ +.. |cartpole-direct-link| replace:: `Isaac-Cartpole-Direct-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/direct/cartpole/cartpole_env.py>`__ Manipulation ~~~~~~~~~~~~ @@ -105,83 +103,107 @@ for the lift-cube environment: * |lift-cube-ik-rel-link|: Franka arm with relative IK control .. table:: - :widths: 33 37 30 - - +-------------------------+------------------------------+-----------------------------------------------------------------------------+ - | World | Environment ID | Description | - +=========================+==============================+=============================================================================+ - | |reach-franka| | |reach-franka-link| | Move the end-effector to a sampled target pose with the Franka robot | - +-------------------------+------------------------------+-----------------------------------------------------------------------------+ - | |reach-ur10| | |reach-ur10-link| | Move the end-effector to a sampled target pose with the UR10 robot | - +-------------------------+------------------------------+-----------------------------------------------------------------------------+ - | |deploy-reach-ur10e| | |deploy-reach-ur10e-link| | Move the end-effector to a sampled target pose with the UR10e robot | - | | | This policy has been deployed to a real robot | - +-------------------------+------------------------------+-----------------------------------------------------------------------------+ - | |lift-cube| | |lift-cube-link| | Pick a cube and bring it to a sampled target position with the Franka robot | - +-------------------------+------------------------------+-----------------------------------------------------------------------------+ - | |stack-cube| | |stack-cube-link| | Stack three cubes (bottom to top: blue, red, green) with the Franka robot. | - | | | Blueprint env used for the NVIDIA Isaac GR00T blueprint for synthetic | - | | |stack-cube-bp-link| | manipulation motion generation | - +-------------------------+------------------------------+-----------------------------------------------------------------------------+ - | |surface-gripper| | |long-suction-link| | Stack three cubes (bottom to top: blue, red, green) | - | | | with the UR10 arm and long surface gripper | - | | |short-suction-link| | or short surface gripper. | - +-------------------------+------------------------------+-----------------------------------------------------------------------------+ - | |cabi-franka| | |cabi-franka-link| | Grasp the handle of a cabinet's drawer and open it with the Franka robot | - | | | | - | | |franka-direct-link| | | - +-------------------------+------------------------------+-----------------------------------------------------------------------------+ - | |cube-allegro| | |cube-allegro-link| | In-hand reorientation of a cube using Allegro hand | - | | | | - | | |allegro-direct-link| | | - +-------------------------+------------------------------+-----------------------------------------------------------------------------+ - | |cube-shadow| | |cube-shadow-link| | In-hand reorientation of a cube using Shadow hand | - | | | | - | | |cube-shadow-ff-link| | | - | | | | - | | |cube-shadow-lstm-link| | | - +-------------------------+------------------------------+-----------------------------------------------------------------------------+ - | |cube-shadow| | |cube-shadow-vis-link| | In-hand reorientation of a cube using Shadow hand using perceptive inputs. | - | | | Requires running with ``--enable_cameras``. | - +-------------------------+------------------------------+-----------------------------------------------------------------------------+ - | |gr1_pick_place| | |gr1_pick_place-link| | Pick up and place an object in a basket with a GR-1 humanoid robot | - +-------------------------+------------------------------+-----------------------------------------------------------------------------+ - | |gr1_pp_waist| | |gr1_pp_waist-link| | Pick up and place an object in a basket with a GR-1 humanoid robot | - | | | with waist degrees-of-freedom enables that provides a wider reach space. | - +-------------------------+------------------------------+-----------------------------------------------------------------------------+ - | |g1_pick_place| | |g1_pick_place-link| | Pick up and place an object in a basket with a Unitree G1 humanoid robot | - +-------------------------+------------------------------+-----------------------------------------------------------------------------+ - | |g1_pick_place_fixed| | |g1_pick_place_fixed-link| | Pick up and place an object in a basket with a Unitree G1 humanoid robot | - | | | with three-fingered hands. Robot is set up with the base fixed in place. | - +-------------------------+------------------------------+-----------------------------------------------------------------------------+ - | |g1_pick_place_lm| | |g1_pick_place_lm-link| | Pick up and place an object in a basket with a Unitree G1 humanoid robot | - | | | with three-fingered hands and in-place locomanipulation capabilities | - | | | enabled (i.e. Robot lower body balances in-place while upper body is | - | | | controlled via Inverse Kinematics). | - +-------------------------+------------------------------+-----------------------------------------------------------------------------+ - | |kuka-allegro-lift| | |kuka-allegro-lift-link| | Pick up a primitive shape on the table and lift it to target position. | - | | | Supports state, single-camera, and dual-camera observation modes via | - | | | ``presets=single_camera`` / ``presets=duo_camera`` (see RL table below). | - +-------------------------+------------------------------+-----------------------------------------------------------------------------+ - | |kuka-allegro-reorient| | |kuka-allegro-reorient-link| | Pick up a primitive shape on the table and orient it to target pose. | - | | | Supports state, single-camera, and dual-camera observation modes via | - | | | ``presets=single_camera`` / ``presets=duo_camera`` (see RL table below). | - +-------------------------+------------------------------+-----------------------------------------------------------------------------+ - | |galbot_stack| | |galbot_stack-link| | Stack three cubes (bottom to top: blue, red, green) with the left arm of | - | | | a Galbot humanoid robot | - +-------------------------+------------------------------+-----------------------------------------------------------------------------+ - | |agibot_place_mug| | |agibot_place_mug-link| | Pick up and place a mug upright with a Agibot A2D humanoid robot | - +-------------------------+------------------------------+-----------------------------------------------------------------------------+ - | |agibot_place_toy| | |agibot_place_toy-link| | Pick up and place an object in a box with a Agibot A2D humanoid robot | - +-------------------------+------------------------------+-----------------------------------------------------------------------------+ - | |reach_openarm_bi| | |reach_openarm_bi-link| | Move the end-effector to sampled target poses with the OpenArm robot | - +-------------------------+------------------------------+-----------------------------------------------------------------------------+ - | |reach_openarm_uni| | |reach_openarm_uni-link| | Move the end-effector to a sampled target pose with the OpenArm robot | - +-------------------------+------------------------------+-----------------------------------------------------------------------------+ - | |lift_openarm_uni| | |lift_openarm_uni-link| | Pick a cube and bring it to a sampled target position with the OpenArm robot| - +-------------------------+------------------------------+-----------------------------------------------------------------------------+ - | |cabi_openarm_uni| | |cabi_openarm_uni-link| | Grasp the handle of a cabinet's drawer and open it with the OpenArm robot | - +-------------------------+------------------------------+-----------------------------------------------------------------------------+ + :widths: 25 30 25 20 + + +-------------------------+------------------------------+-----------------------------------------------------------------------------+------------------------------+ + | World | Environment ID | Description | Presets | + +=========================+==============================+=============================================================================+==============================+ + | |reach-franka| | |reach-franka-link| | Move the end-effector to a sampled target pose with the Franka robot | ``newton_mjwarp``, ``physx`` | + +-------------------------+------------------------------+-----------------------------------------------------------------------------+------------------------------+ + | |reach-ur10| | |reach-ur10-link| | Move the end-effector to a sampled target pose with the UR10 robot | ``newton_mjwarp``, ``physx`` | + +-------------------------+------------------------------+-----------------------------------------------------------------------------+------------------------------+ + | |deploy-reach-ur10e| | |deploy-reach-ur10e-link| | Move the end-effector to a sampled target pose with the UR10e robot | | + | | | This policy has been deployed to a real robot | | + +-------------------------+------------------------------+-----------------------------------------------------------------------------+------------------------------+ + | |lift-cube| | |lift-cube-link| | Pick a cube and bring it to a sampled target position with the Franka robot | | + +-------------------------+------------------------------+-----------------------------------------------------------------------------+------------------------------+ + | |stack-cube| | |stack-cube-link| | Stack three cubes (bottom to top: blue, red, green) with the Franka robot. | | + | | | Blueprint env used for the NVIDIA Isaac GR00T blueprint for synthetic | | + | | |stack-cube-bp-link| | manipulation motion generation | | + +-------------------------+------------------------------+-----------------------------------------------------------------------------+------------------------------+ + | |surface-gripper| | |long-suction-link| | Stack three cubes (bottom to top: blue, red, green) | | + | | | with the UR10 arm and long surface gripper | | + | | |short-suction-link| | or short surface gripper. | | + +-------------------------+------------------------------+-----------------------------------------------------------------------------+------------------------------+ + | |cabi-franka| | |cabi-franka-link| | Grasp the handle of a cabinet's drawer and open it with the Franka robot | ``newton_mjwarp``, ``physx`` | + | | | | | + | | |franka-direct-link| | | | + +-------------------------+------------------------------+-----------------------------------------------------------------------------+------------------------------+ + | |cube-allegro| | |cube-allegro-link| | In-hand reorientation of a cube using Allegro hand | ``newton_mjwarp``, ``physx`` | + | | | | | + | | |allegro-direct-link| | | | + +-------------------------+------------------------------+-----------------------------------------------------------------------------+------------------------------+ + | |cube-shadow| | |cube-shadow-link| | In-hand reorientation of a cube using Shadow hand | ``newton_mjwarp``, ``physx`` | + | | | | | + | | |cube-shadow-ff-link| | | | + | | | | | + | | |cube-shadow-lstm-link| | | | + +-------------------------+------------------------------+-----------------------------------------------------------------------------+------------------------------+ + | |cube-shadow| | |cube-shadow-vis-link| | In-hand reorientation of a cube using Shadow hand using perceptive inputs. | ``newton_mjwarp``, ``physx`` | + | | | Requires running with ``--enable_cameras``. | ``newton_renderer``, | + | | | | ``ovrtx_renderer``, | + | | | | ``rgb``, ``depth``, | + | | | | ``albedo``, ``full``, | + | | | | ``semantic_`` | + | | | | ``segmentation``, | + | | | | ``simple_shading_*`` | + +-------------------------+------------------------------+-----------------------------------------------------------------------------+------------------------------+ + | |gr1_pick_place| | |gr1_pick_place-link| | Pick up and place an object in a basket with a GR-1 humanoid robot | ``physx`` | + +-------------------------+------------------------------+-----------------------------------------------------------------------------+------------------------------+ + | |gr1_pp_waist| | |gr1_pp_waist-link| | Pick up and place an object in a basket with a GR-1 humanoid robot | ``physx`` | + | | | with waist degrees-of-freedom enables that provides a wider reach space. | | + +-------------------------+------------------------------+-----------------------------------------------------------------------------+------------------------------+ + | |g1_pick_place| | |g1_pick_place-link| | Pick up and place an object in a basket with a Unitree G1 humanoid robot | ``physx`` | + +-------------------------+------------------------------+-----------------------------------------------------------------------------+------------------------------+ + | |g1_pick_place_fixed| | |g1_pick_place_fixed-link| | Pick up and place an object in a basket with a Unitree G1 humanoid robot | ``physx`` | + | | | with three-fingered hands. Robot is set up with the base fixed in place. | | + +-------------------------+------------------------------+-----------------------------------------------------------------------------+------------------------------+ + | |g1_pick_place_lm| | |g1_pick_place_lm-link| | Pick up and place an object in a basket with a Unitree G1 humanoid robot | ``physx`` | + | | | with three-fingered hands and in-place locomanipulation capabilities | | + | | | enabled (i.e. Robot lower body balances in-place while upper body is | | + | | | controlled via Inverse Kinematics). | | + +-------------------------+------------------------------+-----------------------------------------------------------------------------+------------------------------+ + | |kuka-allegro-lift| | |kuka-allegro-lift-link| | Pick up a primitive shape on the table and lift it to target position. | ``newton_mjwarp``, ``physx`` | + | | | Supports state, single-camera, and dual-camera observation modes via | ``single_camera``, | + | | | ``presets=single_camera`` / ``presets=duo_camera`` (see RL table below). | ``duo_camera``, | + | | | | ``newton_renderer``, | + | | | | ``ovrtx_renderer``, | + | | | | ``rgb{64,128,256}``, | + | | | | ``depth{..}``, | + | | | | ``albedo{..}``, | + | | | | ``semantic_`` | + | | | | ``segmentation{..}``, | + | | | | ``simple_shading_*`` | + | | | | ``{64,128,256}`` | + +-------------------------+------------------------------+-----------------------------------------------------------------------------+------------------------------+ + | |kuka-allegro-reorient| | |kuka-allegro-reorient-link| | Pick up a primitive shape on the table and orient it to target pose. | ``newton_mjwarp``, ``physx`` | + | | | Supports state, single-camera, and dual-camera observation modes via | ``single_camera``, | + | | | ``presets=single_camera`` / ``presets=duo_camera`` (see RL table below). | ``duo_camera``, | + | | | | ``newton_renderer``, | + | | | | ``ovrtx_renderer``, | + | | | | ``rgb{64,128,256}``, | + | | | | ``depth{..}``, | + | | | | ``albedo{..}``, | + | | | | ``semantic_`` | + | | | | ``segmentation{..}``, | + | | | | ``simple_shading_*`` | + | | | | ``{64,128,256}`` | + +-------------------------+------------------------------+-----------------------------------------------------------------------------+------------------------------+ + | |galbot_stack| | |galbot_stack-link| | Stack three cubes (bottom to top: blue, red, green) with the left arm of | ``physx`` | + | | | a Galbot humanoid robot | | + +-------------------------+------------------------------+-----------------------------------------------------------------------------+------------------------------+ + | |agibot_place_mug| | |agibot_place_mug-link| | Pick up and place a mug upright with a Agibot A2D humanoid robot | | + +-------------------------+------------------------------+-----------------------------------------------------------------------------+------------------------------+ + | |agibot_place_toy| | |agibot_place_toy-link| | Pick up and place an object in a box with a Agibot A2D humanoid robot | | + +-------------------------+------------------------------+-----------------------------------------------------------------------------+------------------------------+ + | |reach_openarm_bi| | |reach_openarm_bi-link| | Move the end-effector to sampled target poses with the OpenArm robot | | + +-------------------------+------------------------------+-----------------------------------------------------------------------------+------------------------------+ + | |reach_openarm_uni| | |reach_openarm_uni-link| | Move the end-effector to a sampled target pose with the OpenArm robot | | + +-------------------------+------------------------------+-----------------------------------------------------------------------------+------------------------------+ + | |lift_openarm_uni| | |lift_openarm_uni-link| | Pick a cube and bring it to a sampled target position with the OpenArm robot| | + +-------------------------+------------------------------+-----------------------------------------------------------------------------+------------------------------+ + | |cabi_openarm_uni| | |cabi_openarm_uni-link| | Grasp the handle of a cabinet's drawer and open it with the OpenArm robot | | + +-------------------------+------------------------------+-----------------------------------------------------------------------------+------------------------------+ .. |reach-franka| image:: ../_static/tasks/manipulation/franka_reach.jpg .. |reach-ur10| image:: ../_static/tasks/manipulation/ur10_reach.jpg @@ -207,38 +229,38 @@ for the lift-cube environment: .. |lift_openarm_uni| image:: ../_static/tasks/manipulation/openarm_uni_lift.jpg .. |cabi_openarm_uni| image:: ../_static/tasks/manipulation/openarm_uni_open_drawer.jpg -.. |reach-franka-link| replace:: `Isaac-Reach-Franka-v0 `__ -.. |reach-ur10-link| replace:: `Isaac-Reach-UR10-v0 `__ -.. |deploy-reach-ur10e-link| replace:: `Isaac-Deploy-Reach-UR10e-v0 `__ -.. |lift-cube-link| replace:: `Isaac-Lift-Cube-Franka-v0 `__ -.. |lift-cube-ik-abs-link| replace:: `Isaac-Lift-Cube-Franka-IK-Abs-v0 `__ -.. |lift-cube-ik-rel-link| replace:: `Isaac-Lift-Cube-Franka-IK-Rel-v0 `__ -.. |cabi-franka-link| replace:: `Isaac-Open-Drawer-Franka-v0 `__ -.. |franka-direct-link| replace:: `Isaac-Franka-Cabinet-Direct-v0 `__ -.. |cube-allegro-link| replace:: `Isaac-Repose-Cube-Allegro-v0 `__ -.. |allegro-direct-link| replace:: `Isaac-Repose-Cube-Allegro-Direct-v0 `__ -.. |stack-cube-link| replace:: `Isaac-Stack-Cube-Franka-v0 `__ -.. |stack-cube-bp-link| replace:: `Isaac-Stack-Cube-Franka-IK-Rel-Blueprint-v0 `__ -.. |gr1_pick_place-link| replace:: `Isaac-PickPlace-GR1T2-Abs-v0 `__ -.. |g1_pick_place-link| replace:: `Isaac-PickPlace-G1-InspireFTP-Abs-v0 `__ -.. |g1_pick_place_fixed-link| replace:: `Isaac-PickPlace-FixedBaseUpperBodyIK-G1-Abs-v0 `__ -.. |g1_pick_place_lm-link| replace:: `Isaac-PickPlace-Locomanipulation-G1-Abs-v0 `__ -.. |long-suction-link| replace:: `Isaac-Stack-Cube-UR10-Long-Suction-IK-Rel-v0 `__ -.. |short-suction-link| replace:: `Isaac-Stack-Cube-UR10-Short-Suction-IK-Rel-v0 `__ -.. |gr1_pp_waist-link| replace:: `Isaac-PickPlace-GR1T2-WaistEnabled-Abs-v0 `__ -.. |galbot_stack-link| replace:: `Isaac-Stack-Cube-Galbot-Left-Arm-Gripper-RmpFlow-v0 `__ -.. |kuka-allegro-lift-link| replace:: `Isaac-Dexsuite-Kuka-Allegro-Lift-v0 `__ -.. |kuka-allegro-reorient-link| replace:: `Isaac-Dexsuite-Kuka-Allegro-Reorient-v0 `__ -.. |cube-shadow-link| replace:: `Isaac-Repose-Cube-Shadow-Direct-v0 `__ -.. |cube-shadow-ff-link| replace:: `Isaac-Repose-Cube-Shadow-OpenAI-FF-Direct-v0 `__ -.. |cube-shadow-lstm-link| replace:: `Isaac-Repose-Cube-Shadow-OpenAI-LSTM-Direct-v0 `__ -.. |cube-shadow-vis-link| replace:: `Isaac-Repose-Cube-Shadow-Vision-Direct-v0 `__ -.. |agibot_place_mug-link| replace:: `Isaac-Place-Mug-Agibot-Left-Arm-RmpFlow-v0 `__ -.. |agibot_place_toy-link| replace:: `Isaac-Place-Toy2Box-Agibot-Right-Arm-RmpFlow-v0 `__ -.. |reach_openarm_bi-link| replace:: `Isaac-Reach-OpenArm-Bi-v0 `__ -.. |reach_openarm_uni-link| replace:: `Isaac-Reach-OpenArm-v0 `__ -.. |lift_openarm_uni-link| replace:: `Isaac-Lift-Cube-OpenArm-v0 `__ -.. |cabi_openarm_uni-link| replace:: `Isaac-Open-Drawer-OpenArm-v0 `__ +.. |reach-franka-link| replace:: `Isaac-Reach-Franka-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/reach/config/franka/joint_pos_env_cfg.py>`__ +.. |reach-ur10-link| replace:: `Isaac-Reach-UR10-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/reach/config/ur_10/joint_pos_env_cfg.py>`__ +.. |deploy-reach-ur10e-link| replace:: `Isaac-Deploy-Reach-UR10e-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/deploy/reach/config/ur_10e/joint_pos_env_cfg.py>`__ +.. |lift-cube-link| replace:: `Isaac-Lift-Cube-Franka-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/lift/config/franka/joint_pos_env_cfg.py>`__ +.. |lift-cube-ik-abs-link| replace:: `Isaac-Lift-Cube-Franka-IK-Abs-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/lift/config/franka/ik_abs_env_cfg.py>`__ +.. |lift-cube-ik-rel-link| replace:: `Isaac-Lift-Cube-Franka-IK-Rel-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/lift/config/franka/ik_rel_env_cfg.py>`__ +.. |cabi-franka-link| replace:: `Isaac-Open-Drawer-Franka-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/cabinet/config/franka/joint_pos_env_cfg.py>`__ +.. |franka-direct-link| replace:: `Isaac-Franka-Cabinet-Direct-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/direct/franka_cabinet/franka_cabinet_env.py>`__ +.. |cube-allegro-link| replace:: `Isaac-Repose-Cube-Allegro-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/inhand/config/allegro_hand/allegro_env_cfg.py>`__ +.. |allegro-direct-link| replace:: `Isaac-Repose-Cube-Allegro-Direct-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/direct/allegro_hand/allegro_hand_env_cfg.py>`__ +.. |stack-cube-link| replace:: `Isaac-Stack-Cube-Franka-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/stack/config/franka/stack_joint_pos_env_cfg.py>`__ +.. |stack-cube-bp-link| replace:: `Isaac-Stack-Cube-Franka-IK-Rel-Blueprint-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/stack/config/franka/stack_ik_rel_blueprint_env_cfg.py>`__ +.. |gr1_pick_place-link| replace:: `Isaac-PickPlace-GR1T2-Abs-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/pick_place/pickplace_gr1t2_env_cfg.py>`__ +.. |g1_pick_place-link| replace:: `Isaac-PickPlace-G1-InspireFTP-Abs-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/pick_place/pickplace_unitree_g1_inspire_hand_env_cfg.py>`__ +.. |g1_pick_place_fixed-link| replace:: `Isaac-PickPlace-FixedBaseUpperBodyIK-G1-Abs-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/locomanipulation/pick_place/fixed_base_upper_body_ik_g1_env_cfg.py>`__ +.. |g1_pick_place_lm-link| replace:: `Isaac-PickPlace-Locomanipulation-G1-Abs-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/locomanipulation/pick_place/locomanipulation_g1_env_cfg.py>`__ +.. |long-suction-link| replace:: `Isaac-Stack-Cube-UR10-Long-Suction-IK-Rel-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/stack/config/ur10_gripper/stack_ik_rel_env_cfg.py>`__ +.. |short-suction-link| replace:: `Isaac-Stack-Cube-UR10-Short-Suction-IK-Rel-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/stack/config/ur10_gripper/stack_ik_rel_env_cfg.py>`__ +.. |gr1_pp_waist-link| replace:: `Isaac-PickPlace-GR1T2-WaistEnabled-Abs-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/pick_place/pickplace_gr1t2_waist_enabled_env_cfg.py>`__ +.. |galbot_stack-link| replace:: `Isaac-Stack-Cube-Galbot-Left-Arm-Gripper-RmpFlow-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/stack/config/galbot/stack_rmp_rel_env_cfg.py>`__ +.. |kuka-allegro-lift-link| replace:: `Isaac-Dexsuite-Kuka-Allegro-Lift-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/dexsuite/config/kuka_allegro/dexsuite_kuka_allegro_env_cfg.py>`__ +.. |kuka-allegro-reorient-link| replace:: `Isaac-Dexsuite-Kuka-Allegro-Reorient-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/dexsuite/config/kuka_allegro/dexsuite_kuka_allegro_env_cfg.py>`__ +.. |cube-shadow-link| replace:: `Isaac-Repose-Cube-Shadow-Direct-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/direct/shadow_hand/shadow_hand_env_cfg.py>`__ +.. |cube-shadow-ff-link| replace:: `Isaac-Repose-Cube-Shadow-OpenAI-FF-Direct-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/direct/shadow_hand/shadow_hand_env_cfg.py>`__ +.. |cube-shadow-lstm-link| replace:: `Isaac-Repose-Cube-Shadow-OpenAI-LSTM-Direct-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/direct/shadow_hand/shadow_hand_env_cfg.py>`__ +.. |cube-shadow-vis-link| replace:: `Isaac-Repose-Cube-Shadow-Vision-Direct-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/direct/shadow_hand/shadow_hand_vision_env.py>`__ +.. |agibot_place_mug-link| replace:: `Isaac-Place-Mug-Agibot-Left-Arm-RmpFlow-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/place/config/agibot/place_upright_mug_rmp_rel_env_cfg.py>`__ +.. |agibot_place_toy-link| replace:: `Isaac-Place-Toy2Box-Agibot-Right-Arm-RmpFlow-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/place/config/agibot/place_toy2box_rmp_rel_env_cfg.py>`__ +.. |reach_openarm_bi-link| replace:: `Isaac-Reach-OpenArm-Bi-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/reach/config/openarm/bimanual/joint_pos_env_cfg.py>`__ +.. |reach_openarm_uni-link| replace:: `Isaac-Reach-OpenArm-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/reach/config/openarm/unimanual/joint_pos_env_cfg.py>`__ +.. |lift_openarm_uni-link| replace:: `Isaac-Lift-Cube-OpenArm-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/lift/config/openarm/joint_pos_env_cfg.py>`__ +.. |cabi_openarm_uni-link| replace:: `Isaac-Open-Drawer-OpenArm-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/cabinet/config/openarm/joint_pos_env_cfg.py>`__ Contact-rich Manipulation @@ -254,25 +276,25 @@ For example: * |factory-nut-link|: Nut-Bolt fastening with the Franka arm .. table:: - :widths: 33 37 30 - - +--------------------+-------------------------+-----------------------------------------------------------------------------+ - | World | Environment ID | Description | - +====================+=========================+=============================================================================+ - | |factory-peg| | |factory-peg-link| | Insert peg into the socket with the Franka robot | - +--------------------+-------------------------+-----------------------------------------------------------------------------+ - | |factory-gear| | |factory-gear-link| | Insert and mesh gear into the base with other gears, using the Franka robot | - +--------------------+-------------------------+-----------------------------------------------------------------------------+ - | |factory-nut| | |factory-nut-link| | Thread the nut onto the first 2 threads of the bolt, using the Franka robot | - +--------------------+-------------------------+-----------------------------------------------------------------------------+ + :widths: 25 30 25 20 + + +--------------------+-------------------------+-----------------------------------------------------------------------------+------------------------------+ + | World | Environment ID | Description | Presets | + +====================+=========================+=============================================================================+==============================+ + | |factory-peg| | |factory-peg-link| | Insert peg into the socket with the Franka robot | | + +--------------------+-------------------------+-----------------------------------------------------------------------------+------------------------------+ + | |factory-gear| | |factory-gear-link| | Insert and mesh gear into the base with other gears, using the Franka robot | | + +--------------------+-------------------------+-----------------------------------------------------------------------------+------------------------------+ + | |factory-nut| | |factory-nut-link| | Thread the nut onto the first 2 threads of the bolt, using the Franka robot | | + +--------------------+-------------------------+-----------------------------------------------------------------------------+------------------------------+ .. |factory-peg| image:: ../_static/tasks/factory/peg_insert.jpg .. |factory-gear| image:: ../_static/tasks/factory/gear_mesh.jpg .. |factory-nut| image:: ../_static/tasks/factory/nut_thread.jpg -.. |factory-peg-link| replace:: `Isaac-Factory-PegInsert-Direct-v0 `__ -.. |factory-gear-link| replace:: `Isaac-Factory-GearMesh-Direct-v0 `__ -.. |factory-nut-link| replace:: `Isaac-Factory-NutThread-Direct-v0 `__ +.. |factory-peg-link| replace:: `Isaac-Factory-PegInsert-Direct-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/direct/factory/factory_env_cfg.py>`__ +.. |factory-gear-link| replace:: `Isaac-Factory-GearMesh-Direct-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/direct/factory/factory_env_cfg.py>`__ +.. |factory-nut-link| replace:: `Isaac-Factory-NutThread-Direct-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/direct/factory/factory_env_cfg.py>`__ AutoMate ~~~~~~~~ @@ -316,21 +338,21 @@ We provide environments for both disassembly and assembly. * To evaluate an assembly policy, we run the command ``python source/isaaclab_tasks/isaaclab_tasks/direct/automate/run_w_id.py --assembly_id=ASSEMBLY_ID --checkpoint=CHECKPOINT --log_eval``. The evaluation results are stored in ``evaluation_{ASSEMBLY_ID}.h5``. .. table:: - :widths: 33 37 30 + :widths: 25 30 25 20 - +--------------------+-------------------------+-----------------------------------------------------------------------------+ - | World | Environment ID | Description | - +====================+=========================+=============================================================================+ - | |disassembly| | |disassembly-link| | Lift a plug out of the socket with the Franka robot | - +--------------------+-------------------------+-----------------------------------------------------------------------------+ - | |assembly| | |assembly-link| | Insert a plug into its corresponding socket with the Franka robot | - +--------------------+-------------------------+-----------------------------------------------------------------------------+ + +--------------------+-------------------------+-----------------------------------------------------------------------------+------------------------------+ + | World | Environment ID | Description | Presets | + +====================+=========================+=============================================================================+==============================+ + | |disassembly| | |disassembly-link| | Lift a plug out of the socket with the Franka robot | | + +--------------------+-------------------------+-----------------------------------------------------------------------------+------------------------------+ + | |assembly| | |assembly-link| | Insert a plug into its corresponding socket with the Franka robot | | + +--------------------+-------------------------+-----------------------------------------------------------------------------+------------------------------+ .. |assembly| image:: ../_static/tasks/automate/00004.jpg .. |disassembly| image:: ../_static/tasks/automate/01053_disassembly.jpg -.. |assembly-link| replace:: `Isaac-AutoMate-Assembly-Direct-v0 `__ -.. |disassembly-link| replace:: `Isaac-AutoMate-Disassembly-Direct-v0 `__ +.. |assembly-link| replace:: `Isaac-AutoMate-Assembly-Direct-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/direct/automate/assembly_env_cfg.py>`__ +.. |disassembly-link| replace:: `Isaac-AutoMate-Disassembly-Direct-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/direct/automate/disassembly_env_cfg.py>`__ FORGE ~~~~~~~~ @@ -349,25 +371,25 @@ These tasks share the same task configurations and control options. You can swit * |forge-nut-link|: Nut-Bolt fastening with the Franka arm .. table:: - :widths: 33 37 30 - - +--------------------+-------------------------+-----------------------------------------------------------------------------+ - | World | Environment ID | Description | - +====================+=========================+=============================================================================+ - | |forge-peg| | |forge-peg-link| | Insert peg into the socket with the Franka robot | - +--------------------+-------------------------+-----------------------------------------------------------------------------+ - | |forge-gear| | |forge-gear-link| | Insert and mesh gear into the base with other gears, using the Franka robot | - +--------------------+-------------------------+-----------------------------------------------------------------------------+ - | |forge-nut| | |forge-nut-link| | Thread the nut onto the first 2 threads of the bolt, using the Franka robot | - +--------------------+-------------------------+-----------------------------------------------------------------------------+ + :widths: 25 30 25 20 + + +--------------------+-------------------------+-----------------------------------------------------------------------------+------------------------------+ + | World | Environment ID | Description | Presets | + +====================+=========================+=============================================================================+==============================+ + | |forge-peg| | |forge-peg-link| | Insert peg into the socket with the Franka robot | | + +--------------------+-------------------------+-----------------------------------------------------------------------------+------------------------------+ + | |forge-gear| | |forge-gear-link| | Insert and mesh gear into the base with other gears, using the Franka robot | | + +--------------------+-------------------------+-----------------------------------------------------------------------------+------------------------------+ + | |forge-nut| | |forge-nut-link| | Thread the nut onto the first 2 threads of the bolt, using the Franka robot | | + +--------------------+-------------------------+-----------------------------------------------------------------------------+------------------------------+ .. |forge-peg| image:: ../_static/tasks/factory/peg_insert.jpg .. |forge-gear| image:: ../_static/tasks/factory/gear_mesh.jpg .. |forge-nut| image:: ../_static/tasks/factory/nut_thread.jpg -.. |forge-peg-link| replace:: `Isaac-Forge-PegInsert-Direct-v0 `__ -.. |forge-gear-link| replace:: `Isaac-Forge-GearMesh-Direct-v0 `__ -.. |forge-nut-link| replace:: `Isaac-Forge-NutThread-Direct-v0 `__ +.. |forge-peg-link| replace:: `Isaac-Forge-PegInsert-Direct-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/direct/forge/forge_env_cfg.py>`__ +.. |forge-gear-link| replace:: `Isaac-Forge-GearMesh-Direct-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/direct/forge/forge_env_cfg.py>`__ +.. |forge-nut-link| replace:: `Isaac-Forge-NutThread-Direct-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/direct/forge/forge_env_cfg.py>`__ Locomotion @@ -376,88 +398,88 @@ Locomotion Environments based on legged locomotion tasks. .. table:: - :widths: 33 37 30 - - +------------------------------+----------------------------------------------+------------------------------------------------------------------------------+ - | World | Environment ID | Description | - +==============================+==============================================+==============================================================================+ - | |velocity-flat-anymal-b| | |velocity-flat-anymal-b-link| | Track a velocity command on flat terrain with the Anymal B robot | - +------------------------------+----------------------------------------------+------------------------------------------------------------------------------+ - | |velocity-rough-anymal-b| | |velocity-rough-anymal-b-link| | Track a velocity command on rough terrain with the Anymal B robot | - +------------------------------+----------------------------------------------+------------------------------------------------------------------------------+ - | |velocity-flat-anymal-c| | |velocity-flat-anymal-c-link| | Track a velocity command on flat terrain with the Anymal C robot | - | | | | - | | |velocity-flat-anymal-c-direct-link| | | - +------------------------------+----------------------------------------------+------------------------------------------------------------------------------+ - | |velocity-rough-anymal-c| | |velocity-rough-anymal-c-link| | Track a velocity command on rough terrain with the Anymal C robot | - | | | | - | | |velocity-rough-anymal-c-direct-link| | | - +------------------------------+----------------------------------------------+------------------------------------------------------------------------------+ - | |velocity-flat-anymal-d| | |velocity-flat-anymal-d-link| | Track a velocity command on flat terrain with the Anymal D robot | - +------------------------------+----------------------------------------------+------------------------------------------------------------------------------+ - | |velocity-rough-anymal-d| | |velocity-rough-anymal-d-link| | Track a velocity command on rough terrain with the Anymal D robot | - +------------------------------+----------------------------------------------+------------------------------------------------------------------------------+ - | |velocity-flat-unitree-a1| | |velocity-flat-unitree-a1-link| | Track a velocity command on flat terrain with the Unitree A1 robot | - +------------------------------+----------------------------------------------+------------------------------------------------------------------------------+ - | |velocity-rough-unitree-a1| | |velocity-rough-unitree-a1-link| | Track a velocity command on rough terrain with the Unitree A1 robot | - +------------------------------+----------------------------------------------+------------------------------------------------------------------------------+ - | |velocity-flat-unitree-go1| | |velocity-flat-unitree-go1-link| | Track a velocity command on flat terrain with the Unitree Go1 robot | - +------------------------------+----------------------------------------------+------------------------------------------------------------------------------+ - | |velocity-rough-unitree-go1| | |velocity-rough-unitree-go1-link| | Track a velocity command on rough terrain with the Unitree Go1 robot | - +------------------------------+----------------------------------------------+------------------------------------------------------------------------------+ - | |velocity-flat-unitree-go2| | |velocity-flat-unitree-go2-link| | Track a velocity command on flat terrain with the Unitree Go2 robot | - +------------------------------+----------------------------------------------+------------------------------------------------------------------------------+ - | |velocity-rough-unitree-go2| | |velocity-rough-unitree-go2-link| | Track a velocity command on rough terrain with the Unitree Go2 robot | - +------------------------------+----------------------------------------------+------------------------------------------------------------------------------+ - | |velocity-flat-spot| | |velocity-flat-spot-link| | Track a velocity command on flat terrain with the Boston Dynamics Spot robot | - +------------------------------+----------------------------------------------+------------------------------------------------------------------------------+ - | |velocity-flat-h1| | |velocity-flat-h1-link| | Track a velocity command on flat terrain with the Unitree H1 robot | - +------------------------------+----------------------------------------------+------------------------------------------------------------------------------+ - | |velocity-rough-h1| | |velocity-rough-h1-link| | Track a velocity command on rough terrain with the Unitree H1 robot | - +------------------------------+----------------------------------------------+------------------------------------------------------------------------------+ - | |velocity-flat-g1| | |velocity-flat-g1-link| | Track a velocity command on flat terrain with the Unitree G1 robot | - +------------------------------+----------------------------------------------+------------------------------------------------------------------------------+ - | |velocity-rough-g1| | |velocity-rough-g1-link| | Track a velocity command on rough terrain with the Unitree G1 robot | - +------------------------------+----------------------------------------------+------------------------------------------------------------------------------+ - | |velocity-flat-digit| | |velocity-flat-digit-link| | Track a velocity command on flat terrain with the Agility Digit robot | - +------------------------------+----------------------------------------------+------------------------------------------------------------------------------+ - | |velocity-rough-digit| | |velocity-rough-digit-link| | Track a velocity command on rough terrain with the Agility Digit robot | - +------------------------------+----------------------------------------------+------------------------------------------------------------------------------+ - | |tracking-loco-manip-digit| | |tracking-loco-manip-digit-link| | Track a root velocity and hand pose command with the Agility Digit robot | - +------------------------------+----------------------------------------------+------------------------------------------------------------------------------+ - -.. |velocity-flat-anymal-b-link| replace:: `Isaac-Velocity-Flat-Anymal-B-v0 `__ -.. |velocity-rough-anymal-b-link| replace:: `Isaac-Velocity-Rough-Anymal-B-v0 `__ - -.. |velocity-flat-anymal-c-link| replace:: `Isaac-Velocity-Flat-Anymal-C-v0 `__ -.. |velocity-rough-anymal-c-link| replace:: `Isaac-Velocity-Rough-Anymal-C-v0 `__ - -.. |velocity-flat-anymal-c-direct-link| replace:: `Isaac-Velocity-Flat-Anymal-C-Direct-v0 `__ -.. |velocity-rough-anymal-c-direct-link| replace:: `Isaac-Velocity-Rough-Anymal-C-Direct-v0 `__ - -.. |velocity-flat-anymal-d-link| replace:: `Isaac-Velocity-Flat-Anymal-D-v0 `__ -.. |velocity-rough-anymal-d-link| replace:: `Isaac-Velocity-Rough-Anymal-D-v0 `__ - -.. |velocity-flat-unitree-a1-link| replace:: `Isaac-Velocity-Flat-Unitree-A1-v0 `__ -.. |velocity-rough-unitree-a1-link| replace:: `Isaac-Velocity-Rough-Unitree-A1-v0 `__ - -.. |velocity-flat-unitree-go1-link| replace:: `Isaac-Velocity-Flat-Unitree-Go1-v0 `__ -.. |velocity-rough-unitree-go1-link| replace:: `Isaac-Velocity-Rough-Unitree-Go1-v0 `__ - -.. |velocity-flat-unitree-go2-link| replace:: `Isaac-Velocity-Flat-Unitree-Go2-v0 `__ -.. |velocity-rough-unitree-go2-link| replace:: `Isaac-Velocity-Rough-Unitree-Go2-v0 `__ - -.. |velocity-flat-spot-link| replace:: `Isaac-Velocity-Flat-Spot-v0 `__ - -.. |velocity-flat-h1-link| replace:: `Isaac-Velocity-Flat-H1-v0 `__ -.. |velocity-rough-h1-link| replace:: `Isaac-Velocity-Rough-H1-v0 `__ - -.. |velocity-flat-g1-link| replace:: `Isaac-Velocity-Flat-G1-v0 `__ -.. |velocity-rough-g1-link| replace:: `Isaac-Velocity-Rough-G1-v0 `__ - -.. |velocity-flat-digit-link| replace:: `Isaac-Velocity-Flat-Digit-v0 `__ -.. |velocity-rough-digit-link| replace:: `Isaac-Velocity-Rough-Digit-v0 `__ -.. |tracking-loco-manip-digit-link| replace:: `Isaac-Tracking-LocoManip-Digit-v0 `__ + :widths: 25 30 25 20 + + +------------------------------+----------------------------------------------+------------------------------------------------------------------------------+------------------------------+ + | World | Environment ID | Description | Presets | + +==============================+==============================================+==============================================================================+==============================+ + | |velocity-flat-anymal-b| | |velocity-flat-anymal-b-link| | Track a velocity command on flat terrain with the Anymal B robot | ``newton_mjwarp``, ``physx`` | + +------------------------------+----------------------------------------------+------------------------------------------------------------------------------+------------------------------+ + | |velocity-rough-anymal-b| | |velocity-rough-anymal-b-link| | Track a velocity command on rough terrain with the Anymal B robot | ``newton_mjwarp``, ``physx`` | + +------------------------------+----------------------------------------------+------------------------------------------------------------------------------+------------------------------+ + | |velocity-flat-anymal-c| | |velocity-flat-anymal-c-link| | Track a velocity command on flat terrain with the Anymal C robot | ``newton_mjwarp``, ``physx`` | + | | | | | + | | |velocity-flat-anymal-c-direct-link| | | | + +------------------------------+----------------------------------------------+------------------------------------------------------------------------------+------------------------------+ + | |velocity-rough-anymal-c| | |velocity-rough-anymal-c-link| | Track a velocity command on rough terrain with the Anymal C robot | ``newton_mjwarp``, ``physx`` | + | | | | | + | | |velocity-rough-anymal-c-direct-link| | | | + +------------------------------+----------------------------------------------+------------------------------------------------------------------------------+------------------------------+ + | |velocity-flat-anymal-d| | |velocity-flat-anymal-d-link| | Track a velocity command on flat terrain with the Anymal D robot | ``newton_mjwarp``, ``physx`` | + +------------------------------+----------------------------------------------+------------------------------------------------------------------------------+------------------------------+ + | |velocity-rough-anymal-d| | |velocity-rough-anymal-d-link| | Track a velocity command on rough terrain with the Anymal D robot | ``newton_mjwarp``, ``physx`` | + +------------------------------+----------------------------------------------+------------------------------------------------------------------------------+------------------------------+ + | |velocity-flat-unitree-a1| | |velocity-flat-unitree-a1-link| | Track a velocity command on flat terrain with the Unitree A1 robot | ``newton_mjwarp``, ``physx`` | + +------------------------------+----------------------------------------------+------------------------------------------------------------------------------+------------------------------+ + | |velocity-rough-unitree-a1| | |velocity-rough-unitree-a1-link| | Track a velocity command on rough terrain with the Unitree A1 robot | ``newton_mjwarp``, ``physx`` | + +------------------------------+----------------------------------------------+------------------------------------------------------------------------------+------------------------------+ + | |velocity-flat-unitree-go1| | |velocity-flat-unitree-go1-link| | Track a velocity command on flat terrain with the Unitree Go1 robot | ``newton_mjwarp``, ``physx`` | + +------------------------------+----------------------------------------------+------------------------------------------------------------------------------+------------------------------+ + | |velocity-rough-unitree-go1| | |velocity-rough-unitree-go1-link| | Track a velocity command on rough terrain with the Unitree Go1 robot | ``newton_mjwarp``, ``physx`` | + +------------------------------+----------------------------------------------+------------------------------------------------------------------------------+------------------------------+ + | |velocity-flat-unitree-go2| | |velocity-flat-unitree-go2-link| | Track a velocity command on flat terrain with the Unitree Go2 robot | ``newton_mjwarp``, ``physx`` | + +------------------------------+----------------------------------------------+------------------------------------------------------------------------------+------------------------------+ + | |velocity-rough-unitree-go2| | |velocity-rough-unitree-go2-link| | Track a velocity command on rough terrain with the Unitree Go2 robot | ``newton_mjwarp``, ``physx`` | + +------------------------------+----------------------------------------------+------------------------------------------------------------------------------+------------------------------+ + | |velocity-flat-spot| | |velocity-flat-spot-link| | Track a velocity command on flat terrain with the Boston Dynamics Spot robot | ``newton_mjwarp``, ``physx`` | + +------------------------------+----------------------------------------------+------------------------------------------------------------------------------+------------------------------+ + | |velocity-flat-h1| | |velocity-flat-h1-link| | Track a velocity command on flat terrain with the Unitree H1 robot | ``newton_mjwarp``, ``physx`` | + +------------------------------+----------------------------------------------+------------------------------------------------------------------------------+------------------------------+ + | |velocity-rough-h1| | |velocity-rough-h1-link| | Track a velocity command on rough terrain with the Unitree H1 robot | ``newton_mjwarp``, ``physx`` | + +------------------------------+----------------------------------------------+------------------------------------------------------------------------------+------------------------------+ + | |velocity-flat-g1| | |velocity-flat-g1-link| | Track a velocity command on flat terrain with the Unitree G1 robot | ``newton_mjwarp``, ``physx`` | + +------------------------------+----------------------------------------------+------------------------------------------------------------------------------+------------------------------+ + | |velocity-rough-g1| | |velocity-rough-g1-link| | Track a velocity command on rough terrain with the Unitree G1 robot | ``newton_mjwarp``, ``physx`` | + +------------------------------+----------------------------------------------+------------------------------------------------------------------------------+------------------------------+ + | |velocity-flat-digit| | |velocity-flat-digit-link| | Track a velocity command on flat terrain with the Agility Digit robot | ``newton_mjwarp``, ``physx`` | + +------------------------------+----------------------------------------------+------------------------------------------------------------------------------+------------------------------+ + | |velocity-rough-digit| | |velocity-rough-digit-link| | Track a velocity command on rough terrain with the Agility Digit robot | ``newton_mjwarp``, ``physx`` | + +------------------------------+----------------------------------------------+------------------------------------------------------------------------------+------------------------------+ + | |tracking-loco-manip-digit| | |tracking-loco-manip-digit-link| | Track a root velocity and hand pose command with the Agility Digit robot | ``newton_mjwarp``, ``physx`` | + +------------------------------+----------------------------------------------+------------------------------------------------------------------------------+------------------------------+ + +.. |velocity-flat-anymal-b-link| replace:: `Isaac-Velocity-Flat-Anymal-B-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/anymal_b/flat_env_cfg.py>`__ +.. |velocity-rough-anymal-b-link| replace:: `Isaac-Velocity-Rough-Anymal-B-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/anymal_b/rough_env_cfg.py>`__ + +.. |velocity-flat-anymal-c-link| replace:: `Isaac-Velocity-Flat-Anymal-C-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/anymal_c/flat_env_cfg.py>`__ +.. |velocity-rough-anymal-c-link| replace:: `Isaac-Velocity-Rough-Anymal-C-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/anymal_c/rough_env_cfg.py>`__ + +.. |velocity-flat-anymal-c-direct-link| replace:: `Isaac-Velocity-Flat-Anymal-C-Direct-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/direct/anymal_c/anymal_c_env.py>`__ +.. |velocity-rough-anymal-c-direct-link| replace:: `Isaac-Velocity-Rough-Anymal-C-Direct-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/direct/anymal_c/anymal_c_env.py>`__ + +.. |velocity-flat-anymal-d-link| replace:: `Isaac-Velocity-Flat-Anymal-D-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/anymal_d/flat_env_cfg.py>`__ +.. |velocity-rough-anymal-d-link| replace:: `Isaac-Velocity-Rough-Anymal-D-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/anymal_d/rough_env_cfg.py>`__ + +.. |velocity-flat-unitree-a1-link| replace:: `Isaac-Velocity-Flat-Unitree-A1-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/a1/flat_env_cfg.py>`__ +.. |velocity-rough-unitree-a1-link| replace:: `Isaac-Velocity-Rough-Unitree-A1-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/a1/rough_env_cfg.py>`__ + +.. |velocity-flat-unitree-go1-link| replace:: `Isaac-Velocity-Flat-Unitree-Go1-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/go1/flat_env_cfg.py>`__ +.. |velocity-rough-unitree-go1-link| replace:: `Isaac-Velocity-Rough-Unitree-Go1-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/go1/rough_env_cfg.py>`__ + +.. |velocity-flat-unitree-go2-link| replace:: `Isaac-Velocity-Flat-Unitree-Go2-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/go2/flat_env_cfg.py>`__ +.. |velocity-rough-unitree-go2-link| replace:: `Isaac-Velocity-Rough-Unitree-Go2-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/go2/rough_env_cfg.py>`__ + +.. |velocity-flat-spot-link| replace:: `Isaac-Velocity-Flat-Spot-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/spot/flat_env_cfg.py>`__ + +.. |velocity-flat-h1-link| replace:: `Isaac-Velocity-Flat-H1-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/h1/flat_env_cfg.py>`__ +.. |velocity-rough-h1-link| replace:: `Isaac-Velocity-Rough-H1-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/h1/rough_env_cfg.py>`__ + +.. |velocity-flat-g1-link| replace:: `Isaac-Velocity-Flat-G1-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/g1/flat_env_cfg.py>`__ +.. |velocity-rough-g1-link| replace:: `Isaac-Velocity-Rough-G1-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/g1/rough_env_cfg.py>`__ + +.. |velocity-flat-digit-link| replace:: `Isaac-Velocity-Flat-Digit-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/digit/flat_env_cfg.py>`__ +.. |velocity-rough-digit-link| replace:: `Isaac-Velocity-Rough-Digit-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/digit/rough_env_cfg.py>`__ +.. |tracking-loco-manip-digit-link| replace:: `Isaac-Tracking-LocoManip-Digit-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/locomanipulation/tracking/config/digit/loco_manip_env_cfg.py>`__ .. |velocity-flat-anymal-b| image:: ../_static/tasks/locomotion/anymal_b_flat.jpg .. |velocity-rough-anymal-b| image:: ../_static/tasks/locomotion/anymal_b_rough.jpg @@ -484,15 +506,15 @@ Navigation ~~~~~~~~~~ .. table:: - :widths: 33 37 30 + :widths: 25 30 25 20 - +----------------+---------------------+-----------------------------------------------------------------------------+ - | World | Environment ID | Description | - +================+=====================+=============================================================================+ - | |anymal_c_nav| | |anymal_c_nav-link| | Navigate towards a target x-y position and heading with the ANYmal C robot. | - +----------------+---------------------+-----------------------------------------------------------------------------+ + +----------------+---------------------+-----------------------------------------------------------------------------+------------------------------+ + | World | Environment ID | Description | Presets | + +================+=====================+=============================================================================+==============================+ + | |anymal_c_nav| | |anymal_c_nav-link| | Navigate towards a target x-y position and heading with the ANYmal C robot. | ``newton_mjwarp``, ``physx`` | + +----------------+---------------------+-----------------------------------------------------------------------------+------------------------------+ -.. |anymal_c_nav-link| replace:: `Isaac-Navigation-Flat-Anymal-C-v0 `__ +.. |anymal_c_nav-link| replace:: `Isaac-Navigation-Flat-Anymal-C-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/navigation/config/anymal_c/navigation_env_cfg.py>`__ .. |anymal_c_nav| image:: ../_static/tasks/navigation/anymal_c_nav.jpg @@ -505,18 +527,18 @@ Multirotor See the `drone_arl` folder and the ARL robot config (`ARL_ROBOT_1_CFG`) in the codebase for details. -.. |arl_robot_track_position_state_based-link| replace:: `Isaac-TrackPositionNoObstacles-ARL-Robot-1-v0 `__ +.. |arl_robot_track_position_state_based-link| replace:: `Isaac-TrackPositionNoObstacles-ARL-Robot-1-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/manager_based/drone_arl/track_position_state_based/config/arl_robot_1/track_position_state_based_env_cfg.py>`__ .. |arl_robot_track_position_state_based| image:: ../_static/tasks/drone_arl/arl_robot_1_track_position_state_based.jpg .. table:: - :widths: 33 37 30 + :widths: 25 30 25 20 - +----------------------------------------+---------------------------------------------+----------------------------------------------------------------------------------------+ - | World | Environment ID | Description | - +========================================+=============================================+========================================================================================+ - | |arl_robot_track_position_state_based| | |arl_robot_track_position_state_based-link| | Setpoint position control for the ARL robot using the track_position_state_based task. | - +----------------------------------------+---------------------------------------------+----------------------------------------------------------------------------------------+ + +----------------------------------------+---------------------------------------------+----------------------------------------------------------------------------------------+------------------------------+ + | World | Environment ID | Description | Presets | + +========================================+=============================================+========================================================================================+==============================+ + | |arl_robot_track_position_state_based| | |arl_robot_track_position_state_based-link| | Setpoint position control for the ARL robot using the track_position_state_based task. | | + +----------------------------------------+---------------------------------------------+----------------------------------------------------------------------------------------+------------------------------+ Others @@ -532,24 +554,24 @@ Others For evaluation, the play script's command line input ``--real-time`` allows the interaction loop between the environment and the agent to run in real time, if possible. .. table:: - :widths: 33 37 30 - - +----------------+---------------------------+-----------------------------------------------------------------------------+ - | World | Environment ID | Description | - +================+===========================+=============================================================================+ - | |quadcopter| | |quadcopter-link| | Fly and hover the Crazyflie copter at a goal point by applying thrust. | - +----------------+---------------------------+-----------------------------------------------------------------------------+ - | |humanoid_amp| | |humanoid_amp_dance-link| | Move a humanoid robot by imitating different pre-recorded human animations | - | | | (Adversarial Motion Priors). | - | | |humanoid_amp_run-link| | | - | | | | - | | |humanoid_amp_walk-link| | | - +----------------+---------------------------+-----------------------------------------------------------------------------+ - -.. |quadcopter-link| replace:: `Isaac-Quadcopter-Direct-v0 `__ -.. |humanoid_amp_dance-link| replace:: `Isaac-Humanoid-AMP-Dance-Direct-v0 `__ -.. |humanoid_amp_run-link| replace:: `Isaac-Humanoid-AMP-Run-Direct-v0 `__ -.. |humanoid_amp_walk-link| replace:: `Isaac-Humanoid-AMP-Walk-Direct-v0 `__ + :widths: 25 30 25 20 + + +----------------+---------------------------+-----------------------------------------------------------------------------+------------------------------+ + | World | Environment ID | Description | Presets | + +================+===========================+=============================================================================+==============================+ + | |quadcopter| | |quadcopter-link| | Fly and hover the Crazyflie copter at a goal point by applying thrust. | | + +----------------+---------------------------+-----------------------------------------------------------------------------+------------------------------+ + | |humanoid_amp| | |humanoid_amp_dance-link| | Move a humanoid robot by imitating different pre-recorded human animations | | + | | | (Adversarial Motion Priors). | | + | | |humanoid_amp_run-link| | | | + | | | | | + | | |humanoid_amp_walk-link| | | | + +----------------+---------------------------+-----------------------------------------------------------------------------+------------------------------+ + +.. |quadcopter-link| replace:: `Isaac-Quadcopter-Direct-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/direct/quadcopter/quadcopter_env.py>`__ +.. |humanoid_amp_dance-link| replace:: `Isaac-Humanoid-AMP-Dance-Direct-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/direct/humanoid_amp/humanoid_amp_env_cfg.py>`__ +.. |humanoid_amp_run-link| replace:: `Isaac-Humanoid-AMP-Run-Direct-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/direct/humanoid_amp/humanoid_amp_env_cfg.py>`__ +.. |humanoid_amp_walk-link| replace:: `Isaac-Humanoid-AMP-Walk-Direct-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/direct/humanoid_amp/humanoid_amp_env_cfg.py>`__ .. |quadcopter| image:: ../_static/tasks/others/quadcopter.jpg .. |humanoid_amp| image:: ../_static/tasks/others/humanoid_amp.jpg @@ -684,17 +706,17 @@ Classic ~~~~~~~ .. table:: - :widths: 33 37 30 + :widths: 25 30 25 20 - +------------------------+------------------------------------+-----------------------------------------------------------------------------------------------------------------------+ - | World | Environment ID | Description | - +========================+====================================+=======================================================================================================================+ - | |cart-double-pendulum| | |cart-double-pendulum-direct-link| | Move the cart and the pendulum to keep the last one upwards in the classic inverted double pendulum on a cart control | - +------------------------+------------------------------------+-----------------------------------------------------------------------------------------------------------------------+ + +------------------------+------------------------------------+-----------------------------------------------------------------------------------------------------------------------+------------------------------+ + | World | Environment ID | Description | Presets | + +========================+====================================+=======================================================================================================================+==============================+ + | |cart-double-pendulum| | |cart-double-pendulum-direct-link| | Move the cart and the pendulum to keep the last one upwards in the classic inverted double pendulum on a cart control | | + +------------------------+------------------------------------+-----------------------------------------------------------------------------------------------------------------------+------------------------------+ .. |cart-double-pendulum| image:: ../_static/tasks/classic/cart_double_pendulum.jpg -.. |cart-double-pendulum-direct-link| replace:: `Isaac-Cart-Double-Pendulum-Direct-v0 `__ +.. |cart-double-pendulum-direct-link| replace:: `Isaac-Cart-Double-Pendulum-Direct-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/direct/cart_double_pendulum/cart_double_pendulum_env.py>`__ Manipulation ~~~~~~~~~~~~ @@ -702,17 +724,17 @@ Manipulation Environments based on fixed-arm manipulation tasks. .. table:: - :widths: 33 37 30 + :widths: 25 30 25 20 - +----------------------+--------------------------------+--------------------------------------------------------+ - | World | Environment ID | Description | - +======================+================================+========================================================+ - | |shadow-hand-over| | |shadow-hand-over-direct-link| | Passing an object from one hand over to the other hand | - +----------------------+--------------------------------+--------------------------------------------------------+ + +----------------------+--------------------------------+--------------------------------------------------------+------------------------------+ + | World | Environment ID | Description | Presets | + +======================+================================+========================================================+==============================+ + | |shadow-hand-over| | |shadow-hand-over-direct-link| | Passing an object from one hand over to the other hand | | + +----------------------+--------------------------------+--------------------------------------------------------+------------------------------+ .. |shadow-hand-over| image:: ../_static/tasks/manipulation/shadow_hand_over.jpg -.. |shadow-hand-over-direct-link| replace:: `Isaac-Shadow-Hand-Over-Direct-v0 `__ +.. |shadow-hand-over-direct-link| replace:: `Isaac-Shadow-Hand-Over-Direct-v0 <../../../source/isaaclab_tasks/isaaclab_tasks/direct/shadow_hand_over/shadow_hand_over_env.py>`__ | @@ -724,308 +746,373 @@ provided when running ``play.py`` or any inferencing workflows. These tasks prov inferencing, including reading from an already trained checkpoint and disabling runtime perturbations used for training. .. list-table:: - :widths: 33 25 19 25 + :widths: 28 20 13 22 17 * - **Task Name** - **Inference Task Name** - **Workflow** - **RL Library** + - **Presets** * - Isaac-Ant-Direct-v0 - - Direct - **rl_games** (PPO), **rsl_rl** (PPO), **skrl** (PPO) + - ``newton_mjwarp``, ``physx``, ``ovphysx`` * - Isaac-Ant-v0 - - Manager Based - **rsl_rl** (PPO), **rl_games** (PPO), **skrl** (PPO), **sb3** (PPO) + - ``newton_mjwarp``, ``physx`` * - Isaac-Cart-Double-Pendulum-Direct-v0 - - Direct - **rl_games** (PPO), **skrl** (IPPO, PPO, MAPPO) + - * - Isaac-Cartpole-Camera-Showcase-Box-Box-Direct-v0 (Requires running with ``--enable_cameras``) - - Direct - **skrl** (PPO) + - ``newton_renderer``, ``ovrtx_renderer``, ``isaacsim_rtx_renderer`` * - Isaac-Cartpole-Camera-Showcase-Box-Discrete-Direct-v0 (Requires running with ``--enable_cameras``) - - Direct - **skrl** (PPO) + - ``newton_renderer``, ``ovrtx_renderer``, ``isaacsim_rtx_renderer`` * - Isaac-Cartpole-Camera-Showcase-Box-MultiDiscrete-Direct-v0 (Requires running with ``--enable_cameras``) - - Direct - **skrl** (PPO) + - ``newton_renderer``, ``ovrtx_renderer``, ``isaacsim_rtx_renderer`` * - Isaac-Cartpole-Camera-Showcase-Dict-Box-Direct-v0 (Requires running with ``--enable_cameras``) - - Direct - **skrl** (PPO) + - ``newton_renderer``, ``ovrtx_renderer``, ``isaacsim_rtx_renderer`` * - Isaac-Cartpole-Camera-Showcase-Dict-Discrete-Direct-v0 (Requires running with ``--enable_cameras``) - - Direct - **skrl** (PPO) + - ``newton_renderer``, ``ovrtx_renderer``, ``isaacsim_rtx_renderer`` * - Isaac-Cartpole-Camera-Showcase-Dict-MultiDiscrete-Direct-v0 (Requires running with ``--enable_cameras``) - - Direct - **skrl** (PPO) + - ``newton_renderer``, ``ovrtx_renderer``, ``isaacsim_rtx_renderer`` * - Isaac-Cartpole-Camera-Showcase-Tuple-Box-Direct-v0 (Requires running with ``--enable_cameras``) - - Direct - **skrl** (PPO) + - ``newton_renderer``, ``ovrtx_renderer``, ``isaacsim_rtx_renderer`` * - Isaac-Cartpole-Camera-Showcase-Tuple-Discrete-Direct-v0 (Requires running with ``--enable_cameras``) - - Direct - **skrl** (PPO) + - ``newton_renderer``, ``ovrtx_renderer``, ``isaacsim_rtx_renderer`` * - Isaac-Cartpole-Camera-Showcase-Tuple-MultiDiscrete-Direct-v0 (Requires running with ``--enable_cameras``) - - Direct - **skrl** (PPO) - * - Isaac-Cartpole-Depth-Camera-Direct-v0 (Requires running with ``--enable_cameras``) + - ``newton_renderer``, ``ovrtx_renderer``, ``isaacsim_rtx_renderer`` + * - Isaac-Cartpole-Camera-Presets-Direct-v0 (Requires running with ``--enable_cameras``) - - Direct - **rl_games** (PPO), **skrl** (PPO) - * - Isaac-Cartpole-Depth-v0 (Requires running with ``--enable_cameras``) - - - - Manager Based - - **rl_games** (PPO) + - ``newton_mjwarp``, ``physx``, ``newton_renderer``, ``ovrtx_renderer``, ``isaacsim_rtx_renderer``, ``rgb``, ``depth``, ``albedo``, ``semantic_segmentation``, ``simple_shading_constant_diffuse``, ``simple_shading_diffuse_mdl``, ``simple_shading_full_mdl`` * - Isaac-Cartpole-Direct-v0 - - Direct - **rl_games** (PPO), **rsl_rl** (PPO), **skrl** (PPO), **sb3** (PPO) - * - Isaac-Cartpole-RGB-Camera-Direct-v0 (Requires running with ``--enable_cameras``) - - - - Direct - - **rl_games** (PPO), **skrl** (PPO) + - ``newton_mjwarp``, ``physx``, ``ovphysx`` * - Isaac-Cartpole-RGB-ResNet18-v0 (Requires running with ``--enable_cameras``) - - Manager Based - **rl_games** (PPO) + - ``newton_mjwarp``, ``physx`` * - Isaac-Cartpole-RGB-TheiaTiny-v0 (Requires running with ``--enable_cameras``) - - Manager Based - **rl_games** (PPO) - * - Isaac-Cartpole-RGB-v0 (Requires running with ``--enable_cameras``) - - - - Manager Based - - **rl_games** (PPO) + - ``newton_mjwarp``, ``physx`` * - Isaac-Cartpole-Showcase-Box-Box-Direct-v0 - - Direct - **skrl** (PPO) + - ``newton_mjwarp``, ``physx``, ``ovphysx`` * - Isaac-Cartpole-Showcase-Box-Discrete-Direct-v0 - - Direct - **skrl** (PPO) + - ``newton_mjwarp``, ``physx``, ``ovphysx`` * - Isaac-Cartpole-Showcase-Box-MultiDiscrete-Direct-v0 - - Direct - **skrl** (PPO) + - ``newton_mjwarp``, ``physx``, ``ovphysx`` * - Isaac-Cartpole-Showcase-Dict-Box-Direct-v0 - - Direct - **skrl** (PPO) + - ``newton_mjwarp``, ``physx``, ``ovphysx`` * - Isaac-Cartpole-Showcase-Dict-Discrete-Direct-v0 - - Direct - **skrl** (PPO) + - ``newton_mjwarp``, ``physx``, ``ovphysx`` * - Isaac-Cartpole-Showcase-Dict-MultiDiscrete-Direct-v0 - - Direct - **skrl** (PPO) + - ``newton_mjwarp``, ``physx``, ``ovphysx`` * - Isaac-Cartpole-Showcase-Discrete-Box-Direct-v0 - - Direct - **skrl** (PPO) + - ``newton_mjwarp``, ``physx``, ``ovphysx`` * - Isaac-Cartpole-Showcase-Discrete-Discrete-Direct-v0 - - Direct - **skrl** (PPO) + - ``newton_mjwarp``, ``physx``, ``ovphysx`` * - Isaac-Cartpole-Showcase-Discrete-MultiDiscrete-Direct-v0 - - Direct - **skrl** (PPO) + - ``newton_mjwarp``, ``physx``, ``ovphysx`` * - Isaac-Cartpole-Showcase-MultiDiscrete-Box-Direct-v0 - - Direct - **skrl** (PPO) + - ``newton_mjwarp``, ``physx``, ``ovphysx`` * - Isaac-Cartpole-Showcase-MultiDiscrete-Discrete-Direct-v0 - - Direct - **skrl** (PPO) + - ``newton_mjwarp``, ``physx``, ``ovphysx`` * - Isaac-Cartpole-Showcase-MultiDiscrete-MultiDiscrete-Direct-v0 - - Direct - **skrl** (PPO) + - ``newton_mjwarp``, ``physx``, ``ovphysx`` * - Isaac-Cartpole-Showcase-Tuple-Box-Direct-v0 - - Direct - **skrl** (PPO) + - ``newton_mjwarp``, ``physx``, ``ovphysx`` * - Isaac-Cartpole-Showcase-Tuple-Discrete-Direct-v0 - - Direct - **skrl** (PPO) + - ``newton_mjwarp``, ``physx``, ``ovphysx`` * - Isaac-Cartpole-Showcase-Tuple-MultiDiscrete-Direct-v0 - - Direct - **skrl** (PPO) + - ``newton_mjwarp``, ``physx``, ``ovphysx`` * - Isaac-Cartpole-v0 - - Manager Based - **rl_games** (PPO), **rsl_rl** (PPO), **skrl** (PPO), **sb3** (PPO) + - ``newton_mjwarp``, ``physx`` * - Isaac-Factory-GearMesh-Direct-v0 - - Direct - **rl_games** (PPO) + - * - Isaac-Factory-NutThread-Direct-v0 - - Direct - **rl_games** (PPO) + - * - Isaac-Factory-PegInsert-Direct-v0 - - Direct - **rl_games** (PPO) + - * - Isaac-AutoMate-Assembly-Direct-v0 - - Direct - **rl_games** (PPO) + - * - Isaac-AutoMate-Disassembly-Direct-v0 - - Direct - + - * - Isaac-Forge-GearMesh-Direct-v0 - - Direct - **rl_games** (PPO) + - * - Isaac-Forge-NutThread-Direct-v0 - - Direct - **rl_games** (PPO) + - * - Isaac-Forge-PegInsert-Direct-v0 - - Direct - **rl_games** (PPO) + - * - Isaac-Franka-Cabinet-Direct-v0 - - Direct - **rl_games** (PPO), **rsl_rl** (PPO), **skrl** (PPO) + - * - Isaac-Humanoid-AMP-Dance-Direct-v0 - - Direct - **skrl** (AMP) + - * - Isaac-Humanoid-AMP-Run-Direct-v0 - - Direct - **skrl** (AMP) + - * - Isaac-Humanoid-AMP-Walk-Direct-v0 - - Direct - **skrl** (AMP) + - * - Isaac-Humanoid-Direct-v0 - - Direct - **rl_games** (PPO), **rsl_rl** (PPO), **skrl** (PPO) + - ``newton_mjwarp``, ``physx``, ``ovphysx`` * - Isaac-Humanoid-v0 - - Manager Based - **rsl_rl** (PPO), **rl_games** (PPO), **skrl** (PPO), **sb3** (PPO) + - ``newton_mjwarp``, ``physx`` * - Isaac-Lift-Cube-Franka-IK-Abs-v0 - - Manager Based - + - * - Isaac-Lift-Cube-Franka-IK-Rel-v0 - - Manager Based - + - * - Isaac-Lift-Cube-Franka-v0 - Isaac-Lift-Cube-Franka-Play-v0 - Manager Based - **rsl_rl** (PPO), **skrl** (PPO), **rl_games** (PPO), **sb3** (PPO) + - * - Isaac-Lift-Teddy-Bear-Franka-IK-Abs-v0 - - Manager Based - + - * - Isaac-Tracking-LocoManip-Digit-v0 - Isaac-Tracking-LocoManip-Digit-Play-v0 - Manager Based - **rsl_rl** (PPO) + - ``newton_mjwarp``, ``physx`` * - Isaac-Navigation-Flat-Anymal-C-v0 - Isaac-Navigation-Flat-Anymal-C-Play-v0 - Manager Based - **rsl_rl** (PPO), **skrl** (PPO) + - ``newton_mjwarp``, ``physx`` * - Isaac-Open-Drawer-Franka-IK-Abs-v0 - - Manager Based - + - * - Isaac-Open-Drawer-Franka-IK-Rel-v0 - - Manager Based - + - * - Isaac-Open-Drawer-Franka-v0 - Isaac-Open-Drawer-Franka-Play-v0 - Manager Based - **rsl_rl** (PPO), **rl_games** (PPO), **skrl** (PPO) + - ``newton_mjwarp``, ``physx`` * - Isaac-Quadcopter-Direct-v0 - - Direct - **rl_games** (PPO), **rsl_rl** (PPO), **skrl** (PPO) + - * - Isaac-Reach-Franka-IK-Abs-v0 - - Manager Based - + - * - Isaac-Reach-Franka-IK-Rel-v0 - - Manager Based - + - * - Isaac-Reach-Franka-OSC-v0 - Isaac-Reach-Franka-OSC-Play-v0 - Manager Based - **rsl_rl** (PPO) + - ``newton_mjwarp``, ``physx`` * - Isaac-Reach-Franka-v0 - Isaac-Reach-Franka-Play-v0 - Manager Based - **rl_games** (PPO), **rsl_rl** (PPO), **skrl** (PPO) + - ``newton_mjwarp``, ``physx`` * - Isaac-Reach-UR10-v0 - Isaac-Reach-UR10-Play-v0 - Manager Based - **rl_games** (PPO), **rsl_rl** (PPO), **skrl** (PPO) + - ``newton_mjwarp``, ``physx`` * - Isaac-Deploy-Reach-UR10e-v0 - Isaac-Deploy-Reach-UR10e-Play-v0 - Manager Based - **rsl_rl** (PPO) + - * - Isaac-Repose-Cube-Allegro-Direct-v0 - - Direct - **rl_games** (PPO), **rsl_rl** (PPO), **skrl** (PPO) + - ``newton_mjwarp``, ``physx`` * - Isaac-Repose-Cube-Allegro-NoVelObs-v0 - Isaac-Repose-Cube-Allegro-NoVelObs-Play-v0 - Manager Based - **rsl_rl** (PPO), **rl_games** (PPO), **skrl** (PPO) + - * - Isaac-Repose-Cube-Allegro-v0 - Isaac-Repose-Cube-Allegro-Play-v0 - Manager Based - **rsl_rl** (PPO), **rl_games** (PPO), **skrl** (PPO) + - * - Isaac-Repose-Cube-Shadow-Direct-v0 - - Direct - **rl_games** (PPO), **rsl_rl** (PPO), **skrl** (PPO) + - ``newton_mjwarp``, ``physx`` * - Isaac-Repose-Cube-Shadow-OpenAI-FF-Direct-v0 - - Direct - **rl_games** (FF), **rsl_rl** (PPO), **skrl** (PPO) + - ``newton_mjwarp``, ``physx`` * - Isaac-Repose-Cube-Shadow-OpenAI-LSTM-Direct-v0 - - Direct - **rl_games** (LSTM) + - ``newton_mjwarp``, ``physx`` * - Isaac-Repose-Cube-Shadow-Vision-Direct-v0 (Requires running with ``--enable_cameras``) - Isaac-Repose-Cube-Shadow-Vision-Direct-Play-v0 (Requires running with ``--enable_cameras``) - Direct - **rsl_rl** (PPO), **rl_games** (VISION) + - ``newton_mjwarp``, ``physx``, ``newton_renderer``, ``ovrtx_renderer``, ``isaacsim_rtx_renderer``, ``rgb``, ``depth``, ``albedo``, ``full``, ``semantic_segmentation``, ``simple_shading_constant_diffuse``, ``simple_shading_diffuse_mdl``, ``simple_shading_full_mdl`` * - Isaac-Shadow-Hand-Over-Direct-v0 - - Direct - **rl_games** (PPO), **skrl** (IPPO, PPO, MAPPO) + - * - Isaac-Stack-Cube-Franka-IK-Rel-v0 - - Manager Based - + - + * - Isaac-Stack-Cube-Franka-IK-Abs-v0 + - + - Manager Based + - + - ``physx`` * - Isaac-Dexsuite-Kuka-Allegro-Lift-v0 Camera variants (requires ``--enable_cameras``): @@ -1041,6 +1128,7 @@ inferencing, including reading from an already trained checkpoint and disabling - Isaac-Dexsuite-Kuka-Allegro-Lift-Play-v0 - Manager Based - **rl_games** (PPO), **rsl_rl** (PPO) + - ``newton_mjwarp``, ``physx``, ``single_camera``, ``duo_camera``, ``state``, ``newton_renderer``, ``ovrtx_renderer``, ``isaacsim_rtx_renderer``, ``rgb64``, ``rgb128``, ``rgb256``, ``depth64``, ``depth128``, ``depth256``, ``albedo64``, ``albedo128``, ``albedo256``, ``semantic_segmentation64``, ``semantic_segmentation128``, ``semantic_segmentation256``, ``simple_shading_constant_diffuse64``, ``simple_shading_constant_diffuse128``, ``simple_shading_constant_diffuse256``, ``simple_shading_diffuse_mdl64``, ``simple_shading_diffuse_mdl128``, ``simple_shading_diffuse_mdl256``, ``simple_shading_full_mdl64``, ``simple_shading_full_mdl128``, ``simple_shading_full_mdl256`` * - Isaac-Dexsuite-Kuka-Allegro-Reorient-v0 Camera variants (requires ``--enable_cameras``): @@ -1053,176 +1141,225 @@ inferencing, including reading from an already trained checkpoint and disabling - Isaac-Dexsuite-Kuka-Allegro-Reorient-Play-v0 - Manager Based - **rl_games** (PPO), **rsl_rl** (PPO) + - ``newton_mjwarp``, ``physx``, ``single_camera``, ``duo_camera``, ``state``, ``newton_renderer``, ``ovrtx_renderer``, ``isaacsim_rtx_renderer``, ``rgb64``, ``rgb128``, ``rgb256``, ``depth64``, ``depth128``, ``depth256``, ``albedo64``, ``albedo128``, ``albedo256``, ``semantic_segmentation64``, ``semantic_segmentation128``, ``semantic_segmentation256``, ``simple_shading_constant_diffuse64``, ``simple_shading_constant_diffuse128``, ``simple_shading_constant_diffuse256``, ``simple_shading_diffuse_mdl64``, ``simple_shading_diffuse_mdl128``, ``simple_shading_diffuse_mdl256``, ``simple_shading_full_mdl64``, ``simple_shading_full_mdl128``, ``simple_shading_full_mdl256`` * - Isaac-Stack-Cube-Franka-v0 - - Manager Based - + - * - Isaac-Stack-Cube-Instance-Randomize-Franka-IK-Rel-v0 - - Manager Based - + - * - Isaac-Stack-Cube-Instance-Randomize-Franka-v0 - - Manager Based - + - * - Isaac-PickPlace-G1-InspireFTP-Abs-v0 - - Manager Based - - * - Isaac-Stack-Cube-UR10-Long-Suction-IK-Rel-v0 + - ``physx`` + * - Isaac-PickPlace-GR1T2-Abs-v0 - - Manager Based - - * - Isaac-Stack-Cube-UR10-Short-Suction-IK-Rel-v0 + - ``physx`` + * - Isaac-PickPlace-GR1T2-WaistEnabled-Abs-v0 - - Manager Based - - * - Isaac-Stack-Cube-Galbot-Left-Arm-Gripper-RmpFlow-v0 + - ``physx`` + * - Isaac-NutPour-GR1T2-Pink-IK-Abs-v0 - - Manager Based - - * - Isaac-Stack-Cube-Galbot-Right-Arm-Suction-RmpFlow-v0 + - ``physx`` + * - Isaac-ExhaustPipe-GR1T2-Pink-IK-Abs-v0 - - Manager Based - - * - Isaac-Stack-Cube-Galbot-Left-Arm-Gripper-Visuomotor-v0 - - Isaac-Stack-Cube-Galbot-Left-Arm-Gripper-Visuomotor-Play-v0 + - ``physx`` + * - Isaac-PickPlace-Locomanipulation-G1-Abs-v0 + - - Manager Based - - * - Isaac-Place-Mug-Agibot-Left-Arm-RmpFlow-v0 + - ``physx`` + * - Isaac-PickPlace-FixedBaseUpperBodyIK-G1-Abs-v0 - - Manager Based - - * - Isaac-Place-Toy2Box-Agibot-Right-Arm-RmpFlow-v0 + - ``physx`` + * - Isaac-Stack-Cube-UR10-Long-Suction-IK-Rel-v0 - - Manager Based - + - + * - Isaac-Stack-Cube-UR10-Short-Suction-IK-Rel-v0 + - + - Manager Based + - + - * - Isaac-Stack-Cube-Galbot-Left-Arm-Gripper-RmpFlow-v0 - - Manager Based - + - ``physx`` * - Isaac-Stack-Cube-Galbot-Right-Arm-Suction-RmpFlow-v0 - - Manager Based - + - ``physx`` * - Isaac-Stack-Cube-Galbot-Left-Arm-Gripper-Visuomotor-v0 - Isaac-Stack-Cube-Galbot-Left-Arm-Gripper-Visuomotor-Play-v0 - Manager Based - + - ``physx`` * - Isaac-Place-Mug-Agibot-Left-Arm-RmpFlow-v0 - - Manager Based - + - * - Isaac-Place-Toy2Box-Agibot-Right-Arm-RmpFlow-v0 - - Manager Based - + - * - Isaac-Velocity-Flat-Anymal-B-v0 - Isaac-Velocity-Flat-Anymal-B-Play-v0 - Manager Based - **rsl_rl** (PPO), **skrl** (PPO) + - ``newton_mjwarp``, ``physx`` * - Isaac-Velocity-Flat-Anymal-C-Direct-v0 - - Direct - **rl_games** (PPO), **rsl_rl** (PPO), **skrl** (PPO) + - * - Isaac-Velocity-Flat-Anymal-C-v0 - Isaac-Velocity-Flat-Anymal-C-Play-v0 - Manager Based - **rsl_rl** (PPO), **rl_games** (PPO), **skrl** (PPO) + - ``newton_mjwarp``, ``physx`` * - Isaac-Velocity-Flat-Anymal-D-v0 - Isaac-Velocity-Flat-Anymal-D-Play-v0 - Manager Based - **rsl_rl** (PPO), **skrl** (PPO) + - ``newton_mjwarp``, ``physx`` * - Isaac-Velocity-Flat-Cassie-v0 - Isaac-Velocity-Flat-Cassie-Play-v0 - Manager Based - **rsl_rl** (PPO), **skrl** (PPO) + - * - Isaac-Velocity-Flat-Digit-v0 - Isaac-Velocity-Flat-Digit-Play-v0 - Manager Based - **rsl_rl** (PPO) + - ``newton_mjwarp``, ``physx`` * - Isaac-Velocity-Flat-G1-v0 - Isaac-Velocity-Flat-G1-Play-v0 - Manager Based - **rsl_rl** (PPO), **skrl** (PPO) + - ``newton_mjwarp``, ``physx`` * - Isaac-Velocity-Flat-H1-v0 - Isaac-Velocity-Flat-H1-Play-v0 - Manager Based - **rsl_rl** (PPO), **skrl** (PPO) + - ``newton_mjwarp``, ``physx`` * - Isaac-Velocity-Flat-Spot-v0 - Isaac-Velocity-Flat-Spot-Play-v0 - Manager Based - **rsl_rl** (PPO), **skrl** (PPO) + - ``newton_mjwarp``, ``physx`` * - Isaac-Velocity-Flat-Unitree-A1-v0 - Isaac-Velocity-Flat-Unitree-A1-Play-v0 - Manager Based - **rsl_rl** (PPO), **skrl** (PPO), **sb3** (PPO) + - ``newton_mjwarp``, ``physx`` * - Isaac-Velocity-Flat-Unitree-Go1-v0 - Isaac-Velocity-Flat-Unitree-Go1-Play-v0 - Manager Based - **rsl_rl** (PPO), **skrl** (PPO) + - ``newton_mjwarp``, ``physx`` * - Isaac-Velocity-Flat-Unitree-Go2-v0 - Isaac-Velocity-Flat-Unitree-Go2-Play-v0 - Manager Based - **rsl_rl** (PPO), **skrl** (PPO) + - ``newton_mjwarp``, ``physx`` * - Isaac-Velocity-Rough-Anymal-B-v0 - Isaac-Velocity-Rough-Anymal-B-Play-v0 - Manager Based - **rsl_rl** (PPO), **skrl** (PPO) + - ``newton_mjwarp``, ``physx`` * - Isaac-Velocity-Rough-Anymal-C-Direct-v0 - - Direct - **rl_games** (PPO), **rsl_rl** (PPO), **skrl** (PPO) + - * - Isaac-Velocity-Rough-Anymal-C-v0 - Isaac-Velocity-Rough-Anymal-C-Play-v0 - Manager Based - **rl_games** (PPO), **rsl_rl** (PPO), **skrl** (PPO) + - ``newton_mjwarp``, ``physx`` * - Isaac-Velocity-Rough-Anymal-D-v0 - Isaac-Velocity-Rough-Anymal-D-Play-v0 - Manager Based - **rsl_rl** (PPO), **skrl** (PPO) + - ``newton_mjwarp``, ``physx`` * - Isaac-Velocity-Rough-Cassie-v0 - Isaac-Velocity-Rough-Cassie-Play-v0 - Manager Based - **rsl_rl** (PPO), **skrl** (PPO) + - * - Isaac-Velocity-Rough-Digit-v0 - Isaac-Velocity-Rough-Digit-Play-v0 - Manager Based - **rsl_rl** (PPO) + - ``newton_mjwarp``, ``physx`` * - Isaac-Velocity-Rough-G1-v0 - Isaac-Velocity-Rough-G1-Play-v0 - Manager Based - **rsl_rl** (PPO), **skrl** (PPO) + - ``newton_mjwarp``, ``physx`` * - Isaac-Velocity-Rough-H1-v0 - Isaac-Velocity-Rough-H1-Play-v0 - Manager Based - **rsl_rl** (PPO), **skrl** (PPO) + - ``newton_mjwarp``, ``physx`` * - Isaac-Velocity-Rough-Unitree-A1-v0 - Isaac-Velocity-Rough-Unitree-A1-Play-v0 - Manager Based - **rsl_rl** (PPO), **skrl** (PPO), **sb3** (PPO) + - ``newton_mjwarp``, ``physx`` * - Isaac-Velocity-Rough-Unitree-Go1-v0 - Isaac-Velocity-Rough-Unitree-Go1-Play-v0 - Manager Based - **rsl_rl** (PPO), **skrl** (PPO) + - ``newton_mjwarp``, ``physx`` * - Isaac-Velocity-Rough-Unitree-Go2-v0 - Isaac-Velocity-Rough-Unitree-Go2-Play-v0 - Manager Based - **rsl_rl** (PPO), **skrl** (PPO) + - ``newton_mjwarp``, ``physx`` * - Isaac-Reach-OpenArm-Bi-v0 - Isaac-Reach-OpenArm-Bi-Play-v0 - Manager Based - **rsl_rl** (PPO), **rl_games** (PPO) + - * - Isaac-Reach-OpenArm-v0 - Isaac-Reach-OpenArm-Play-v0 - Manager Based - **rsl_rl** (PPO), **skrl** (PPO), **rl_games** (PPO) + - * - Isaac-Lift-Cube-OpenArm-v0 - Isaac-Lift-Cube-OpenArm-Play-v0 - Manager Based - **rsl_rl** (PPO), **rl_games** (PPO) + - * - Isaac-Open-Drawer-OpenArm-v0 - Isaac-Open-Drawer-OpenArm-Play-v0 - Manager Based - **rsl_rl** (PPO), **rl_games** (PPO) + - diff --git a/docs/source/overview/imitation-learning/augmented_imitation.rst b/docs/source/overview/imitation-learning/augmented_imitation.rst index 376f447f97a3..2a97c58e293d 100644 --- a/docs/source/overview/imitation-learning/augmented_imitation.rst +++ b/docs/source/overview/imitation-learning/augmented_imitation.rst @@ -5,6 +5,10 @@ Augmented Imitation Learning This section describes how to use Isaac Lab's imitation learning capabilities with the visual augmentation capabilities of `Cosmos `_ models to generate demonstrations at scale to train visuomotor policies robust against visual variations. + +.. important:: + The `Cosmos Transfer1 `_ model used in this tutorial is `supported `_ on Ampere and Hopper GPUs. + Generating Demonstrations ~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -308,7 +312,7 @@ Using the generated data, we can now train a visuomotor BC agent for ``Isaac-Sta --name bc_rnn_image_franka_stack_mimic_cosmos .. note:: - By default the trained models and logs will be saved to ``IssacLab/logs/robomimic``. + By default the trained models and logs will be saved to ``IsaacLab/logs/robomimic``. Evaluation ^^^^^^^^^^ diff --git a/docs/source/overview/imitation-learning/humanoids_imitation.rst b/docs/source/overview/imitation-learning/humanoids_imitation.rst index d4782b14ab6a..694c3225dbf1 100644 --- a/docs/source/overview/imitation-learning/humanoids_imitation.rst +++ b/docs/source/overview/imitation-learning/humanoids_imitation.rst @@ -11,7 +11,7 @@ This page covers data generation and imitation learning workflows for humanoid r .. important:: - Complete the tutorial in :ref:`Teleoperation and Imitation Learning with Isaac Lab Mimic ` + Complete the tutorial in :ref:`Synthetic Data Generation and Imitation Learning with Isaac Lab Mimic ` before proceeding with the following demonstrations to understand the data collection, annotation, and generation steps of Isaac Lab Mimic. @@ -83,7 +83,6 @@ Collect five demonstrations by running the following command: --visualizer kit \ --xr \ --device cpu \ - --xr \ --num_demos 5 \ --dataset_file ./datasets/dataset_gr1.hdf5 @@ -114,7 +113,7 @@ You can replay the collected demonstrations by running the following command: Annotate the demonstrations """"""""""""""""""""""""""" -Unlike the :ref:`Franka stacking task `, the GR-1 pick and place task uses manual annotation to define subtasks. +Unlike the :ref:`Franka stacking task `, the GR-1 pick and place task uses manual annotation to define subtasks. The pick and place task has one subtask for the left arm (pick) and two subtasks for the right arm (idle, place). Annotations denote the end of a subtask. For the pick and place task, this means there are no annotations for the left arm and one annotation for the right arm (the end of the final subtask is always implicit). @@ -194,7 +193,7 @@ The normalization parameters are saved in the model directory under ``PATH_TO_MO Record the normalization parameters for later use in the visualization step. .. note:: - By default the trained models and logs will be saved to ``IssacLab/logs/robomimic``. + By default the trained models and logs will be saved to ``IsaacLab/logs/robomimic``. Visualize the results ^^^^^^^^^^^^^^^^^^^^^ @@ -563,7 +562,7 @@ To generate the locomanipulation dataset, use the following command: ./isaaclab.sh -p \ scripts/imitation_learning/locomanipulation_sdg/generate_data.py \ --device cpu \ - --kit_args="--enable isaacsim.replicator.mobility_gen" \ + --kit_args="--enable isaacsim.replicator.experimental.mobility_gen" \ --task="Isaac-G1-SteeringWheel-Locomanipulation" \ --dataset ./datasets/generated_dataset_g1_locomanip.hdf5 \ --num_runs 1 \ @@ -736,7 +735,7 @@ Download the files and place them under ````, then run the fo ./isaaclab.sh -p scripts/imitation_learning/locomanipulation_sdg/generate_data.py \ --device cpu \ - --kit_args="--enable isaacsim.replicator.mobility_gen" \ + --kit_args="--enable isaacsim.replicator.experimental.mobility_gen" \ --task="Isaac-G1-SteeringWheel-Locomanipulation" \ --dataset /dataset_annotated_g1_locomanip.hdf5 \ --num_runs 1 \ diff --git a/docs/source/overview/imitation-learning/skillgen.rst b/docs/source/overview/imitation-learning/skillgen.rst index be8382b5c5e1..4bd17067f689 100644 --- a/docs/source/overview/imitation-learning/skillgen.rst +++ b/docs/source/overview/imitation-learning/skillgen.rst @@ -407,7 +407,7 @@ Train a policy for the more complex adaptive bin stacking: .. note:: - The training script will save the model checkpoints in the model directory under ``IssacLab/logs/robomimic``. + The training script will save the model checkpoints in the model directory under ``IsaacLab/logs/robomimic``. Evaluating Trained Policies ^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/docs/source/overview/imitation-learning/teleop_imitation.rst b/docs/source/overview/imitation-learning/teleop_imitation.rst index 2511b6a57b73..b12c9062f167 100644 --- a/docs/source/overview/imitation-learning/teleop_imitation.rst +++ b/docs/source/overview/imitation-learning/teleop_imitation.rst @@ -1,70 +1,122 @@ .. _teleoperation-imitation-learning: -Teleoperation and Imitation Learning with Isaac Lab Mimic -========================================================= +Synthetic Data Generation and Imitation Learning with Isaac Lab Mimic +===================================================================== +.. important:: + Isaac Lab Mimic is only supported on Linux. -Teleoperation -~~~~~~~~~~~~~ +What is Isaac Lab Mimic? +~~~~~~~~~~~~~~~~~~~~~~~~ -We provide interfaces for providing commands in SE(2) and SE(3) space -for robot control. In case of SE(2) teleoperation, the returned command -is the linear x-y velocity and yaw rate, while in SE(3), the returned -command is a 6-D vector representing the change in pose. +.. figure:: ../../_static/mimic/franka_mimic_imitation_learning.jpg + :width: 100% + :align: center + :alt: Franka robot performing a stacking task + :figclass: align-center -.. note:: +Isaac Lab Mimic (Mimic) is a trajectory data generation tool that can be used to +augment human demonstrations by generating new synthetic data. Given a set of human demonstrations, +Mimic can automatically generate new demonstrations involving the same task but with different spatial configurations. +The generated data can be used to train imitation learning policies that are more robust to spatial variations +even if just a handful of manual demonstrations are available. + +Mimic works by taking a set of human demonstrations and splitting each demonstration into a sequence of subtasks. +Subtasks are defined based on reference objects that dictate the motion of the robot's end-effectors (eefs). Each subtask +is a contiguous segment of the demonstration where the eef's motion is dictated by a single reference object. A new subtask begins +when the reference object changes. Annotations mark points in the demonstration where a subtask is completed. - Presently, Isaac Lab Mimic is only supported in Linux. +During data generation, Mimic takes the human demonstration subtask segments and applies rigid body transformations to the robot's actions +to transform them into new demonstrations involving the same task but with different spatial configurations. +The new demonstrations are evaluated to determine if they are successful, and if so, are added to the output dataset. -To play inverse kinematics (IK) control with a keyboard device: +Mimic is compatible with a variety of embodiments including single-eef (e.g. manipulator robots) and multi-eef (e.g. humanoid robots). +The use of rigid body transformations requires that the embodiment's action space is defined in **task space**. If +the embodiment's action is in joint space, then the action must be converted to task space using forward kinematics. -.. code:: bash +In the following sections, we will show how to collect a small batch of human demonstrations for a stacking task +with the Franka robot, increase the size of the dataset by generating new synthetic data using Isaac Lab Mimic, and +lastly train a policy to perform the stacking task. - ./isaaclab.sh -p scripts/environments/teleoperation/teleop_se3_agent.py --task Isaac-Stack-Cube-Franka-IK-Rel-v0 --num_envs 1 --teleop_device keyboard -For smoother operation and off-axis operation, we recommend using a SpaceMouse as the input device. Providing smoother demonstrations will make it easier for the policy to clone the behavior. To use a SpaceMouse, simply change the teleop device accordingly: -.. code:: bash +.. _teleop-imitation-step-1-human-data-collection: - ./isaaclab.sh -p scripts/environments/teleoperation/teleop_se3_agent.py --task Isaac-Stack-Cube-Franka-IK-Rel-v0 --num_envs 1 --teleop_device spacemouse +Step 1: Human Data Collection +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. note:: + You may skip this step and proceed directly to :ref:`Step 2: Synthetic Data Generation using Isaac Lab Mimic ` + if you do not wish to collect your own demonstrations. - If the SpaceMouse is not detected, you may need to grant additional user permissions by running ``sudo chmod 666 /dev/hidraw<#>`` where ``<#>`` corresponds to the device index - of the connected SpaceMouse. - To determine the device index, list all ``hidraw`` devices by running ``ls -l /dev/hidraw*``. - Identify the device corresponding to the SpaceMouse by running ``cat /sys/class/hidraw/hidraw<#>/device/uevent`` on each of the devices listed - from the prior step. - We recommend using local deployment of Isaac Lab to use the SpaceMouse. If using container deployment (:ref:`deployment-docker`), you must manually mount the SpaceMouse to the ``isaac-lab-base`` container by - adding a ``devices`` attribute with the path to the device in your ``docker-compose.yaml`` file: +Environment Introduction +^^^^^^^^^^^^^^^^^^^^^^^^ - .. code:: yaml +The environment we will be using in this tutorial is ``Isaac-Stack-Cube-Franka-IK-Rel-v0`` and its variations. +This environment contains a Franka robot attached to a table with three cubes. +The task is to stack the cubes in the following order: blue (bottom), red (middle), green (top). As you proceed through +the rest of this tutorial, you will encounter variations of this environment with different observation spaces +(e.g. state-based, visuomotor, etc.). - devices: - - /dev/hidraw<#>:/dev/hidraw<#> +Run the following command to spin up and visualize the environment using the ``zero_agent.py`` +script provided by Isaac Lab. This script create and step through the environment in a loop with zero tensor actions. +You will see the robot remain stationary while the environment is running. Use the scroll wheel to zoom in and out of the scene. +Press and hold the alt key while clicking and dragging to pan around the scene. - where ``<#>`` is the device index of the connected SpaceMouse. +.. code:: bash + + ./isaaclab.sh -p scripts/environments/zero_agent.py \ + --task Isaac-Stack-Cube-Franka-IK-Rel-v0 \ + --viz kit \ + --num_envs 1 - Isaac Lab is only compatible with the SpaceMouse Wireless and SpaceMouse Compact models from 3Dconnexion. -For tasks that benefit from the use of an extended reality (XR) device with hand tracking, Isaac Lab supports using `Isaac Teleop `_ with NVIDIA CloudXR to immersively stream the scene to compatible XR devices for teleoperation. Note that when using hand tracking we recommend using the absolute variant of the task (``Isaac-Stack-Cube-Franka-IK-Abs-v0``): +Next, use the ``random_agent.py`` script to spin up the environment and perform random actions. The script will create +and step through the environment in a loop with random tensor actions. You will see the robot move in random +directions. .. code:: bash - ./isaaclab.sh -p scripts/environments/teleoperation/teleop_se3_agent.py --task Isaac-Stack-Cube-Franka-IK-Abs-v0 --visualizer kit --xr + ./isaaclab.sh -p scripts/environments/random_agent.py \ + --task Isaac-Stack-Cube-Franka-IK-Rel-v0 \ + --viz kit \ + --num_envs 1 -.. note:: +.. figure:: ../../_static/mimic/franka_cube_stacking_env.jpg + :width: 100% + :align: center + :alt: Franka cube stacking environment + :figclass: align-center + + Franka cube stacking environment + + + +Teleoperation +^^^^^^^^^^^^^ + +Isaac Lab supports teleoperation of robots through a variety of input devices including keyboard, SpaceMouse, and XR headsets. - See :ref:`cloudxr-teleoperation` to learn how to install Isaac Teleop and set up CloudXR for - teleoperation. For architecture details, retargeting pipelines, and control scheme - recommendations, see :ref:`isaac-teleop-feature`. +Run the following command to spin up the environment and teleoperate the robot using the keyboard. Familiarize yourself +with the controls and perform the stacking task. The order of the stacked cubes should be blue (bottom), red (middle), green (top). +Once you feel sufficiently comfortable with the controls, you may shutdown +the environment by quitting the script with Ctrl+C. +.. code:: bash + + ./isaaclab.sh -p scripts/environments/teleoperation/teleop_se3_agent.py \ + --task Isaac-Stack-Cube-Franka-IK-Rel-v0 \ + --viz kit \ + --num_envs 1 \ + --sensitivity 4 \ + --teleop_device keyboard -The script prints the teleoperation events configured. For keyboard, -these are as follows: + +The script will print a helper message with key bindings. For keyboard, +the key bindings are: .. code:: text @@ -78,7 +130,23 @@ these are as follows: Rotate arm along y-axis: T/G Rotate arm along z-axis: C/V -For SpaceMouse, these are as follows: +For smoother and simultaneous multi-axis operation, we recommend using a SpaceMouse as the input device. +Providing smoother demonstrations will make it easier for the policy to clone the behavior. +Isaac Lab supports the 3Dconnexion `SpaceMouse Compact `__ +and `SpaceMouse Wireless `__. +To use a SpaceMouse, simply change ``--teleop_device`` accordingly: + +.. code:: bash + + ./isaaclab.sh -p scripts/environments/teleoperation/teleop_se3_agent.py \ + --task Isaac-Stack-Cube-Franka-IK-Rel-v0 \ + --viz kit \ + --num_envs 1 \ + --sensitivity 4 \ + --teleop_device spacemouse + +The script will print a helper message with key bindings. For SpaceMouse, +the key bindings are: .. code:: text @@ -89,91 +157,125 @@ For SpaceMouse, these are as follows: Move arm along z-axis: Push or pull the SpaceMouse Rotate arm: Twist the SpaceMouse -The next section describes how teleoperation devices can be used for data collection for imitation learning. +.. tip:: + If the SpaceMouse is not detected, you may need to grant additional user permissions by running ``sudo chmod 666 /dev/hidraw<#>`` where ``<#>`` corresponds to the device index + of the connected SpaceMouse. -Imitation Learning with Isaac Lab Mimic -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + To determine the device index, list all ``hidraw`` devices by running ``ls -l /dev/hidraw*``. + Identify the device corresponding to the SpaceMouse by running ``cat /sys/class/hidraw/hidraw<#>/device/uevent`` on each of the devices listed + from the prior step. -.. figure:: ../../_static/mimic/franka_mimic_imitation_learning.jpg - :width: 100% - :align: center - :alt: Franka robot performing a stacking task - :figclass: align-center + We recommend using local deployment of Isaac Lab to use the SpaceMouse. If using container deployment (:ref:`deployment-docker`), you must manually mount the SpaceMouse to the ``isaac-lab-base`` container by + adding a ``devices`` attribute with the path to the device in your ``docker-compose.yaml`` file: -What is Isaac Lab Mimic? -^^^^^^^^^^^^^^^^^^^^^^^^ + .. code:: yaml -Isaac Lab Mimic (Mimic) is a trajectory data generation tool that can be used to -augment human demonstrations by generating new synthetic data. Given a set of human demonstrations, -Mimic can automatically generate new demonstrations involving the same task but with different spatial configurations. -The generated data can be used to train imitation learning policies that are more robust to spatial variations -even if just a handful of manual demonstrations are available. + devices: + - /dev/hidraw<#>:/dev/hidraw<#> -Mimic works by taking a set of human demonstrations and splitting each demonstration into a sequence of subtasks. -Subtasks are defined based on reference objects that dictate the motion of the robot's end-effectors (eefs). Each subtask -is a contiguous segment of the demonstration where the eef's motion is dictated by a single reference object. A new subtask begins -when the reference object changes. Annotations mark points in the demonstration where a subtask is completed. + where ``<#>`` is the device index of the connected SpaceMouse. -During data generation, Mimic takes the human demonstration subtask segments and applies rigid body transformations to the robot's actions -to transform them into new demonstrations involving the same task but with different spatial configurations. -The new demonstrations are evaluated to determine if they are successful, and if so, are added to the output dataset. + Isaac Lab is only compatible with the SpaceMouse Wireless and SpaceMouse Compact models from 3Dconnexion. -Mimic is compatible with a variety of embodiments including single-eef (e.g. manipulator robots) and multi-eef (e.g. humanoid robots). -The use of rigid body transformations requires that the embodiment's action space is defined in **task space**. If -the embodiment's action is in joint space, then the action must be converted to task space using forward kinematics. -In the following section, we will show how to collect a small batch of human demonstrations for a stacking task -with the Franka robot and then increase the size of the dataset by generating new synthetic data using Isaac Lab Mimic. +(Optional) Teleoperation with XR Headsets +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -Pre-recorded demonstrations -^^^^^^^^^^^^^^^^^^^^^^^^^^^ +For tasks that benefit from the use of an extended reality (XR) device with hand tracking, +Isaac Lab supports using `Isaac Teleop `_ with NVIDIA CloudXR +to immersively stream the scene to compatible XR devices for teleoperation. -We provide a pre-recorded ``dataset.hdf5`` containing 10 human demonstrations for ``Isaac-Stack-Cube-Franka-IK-Rel-v0`` -here: `[Franka Dataset] `__. -This dataset may be downloaded and used in the remaining tutorial steps if you do not wish to collect your own demonstrations. +Follow the steps in :ref:`cloudxr-teleoperation` to learn how to install Isaac Teleop and set up CloudXR for +teleoperation. Once you have set it up, you can launch the cube stacking environment with the follow command to try it out +with an XR headset. Note that when using hand tracking, we recommend using the absolute action space +variant of the task (``Isaac-Stack-Cube-Franka-IK-Abs-v0``): -If using the pre-recorded dataset, skip the next section and proceed directly to the :ref:`Generating additional demonstrations ` section. +.. code:: bash -.. note:: - Use of the pre-recorded dataset is optional. + ./isaaclab.sh -p scripts/environments/teleoperation/teleop_se3_agent.py \ + --task Isaac-Stack-Cube-Franka-IK-Abs-v0 \ + --viz kit \ + --xr + +.. tip:: + + For more information on teleoperation devices in Isaac Lab, see :ref:`isaac-teleop-feature` for a comprehensive + overview of the teleop framework. See :ref:`isaac-teleop-supported-devices` for a list of supported XR devices + and :ref:`isaac-teleop-new-device` for information on adding new devices. -Collecting demonstrations -^^^^^^^^^^^^^^^^^^^^^^^^^ -To collect demonstrations with teleoperation for the environment ``Isaac-Stack-Cube-Franka-IK-Rel-v0``, use the following commands: +Collect a Dataset of Human Demonstrations +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Make a new folder in the ``IsaacLab`` root directory to store datasets: .. code:: bash - #Create folder for datasets mkdir -p datasets - # Collect data with a selected teleoperation device. Replace with your preferred input device. - # Recommended options: spacemouse, keyboard - ./isaaclab.sh -p scripts/tools/record_demos.py --task Isaac-Stack-Cube-Franka-IK-Rel-v0 --visualizer kit --teleop_device --dataset_file ./datasets/dataset.hdf5 --num_demos 10 +Change ```` to the teleoperation device you want to use (e.g. ``spacemouse``, ``keyboard``) and +run the record demos script to collect a set of 10 human demonstrations for the cube stacking task. -.. note:: +.. code:: bash - The order of the stacked cubes should be blue (bottom), red (middle), green (top). + ./isaaclab.sh -p scripts/tools/record_demos.py \ + --task Isaac-Stack-Cube-Franka-IK-Rel-v0 \ + --viz kit \ + --dataset_file ./datasets/dataset.hdf5 \ + --num_demos 10 \ + --teleop_device -Collect 10 successful demonstrations before proceeding with the next step. +.. important:: + The order of the stacked cubes should be blue (bottom), red (middle), green (top). -Here are some tips to perform demonstrations that lead to successful policy training: +Tips for collecting good demonstrations: * Keep demonstrations short. Shorter demonstrations mean fewer decisions for the policy, making training easier. -* Take a direct path. Do not follow along arbitrary axis, but move straight toward the goal. -* Do not pause. Perform smooth, continuous motions instead. It is not obvious for a policy why and when to pause, hence continuous motions are easier to learn. +* Take a direct path and move efficiently toward the goal. +* Do not have extended pauses. Instead, perform smooth, continuous motions. It is not obvious for a policy why and when to pause, hence continuous motions are easier to learn. If a mistake is made while performing a demonstration, press the ``R`` key (if using a keyboard) or the right button (if using a SpaceMouse) to discard the current demonstration and reset to a new starting position. +You can replay the collected demonstrations by running: + +.. code:: bash + + ./isaaclab.sh -p scripts/tools/replay_demos.py \ + --task Isaac-Stack-Cube-Franka-IK-Rel-v0 \ + --viz kit \ + --num_envs 1 \ + --reset_sim_buffer_each_episode \ + --dataset_file ./datasets/dataset.hdf5 + +**Collect 10 successful demonstrations before proceeding to the next step.** + + + +.. _teleop-imitation-step-2-synthetic-data: + +Step 2: Synthetic Data Generation using Isaac Lab Mimic +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +(Optional) Download Pre-recorded Human Demonstrations +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +We provide a pre-recorded HDF5 dataset containing 10 human demonstrations for the cube stacking task +here: `[Cube Stacking Human Dataset] `__. +If you skipped :ref:`Step 1: Human Data Collection `, you can download this dataset and use it in the remaining tutorial steps. + +Place the dataset in the ``IsaacLab/datasets`` folder. You may need to create the folder if you skipped Step 1 and +have not created it yet. -.. _generating-additional-demonstrations: -Generating additional demonstrations with Isaac Lab Mimic -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +.. _generate-additional-demonstrations: + +Generate Additional Synthetic Demonstrations +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ In the following example, we will show how to use Isaac Lab Mimic to generate additional demonstrations that can be used to train either a state-based policy (using the ``Isaac-Stack-Cube-Franka-IK-Rel-Mimic-v0`` environment) or visuomotor policy (using the ``Isaac-Stack-Cube-Franka-IK-Rel-Visuomotor-Mimic-v0`` environment) @@ -202,7 +304,7 @@ Annotate the subtasks in the recording: ./isaaclab.sh -p scripts/imitation_learning/isaaclab_mimic/annotate_demos.py \ --task Isaac-Stack-Cube-Franka-IK-Rel-Mimic-v0 \ - --visualizer kit \ + --viz kit \ --auto \ --input_file ./datasets/dataset.hdf5 \ --output_file ./datasets/annotated_dataset.hdf5 @@ -214,7 +316,7 @@ Annotate the subtasks in the recording: ./isaaclab.sh -p scripts/imitation_learning/isaaclab_mimic/annotate_demos.py \ --task Isaac-Stack-Cube-Franka-IK-Rel-Visuomotor-Mimic-v0 \ - --visualizer kit \ + --viz kit \ --enable_cameras \ --auto \ --input_file ./datasets/dataset.hdf5 \ @@ -232,8 +334,8 @@ Next, use Isaac Lab Mimic to generate some additional demonstrations: .. code:: bash ./isaaclab.sh -p scripts/imitation_learning/isaaclab_mimic/generate_dataset.py \ - --visualizer kit \ - --num_envs 10 \ + --viz kit \ + --num_envs 20 \ --generation_num_trials 10 \ --input_file ./datasets/annotated_dataset.hdf5 \ --output_file ./datasets/generated_dataset_small.hdf5 @@ -244,26 +346,26 @@ Next, use Isaac Lab Mimic to generate some additional demonstrations: .. code:: bash ./isaaclab.sh -p scripts/imitation_learning/isaaclab_mimic/generate_dataset.py \ - --visualizer kit \ + --viz kit \ --enable_cameras \ - --num_envs 10 \ + --num_envs 20 \ --generation_num_trials 10 \ --input_file ./datasets/annotated_dataset.hdf5 \ --output_file ./datasets/generated_dataset_small.hdf5 +.. tip:: + + The output_file of ``annotate_demos.py`` is the input_file to ``generate_dataset.py``. + .. figure:: ../../_static/mimic/franka_datagen.jpg :width: 100% :align: center :alt: Franka robot performing a stacking task :figclass: align-center - Parallel data generation for the Franka robot stacking task. - -.. note:: - - The output_file of the ``annotate_demos.py`` script is the input_file to the ``generate_dataset.py`` script + Parallel data generation for the Franka cube stacking task -Inspect the output of generated data (filename: ``generated_dataset_small.hdf5``), and if satisfactory, generate the full dataset: +Inspect the generated data (``generated_dataset_small.hdf5``) and if satisfactory, generate the full dataset: .. tab-set:: :sync-group: policy_type @@ -275,7 +377,7 @@ Inspect the output of generated data (filename: ``generated_dataset_small.hdf5`` ./isaaclab.sh -p scripts/imitation_learning/isaaclab_mimic/generate_dataset.py \ --headless \ - --num_envs 10 \ + --num_envs 1000 \ --generation_num_trials 1000 \ --input_file ./datasets/annotated_dataset.hdf5 \ --output_file ./datasets/generated_dataset.hdf5 @@ -286,27 +388,42 @@ Inspect the output of generated data (filename: ``generated_dataset_small.hdf5`` .. code:: bash ./isaaclab.sh -p scripts/imitation_learning/isaaclab_mimic/generate_dataset.py \ - --visualizer kit \ --enable_cameras \ --headless \ - --num_envs 10 \ + --num_envs 300 \ --generation_num_trials 1000 \ --input_file ./datasets/annotated_dataset.hdf5 \ --output_file ./datasets/generated_dataset.hdf5 -The number of demonstrations ``--generation_num_trials`` can be changed. 1000 demonstrations have been shown to provide good training results for this task. +The number of demonstrations ``--generation_num_trials`` can be adjusted to your policy needs. +1000 demonstrations have been shown to provide good training results for the BC RNN policy used in this tutorial. + +The number of environments in the ``--num_envs`` parameter can be adjusted to speed up or slow down data generation. +The suggested values assume an RTX PRO 6000 Blackwell GPU. +You may need to adjust the number of environments to fit your VRAM if you are using a different GPU. + +.. note:: + + **Expected Data Generation Success Rate and Time** + + * Data generation success rate: ~40% for both state and visuomotor + * Data generation time: ~15 mins for state, ~1 hour for visuomotor + + *Numbers are based on using an RTX PRO 6000 Blackwell GPU with the provided commands.* + -The number of environments in the ``--num_envs`` parameter can be adjusted to speed up data generation. -The suggested number of 10 can be executed on a moderate laptop GPU. -On a more powerful desktop machine, use a larger number of environments for a significant speedup of this step. -Robomimic setup -^^^^^^^^^^^^^^^ +Step 3: Policy Training +~~~~~~~~~~~~~~~~~~~~~~~ -Next, we will train a Behavior Cloning (BC) agent implemented in `Robomimic `__ to demonstrate a policy. +Install Robomimic +^^^^^^^^^^^^^^^^^ + +In this step, we will train a Behavior Cloning (BC) RNN agent using `Robomimic `__ +to demonstrate a policy for the cube stacking task using the synthetic data generated in the previous step. -To install the robomimic framework, use the following command: +Install the Robomimic framework using the following command: .. code:: bash @@ -315,10 +432,14 @@ To install the robomimic framework, use the following command: # install python module (for robomimic) ./isaaclab.sh -i robomimic -Training an agent -^^^^^^^^^^^^^^^^^ -Using the Mimic generated data we can now train a state-based BC agent for ``Isaac-Stack-Cube-Franka-IK-Rel-v0``, or a visuomotor BC agent for ``Isaac-Stack-Cube-Franka-IK-Rel-Visuomotor-v0``: + +Train an Agent +^^^^^^^^^^^^^^ + +Using the Isaac Lab Mimic generated data we can now train a state-based BC RNN agent for +``Isaac-Stack-Cube-Franka-IK-Rel-v0``, or a visuomotor BC RNN agent for +``Isaac-Stack-Cube-Franka-IK-Rel-Visuomotor-v0``: .. tab-set:: :sync-group: policy_type @@ -343,22 +464,15 @@ Using the Mimic generated data we can now train a state-based BC agent for ``Isa --algo bc \ --dataset ./datasets/generated_dataset.hdf5 -.. note:: - By default the trained models and logs will be saved to ``IssacLab/logs/robomimic``. +.. important:: + The trained models and logs are saved to ``IsaacLab/logs/robomimic``. -Visualizing results -^^^^^^^^^^^^^^^^^^^ -.. tip:: - **Important: Testing Multiple Checkpoint Epochs** +Visualize the Results +^^^^^^^^^^^^^^^^^^^^^ - When evaluating policy performance, it is common for different training epochs to yield different results. - If you don't see the expected performance, **always test policies from various epochs** (not just the final checkpoint) - to find the best-performing model. Model performance can vary substantially across training, and the final epoch - is not always optimal. - -Run a the trained policy to visualize the results: +Run the trained policy to visualize the results: .. tab-set:: :sync-group: policy_type @@ -370,7 +484,7 @@ Run a the trained policy to visualize the results: ./isaaclab.sh -p scripts/imitation_learning/robomimic/play.py \ --task Isaac-Stack-Cube-Franka-IK-Rel-v0 \ - --visualizer kit \ + --viz kit \ --num_rollouts 50 \ --checkpoint /PATH/TO/desired_model_checkpoint.pth @@ -381,72 +495,59 @@ Run a the trained policy to visualize the results: ./isaaclab.sh -p scripts/imitation_learning/robomimic/play.py \ --task Isaac-Stack-Cube-Franka-IK-Rel-Visuomotor-v0 \ - --visualizer kit \ + --viz kit \ --enable_cameras \ --num_rollouts 50 \ --checkpoint /PATH/TO/desired_model_checkpoint.pth -.. note:: - - **Expected Success Rates and Timings for Franka Cube Stack Task** +When evaluating policy performance, it is common for different training epochs to yield different results. +If you don't see the expected performance, **always test policies from various epochs** (not just the final checkpoint) +to find the best-performing model. Model performance can vary substantially across training, and the final epoch +is not always optimal. - * Data generation success rate: ~40% (for both state + visuomotor) - * Data generation time: ~30 mins for state, ~4 hours for visuomotor (varies based on num envs the user runs) - * BC RNN training time: 1000 epochs + ~30 mins (for state), 600 epochs + ~6 hours (for visuomotor) - * BC RNN policy success rate: ~40-60% (for both state + visuomotor) - * **Recommendation:** Evaluate checkpoints from various epochs throughout training to identify the best-performing model - - -Humanoid Examples -~~~~~~~~~~~~~~~~~ - -For examples of data generation and policy training with humanoid robots (GR-1, G1), -see the page: :ref:`Examples: Data Generation and Imitation Learning for Humanoids `. +.. figure:: https://download.isaacsim.omniverse.nvidia.com/isaaclab/images/franka_cube_stack_robomimic_mimic_bcrnn.gif + :width: 100% + :align: center + :alt: Robomimic BCRNN policy performing the cube stacking task + :figclass: align-center + Robomimic BC RNN policy performing the cube stacking task -.. _common-pitfalls-generating-data: +.. note:: -Common Pitfalls when Generating Data -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + **Expected Policy Training Time and Success Rate** -**Demonstrations are too long:** - -* Longer time horizon is harder to learn for a policy -* Start close to the first object and minimize motions + * BC RNN training time: ~30 mins for state (1000 epochs), ~6 hours for visuomotor (600 epochs) + * BC RNN policy success rate: ~40-60% for both state and visuomotor + * **Recommendation:** Evaluate checkpoints from various epochs throughout training to identify the best-performing model -**Demonstrations are not smooth:** + *Numbers are based on using an RTX PRO 6000 Blackwell GPU with the provided commands.* -* Irregular motion is hard for policy to decipher -* Better teleop devices result in better data (i.e. SpaceMouse is better than Keyboard) -**Pauses in demonstrations:** - -* Pauses are difficult to learn -* Keep the human motions smooth and fluid +**You have now completed the introductory tutorial on synthetic data generation and policy training with Isaac Lab Mimic. +In the sections below, you can explore examples with other robot embodiments (e.g. humanoids) and how to create your +own Isaac Lab Mimic compatible environments.** -**Excessive number of subtasks:** -* Minimize the number of defined subtasks for completing a given task -* Less subtacks results in less stitching of trajectories, yielding higher data generation success rate -**Lack of action noise:** +Humanoid Examples +~~~~~~~~~~~~~~~~~ -* Action noise makes policies more robust +For examples of data generation and policy training with humanoid robots (GR-1, G1), +see the page: :ref:`Examples: Data Generation and Imitation Learning for Humanoids `. -**Recording cropped too tight:** -* If recording stops on the frame the success term triggers, it may not re-trigger during replay -* Allow for some buffer at the end of recording -**Non-deterministic replay:** +Creating Your Own Isaac Lab Mimic Compatible Environments +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -* Physics in IsaacLab are not deterministically reproducible when using ``env.reset`` so demonstrations may fail on replay -* Collect more human demos than needed, use the ones that succeed during annotation -* All data in Isaac Lab Mimic generated HDF5 file represent a successful demo and can be used for training (even if non-determinism causes failure when replayed) +.. figure:: ../../_static/mimic/mimic_env_architecture.jpg + :align: center + :figwidth: 100% + :alt: Mimic compatible environment class and config hierarchy + Mimic compatible environment class and config hierarchy -Creating Your Own Isaac Lab Mimic Compatible Environments -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ How it works ^^^^^^^^^^^^ @@ -566,6 +667,49 @@ smooth and natural. .. centered:: Left: 0 steps. Middle: 5 steps. Right: 20 steps. + +.. _common-pitfalls-generating-data: + +Common Pitfalls when Generating Data +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +**Demonstrations are too long:** + +* Longer time horizon is harder to learn for a policy +* Start close to the first object and minimize motions + +**Demonstrations are not smooth:** + +* Irregular motion is hard for policy to decipher +* Better teleop devices result in better data (i.e. SpaceMouse is better than Keyboard) + +**Pauses in demonstrations:** + +* Pauses are difficult to learn +* Keep the human motions smooth and fluid + +**Excessive number of subtasks:** + +* Minimize the number of defined subtasks for completing a given task +* Less subtacks results in less stitching of trajectories, yielding higher data generation success rate + +**Lack of action noise:** + +* Action noise makes policies more robust + +**Recording cropped too tight:** + +* If recording stops on the frame the success term triggers, it may not re-trigger during replay +* Allow for some buffer at the end of recording + +**Non-deterministic replay:** + +* Physics in IsaacLab are not deterministically reproducible when using ``env.reset`` so demonstrations may fail on replay +* Collect more human demos than needed, use the ones that succeed during annotation +* All data in Isaac Lab Mimic generated HDF5 file represent a successful demo and can be used for training (even if non-determinism causes failure when replayed) + + + .. _glossary-mimic-terminology: Glossary diff --git a/docs/source/overview/reinforcement-learning/rl_existing_scripts.rst b/docs/source/overview/reinforcement-learning/rl_existing_scripts.rst index 66eb59483973..008ebf91c0d8 100644 --- a/docs/source/overview/reinforcement-learning/rl_existing_scripts.rst +++ b/docs/source/overview/reinforcement-learning/rl_existing_scripts.rst @@ -7,19 +7,19 @@ from the environments into the respective libraries function argument and return Newton Backend -------------- -All training and play scripts support the **Newton physics backend** via the ``presets=newton`` -Hydra override. Appending ``presets=newton`` to any command below switches the physics engine +All training and play scripts support the **Newton physics backend** via the ``presets=newton_mjwarp`` +Hydra override. Appending ``presets=newton_mjwarp`` to any command below switches the physics engine from the default PhysX to Newton: .. code:: bash # Generic pattern — works with any framework and task that supports Newton ./isaaclab.sh -p scripts/reinforcement_learning//train.py \ - --task --headless presets=newton + --task --headless presets=newton_mjwarp .. note:: - **Not all environments support the Newton backend yet.** Using ``presets=newton`` with an + **Not all environments support the Newton backend yet.** Using ``presets=newton_mjwarp`` with an environment that has not been configured for Newton will raise an error at launch. See :doc:`/source/experimental-features/newton-physics-integration/index` for more details, and the :ref:`migrating-to-isaaclab-3-0` @@ -94,7 +94,7 @@ RL-Games # run script for training ./isaaclab.sh -p scripts/reinforcement_learning/rl_games/train.py --task Isaac-Ant-v0 --headless # run script for training with Newton backend - ./isaaclab.sh -p scripts/reinforcement_learning/rl_games/train.py --task Isaac-Ant-v0 --headless presets=newton + ./isaaclab.sh -p scripts/reinforcement_learning/rl_games/train.py --task Isaac-Ant-v0 --headless presets=newton_mjwarp # run script for playing with 32 environments ./isaaclab.sh -p scripts/reinforcement_learning/rl_games/play.py --task Isaac-Ant-v0 --num_envs 32 --checkpoint /PATH/TO/model.pth # run script for recording video of a trained agent (requires installing `ffmpeg`) @@ -110,7 +110,7 @@ RL-Games :: run script for training isaaclab.bat -p scripts\reinforcement_learning\rl_games\train.py --task Isaac-Ant-v0 --headless :: run script for training with Newton backend - isaaclab.bat -p scripts\reinforcement_learning\rl_games\train.py --task Isaac-Ant-v0 --headless presets=newton + isaaclab.bat -p scripts\reinforcement_learning\rl_games\train.py --task Isaac-Ant-v0 --headless presets=newton_mjwarp :: run script for playing with 32 environments isaaclab.bat -p scripts\reinforcement_learning\rl_games\play.py --task Isaac-Ant-v0 --num_envs 32 --checkpoint /PATH/TO/model.pth :: run script for recording video of a trained agent (requires installing `ffmpeg`) @@ -135,7 +135,7 @@ RSL-RL # run script for training ./isaaclab.sh -p scripts/reinforcement_learning/rsl_rl/train.py --task Isaac-Reach-Franka-v0 --headless # run script for training with Newton backend - ./isaaclab.sh -p scripts/reinforcement_learning/rsl_rl/train.py --task Isaac-Reach-Franka-v0 --headless presets=newton + ./isaaclab.sh -p scripts/reinforcement_learning/rsl_rl/train.py --task Isaac-Reach-Franka-v0 --headless presets=newton_mjwarp # run script for playing with 32 environments ./isaaclab.sh -p scripts/reinforcement_learning/rsl_rl/play.py --task Isaac-Reach-Franka-v0 --num_envs 32 --load_run run_folder_name --checkpoint /PATH/TO/model.pt # run script for recording video of a trained agent (requires installing `ffmpeg`) @@ -151,7 +151,7 @@ RSL-RL :: run script for training isaaclab.bat -p scripts\reinforcement_learning\rsl_rl\train.py --task Isaac-Reach-Franka-v0 --headless :: run script for training with Newton backend - isaaclab.bat -p scripts\reinforcement_learning\rsl_rl\train.py --task Isaac-Reach-Franka-v0 --headless presets=newton + isaaclab.bat -p scripts\reinforcement_learning\rsl_rl\train.py --task Isaac-Reach-Franka-v0 --headless presets=newton_mjwarp :: run script for playing with 32 environments isaaclab.bat -p scripts\reinforcement_learning\rsl_rl\play.py --task Isaac-Reach-Franka-v0 --num_envs 32 --load_run run_folder_name --checkpoint /PATH/TO/model.pt :: run script for recording video of a trained agent (requires installing `ffmpeg`) @@ -173,7 +173,7 @@ RSL-RL # run script for rl training of the teacher agent ./isaaclab.sh -p scripts/reinforcement_learning/rsl_rl/train.py --task Isaac-Velocity-Flat-Anymal-D-v0 --headless # run script for rl training of the teacher agent with Newton backend - ./isaaclab.sh -p scripts/reinforcement_learning/rsl_rl/train.py --task Isaac-Velocity-Flat-Anymal-D-v0 --headless presets=newton + ./isaaclab.sh -p scripts/reinforcement_learning/rsl_rl/train.py --task Isaac-Velocity-Flat-Anymal-D-v0 --headless presets=newton_mjwarp # run script for distilling the teacher agent into a student agent ./isaaclab.sh -p scripts/reinforcement_learning/rsl_rl/train.py --task Isaac-Velocity-Flat-Anymal-D-v0 --headless --agent rsl_rl_distillation_cfg_entry_point --load_run teacher_run_folder_name # run script for playing the student with 64 environments @@ -189,7 +189,7 @@ RSL-RL :: run script for rl training of the teacher agent isaaclab.bat -p scripts\reinforcement_learning\rsl_rl\train.py --task Isaac-Velocity-Flat-Anymal-D-v0 --headless :: run script for rl training of the teacher agent with Newton backend - isaaclab.bat -p scripts\reinforcement_learning\rsl_rl\train.py --task Isaac-Velocity-Flat-Anymal-D-v0 --headless presets=newton + isaaclab.bat -p scripts\reinforcement_learning\rsl_rl\train.py --task Isaac-Velocity-Flat-Anymal-D-v0 --headless presets=newton_mjwarp :: run script for distilling the teacher agent into a student agent isaaclab.bat -p scripts\reinforcement_learning\rsl_rl\train.py --task Isaac-Velocity-Flat-Anymal-D-v0 --headless --agent rsl_rl_distillation_cfg_entry_point --load_run teacher_run_folder_name :: run script for playing the student with 64 environments @@ -218,7 +218,7 @@ SKRL # run script for training ./isaaclab.sh -p scripts/reinforcement_learning/skrl/train.py --task Isaac-Reach-Franka-v0 --headless # run script for training with Newton backend - ./isaaclab.sh -p scripts/reinforcement_learning/skrl/train.py --task Isaac-Reach-Franka-v0 --headless presets=newton + ./isaaclab.sh -p scripts/reinforcement_learning/skrl/train.py --task Isaac-Reach-Franka-v0 --headless presets=newton_mjwarp # run script for playing with 32 environments ./isaaclab.sh -p scripts/reinforcement_learning/skrl/play.py --task Isaac-Reach-Franka-v0 --num_envs 32 --checkpoint /PATH/TO/model.pt # run script for recording video of a trained agent (requires installing `ffmpeg`) @@ -234,7 +234,7 @@ SKRL :: run script for training isaaclab.bat -p scripts\reinforcement_learning\skrl\train.py --task Isaac-Reach-Franka-v0 --headless :: run script for training with Newton backend - isaaclab.bat -p scripts\reinforcement_learning\skrl\train.py --task Isaac-Reach-Franka-v0 --headless presets=newton + isaaclab.bat -p scripts\reinforcement_learning\skrl\train.py --task Isaac-Reach-Franka-v0 --headless presets=newton_mjwarp :: run script for playing with 32 environments isaaclab.bat -p scripts\reinforcement_learning\skrl\play.py --task Isaac-Reach-Franka-v0 --num_envs 32 --checkpoint /PATH/TO/model.pt :: run script for recording video of a trained agent (requires installing `ffmpeg`) @@ -270,7 +270,7 @@ SKRL # run script for training ./isaaclab.sh -p scripts/reinforcement_learning/skrl/train.py --task Isaac-Reach-Franka-v0 --headless --ml_framework jax # run script for training with Newton backend - ./isaaclab.sh -p scripts/reinforcement_learning/skrl/train.py --task Isaac-Reach-Franka-v0 --headless --ml_framework jax presets=newton + ./isaaclab.sh -p scripts/reinforcement_learning/skrl/train.py --task Isaac-Reach-Franka-v0 --headless --ml_framework jax presets=newton_mjwarp # run script for playing with 32 environments ./isaaclab.sh -p scripts/reinforcement_learning/skrl/play.py --task Isaac-Reach-Franka-v0 --num_envs 32 --ml_framework jax --checkpoint /PATH/TO/model.pt # run script for recording video of a trained agent (requires installing `ffmpeg`) @@ -325,7 +325,7 @@ Stable-Baselines3 # run script for training ./isaaclab.sh -p scripts/reinforcement_learning/sb3/train.py --task Isaac-Velocity-Flat-Unitree-A1-v0 --headless # run script for training with Newton backend - ./isaaclab.sh -p scripts/reinforcement_learning/sb3/train.py --task Isaac-Velocity-Flat-Unitree-A1-v0 --headless presets=newton + ./isaaclab.sh -p scripts/reinforcement_learning/sb3/train.py --task Isaac-Velocity-Flat-Unitree-A1-v0 --headless presets=newton_mjwarp # run script for playing with 32 environments ./isaaclab.sh -p scripts/reinforcement_learning/sb3/play.py --task Isaac-Velocity-Flat-Unitree-A1-v0 --num_envs 32 --checkpoint /PATH/TO/model.zip # run script for recording video of a trained agent (requires installing `ffmpeg`) @@ -341,7 +341,7 @@ Stable-Baselines3 :: run script for training isaaclab.bat -p scripts\reinforcement_learning\sb3\train.py --task Isaac-Velocity-Flat-Unitree-A1-v0 --headless :: run script for training with Newton backend - isaaclab.bat -p scripts\reinforcement_learning\sb3\train.py --task Isaac-Velocity-Flat-Unitree-A1-v0 --headless presets=newton + isaaclab.bat -p scripts\reinforcement_learning\sb3\train.py --task Isaac-Velocity-Flat-Unitree-A1-v0 --headless presets=newton_mjwarp :: run script for playing with 32 environments isaaclab.bat -p scripts\reinforcement_learning\sb3\play.py --task Isaac-Velocity-Flat-Unitree-A1-v0 --num_envs 32 --checkpoint /PATH/TO/model.zip :: run script for recording video of a trained agent (requires installing `ffmpeg`) diff --git a/docs/source/policy_deployment/02_gear_assembly/gear_assembly_policy.rst b/docs/source/policy_deployment/02_gear_assembly/gear_assembly_policy.rst index de8497f181b7..0021c2da8b09 100644 --- a/docs/source/policy_deployment/02_gear_assembly/gear_assembly_policy.rst +++ b/docs/source/policy_deployment/02_gear_assembly/gear_assembly_policy.rst @@ -3,14 +3,17 @@ Training a Gear Insertion Policy and ROS Deployment ==================================================== -This tutorial walks you through how to train a gear insertion assembly reinforcement learning (RL) policy that transfers from simulation to a real robot. The workflow consists of two main stages: +This tutorial walks you through how to train a gear insertion reinforcement learning (RL) policy that transfers from simulation to a real robot. The workflow consists of two main stages: 1. **Simulation Training in Isaac Lab**: Train the policy in a high-fidelity physics simulation with domain randomization 2. **Real Robot Deployment with Isaac ROS**: Deploy the trained policy on real hardware using Isaac ROS and a custom ROS inference node -This walkthrough covers the key principles and best practices for sim-to-real transfer using Isaac Lab, illustrated with a real-world example: +This walkthrough covers the key principles and best practices for sim-to-real transfer using Isaac Lab. -- the Gear Assembly task for the UR10e robot with the Robotiq 2F-140 gripper or 2F-85 gripper +**Supported Robots:** + +- **Universal Robots UR10e**: 6-DOF industrial robot arm with Robotiq 2F-140 or 2F-85 gripper +- **Flexiv Rizon 4s**: 7-DOF collaborative robot arm with Grav parallel gripper **Task Details:** @@ -29,11 +32,11 @@ The gear assembly policy operates as follows: Sim-to-real transfer: Gear assembly policy trained in Isaac Lab (left) successfully deployed on real UR10e robot (right). -This environment has been successfully deployed on real UR10e robots without an IsaacLab dependency. +This environment has been successfully deployed on real UR10e and Flexiv Rizon 4s robots without an IsaacLab dependency. **Scope of This Tutorial:** -This tutorial focuses exclusively on the **training part** of the sim-to-real transfer workflow in Isaac Lab. For the complete deployment workflow on the real robot, including the exact steps to set up the vision pipeline, robot interface and the ROS inference node to run your trained policy on real hardware, please refer to the `Isaac ROS Documentation `_. +This tutorial focuses exclusively on the **training part** of the sim-to-real transfer workflow in Isaac Lab. For the complete deployment workflow on the real robot, including the exact steps to set up the vision pipeline, robot interface and the ROS inference node to run your trained policy on real hardware, please refer to the `Isaac ROS Documentation `_. Overview -------- @@ -62,41 +65,55 @@ Using Real-Robot-Available Observations Your simulation environment should only use observations that are available on the real robot and not use "privileged" information that wouldn't be available in deployment. -Observation Specification: Isaac-Deploy-GearAssembly-UR10e-2F140-v0 -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +Observation Specification +^^^^^^^^^^^^^^^^^^^^^^^^^ The Gear Assembly environment uses both proprioceptive and exteroceptive (vision) observations: .. list-table:: Gear Assembly Environment Observations - :widths: 25 25 25 25 + :widths: 20 10 10 20 20 20 :header-rows: 1 * - Observation - - Dimension + - UR10e Dim + - Rizon 4s Dim - Real-World Source - - Noise in Training + - UR10e Noise + - Rizon 4s Noise * - ``joint_pos`` - - 6 (UR10e arm joints) - - UR10e controller - - None (proprioceptive) + - 6 + - 7 + - Robot controller + - None + - None * - ``joint_vel`` - - 6 (UR10e arm joints) - - UR10e controller - - None (proprioceptive) + - 6 + - 7 + - Robot controller + - None + - None * - ``gear_shaft_pos`` - - 3 (x, y, z position) + - 3 + - 3 - FoundationPose + RealSense depth - - ±0.005 m (5mm, estimated error from FoundationPose + RealSense depth pipeline) + - ±5mm + - ±10mm * - ``gear_shaft_quat`` - - 4 (quaternion orientation) + - 4 + - 4 - FoundationPose + RealSense depth - - ±0.01 per component (~5° angular error, estimated error from FoundationPose + RealSense depth pipeline) + - None + - ±2° -**Implementation:** +**Total observation dimension:** 19 (UR10e) or 21 (Rizon 4s) -.. code-block:: python +.. note:: + + The Rizon 4s uses higher observation noise than the UR10e. The position noise is doubled (±10mm vs ±5mm) and quaternion noise (±2° per axis via quaternion multiplication) is added to the gear shaft orientation. These noise levels are set in the Rizon4s-specific config (``joint_pos_env_cfg.py``) rather than the shared base class, so they do not affect UR10e environments. The higher noise trains a more robust policy for the Rizon 4s perception pipeline. - from isaaclab.utils.noise import UniformNoiseCfg as Unoise +**Implementation (base class, shared by all robots):** + +.. code-block:: python @configclass class PolicyCfg(ObsGroup): @@ -105,36 +122,41 @@ The Gear Assembly environment uses both proprioceptive and exteroceptive (vision # Robot joint states - NO noise for proprioceptive observations joint_pos = ObsTerm( func=mdp.joint_pos, - params={"asset_cfg": SceneEntityCfg("robot", joint_names=["shoulder_pan_joint", ...])}, + params={"asset_cfg": SceneEntityCfg("robot", joint_names=[".*"])}, ) - joint_vel = ObsTerm( func=mdp.joint_vel, - params={"asset_cfg": SceneEntityCfg("robot", joint_names=["shoulder_pan_joint", ...])}, + params={"asset_cfg": SceneEntityCfg("robot", joint_names=[".*"])}, ) - # Gear shaft pose from FoundationPose perception - # ADD noise for exteroceptive (vision-based) observations - # Calibrated to match FoundationPose + RealSense D435 error - # Typical error: 3-8mm position, 3-7° orientation + # Vision-based observations with noise calibrated to FoundationPose + RealSense D435 error gear_shaft_pos = ObsTerm( func=mdp.gear_shaft_pos_w, - params={"asset_cfg": SceneEntityCfg("factory_gear_base")}, - noise=Unoise(n_min=-0.005, n_max=0.005), # ±5mm - ) - - # Quaternion noise: small uniform noise on each component - # Results in ~5° orientation error - gear_shaft_quat = ObsTerm( - func=mdp.gear_shaft_quat_w, - params={"asset_cfg": SceneEntityCfg("factory_gear_base")}, - noise=Unoise(n_min=-0.01, n_max=0.01), + params={}, + noise=ResetSampledConstantNoiseModelCfg( + noise_cfg=UniformNoiseCfg(n_min=-0.005, n_max=0.005, operation="add") # ±5mm + ), ) + gear_shaft_quat = ObsTerm(func=mdp.gear_shaft_quat_w) def __post_init__(self): self.enable_corruption = True # Enable for perception observations only self.concatenate_terms = True +**Rizon 4s overrides** (in ``joint_pos_env_cfg.py``): + +.. code-block:: python + + # Higher noise for Rizon 4s perception pipeline + self.observations.policy.gear_shaft_pos.noise = ResetSampledConstantNoiseModelCfg( + noise_cfg=UniformNoiseCfg(n_min=-0.01, n_max=0.01, operation="add") # ±10mm + ) + self.observations.policy.gear_shaft_quat.noise = ResetSampledQuaternionNoiseModelCfg( + roll_range=(-0.03491, 0.03491), # ±2 degrees + pitch_range=(-0.03491, 0.03491), + yaw_range=(-0.03491, 0.03491), + ) + **Why No Noise for Proprioceptive Observations?** Empirically, we found that policies trained without noise on proprioceptive observations (joint positions and velocities) transfer well to real hardware. The UR10e controller provides sufficiently accurate joint state feedback that modeling sensor noise doesn't improve sim-to-real transfer for these tasks. @@ -163,41 +185,69 @@ Accurate physics simulation is critical for contact-rich tasks. Key parameters i The Gear Assembly task requires accurate contact modeling for insertion. Here's how friction is configured: -.. code-block:: python - - # From joint_pos_env_cfg.py in Isaac-Deploy-GearAssembly-UR10e-2F140-v0 - - @configclass - class EventCfg: - """Configuration for events including physics randomization.""" - - # Randomize friction for gear objects - small_gear_physics_material = EventTerm( - func=mdp.randomize_rigid_body_material, - mode="startup", - params={ - "asset_cfg": SceneEntityCfg("factory_gear_small", body_names=".*"), - "static_friction_range": (0.75, 0.75), # Calibrated to real gear material - "dynamic_friction_range": (0.75, 0.75), - "restitution_range": (0.0, 0.0), # No bounce - "num_buckets": 16, - }, - ) - - # Similar configuration for gripper fingers - robot_physics_material = EventTerm( - func=mdp.randomize_rigid_body_material, - mode="startup", - params={ - "asset_cfg": SceneEntityCfg("robot", body_names=".*finger"), - "static_friction_range": (0.75, 0.75), # Calibrated to real gripper - "dynamic_friction_range": (0.75, 0.75), - "restitution_range": (0.0, 0.0), - "num_buckets": 16, - }, - ) - -These friction values (0.75) were determined through iterative visual comparison: +.. tab-set:: + + .. tab-item:: UR10e + + .. code-block:: python + + # From config/ur_10e/joint_pos_env_cfg.py + + small_gear_physics_material = EventTerm( + func=mdp.randomize_rigid_body_material, + mode="startup", + params={ + "asset_cfg": SceneEntityCfg("factory_gear_small", body_names=".*"), + "static_friction_range": (0.75, 0.75), + "dynamic_friction_range": (0.75, 0.75), + "restitution_range": (0.0, 0.0), + "num_buckets": 16, + }, + ) + + robot_physics_material = EventTerm( + func=mdp.randomize_rigid_body_material, + mode="startup", + params={ + "asset_cfg": SceneEntityCfg("robot", body_names=".*finger"), + "static_friction_range": (0.75, 0.75), + "dynamic_friction_range": (0.75, 0.75), + "restitution_range": (0.0, 0.0), + "num_buckets": 16, + }, + ) + + .. tab-item:: Flexiv Rizon 4s + + .. code-block:: python + + # From config/rizon_4s/joint_pos_env_cfg.py + + small_gear_physics_material = EventTerm( + func=mdp.randomize_rigid_body_material, + mode="startup", + params={ + "asset_cfg": SceneEntityCfg("factory_gear_small", body_names=".*"), + "static_friction_range": (0.75, 0.75), + "dynamic_friction_range": (0.75, 0.75), + "restitution_range": (0.0, 0.0), + "num_buckets": 16, + }, + ) + + robot_physics_material = EventTerm( + func=mdp.randomize_rigid_body_material, + mode="startup", + params={ + "asset_cfg": SceneEntityCfg("robot", body_names=".*finger.*"), + "static_friction_range": (3.0, 3.0), + "dynamic_friction_range": (3.0, 3.0), + "restitution_range": (0.0, 0.0), + "num_buckets": 16, + }, + ) + +These friction values were determined through iterative visual comparison: 1. Record videos of the gear being grasped and manipulated on real hardware 2. Start training in simulation and observe the live simulation viewer @@ -207,12 +257,25 @@ These friction values (0.75) were determined through iterative visual comparison 6. Repeat adjustments until behavior matches (no need to wait for full policy training) 7. Once physics looks good, train in headless mode with video recording: - .. code-block:: bash + .. tab-set:: - python scripts/reinforcement_learning/rsl_rl/train.py \ - --task Isaac-Deploy-GearAssembly-UR10e-2F140-v0 \ - --headless \ - --video --video_length 800 --video_interval 5000 + .. tab-item:: UR10e + + .. code-block:: bash + + python scripts/reinforcement_learning/rsl_rl/train.py \ + --task Isaac-Deploy-GearAssembly-UR10e-2F140-v0 \ + --headless \ + --video --video_length 800 --video_interval 5000 + + .. tab-item:: Flexiv Rizon 4s + + .. code-block:: bash + + python scripts/reinforcement_learning/rsl_rl/train.py \ + --task Isaac-Deploy-GearAssembly-Rizon4s-Grav-ROS-Inference-v0 \ + --headless \ + --video --video_length 800 --video_interval 5000 8. Review the recorded videos and compare with real hardware videos to verify physics behavior @@ -264,36 +327,74 @@ Accurate actuator modeling ensures the simulated robot moves like the real one. **Controller Choice: Impedance Control** -For the UR10e deployment, we use an impedance controller interface. Using a simpler controller like impedance control reduces the chances of variation between simulation and reality compared to more complex controllers (e.g., operational space control, hybrid force-position control). Simpler controllers: +For the UR10e and Flexiv Rizon 4s deployments, we use an impedance controller interface. Using a simpler controller like impedance control reduces the chances of variation between simulation and reality compared to more complex controllers (e.g., operational space control, hybrid force-position control). Simpler controllers: - Have fewer parameters that can mismatch between sim and real - Are easier to model accurately in simulation - Have more predictable behavior that's easier to replicate - Reduce the controller complexity as a source of sim-real gap -**Example: UR10e Actuator Configuration** - -.. code-block:: python - - # Default UR10e actuator configuration - actuators = { - "arm": ImplicitActuatorCfg( - joint_names_expr=["shoulder_pan_joint", "shoulder_lift_joint", - "elbow_joint", "wrist_1_joint", "wrist_2_joint", "wrist_3_joint"], - effort_limit=87.0, # From UR10e specifications - velocity_limit=2.0, # From UR10e specifications - stiffness=800.0, # Calibrated to match real behavior - damping=40.0, # Calibrated to match real behavior - ), - } - -**Domain Randomization of Actuator Parameters** - -To account for variations in real robot behavior, randomize actuator gains during training: +**Actuator Configurations:** + +.. tab-set:: + + .. tab-item:: UR10e + + .. code-block:: python + + # Default UR10e actuator configuration + actuators = { + "arm": ImplicitActuatorCfg( + joint_names_expr=["shoulder_pan_joint", "shoulder_lift_joint", + "elbow_joint", "wrist_1_joint", "wrist_2_joint", "wrist_3_joint"], + effort_limit=87.0, # From UR10e specifications + velocity_limit=2.0, # From UR10e specifications + stiffness=800.0, # Calibrated to match real behavior + damping=40.0, # Calibrated to match real behavior + ), + } + + .. tab-item:: Flexiv Rizon 4s + Grav Gripper + + The Rizon 4s uses ``ImplicitActuatorCfg`` with per-joint-group tuning, plus actuators for the Grav parallel gripper: + + .. code-block:: python + + actuators = { + "shoulder": ImplicitActuatorCfg( + joint_names_expr=["joint[1-2]"], + effort_limit=123.0, velocity_limit=2.094, + stiffness=6000.0, damping=108.4, + ), + "elbow": ImplicitActuatorCfg( + joint_names_expr=["joint[3-4]"], + effort_limit=64.0, velocity_limit=2.443, + stiffness=4200.0, damping=90.7, + ), + "wrist": ImplicitActuatorCfg( + joint_names_expr=["joint[5-7]"], + effort_limit=39.0, velocity_limit=4.887, + stiffness=1500.0, damping=54.2, + ), + "gripper_drive": ImplicitActuatorCfg( + joint_names_expr=["finger_joint"], + effort_limit=2.0, velocity_limit=1.0, + stiffness=2e3, damping=1e1, + ), + "gripper_passive": ImplicitActuatorCfg( + joint_names_expr=[".*_knuckle_joint"], + effort_limit=1.0, velocity_limit=1.0, + stiffness=0.0, damping=0.0, + ), + } + +**Domain Randomization of Actuator Parameters (UR10e only)** + +To account for variations in real robot behavior, the UR10e configuration randomizes actuator gains during training: .. code-block:: python - # From EventCfg in the Gear Assembly environment + # From EventCfg in config/ur_10e/joint_pos_env_cfg.py robot_joint_stiffness_and_damping = EventTerm( func=mdp.randomize_actuator_gains, mode="reset", @@ -307,7 +408,7 @@ To account for variations in real robot behavior, randomize actuator gains durin ) -**Joint Friction Randomization** +**Joint Friction Randomization (UR10e only)** Real robots have friction in their joints that varies with position, velocity, and temperature. For the UR10e with impedance controller interface, we observed significant stiction (static friction) causing the controller to not reach target joint positions. @@ -317,6 +418,7 @@ To quantify this behavior, we plotted the step response of the impedance control .. code-block:: python + # From EventCfg in config/ur_10e/joint_pos_env_cfg.py joint_friction = EventTerm( func=mdp.randomize_joint_parameters, mode="reset", @@ -330,6 +432,10 @@ To quantify this behavior, we plotted the step response of the impedance control **Why Joint Friction Matters**: Without modeling joint friction in simulation, the policy learns to expect that commanded joint positions are always reached. On the real robot, stiction prevents small movements and causes steady-state errors. By adding friction during training, the policy learns to account for these effects and commands appropriately larger motions to overcome friction. +.. note:: + + **Flexiv Rizon 4s**: Domain randomization for actuator gains and joint friction is not included in the Rizon 4s ``EventCfg`` (``config/rizon_4s/joint_pos_env_cfg.py``). We found the Rizon 4s real-world controller is more stable and precise than the UR10e's, with negligible stiction and steady-state error. As a result, the simulation policy transfers well to the real robot without needing these additional randomizations. + **Compensating for Stiction with Action Scaling:** To help the policy overcome stiction on the real robot, we also increased the output action scaling. The Isaac ROS documentation notes that a higher action scale (0.0325 vs 0.025) is needed to overcome the higher static friction (stiction) compared to the 2F-85 gripper. This increased scaling ensures the policy commands are large enough to overcome the friction forces observed in the step response analysis. @@ -339,20 +445,41 @@ Action Space Design Your action space should match what the real robot controller can execute. For this task we found that **incremental joint position control** is the most reliable approach. -**Example: Gear Assembly Action Configuration** +**Action Configuration:** -.. code-block:: python +.. tab-set:: - # For contact-rich manipulation, smaller action scale for more precise control - self.joint_action_scale = 0.025 # ±2.5 degrees per step + .. tab-item:: UR10e - self.actions.arm_action = mdp.RelativeJointPositionActionCfg( - asset_name="robot", - joint_names=["shoulder_pan_joint", "shoulder_lift_joint", "elbow_joint", - "wrist_1_joint", "wrist_2_joint", "wrist_3_joint"], - scale=self.joint_action_scale, - use_zero_offset=True, - ) + .. code-block:: python + + self.joint_action_scale = 0.025 # ±1.4 degrees per step + + self.actions.arm_action = mdp.RelativeJointPositionActionCfg( + asset_name="robot", + joint_names=["shoulder_pan_joint", "shoulder_lift_joint", "elbow_joint", + "wrist_1_joint", "wrist_2_joint", "wrist_3_joint"], + scale=self.joint_action_scale, + use_zero_offset=True, + ) + + **Action dimension:** 6 + + .. tab-item:: Flexiv Rizon 4s + + .. code-block:: python + + self.joint_action_scale = 0.025 # ±1.4 degrees per step + + self.actions.arm_action = mdp.RelativeJointPositionActionCfg( + asset_name="robot", + joint_names=["joint1", "joint2", "joint3", "joint4", + "joint5", "joint6", "joint7"], + scale=self.joint_action_scale, + use_zero_offset=True, + ) + + **Action dimension:** 7 The action scale is a critical hyperparameter that should be tuned based on: @@ -366,11 +493,11 @@ Domain randomization should cover the range of conditions in which you want the **Pose Randomization** -For manipulation tasks, randomize object poses to ensure the policy works across the workspace: +For manipulation tasks, randomize object poses to ensure the policy works across the workspace. Both robots use the same gear and base pose randomization: .. code-block:: python - # From Gear Assembly environment + # Shared by both UR10e and Rizon 4s EventCfg randomize_gears_and_base_pose = EventTerm( func=gear_assembly_events.randomize_gears_and_base_pose, mode="reset", @@ -388,11 +515,7 @@ For manipulation tasks, randomize object poses to ensure the policy works across "y": [-0.02, 0.02], "z": [0.0575, 0.0775], # 5.75-7.75cm above base }, - "rot_randomization_range": { - "roll": [-math.pi/36, math.pi/36], # ±5 degrees - "pitch": [-math.pi/36, math.pi/36], - "yaw": [-math.pi/36, math.pi/36], - }, + "velocity_range": {}, }, ) @@ -400,23 +523,117 @@ For manipulation tasks, randomize object poses to ensure the policy works across Randomizing the robot's initial configuration helps the policy handle different starting conditions: +.. tab-set:: + + .. tab-item:: UR10e + + .. code-block:: python + + set_robot_to_grasp_pose = EventTerm( + func=gear_assembly_events.set_robot_to_grasp_pose, + mode="reset", + params={ + "robot_asset_cfg": SceneEntityCfg("robot"), + "pos_randomization_range": { + "x": [-0.0, 0.0], + "y": [-0.005, 0.005], # ±5mm variation + "z": [-0.003, 0.003], # ±3mm variation + }, + }, + ) + + .. tab-item:: Flexiv Rizon 4s + + .. code-block:: python + + set_robot_to_grasp_pose = EventTerm( + func=gear_assembly_events.set_robot_to_grasp_pose, + mode="reset", + params={ + "robot_asset_cfg": SceneEntityCfg("robot"), + "pos_randomization_range": { + "x": [-0.0, 0.0], + "y": [-0.0, 0.0], + "z": [-0.0, 0.0], + }, + }, + ) + +Reward Shaping +~~~~~~~~~~~~~~ + +The gear assembly environment uses keypoint-based rewards that measure the distance between keypoints on the gear and corresponding keypoints on the gear shaft. Both robots share a base set of reward terms defined in ``gear_assembly_env_cfg.py``: + +- **Keypoint tracking** (``keypoint_entity_error``): Penalizes the L2 distance between gear and shaft keypoints, encouraging the gear to approach the shaft. +- **Exponential keypoint tracking** (``keypoint_entity_error_exp``): Provides a dense exponential reward that grows sharply as keypoints align, helping the policy refine fine-grained insertion. +- **Action rate** (``action_rate_l2``): Penalizes large changes in actions between timesteps, promoting smooth motions. + +**Rizon 4s additional reward terms:** + +The Rizon 4s configuration adds two reward terms that measure the distance between the robot's end effector and the grasp-corrected pose computed from the active gear. For each gear, the code applies ``grasp_rot_offset`` and per-gear-size ``gear_offsets_grasp`` to compute where the EE should be if properly grasping that gear, then measures keypoint distance between the actual EE pose and that target. This acts as a grasp quality metric. These terms are defined only in the Rizon4s config (``joint_pos_env_cfg.py``) so they do not affect UR10e training: + .. code-block:: python - set_robot_to_grasp_pose = EventTerm( - func=gear_assembly_events.set_robot_to_grasp_pose, - mode="reset", + # Penalizes distance between EE and grasp-corrected pose + self.rewards.end_effector_grasp_keypoint_tracking = RewTerm( + func=mdp.keypoint_ee_grasp_error, + weight=-0.5, params={ "robot_asset_cfg": SceneEntityCfg("robot"), - "rot_offset": [0.0, math.sqrt(2)/2, math.sqrt(2)/2, 0.0], # Base gripper orientation - "pos_randomization_range": { - "x": [-0.0, 0.0], - "y": [-0.005, 0.005], # ±5mm variation - "z": [-0.003, 0.003], # ±3mm variation - }, - "gripper_type": "2f_140", + "keypoint_scale": 0.15, + "ee_grasp_threshold": 0.00, + "weight_ramp_start": 0.0, + "weight_ramp_steps": 250_000, + "end_effector_body_name": self.end_effector_body_name, + "grasp_rot_offset": self.grasp_rot_offset, + "gear_offsets_grasp": self.gear_offsets_grasp, + }, + ) + + # Exponential version for dense reward near alignment + self.rewards.end_effector_grasp_keypoint_tracking_exp = RewTerm( + func=mdp.keypoint_ee_grasp_error_exp, + weight=0.5, + params={ + "robot_asset_cfg": SceneEntityCfg("robot"), + "kp_exp_coeffs": [(50, 0.0001), (300, 0.0001)], + "kp_use_sum_of_exps": False, + "keypoint_scale": 0.15, + "ee_grasp_threshold": 0.00, + "weight_ramp_start": 0.0, + "weight_ramp_steps": 250_000, + "end_effector_body_name": self.end_effector_body_name, + "grasp_rot_offset": self.grasp_rot_offset, + "gear_offsets_grasp": self.gear_offsets_grasp, }, ) +These terms encourage the Rizon 4s policy to keep the gripper properly aligned with the gear during insertion. The distance is ~0 when the EE is correctly grasping the gear, and increases when the gripper drifts away. The ``weight_ramp_steps`` parameter linearly ramps the reward weight from zero over the first 512k environment steps, allowing the policy to first learn coarse approach/insertion behavior before the grasp quality reward becomes active. + +.. list-table:: Reward Terms Comparison + :widths: 40 15 15 + :header-rows: 1 + + * - Reward Term + - UR10e + - Rizon 4s + * - ``keypoint_entity_error`` (gear-shaft distance) + - Yes + - Yes + * - ``keypoint_entity_error_exp`` (exponential gear-shaft) + - Yes + - Yes + * - ``action_rate_l2`` (smooth actions) + - Yes + - Yes + * - ``keypoint_ee_grasp_error`` (EE vs grasp-corrected gear) + - No + - Yes + * - ``keypoint_ee_grasp_error_exp`` (exponential EE vs gear) + - No + - Yes + + Part 3: Training the Policy in Isaac Lab ----------------------------------------- @@ -427,16 +644,34 @@ Step 1: Visualize the Environment First, launch the training with a small number of environments and visualization enabled to verify that the environment is set up correctly: -.. code-block:: bash +.. tab-set:: - # Launch training with visualization - python scripts/reinforcement_learning/rsl_rl/train.py \ - --task Isaac-Deploy-GearAssembly-UR10e-2F140-v0 \ - --num_envs 4 + .. tab-item:: UR10e (2F-140) -.. note:: + .. code-block:: bash + + python scripts/reinforcement_learning/rsl_rl/train.py \ + --task Isaac-Deploy-GearAssembly-UR10e-2F140-ROS-Inference-v0 \ + --num_envs 4 \ + --visualizer kit + + .. tab-item:: UR10e (2F-85) + + .. code-block:: bash + + python scripts/reinforcement_learning/rsl_rl/train.py \ + --task Isaac-Deploy-GearAssembly-UR10e-2F85-ROS-Inference-v0 \ + --num_envs 4 \ + --visualizer kit + + .. tab-item:: Flexiv Rizon 4s + Grav - For the Robotiq 2F-85 gripper, use ``--task Isaac-Deploy-GearAssembly-UR10e-2F85-v0`` instead. + .. code-block:: bash + + python scripts/reinforcement_learning/rsl_rl/train.py \ + --task Isaac-Deploy-GearAssembly-Rizon4s-Grav-ROS-Inference-v0 \ + --num_envs 4 \ + --visualizer kit This will open the Isaac Sim viewer where you can observe the training process in real-time. @@ -456,21 +691,44 @@ Step 2: Full-Scale Training with Video Recording Now launch the full training run with more parallel environments in headless mode for faster training. We'll also enable video recording to monitor progress: -.. code-block:: bash +.. tab-set:: + + .. tab-item:: UR10e (2F-140) + + .. code-block:: bash + + python scripts/reinforcement_learning/rsl_rl/train.py \ + --task Isaac-Deploy-GearAssembly-UR10e-2F140-ROS-Inference-v0 \ + --headless \ + --num_envs 256 \ + --video --video_length 200 --video_interval 76800 + + .. tab-item:: UR10e (2F-85) + + .. code-block:: bash - # Full training with video recording - python scripts/reinforcement_learning/rsl_rl/train.py \ - --task Isaac-Deploy-GearAssembly-UR10e-2F140-v0 \ - --headless \ - --num_envs 256 \ - --video --video_length 800 --video_interval 5000 + python scripts/reinforcement_learning/rsl_rl/train.py \ + --task Isaac-Deploy-GearAssembly-UR10e-2F85-ROS-Inference-v0 \ + --headless \ + --num_envs 256 \ + --video --video_length 200 --video_interval 76800 -This command will: + .. tab-item:: Flexiv Rizon 4s + Grav -- Run 256 parallel environments for efficient training -- Run in headless mode (no visualization) for maximum performance -- Record videos every 5000 steps to monitor training progress -- Save videos with 800 frames each + .. code-block:: bash + + python scripts/reinforcement_learning/rsl_rl/train.py \ + --task Isaac-Deploy-GearAssembly-Rizon4s-Grav-ROS-Inference-v0 \ + --headless \ + --num_envs 256 \ + --video --video_length 200 --video_interval 76800 + +**Command breakdown:** + +- ``--headless``: Disables visualization for maximum training speed +- ``--num_envs 256``: Runs 256 parallel environments for efficient training +- ``--video_length 200``: Each video captures approximately one full episode (``episode_length_s / (sim.dt * decimation)`` = ``6.66 / (1/1000 * 33)`` ≈ 200 steps) +- ``--video_interval 76800``: Records a video every 76,800 environment steps (~every 150 iterations), producing ~10 videos over full training Training typically takes ~12-24 hours for a robust insertion policy. The videos will be saved in the ``logs`` directory and can be reviewed to assess policy performance during training. @@ -483,17 +741,27 @@ Training typically takes ~12-24 hours for a robust insertion policy. The videos You can monitor training metrics in real-time using TensorBoard. Open a new terminal and run: -.. code-block:: bash +.. tab-set:: + + .. tab-item:: UR10e + + .. code-block:: bash + + ./isaaclab.sh -p -m tensorboard.main --logdir logs/rsl_rl/gear_assembly_ur10e - ./isaaclab.sh -p -m tensorboard.main --logdir + .. tab-item:: Flexiv Rizon 4s -Replace ```` with the path to your training logs (e.g., ``logs/rsl_rl/gear_assembly_ur10e/2025-11-19_19-31-01``). TensorBoard will display plots showing rewards, episode lengths, and other metrics. Verify that the rewards are increasing over iterations to ensure the policy is learning successfully. + .. code-block:: bash + + ./isaaclab.sh -p -m tensorboard.main --logdir logs/rsl_rl/gear_assembly_rizon4s_grav + +Replace the log directory path with your actual training log location if different. TensorBoard will display plots showing rewards, episode lengths, and other metrics. Verify that the rewards are increasing over iterations to ensure the policy is learning successfully. Step 3: Deploy on Real Robot ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Once training is complete, follow the `Isaac ROS inference documentation `_ to deploy your policy. +Once training is complete, follow the `Isaac ROS inference documentation `_ to deploy your policy. The Isaac ROS deployment pipeline directly uses the trained model checkpoint (``.pt`` file) along with the ``agent.yaml`` and ``env.yaml`` configuration files generated during training. No additional export step is required. @@ -594,6 +862,54 @@ CUDA Out of Memory You can always evaluate the trained policy later with visualization. +Deterministic Debugging (Play Environment) +------------------------------------------- + +The ``Isaac-Deploy-GearAssembly-Rizon4s-Grav-Play-v0`` environment provides a fully +deterministic setup for debugging policy behavior against a specific real-world scenario. +All randomization is disabled and observation noise is turned off, so the simulation is +identical on every reset. + +To use it, run the standard ``play.py`` script: + +.. code-block:: bash + + python scripts/reinforcement_learning/rsl_rl/play.py \ + --task Isaac-Deploy-GearAssembly-Rizon4s-Grav-Play-v0 \ + --num_envs 1 \ + --checkpoint + +To match a specific real-world setup, edit the constants at the top of the +``Rizon4sGearAssemblyEnvCfg_PLAY`` class in +``isaaclab_tasks/.../gear_assembly/config/rizon_4s/ros_inference_env_cfg.py``: + +.. code-block:: python + + @configclass + class Rizon4sGearAssemblyEnvCfg_PLAY(Rizon4sGearAssemblyROSInferenceEnvCfg): + # ── Scene setup ── + GEAR_TYPE: str = "gear_large" # which gear to grasp + GEAR_BASE_POS: tuple = (0.481, -0.073, -0.005) # (x, y, z) meters + GEAR_BASE_ROT: tuple = (0.0, 0.0, 0.70711, -0.70711) # quaternion (x,y,z,w) + GEAR_Z_OFFSET: float = 0.0675 # gear height above base + + # ── Observation overrides (None = use simulated values) ── + OBS_SHAFT_POS: tuple | None = None # e.g. (0.481, -0.073, -0.005) + OBS_SHAFT_QUAT: tuple | None = None # e.g. (0.0, 0.0, 0.70711, -0.70711) + +When ``OBS_SHAFT_POS`` or ``OBS_SHAFT_QUAT`` are set (not ``None``), the +``play.py`` script automatically overwrites the corresponding portions of the +policy's observation tensor every step, regardless of simulation state. This +lets you test what the policy does when given a specific observation (e.g. a +pose captured from the real robot). + +This environment is particularly useful for: + +- Comparing simulated and real-world policy behavior at a known pose +- Injecting real-world observations to verify policy actions match expectations +- Debugging insertion failures at a specific gear base position/orientation + + Further Resources ----------------- diff --git a/docs/source/policy_deployment/04_reach/reach_policy.rst b/docs/source/policy_deployment/04_reach/reach_policy.rst new file mode 100644 index 000000000000..9317ed6f6c04 --- /dev/null +++ b/docs/source/policy_deployment/04_reach/reach_policy.rst @@ -0,0 +1,672 @@ +.. _walkthrough_reach_sim_to_real: + +Training a Reach Policy for Real Robot Deployment +================================================= + +This tutorial walks you through training an end-effector pose tracking (reach) reinforcement learning (RL) policy that transfers from simulation to a real robot. By the end of this guide, you will have a trained policy capable of controlling a robot arm to reach arbitrary target end-effector poses within its workspace. + +**Supported Robots:** + +- **Universal Robots UR10e**: 6-DOF industrial robot arm +- **Flexiv Rizon 4s**: 7-DOF collaborative robot arm + +**Scope of This Tutorial:** + +This tutorial focuses on the **training** portion of the sim-to-real workflow. For deployment on real hardware, including robot interface setup and ROS inference node configuration, refer to the `Isaac ROS Documentation `_. + +**Prerequisites:** + +Before starting this tutorial, ensure you have Isaac Lab installed and configured. Follow the :ref:`installation guide ` if you haven't already set up your environment. + + +Task Overview +------------- + +The reach task trains a policy to track randomly sampled end-effector poses within the robot's workspace. + +**How It Works:** + +1. A target pose (position and orientation) is randomly sampled within a defined workspace +2. The policy receives the current joint states and the target pose as observations +3. The policy outputs incremental joint position commands to move the end-effector toward the target +4. The target is resampled periodically during training to ensure the policy generalizes across the workspace + + +Key Concepts for Sim-to-Real Transfer +------------------------------------- + +Successful sim-to-real transfer requires consistency across three areas: + +1. **Input Consistency**: Observations available in simulation must match those available on the real robot +2. **System Response Consistency**: The simulated robot must respond to actions similarly to the real robot +3. **Output Consistency**: Any post-processing on policy outputs must be replicated during deployment + +When these are properly addressed, policies trained purely in simulation can transfer to real hardware without any real-world training data. + + +Observation Space +----------------- + +The policy receives only proprioceptive observations, which are reliably available from the robot controller: + +.. list-table:: Reach Environment Observations + :widths: 25 20 20 35 + :header-rows: 1 + + * - Observation + - UR10e Dim + - Rizon 4s Dim + - Source + * - ``joint_pos`` + - 6 + - 7 + - Robot joint encoders + * - ``joint_vel`` + - 6 + - 7 + - Robot joint encoders + * - ``pose_command`` + - 7 + - 7 + - Target pose (3D position + quaternion) + +**Total observation dimension:** 19 (UR10e) or 21 (Rizon 4s) + +**Implementation:** + +.. code-block:: python + + @configclass + class PolicyCfg(ObsGroup): + """Observations for policy group.""" + + joint_pos = ObsTerm(func=mdp.joint_pos, noise=Unoise(n_min=-0.0, n_max=0.0)) + joint_vel = ObsTerm(func=mdp.joint_vel, noise=Unoise(n_min=-0.0, n_max=0.0)) + pose_command = ObsTerm(func=mdp.generated_commands, params={"command_name": "ee_pose"}) + + def __post_init__(self): + self.enable_corruption = True + self.concatenate_terms = True + +.. note:: + + The noise terms are set to zero by default (``Unoise(n_min=-0.0, n_max=0.0)``), meaning no observation noise is applied. This can be adjusted if noise modeling is desired for additional robustness. Modern robot controllers provide sufficiently accurate joint state feedback that adding noise during training is not required for sim-to-real transfer of this task. + + +Action Space +------------ + +The policy outputs **incremental joint position commands**. Each action specifies a delta (change) to apply to the current joint positions: + +.. tab-set:: + + .. tab-item:: UR10e + + .. code-block:: python + + self.actions.arm_action = mdp.RelativeJointPositionActionCfg( + asset_name="robot", + joint_names=[".*"], + scale=0.0625, # ~3.6 degrees per action step + use_zero_offset=True, + ) + + .. tab-item:: Flexiv Rizon 4s + + .. code-block:: python + + self.actions.arm_action = mdp.RelativeJointPositionActionCfg( + asset_name="robot", + joint_names=["joint[1-7]"], + scale=0.0625, # ~3.6 degrees per action step + use_zero_offset=True, + ) + +The action scale of 0.0625 radians (~3.6 degrees) per step provides a balance between responsiveness and smooth motion. The UR10e uses ``[".*"]`` to match all joints, while the Rizon 4s explicitly specifies ``["joint[1-7]"]`` to match its 7 arm joints. + +**Action dimension:** 6 (UR10e) or 7 (Rizon 4s) + + +Robot Configurations +-------------------- + +Each robot has specific actuator configurations and workspace definitions. + +.. tab-set:: + + .. tab-item:: UR10e + + The UR10e is a 6-DOF industrial robot with the following actuator configuration: + + .. code-block:: python + + actuators = { + "shoulder": ImplicitActuatorCfg( + joint_names_expr=["shoulder_.*"], + stiffness=1320.0, + damping=72.66, + friction=0.0, + armature=0.0, + ), + "elbow": ImplicitActuatorCfg( + joint_names_expr=["elbow_joint"], + stiffness=600.0, + damping=34.64, + friction=0.0, + armature=0.0, + ), + "wrist": ImplicitActuatorCfg( + joint_names_expr=["wrist_.*"], + stiffness=216.0, + damping=29.39, + friction=0.0, + armature=0.0, + ), + } + + **End-Effector:** + + - Link: ``wrist_3_link`` + - Default orientation: End-effector facing down (roll = pi, yaw = -pi/2) + + **Target Workspace:** + + .. code-block:: python + + # Position (meters, relative to robot base) + pos_center = (0.8875, -0.225, 0.2) + pos_range = (0.25, 0.125, 0.1) # ±25cm x, ±12.5cm y, ±10cm z + + # Orientation (radians) + rot_center = (pi, 0.0, -pi/2) + rot_range = (pi/6, pi/6, pi*2/3) # ±30 deg roll/pitch, ±120 deg yaw + + .. tab-item:: Flexiv Rizon 4s + + The Rizon 4s is a 7-DOF collaborative robot with different torque, speed, and stiffness characteristics per joint group: + + .. code-block:: python + + actuators = { + # Joints 1-2: Higher torque (123 Nm), lower speed + "shoulder": ImplicitActuatorCfg( + joint_names_expr=["joint[1-2]"], + effort_limit_sim=123.0, + velocity_limit_sim=2.094, # 120 deg/s + stiffness=6000.0, + damping=108.5, + friction=0.0, + armature=0.0, + ), + # Joints 3-4: Medium torque (64 Nm), medium speed + "elbow": ImplicitActuatorCfg( + joint_names_expr=["joint[3-4]"], + effort_limit_sim=64.0, + velocity_limit_sim=2.443, # 140 deg/s + stiffness=4200.0, + damping=90.7, + friction=0.0, + armature=0.0, + ), + # Joints 5-7: Lower torque (39 Nm), higher speed + "wrist": ImplicitActuatorCfg( + joint_names_expr=["joint[5-7]"], + effort_limit_sim=39.0, + velocity_limit_sim=4.887, # 280 deg/s + stiffness=1500.0, + damping=54.2, + friction=0.0, + armature=0.0, + ), + } + + **End-Effector:** + + - Link: ``flange`` + - Default orientation: End-effector facing down (roll = pi) + + **Target Workspace:** + + .. code-block:: python + + # Position (meters, relative to robot base) + pos_center = (0.4, 0.0, 0.4) + pos_range = (0.4, 0.4, 0.35) # ±40cm x, ±40cm y, ±35cm z + + # Orientation (radians) + rot_center = (pi, 0.0, 0.0) + rot_range = (pi/2, pi/2, pi) # ±90 deg roll/pitch, ±180 deg yaw + + +Customizing the Workspace +------------------------- + +You may need to modify the target workspace to match your deployment scenario. Key parameters you can adjust: + +**Target Position Range** + +Modify ``target_pos_centre`` and ``target_pos_range`` in the robot-specific config file (e.g., ``joint_pos_env_cfg.py``): + +.. code-block:: python + + # Center of the target workspace (meters, relative to robot base) + self.target_pos_centre = (0.5, 0.0, 0.4) + + # Half-extents of the workspace in each dimension + self.target_pos_range = (0.2, 0.2, 0.15) # ±20cm x, ±20cm y, ±15cm z + +**Effects:** + +- Larger ranges increase task difficulty but improve generalization +- Ensure all target positions are reachable by the robot (within kinematic limits) +- Targets outside reachable workspace will cause the policy to fail + +**Target Orientation Range** + +Modify ``target_rot_centre`` and ``target_rot_range``: + +.. code-block:: python + + # Center orientation (roll, pitch, yaw in radians) + self.target_rot_centre = (math.pi, 0.0, 0.0) + + # Range of rotation variation around the center + self.target_rot_range = (math.pi/6, math.pi/6, math.pi) # ±30 deg, ±30 deg, ±180 deg + +**Effects:** + +- Wider orientation ranges train more versatile policies but may slow convergence +- Very wide ranges (e.g., full rotation) significantly increase training difficulty + +**Action Scale** + +Modify the ``scale`` parameter in the action configuration: + +.. code-block:: python + + self.actions.arm_action = mdp.RelativeJointPositionActionCfg( + asset_name="robot", + joint_names=[".*"], + scale=0.0625, # Decrease for finer control, increase for faster motion + use_zero_offset=True, + ) + +**Effects:** + +- Smaller scale: Finer control, smoother motion, but slower reaching +- Larger scale: Faster motion, but potentially jerky or overshooting targets +- The same scale must be used during deployment on the real robot + +**Target Resampling Interval** + +Modify ``resampling_time_range`` in the commands configuration: + +.. code-block:: python + + self.commands.ee_pose.resampling_time_range = (4.0, 4.0) # Resample every 4 seconds + +**Effects:** + +- Shorter intervals: More diverse targets per episode, but less time to converge to each target +- Longer intervals: More time to refine tracking, but fewer targets seen during training + + +Domain Randomization +-------------------- + +Domain randomization helps the policy generalize across variations in real robot behavior. + +**Actuator Gain Randomization:** + +.. code-block:: python + + robot_joint_stiffness_and_damping = EventTerm( + func=mdp.randomize_actuator_gains, + min_step_count_between_reset=200, + mode="reset", + params={ + "asset_cfg": SceneEntityCfg("robot"), + "stiffness_distribution_params": (0.9, 1.1), # 90-110% of nominal + "damping_distribution_params": (0.75, 1.5), # 75-150% of nominal + "operation": "scale", + "distribution": "uniform", + }, + ) + +The ``min_step_count_between_reset=200`` ensures that actuator gains are not re-randomized too frequently, giving the policy time to adapt to each set of parameters before they change. + +**Joint Friction Randomization:** + +.. code-block:: python + + joint_friction = EventTerm( + func=mdp.randomize_joint_parameters, + min_step_count_between_reset=200, + mode="reset", + params={ + "asset_cfg": SceneEntityCfg("robot"), + "friction_distribution_params": (0.0, 0.1), # Add 0-0.1 Nm friction + "operation": "add", + "distribution": "uniform", + }, + ) + +**Initial Joint Position Randomization:** + +.. code-block:: python + + reset_robot_joints = EventTerm( + func=mdp.reset_joints_by_offset, + mode="reset", + params={ + "position_range": (-0.125, 0.125), # ±7 degrees + "velocity_range": (0.0, 0.0), + }, + ) + + +Reward Structure +---------------- + +The policy is trained using a keypoint-based reward that captures both position and orientation accuracy: + +.. code-block:: python + + @configclass + class RewardsCfg: + """Reward terms for the MDP.""" + + # Linear penalty for keypoint tracking error + end_effector_keypoint_tracking = RewTerm( + func=mdp.keypoint_command_error, + weight=-1.5, + params={ + "asset_cfg": SceneEntityCfg("ee_frame"), + "command_name": "ee_pose", + "keypoint_scale": 0.45, + }, + ) + + # Exponential reward for fine precision + end_effector_keypoint_tracking_exp = RewTerm( + func=mdp.keypoint_command_error_exp, + weight=1.5, + params={ + "asset_cfg": SceneEntityCfg("ee_frame"), + "command_name": "ee_pose", + "kp_exp_coeffs": [(50, 0.0001), (300, 0.0001), (5000, 0.0001)], + "kp_use_sum_of_exps": False, + "keypoint_scale": 0.45, + }, + ) + + # Penalties for smooth motion + action_rate = RewTerm(func=mdp.action_rate_l2, weight=-0.005) + action = RewTerm(func=mdp.action_l2, weight=-0.005) + +The keypoint-based reward places virtual markers on the end-effector frame and measures the distance to corresponding markers on the target frame. This provides a robust metric that naturally captures both position and orientation errors. + + +Training the Policy +------------------- + +Step 1: Verify the Environment +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Before starting full training, launch a quick visualization run to verify the environment is set up correctly: + +.. tab-set:: + + .. tab-item:: UR10e + + .. code-block:: bash + + python scripts/reinforcement_learning/rsl_rl/train.py \ + --task Isaac-Deploy-Reach-UR10e-ROS-Inference-v0 \ + --num_envs 4 \ + --visualizer kit + + .. tab-item:: Flexiv Rizon 4s + + .. code-block:: bash + + python scripts/reinforcement_learning/rsl_rl/train.py \ + --task Isaac-Deploy-Reach-Rizon4s-ROS-Inference-v0 \ + --num_envs 4 \ + --visualizer kit + +This opens the Isaac Sim viewer where you can observe the training in real-time. + +.. figure:: ../../_static/policy_deployment/04_reach/reach_train.png + :align: center + :figwidth: 100% + :alt: Reach policy training visualization in Isaac Lab + + Training visualization showing multiple parallel environments with robots reaching toward target poses. + +**What to look for:** + +- The robot should be moving its arm attempting to reach different poses +- Early on, motion will be erratic as the policy explores; this is expected +- For **Rizon 4s**: Target pose markers appear as coordinate frames in the scene +- For **UR10e**: Target visualization is disabled (``debug_vis = False``) because commands are generated in the ``base`` frame, which is 180 degrees offset from the ``base_link`` frame used for rendering. The robot will still track targets, but markers won't be visible. + +Once you confirm the environment looks correct, stop training with ``Ctrl+C`` and proceed to full-scale training. + + +Step 2: Full-Scale Training +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Launch full training with many parallel environments in headless mode: + +.. tab-set:: + + .. tab-item:: UR10e + + .. code-block:: bash + + python scripts/reinforcement_learning/rsl_rl/train.py \ + --task Isaac-Deploy-Reach-UR10e-ROS-Inference-v0 \ + --headless \ + --num_envs 4096 \ + --video --video_length 720 --video_interval 72000 + + .. tab-item:: Flexiv Rizon 4s + + .. code-block:: bash + + python scripts/reinforcement_learning/rsl_rl/train.py \ + --task Isaac-Deploy-Reach-Rizon4s-ROS-Inference-v0 \ + --headless \ + --num_envs 4096 \ + --video --video_length 720 --video_interval 72000 + +**Command breakdown:** + +- ``--headless``: Disables visualization for maximum training speed +- ``--num_envs 4096``: Runs 4096 parallel environments for efficient data collection +- ``--video``: Records videos to monitor training progress +- ``--video_length 720``: Each video captures exactly one full episode (``episode_length_s / (sim.dt * decimation)`` = ``12.0 / (1/120 * 2)`` = 720 steps) +- ``--video_interval 72000``: Records a video every 72000 environment steps (~every 100 training iterations). + +**Training Configuration:** + +The training hyperparameters are the same for both robots: + +.. code-block:: python + + num_steps_per_env = 512 + max_iterations = 1500 + save_interval = 50 + empirical_normalization = True + obs_groups = {"policy": ["policy"], "critic": ["policy"]} + + policy = RslRlPpoActorCriticCfg( + init_noise_std=1.0, + actor_hidden_dims=[256, 128, 64], + critic_hidden_dims=[256, 128, 64], + activation="elu", + ) + + algorithm = RslRlPpoAlgorithmCfg( + value_loss_coef=1.0, + use_clipped_value_loss=True, + clip_param=0.2, + entropy_coef=0.0, + num_learning_epochs=8, + num_mini_batches=8, + learning_rate=5.0e-4, + schedule="adaptive", + gamma=0.99, + lam=0.95, + desired_kl=0.008, + max_grad_norm=1.0, + ) + +The ``experiment_name`` is ``"reach_ur10e"`` for UR10e and ``"reach_rizon4s"`` for Rizon 4s. Training typically takes 1-3 hours depending on your GPU. + + +Step 3: Monitor Training Progress +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Use TensorBoard to monitor training metrics: + +.. tab-set:: + + .. tab-item:: UR10e + + .. code-block:: bash + + ./isaaclab.sh -p -m tensorboard.main --logdir logs/rsl_rl/reach_ur10e + + .. tab-item:: Flexiv Rizon 4s + + .. code-block:: bash + + ./isaaclab.sh -p -m tensorboard.main --logdir logs/rsl_rl/reach_rizon4s + +Replace the log directory path with your actual training log location if different. + +**Key metrics to watch:** + +- **Mean reward**: Should increase steadily and plateau once the policy converges +- **Reward terms**: Monitor individual reward components to understand policy behavior: + + - ``end_effector_keypoint_tracking``: Linear keypoint tracking penalty -- should become less negative as the policy improves + - ``end_effector_keypoint_tracking_exp``: Exponential precision reward -- should increase as the policy achieves finer tracking + - ``action_rate`` and ``action``: Motion smoothness penalties -- these are small in magnitude but should increase (become less negative) over training, indicating the policy is converging toward smoother motion + +- **Position error**: Tracks the Euclidean distance (in meters) between the end-effector and target position -- should decrease over training +- **Orientation error**: Tracks the angular difference between the end-effector and target orientation -- should decrease over training + + +Step 4: Evaluate the Trained Policy +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Once training completes, evaluate the policy in the play environment: + +.. tab-set:: + + .. tab-item:: UR10e + + .. code-block:: bash + + python scripts/reinforcement_learning/rsl_rl/play.py \ + --task Isaac-Deploy-Reach-UR10e-Play-v0 \ + --num_envs 50 \ + --visualizer kit + + .. tab-item:: Flexiv Rizon 4s + + .. code-block:: bash + + python scripts/reinforcement_learning/rsl_rl/play.py \ + --task Isaac-Deploy-Reach-Rizon4s-Play-v0 \ + --num_envs 50 \ + --visualizer kit + +The play environments disable observation corruption for cleaner evaluation and use fewer environments for better visualization. + +**Checkpoint Loading:** + +By default, ``play.py`` automatically loads the most recent checkpoint from the most recent training run. The script searches in ``logs/rsl_rl//`` and selects the latest run folder and checkpoint file (sorted alphabetically). + +To load a specific checkpoint, use these arguments: + +.. code-block:: bash + + # Load from a specific run folder + python scripts/reinforcement_learning/rsl_rl/play.py \ + --task Isaac-Deploy-Reach-UR10e-Play-v0 \ + --load_run 2025-01-15_14-30-00 + + # Load a specific checkpoint file + python scripts/reinforcement_learning/rsl_rl/play.py \ + --task Isaac-Deploy-Reach-UR10e-Play-v0 \ + --checkpoint /path/to/model_1500.pt + + +Step 5: Deploy on Real Robot +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Once satisfied with the trained policy, deploy it on real hardware using the Isaac ROS deployment pipeline. The pipeline uses: + +- The trained model checkpoint (``.pt`` file) +- The ``agent.yaml`` and ``env.yaml`` configuration files generated during training + +No additional export step is required. + +For detailed deployment instructions, see the `Isaac ROS Documentation `_. + + +Troubleshooting +--------------- + +CUDA Out of Memory +~~~~~~~~~~~~~~~~~~ + +**Error:** + +.. code-block:: text + + torch.OutOfMemoryError: CUDA out of memory. + +**Solutions:** + +1. **Reduce parallel environments:** + + .. code-block:: bash + + --num_envs 2048 # or 1024, 512, etc. + +2. **Disable video recording:** + + Remove the ``--video`` flags to free GPU memory. + +Policy Does Not Converge +~~~~~~~~~~~~~~~~~~~~~~~~ + +If rewards do not improve after many iterations: + +1. **Check target workspace ranges**: Ensure all target poses are reachable by the robot +2. **Verify joint names**: Confirm joint ordering matches between simulation and configuration +3. **Reduce domain randomization**: Temporarily disable randomization to verify the base task works + +Jerky Motion on Real Robot +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +If the deployed policy produces jerky or unstable motion: + +1. **Reduce action scale**: Lower the ``scale`` parameter in ``RelativeJointPositionActionCfg`` +2. **Verify control frequency**: Ensure the real robot runs at the same frequency as simulation (60 Hz by default) +3. **Check joint ordering**: Verify joint names and ordering match between simulation and real robot + + +Further Resources +----------------- + +- `IndustReal: Transferring Contact-Rich Assembly Tasks from Simulation to Reality `_ +- `FORGE: Force-Guided Exploration for Robust Contact-Rich Manipulation under Uncertainty `_ +- `Isaac ROS Manipulation Documentation `_ +- Gear Assembly Sim-to-Real Tutorial: :ref:`walkthrough_sim_to_real` +- RL Training Tutorial: :ref:`tutorial-run-rl-training` diff --git a/docs/source/policy_deployment/05_leapp/exporting_policies_with_leapp.rst b/docs/source/policy_deployment/05_leapp/exporting_policies_with_leapp.rst new file mode 100644 index 000000000000..dc07a42fc141 --- /dev/null +++ b/docs/source/policy_deployment/05_leapp/exporting_policies_with_leapp.rst @@ -0,0 +1,251 @@ +Exporting Policies with LEAPP +============================= + +.. currentmodule:: isaaclab + +This guide covers how to export trained reinforcement learning policies from Isaac Lab using +`LEAPP `_ (Lightweight Export Annotations for Policy Pipelines). +The main goal of the LEAPP export path is to package the policy together with the input and +output semantics needed for deployment, so downstream users do not need to reimplement Isaac Lab +observation preprocessing, action postprocessing, or recurrent-state handling by hand. + +In practice, this makes the exported policy a much better fit for Isaac deployment libraries. +Isaac Lab can already consume these exports through :class:`~envs.LeappDeploymentEnv`, and Isaac +ROS will add direct support for running LEAPP-exported policies in a future release. + +.. note:: + + This export path currently supports **manager-based RL environments** (``ManagerBasedRLEnv``) + trained with **RSL-RL** only. Other environments are not yet supported. + + +Prerequisites +------------- + +LEAPP requires Python >= 3.8 and PyTorch >= 2.6. Install it with: + +.. code-block:: bash + + pip install leapp + +Ensure you have a trained RSL-RL checkpoint before proceeding. The standard Isaac Lab +training workflow produces checkpoints under ``logs/rsl_rl//``. + + +Why Export with LEAPP +--------------------- + +Running the export script generates a self-contained export directory alongside your +checkpoint (or at a custom path). The directory contains: + +- **Exported model files** — ``.onnx`` (default) or ``.pt`` depending on the chosen backend. +- **Export metadata** — LEAPP records the semantic information and wiring needed by downstream + deployment runtimes. +- **Initial values** — a ``.safetensors`` file for any feedback state, such as recurrent hidden + state or last action. +- **A graph visualization** — a ``.png`` diagram of the pipeline (can be disabled). + +The important outcome for Isaac deployment workflows is that the exported artifact preserves the +same dataflow that was used during training and inference inside Isaac Lab. That means downstream +consumers can run the policy without reconstructing observation ordering, command wiring, actuator +targets, or policy feedback loops themselves. + +For a detailed description of LEAPP's generated artifacts and APIs, refer to the +`LEAPP documentation `_. + + +Exporting a Policy +------------------ + +Use the RSL-RL export script to export a trained checkpoint: + +.. code-block:: bash + + ./isaaclab.sh -p scripts/reinforcement_learning/leapp/rsl_rl/export.py \ + --task \ + --checkpoint + +For example, to export a UR10 reach policy: + +.. code-block:: bash + + ./isaaclab.sh -p scripts/reinforcement_learning/leapp/rsl_rl/export.py \ + --task Isaac-Reach-UR10-v0 \ + --checkpoint logs/rsl_rl/ur10_reach/< date timestamp >/model_4999.pt + +By default, the export artifacts are saved in the same directory as the checkpoint. The +exported graph is named after the task. + + +CLI Options +^^^^^^^^^^^ + +The export script accepts the following LEAPP-specific arguments in addition to the standard +RSL-RL and AppLauncher arguments: + +.. list-table:: + :widths: 30 15 55 + :header-rows: 1 + + * - Argument + - Default + - Description + * - ``--export_task_name`` + - Task name + - Name for the exported graph and output directory. + * - ``--export_method`` + - ``onnx-dynamo`` + - Export backend. Choices: ``onnx-dynamo``, ``onnx-torchscript``, ``jit-script``, + ``jit-trace``. + * - ``--export_save_path`` + - Checkpoint dir + - Base directory for export output. + * - ``--validation_steps`` + - ``5`` + - Number of environment steps to run during the traced rollout. Set to ``0`` to skip + validation. + * - ``--disable_graph_visualization`` + - ``False`` + - Skip generating the pipeline graph PNG. + +The script also accepts the standard ``--checkpoint``, ``--load_run``, ``--load_checkpoint``, +and ``--use_pretrained_checkpoint`` arguments for locating the trained model. + + +How It Works (High Level) +^^^^^^^^^^^^^^^^^^^^^^^^^ + +The export script performs the following steps: + +1. **Creates the environment** with ``num_envs=1`` and loads the trained checkpoint. +2. **Patches the environment** for export. This step injects annotations into the environment + so that tensor i/o to the pipeline are identified by LEAPP during execution. +3. **Runs a short rollout** (controlled by ``--validation_steps``) with LEAPP tracing + active. During this rollout, LEAPP traces all tensor operations in the pipeline and automatically + builds an onnx file. +4. **Compiles the graph** so the exported model and deployment metadata can be consumed by + downstream runtimes, and optionally validates that the exported model reproduces the traced + outputs. + +The patching is transparent to the policy — no changes to your training code or environment +configuration are needed. + +.. warning:: + + LEAPP is designed to support a broad range of model architectures, but the current + implementation has a few important limitations: + + - **Dynamic control flow** is not supported when the condition depends on runtime tensor + values, such as tensor-dependent ``if``, ``for``, or ``while`` logic. + - **Complex slicing** is not fully supported. Examples include dynamic masked indexing + using multiple traced tensors such as ``tensor[traced1, traced2]``. Slicing with constant values + or with a single traced tensor is supported such as ``tensor[mask]`` or ``tensor[1:5]``. + - **Critical traced operations must be written in PyTorch.** For this release, Warp and + NumPy operations cannot be traced by LEAPP. + + +Verifying an Export +------------------- + +After export, we recommend validating the result in three ways. + +1. **Use LEAPP's automatic verification on seen traced data.** +2. **Inspect the generated graph visualization.** +3. **Read the LEAPP log carefully, especially when the export fails or emits warnings.** + +Automatic Verification on Seen Data +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +By default, Isaac Lab asks LEAPP to validate the exported model after compilation. LEAPP does +this by replaying the data it already saw during the traced rollout and checking that the +exported artifact reproduces the same outputs. + +This is a strong first-line check because it is good at catching export-time issues such as: + +- backend conversion problems +- unsupported or incorrectly lowered operators +- output shape or dtype mismatches +- numerical discrepancies between the original policy and the exported artifact +- recurrent or feedback-state handling mistakes that show up during replay + +This validation is controlled by ``--validation_steps``. Setting it to a positive value gives +LEAPP rollout data to validate against. Setting it to ``0`` skips this automatic check, which +is useful for debugging but not recommended for normal export workflows. + +Inspect the Graph Visualization +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +LEAPP can generate a diagram of the exported pipeline as part of ``compile_graph()``. Even when +automatic verification passes, it is still worth opening the diagram and doing a quick visual +inspection. + +This is especially useful for catching structural issues such as: + +- missing inputs or outputs +- unexpected extra nodes +- incorrect feedback edges +- naming mistakes that make deployment harder to reason about + +You can disable the diagram with ``--disable_graph_visualization``, but we recommend keeping it +enabled while developing and validating a new export path. + +Inspect the LEAPP Log +^^^^^^^^^^^^^^^^^^^^^ + +If something breaks, the LEAPP-generated log is usually the best place to determine exactly what +happened. Read it closely and pay attention to both hard errors and warnings. + +The log is useful for diagnosing issues such as: + +- export backend failures +- warnings about graph construction or validation +- missing metadata +- unsupported model patterns +- file generation problems + +In practice, this should be your first stop when the export does not complete or when the output +artifacts do not look correct. + + +Export Backends +^^^^^^^^^^^^^^^ + +The ``--export_method`` argument controls how the policy network is serialized: + +- **onnx-dynamo** (default) — Uses ``torch.onnx.dynamo_export``. Best compatibility with + modern PyTorch features. +- **onnx-torchscript** — Uses the legacy ``torch.onnx.export`` path. May be needed for + certain model architectures. +- **jit-script** / **jit-trace** — Produces TorchScript ``.pt`` files instead of ONNX. + + +Recurrent Policies +^^^^^^^^^^^^^^^^^^ + +Recurrent policies (e.g., using GRU or LSTM memory) are supported automatically. The export +script detects recurrent hidden state in the RSL-RL policy, registers it as LEAPP feedback +state, and ensures it appears in the ``feedback_flow`` section of the output YAML. The +initial hidden state values are saved in the ``.safetensors`` file. + + +Running the Exported Policy in Simulation +----------------------------------------- + +Isaac Lab provides :class:`~envs.LeappDeploymentEnv` for running exported policies back in +simulation without the training infrastructure. This is the Isaac Lab deployment path for +LEAPP-exported policies and is useful for validating that the packaged policy still behaves +correctly when driven through the deployment stack instead of the training stack. + +For Direct workflow policies, see the +:doc:`Direct workflow LEAPP export tutorial `. +That guide shows how to add LEAPP annotations to a direct RL environment so it can be +exported with ``scripts/reinforcement_learning/leapp/rsl_rl/export.py``. Direct +workflow policies are not currently supported by ``scripts/reinforcement_learning/leapp/deploy.py``. + + +Further Reading +--------------- + +- `LEAPP documentation `_ +- `LEAPP API reference `_ +- :class:`~envs.LeappDeploymentEnv` API reference diff --git a/docs/source/policy_deployment/index.rst b/docs/source/policy_deployment/index.rst index 32a10a42034f..70cb7244078e 100644 --- a/docs/source/policy_deployment/index.rst +++ b/docs/source/policy_deployment/index.rst @@ -3,7 +3,7 @@ Sim2Real Deployment of Policies Trained in Isaac Lab Welcome to the Policy Deployment Guide! This section provides examples of training policies in Isaac Lab and deploying them to both simulation and real robots. -Below, you’ll find detailed examples of various policies for training and deploying them, along with essential configuration details. +Below, you'll find detailed examples of various policies for training and deploying them, along with essential configuration details. .. toctree:: :maxdepth: 1 @@ -12,3 +12,5 @@ Below, you’ll find detailed examples of various policies for training and depl 01_io_descriptors/io_descriptors_101 02_gear_assembly/gear_assembly_policy 03_compass_with_NuRec/compass_navigation_policy_with_NuRec + 04_reach/reach_policy + 05_leapp/exporting_policies_with_leapp diff --git a/docs/source/refs/troubleshooting.rst b/docs/source/refs/troubleshooting.rst index 20094c617bfb..3196b2938e60 100644 --- a/docs/source/refs/troubleshooting.rst +++ b/docs/source/refs/troubleshooting.rst @@ -26,7 +26,7 @@ You are running a script that requires Isaac Sim, but it is not installed. Either: - Install Isaac Sim: ``./isaaclab.sh -i isaacsim``, or -- Use a Newton-based task with ``presets=newton --visualizer newton`` (Kit-less path) +- Use a Newton-based task with ``presets=newton_mjwarp --visualizer newton`` (Kit-less path) ``ModuleNotFoundError: No module named 'isaaclab_physx'`` or ``'isaaclab_ov'`` ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -77,6 +77,13 @@ Ubuntu 22.04+ satisfies this. For older distributions, use the `binary installation `_ method for Isaac Sim. +Troubleshooting distributed training NCCL errors +------------------------------------------------ + +On some Linux multi-GPU systems, distributed training may fail with +``CUDA error: an illegal memory access was encountered`` reported by ``ProcessGroupNCCL``. +For documented NCCL workarounds, see :ref:`multi-gpu-nccl-troubleshooting`. + Debugging physics simulation stability issues --------------------------------------------- diff --git a/docs/source/setup/installation/cloud_installation.rst b/docs/source/setup/installation/cloud_installation.rst index cadecfce1c43..b6d9137680a3 100644 --- a/docs/source/setup/installation/cloud_installation.rst +++ b/docs/source/setup/installation/cloud_installation.rst @@ -2,15 +2,15 @@ Cloud Deployment ================ Isaac Lab can be run in various cloud infrastructures with the use of -`Isaac Automator `__. +`Isaac Automator `__ (v4). -Isaac Automator allows for quick deployment of Isaac Sim and Isaac Lab onto -the public clouds (AWS, GCP, Azure, and Alibaba Cloud are currently supported). -The result is a fully configured remote desktop cloud workstation, which can -be used for development and testing of Isaac Lab within minutes and on a budget. -Isaac Automator supports variety of GPU instances and stop-start functionality -to save on cloud costs and a variety of tools to aid the workflow -(such as uploading and downloading data, autorun, deployment management, etc). +Isaac Automator allows quick deployment of Isaac Sim, Isaac Lab, and Isaac Lab Arena +onto public clouds (AWS, GCP, Azure, and Alibaba Cloud are currently supported). +The result is a fully configured remote desktop cloud workstation (Isaac Workstation), +which can be used for development and testing of Isaac Lab within minutes and on a budget. +Isaac Automator supports a variety of GPU instances and stop/start functionality +to save on cloud costs, and provides tools to aid the workflow +(uploading and downloading data, autorun scripts, deployment management, etc.). System Requirements @@ -19,17 +19,16 @@ System Requirements Isaac Automator requires having ``docker`` pre-installed on the system. * To install Docker, please follow the instructions for your operating system on the - `Docker website`_. A minimum version of 26.0.0 for Docker Engine and 2.25.0 for Docker - compose are required to work with Isaac Automator. + `Docker website`_. * Follow the post-installation steps for Docker on the `post-installation steps`_ page. These steps allow you to run Docker without using ``sudo``. Installing Isaac Automator --------------------------- +--------------------------- -For the most update-to-date and complete installation instructions, please refer to -`Isaac Automator `__. +For the most up-to-date and complete installation instructions, please refer to +the `Isaac Automator README `__. To use Isaac Automator, first clone the repo: @@ -48,37 +47,15 @@ To use Isaac Automator, first clone the repo: git clone git@github.com:isaac-sim/IsaacAutomator.git -Isaac Automator requires obtaining a NGC API key. - -* Get access to the `Isaac Sim container`_ by joining the NVIDIA Developer Program credentials. -* Generate your `NGC API key`_ to access locked container images from NVIDIA GPU Cloud (NGC). - - * This step requires you to create an NGC account if you do not already have one. - * Once you have your generated API key, you need to log in to NGC - from the terminal. - - .. code:: bash - - docker login nvcr.io - - * For the username, enter ``$oauthtoken`` exactly as shown. It is a special username that is used to - authenticate with NGC. - - .. code:: text - - Username: $oauthtoken - Password: - - -Building the container +Building the Container ---------------------- -To run Isaac Automator, first build the Isaac Automator container: +Build the Isaac Automator container: .. tab-set:: :sync-group: os - .. tab-item:: :icon:`fa-brands fa-linux` Linux + .. tab-item:: :icon:`fa-brands fa-linux` Linux / macOS :sync: linux .. code-block:: bash @@ -90,149 +67,138 @@ To run Isaac Automator, first build the Isaac Automator container: .. code-block:: batch - docker build --platform linux/x86_64 -t isa . + docker build --platform linux/x86_64 -t isaac_automator . +This will build the Isaac Automator container and tag it as ``isaac_automator``. -This will build the Isaac Automator container and tag it as ``isa``. - -Running the Automator Commands +Deploying an Isaac Workstation ------------------------------ -First, enter the Automator container: - .. tab-set:: :sync-group: os - .. tab-item:: :icon:`fa-brands fa-linux` Linux + .. tab-item:: :icon:`fa-brands fa-linux` Linux / macOS :sync: linux + Enter the Automator container and run the deployment command: + .. code-block:: bash ./run + # inside container: + ./deploy-aws + + Alternatively, run it in one step: + + .. code-block:: bash + + ./run ./deploy-aws .. tab-item:: :icon:`fa-brands fa-windows` Windows :sync: windows .. code-block:: batch - docker run --platform linux/x86_64 -it --rm -v .:/app isa bash + docker run --platform linux/x86_64 -it --rm -v .:/app isaac_automator bash + :: inside container: + ./deploy-aws -Next, run the deployment script for your preferred cloud: +Replace ``deploy-aws`` with ``deploy-gcp``, ``deploy-azure``, or ``deploy-alicloud`` +for other cloud providers. .. note:: - The ``--isaaclab`` flag is used to specify the version of Isaac Lab to deploy. - The ``v3.0.0`` tag is the latest release of Isaac Lab. - -.. tab-set:: - :sync-group: cloud - - .. tab-item:: AWS - :sync: aws - - .. code-block:: bash - - ./deploy-aws --isaaclab v3.0.0 - - .. tab-item:: Azure - :sync: azure + The ``--isaaclab`` and ``--isaacsim`` flags accept any valid Git reference + to specify the version to deploy. Use ``--isaaclab no`` or ``--isaacsim no`` + to skip installation of the respective component. - .. code-block:: bash + .. code-block:: bash - ./deploy-azure --isaaclab v3.0.0 + ./deploy-aws --isaaclab v3.0.0 --isaacsim main - .. tab-item:: GCP - :sync: gcp +On the first run (or when credentials expire), you will be prompted to enter +your cloud credentials. Credentials are stored in ``state/`` and persist +across container restarts. Run ``./deploy- --help`` to see all available +options. - .. code-block:: bash +Key deployment options: - ./deploy-gcp --isaaclab v3.0.0 - - .. tab-item:: Alibaba Cloud - :sync: alicloud - - .. code-block:: bash +- ``--instance-type`` -- Cloud VM instance type. +- ``--isaacsim`` / ``--isaaclab`` / ``--isaaclab-arena`` -- Git ref for the version + to install, or ``no`` to skip. +- ``--existing`` -- What to do if a deployment already exists: ``ask`` (default), + ``repair``, ``modify``, ``replace``, or ``run_ansible``. +- ``--from-image`` -- Deploy from a pre-built VM image for faster provisioning + (AWS only at this time). - ./deploy-alicloud --isaaclab v3.0.0 +Connecting to the Isaac Workstation +----------------------------------- -Follow the prompts for entering information regarding the environment setup and credentials. -Once successful, instructions for connecting to the cloud instance will be available -in the terminal. The deployed Isaac Sim instances can be accessed via: +Deployed Isaac Workstations can be accessed via: -- SSH -- noVCN (browser-based VNC client) -- NoMachine (remote desktop client) +- **SSH**: ``./ssh `` +- **noVNC** (browser-based): ``./novnc `` +- **NoMachine** (remote desktop client) -Look for the connection instructions at the end of the deployment command output. -Additionally, this info is saved in ``state//info.txt`` file. - -For details on the credentials and setup required for each cloud, please visit the -`Isaac Automator `__ -page for more instructions. +Connection instructions are displayed at the end of the deployment command +output and saved in ``state//info.txt``. Running Isaac Lab on the Cloud ------------------------------ -Once connected to the cloud instance, the desktop will have an icon showing ``isaaclab.sh``. -Launch the ``isaaclab.sh`` executable, which will open a new Terminal. Within the terminal, -Isaac Lab commands can be executed in the same way as running locally. - -For example: - -.. tab-set:: - :sync-group: os - - .. tab-item:: :icon:`fa-brands fa-linux` Linux - :sync: linux +Isaac Lab is installed from source on the deployed workstation at ``~/IsaacLab``. +To run Isaac Lab commands, open a terminal on the workstation: - .. code-block:: bash +.. code-block:: bash - ./isaaclab.sh -p scripts/reinforcement_learning/rl_games/train.py --task=Isaac-Cartpole-v0 + ~/IsaacLab/isaaclab.sh -p scripts/reinforcement_learning/rsl_rl/train.py \ + --task=Isaac-Cartpole-Direct-v0 --headless - .. tab-item:: :icon:`fa-brands fa-windows` Windows - :sync: windows - .. code-block:: batch +Pausing and Resuming +-------------------- - isaaclab.bat -p scripts/reinforcement_learning/rl_games/train.py --task=Isaac-Cartpole-v0 +You can stop and restart instances to save on cloud costs: +.. code-block:: bash -Destroying a Deployment ------------------------ + # inside the Automator container: + ./stop + ./start -To save costs, deployments can be destroyed when not being used. -This can be done from within the Automator container. +Use ``./start --quick`` to skip full Ansible provisioning +and only run the autorun script. -Enter the Automator container with the command described in the previous section: -.. tab-set:: - :sync-group: os +Uploading and Downloading Data +------------------------------ - .. tab-item:: :icon:`fa-brands fa-linux` Linux - :sync: linux +.. code-block:: bash - .. code-block:: bash + # upload local uploads/ folder to the instance + ./upload - ./run + # download results from the instance to local results/ folder + ./download - .. tab-item:: :icon:`fa-brands fa-windows` Windows - :sync: windows - .. code-block:: batch +Destroying a Deployment +----------------------- - docker run --platform linux/x86_64 -it --rm -v .:/app isa bash +To save costs, destroy deployments when no longer needed: +.. code-block:: bash -To destroy a deployment, run the following command from within the container: + # inside the Automator container: + ./destroy -.. code:: bash +.. note:: - ./destroy + Deployment metadata is stored in the ``state/`` directory. Do not delete this + directory, as it is required for managing deployments. -.. _`Docker website`: https://docs.docker.com/desktop/install/linux-install/ +.. _`Docker website`: https://docs.docker.com/engine/install/ .. _`post-installation steps`: https://docs.docker.com/engine/install/linux-postinstall/ -.. _`Isaac Sim container`: https://catalog.ngc.nvidia.com/orgs/nvidia/containers/isaac-sim -.. _`NGC API key`: https://docs.nvidia.com/ngc/gpu-cloud/ngc-user-guide/index.html#generating-api-key diff --git a/docs/source/setup/installation/include/bin_verify_isaacsim.rst b/docs/source/setup/installation/include/bin_verify_isaacsim.rst index 19da95e16236..4d5bbd1f5a0d 100644 --- a/docs/source/setup/installation/include/bin_verify_isaacsim.rst +++ b/docs/source/setup/installation/include/bin_verify_isaacsim.rst @@ -34,7 +34,7 @@ Check that the simulator runs from a standalone python script: # checks that python path is set correctly ${ISAACSIM_PYTHON_EXE} -c "print('Isaac Sim configuration is now complete.')" # checks that Isaac Sim can be launched from python - ${ISAACSIM_PYTHON_EXE} ${ISAACSIM_PATH}/standalone_examples/api/isaacsim.core.api/add_cubes.py + ${ISAACSIM_PYTHON_EXE} ${ISAACSIM_PATH}/standalone_examples/api/isaacsim.core.experimental.api/add_cubes.py .. tab-item:: :icon:`fa-brands fa-windows` Windows :sync: windows @@ -44,7 +44,7 @@ Check that the simulator runs from a standalone python script: :: checks that python path is set correctly %ISAACSIM_PYTHON_EXE% -c "print('Isaac Sim configuration is now complete.')" :: checks that Isaac Sim can be launched from python - %ISAACSIM_PYTHON_EXE% %ISAACSIM_PATH%\standalone_examples\api\isaacsim.core.api\add_cubes.py + %ISAACSIM_PYTHON_EXE% %ISAACSIM_PATH%\standalone_examples\api\isaacsim.core.experimental.api\add_cubes.py .. caution:: diff --git a/docs/source/setup/installation/include/pip_extras_note.rst b/docs/source/setup/installation/include/pip_extras_note.rst new file mode 100644 index 000000000000..67df28e15089 --- /dev/null +++ b/docs/source/setup/installation/include/pip_extras_note.rst @@ -0,0 +1,8 @@ +.. note:: + + The bare ``isaaclab`` install ships only the core extension. To run + the bundled training scripts under ``scripts/reinforcement_learning/`` + you must install with the ``[all]`` extras (or the per-framework + extras ``[skrl]`` / ``[sb3]`` / ``[rsl-rl]``); otherwise commands such + as ``python scripts/reinforcement_learning/skrl/train.py ...`` fail + at import time with ``ModuleNotFoundError: No module named 'skrl'``. diff --git a/docs/source/setup/installation/include/src_python_virtual_env.rst b/docs/source/setup/installation/include/src_python_virtual_env.rst index 617e29ace75a..4ca31fafb17a 100644 --- a/docs/source/setup/installation/include/src_python_virtual_env.rst +++ b/docs/source/setup/installation/include/src_python_virtual_env.rst @@ -62,7 +62,7 @@ instead of *./isaaclab.sh -p* or *isaaclab.bat -p*. .. warning:: Windows support for UV is currently unavailable. Please check - `issue #3483 `_ to track progress. + `issue #3438 `_ to track progress. .. tab-item:: Conda Environment @@ -103,7 +103,7 @@ instead of *./isaaclab.sh -p* or *isaaclab.bat -p*. .. code:: batch :: Activate environment - conda activate env_isaaclab # or "conda activate my_env" + conda activate env_isaaclab :: or "conda activate my_env" Once you are in the virtual environment, you do not need to use ``./isaaclab.sh -p`` or ``isaaclab.bat -p`` to run python scripts. You can use the default python executable in your diff --git a/docs/source/setup/installation/include/src_verify_isaaclab.rst b/docs/source/setup/installation/include/src_verify_isaaclab.rst index a747a1ccdc35..38f51100ec5f 100644 --- a/docs/source/setup/installation/include/src_verify_isaaclab.rst +++ b/docs/source/setup/installation/include/src_verify_isaaclab.rst @@ -14,10 +14,10 @@ top of the repository: # Option 1: Using the isaaclab.sh executable # note: this works for both the bundled python and the virtual environment - ./isaaclab.sh -p scripts/tutorials/00_sim/create_empty.py + ./isaaclab.sh -p scripts/tutorials/00_sim/create_empty.py --viz kit # Option 2: Using python in your virtual environment - python scripts/tutorials/00_sim/create_empty.py + python scripts/tutorials/00_sim/create_empty.py --viz kit .. tab-item:: :icon:`fa-brands fa-windows` Windows :sync: windows @@ -26,10 +26,10 @@ top of the repository: :: Option 1: Using the isaaclab.bat executable :: note: this works for both the bundled python and the virtual environment - isaaclab.bat -p scripts\tutorials\00_sim\create_empty.py + isaaclab.bat -p scripts\tutorials\00_sim\create_empty.py --viz kit :: Option 2: Using python in your virtual environment - python scripts\tutorials\00_sim\create_empty.py + python scripts\tutorials\00_sim\create_empty.py --viz kit The above command should launch the simulator and display a window with a black diff --git a/docs/source/setup/installation/index.rst b/docs/source/setup/installation/index.rst index dd92d178be60..6d00776ee754 100644 --- a/docs/source/setup/installation/index.rst +++ b/docs/source/setup/installation/index.rst @@ -42,6 +42,13 @@ installation methods. .. caution:: + **Compatibility warning for Isaac Sim GitHub develop:** A recent breaking change on the Isaac Lab + ``develop`` branch is not compatible with the ``develop`` branch of Isaac Sim on GitHub. To run + Isaac Lab with Isaac Sim's GitHub ``develop`` branch, use Isaac Lab commit + `f0234a82e432e2a0b0f0a26ca3c5b59e527ddaaa `__ + or an earlier commit. Alternatively, use the Isaac Lab + `v3.0.0-beta `__ tag. + We have dropped support for Isaac Sim versions 5.1.0 and below. We recommend using the latest Isaac Sim 6.0.0 release to benefit from the latest features and improvements. diff --git a/docs/source/setup/installation/isaaclab_pip_installation.rst b/docs/source/setup/installation/isaaclab_pip_installation.rst index d3070fd51f50..bf6aebfefe2e 100644 --- a/docs/source/setup/installation/isaaclab_pip_installation.rst +++ b/docs/source/setup/installation/isaaclab_pip_installation.rst @@ -61,7 +61,7 @@ Isaac Lab sub-packages: uv pip install isaaclab==3.0.0 # specific version # Isaac Lab + Isaac Sim - uv pip install "isaaclab[isaacsim]" --index-strategy unsafe-best-match --prerelease=allow + uv pip install "isaaclab[isaacsim]" --extra-index-url https://pypi.nvidia.com --index-strategy unsafe-best-match --prerelease=allow # Isaac Lab + specific sub-package(s) # Note: flags above are only needed when installing the isaacsim extra @@ -69,7 +69,9 @@ Isaac Lab sub-packages: uv pip install "isaaclab[rl,tasks]" # Isaac Lab + Isaac Sim + all sub-packages - uv pip install "isaaclab[isaacsim,all]" --index-strategy unsafe-best-match --prerelease=allow + uv pip install "isaaclab[isaacsim,all]" --extra-index-url https://pypi.nvidia.com --index-strategy unsafe-best-match --prerelease=allow + + .. include:: include/pip_extras_note.rst .. tab-item:: pip @@ -90,6 +92,8 @@ Isaac Lab sub-packages: # Isaac Lab + Isaac Sim + all Isaac Lab sub-packages pip install "isaaclab[isaacsim,all]" --extra-index-url https://pypi.nvidia.com --pre + .. include:: include/pip_extras_note.rst + Installing dependencies ~~~~~~~~~~~~~~~~~~~~~~~ @@ -145,7 +149,7 @@ Installing dependencies .. code-block:: bash unset LD_PRELOAD - export LD_PRELOAD="$LD_PRELOAD:/lib/aarch64-linux-gnu/libgomp.so.1" + export LD_PRELOAD=/lib/aarch64-linux-gnu/libgomp.so.1 This ensures the correct ``libgomp`` library is preloaded for both Isaac Sim and Isaac Lab, removing the preload warnings during runtime. @@ -170,8 +174,9 @@ Installing dependencies When using a conda environment, the preload is set up via the conda activation hook. -- If you want to use ``rl_games`` for training and inferencing, install - its Python 3.11+ enabled fork: +- If you want to use ``rl_games`` for training and inferencing **and did not + install the** ``rl`` **extra above**, install its Python 3.11+ enabled fork + manually: .. code-block:: none diff --git a/docs/source/setup/installation/kitless_installation.rst b/docs/source/setup/installation/kitless_installation.rst index b886d2d941a6..8a01caddc4d3 100644 --- a/docs/source/setup/installation/kitless_installation.rst +++ b/docs/source/setup/installation/kitless_installation.rst @@ -15,11 +15,11 @@ fastest way to get started and is ideal for users who only need the Newton physi # Install Isaac Lab (Newton backend, no Isaac Sim required) ./isaaclab.sh --install # or ./isaaclab.sh -i - # Kickoff training with Newton physics and Newton visualizer + # Kickoff training with MJWarp physics and Newton visualizer ./isaaclab.sh -p scripts/reinforcement_learning/rsl_rl/train.py \ --task=Isaac-Cartpole-Direct-v0 \ --num_envs=16 --max_iterations=10 \ - presets=newton --visualizer newton + presets=newton_mjwarp --visualizer newton **Features available in kit-less mode (Newton backend, no Isaac Sim):** @@ -110,7 +110,7 @@ OVRTX provides GPU-accelerated rendering for vision tasks without Kit. ./isaaclab.sh -p scripts/benchmarks/benchmark_rsl_rl.py \ --task Isaac-Repose-Cube-Shadow-Vision-Benchmark-Direct-v0 \ --headless --enable_cameras --num_envs 16 --max_iterations 10 \ - presets=newton,ovrtx_renderer,simple_shading_diffuse_mdl + presets=newton_mjwarp,ovrtx_renderer,simple_shading_diffuse_mdl Running Installation Tests diff --git a/docs/source/setup/installation/pip_installation.rst b/docs/source/setup/installation/pip_installation.rst index a45a66d1de3d..defaab955016 100644 --- a/docs/source/setup/installation/pip_installation.rst +++ b/docs/source/setup/installation/pip_installation.rst @@ -95,7 +95,7 @@ Installing dependencies .. code-block:: bash unset LD_PRELOAD - export LD_PRELOAD="$LD_PRELOAD:/lib/aarch64-linux-gnu/libgomp.so.1" + export LD_PRELOAD=/lib/aarch64-linux-gnu/libgomp.so.1 This ensures the correct ``libgomp`` library is preloaded for both Isaac Sim and Isaac Lab, removing the preload warnings during runtime. diff --git a/docs/source/setup/installation/source_installation.rst b/docs/source/setup/installation/source_installation.rst index c697c1dd2054..a4a9efebf05f 100644 --- a/docs/source/setup/installation/source_installation.rst +++ b/docs/source/setup/installation/source_installation.rst @@ -23,6 +23,15 @@ or want to test Isaac Lab with the nightly version of Isaac Sim. The following instructions are adapted from the `Isaac Sim documentation `_ for the convenience of users. +.. warning:: + + **Compatibility warning for Isaac Sim GitHub develop:** A recent breaking change on the Isaac Lab + ``develop`` branch is not compatible with the ``develop`` branch of Isaac Sim on GitHub. To run + Isaac Lab with Isaac Sim's GitHub ``develop`` branch, use Isaac Lab commit + `f0234a82e432e2a0b0f0a26ca3c5b59e527ddaaa `__ + or an earlier commit. Alternatively, use the Isaac Lab + `v3.0.0-beta `__ tag. + .. attention:: Building Isaac Sim from source requires Ubuntu 22.04 LTS or higher. @@ -56,7 +65,7 @@ for the convenience of users. .. tab-item:: :icon:`fa-brands fa-windows` Windows :sync: windows - .. code:: bash + .. code:: batch cd IsaacSim build.bat @@ -78,7 +87,7 @@ variables to your terminal for the remaining of the installation instructions: .. code:: bash # Isaac Sim root directory - export ISAACSIM_PATH="${pwd}/_build/linux-x86_64/release" + export ISAACSIM_PATH="${PWD}/_build/linux-x86_64/release" # Isaac Sim python executable export ISAACSIM_PYTHON_EXE="${ISAACSIM_PATH}/python.sh" diff --git a/docs/source/setup/quick_installation.rst b/docs/source/setup/quick_installation.rst index 3a4b60cb3317..c377318c5c1d 100644 --- a/docs/source/setup/quick_installation.rst +++ b/docs/source/setup/quick_installation.rst @@ -15,15 +15,15 @@ Quick Installation cd IsaacLab # Create environment and install - uv venv .venv --python 3.12 - source .venv/bin/activate + uv venv --python 3.12 --seed env_isaaclab + source env_isaaclab/bin/activate ./isaaclab.sh -i - # Run training (Newton backend, 16 envs) + # Run training (MJWarp on the Newton backend, 16 envs) ./isaaclab.sh -p scripts/reinforcement_learning/rsl_rl/train.py \ --task=Isaac-Cartpole-Direct-v0 \ --num_envs=16 --max_iterations=10 \ - presets=newton --visualizer newton + presets=newton_mjwarp --visualizer newton Running Tasks @@ -33,11 +33,11 @@ The ``presets=`` Hydra override selects the physics backend and renderer at runt .. code-block:: bash - # Newton (Kit-less) + # MJWarp (Newton backend, Kit-less) ./isaaclab.sh -p scripts/reinforcement_learning/rsl_rl/train.py \ --task Isaac-Cartpole-Direct-v0 \ --num_envs 4096 \ - presets=newton \ + presets=newton_mjwarp \ --visualizer newton # PhysX (Kit — requires Isaac Sim) @@ -46,11 +46,11 @@ The ``presets=`` Hydra override selects the physics backend and renderer at runt --num_envs 4096 \ presets=physx - # Newton with a specific visualizer + # MJWarp with a specific visualizer ./isaaclab.sh -p scripts/reinforcement_learning/rsl_rl/train.py \ --task Isaac-Cartpole-Direct-v0 \ --num_envs 4096 \ - presets=newton \ + presets=newton_mjwarp \ --visualizer viser Kit-less visualizer options: ``newton``, ``rerun``, ``viser``. Multiple can be @@ -66,21 +66,21 @@ combined: ``--visualizer newton,rerun``. Available Presets ^^^^^^^^^^^^^^^^^ -Presets are combined with commas: ``presets=newton,newton_renderer,depth``. +Presets are combined with commas: ``presets=newton_mjwarp,newton_renderer,depth``. .. code-block:: bash - presets=newton,newton_renderer,rgb # presets=physics,renderer,render mode - presets=newton,newton_renderer,depth + presets=newton_mjwarp,newton_renderer,rgb # presets=physics,renderer,render mode + presets=newton_mjwarp,newton_renderer,depth presets=physx,isaacsim_rtx_renderer,rgb presets=physx,isaacsim_rtx_renderer,depth presets=physx,isaacsim_rtx_renderer,albedo presets=physx,isaacsim_rtx_renderer,simple_shading_constant_diffuse presets=physx,isaacsim_rtx_renderer,simple_shading_diffuse_mdl presets=physx,isaacsim_rtx_renderer,simple_shading_full_mdl - presets=newton,ovrtx_renderer,rgb - presets=newton,ovrtx_renderer,depth - presets=newton,ovrtx_renderer,albedo - presets=newton,ovrtx_renderer,simple_shading_constant_diffuse - presets=newton,ovrtx_renderer,simple_shading_diffuse_mdl - presets=newton,ovrtx_renderer,simple_shading_full_mdl + presets=newton_mjwarp,ovrtx_renderer,rgb + presets=newton_mjwarp,ovrtx_renderer,depth + presets=newton_mjwarp,ovrtx_renderer,albedo + presets=newton_mjwarp,ovrtx_renderer,simple_shading_constant_diffuse + presets=newton_mjwarp,ovrtx_renderer,simple_shading_diffuse_mdl + presets=newton_mjwarp,ovrtx_renderer,simple_shading_full_mdl diff --git a/docs/source/setup/quickstart.rst b/docs/source/setup/quickstart.rst index 4ebdcd024046..7b4f7ace2b5e 100644 --- a/docs/source/setup/quickstart.rst +++ b/docs/source/setup/quickstart.rst @@ -53,9 +53,9 @@ package manager. To begin, create a virtual environment: .. code-block:: batch - # create a virtual environment named env_isaaclab with python3.12 + :: create a virtual environment named env_isaaclab with python3.12 uv venv --python 3.12 --seed env_isaaclab - # activate the virtual environment + :: activate the virtual environment env_isaaclab\Scripts\activate .. tab-item:: conda @@ -68,11 +68,31 @@ package manager. To begin, create a virtual environment: conda activate env_isaaclab -Next, install a CUDA-enabled PyTorch build. +Next, install a CUDA-enabled PyTorch build that matches your system architecture. + +.. tab-set:: + :sync-group: pip-platform + + .. tab-item:: :icon:`fa-brands fa-linux` Linux (x86_64) + :sync: linux-x86_64 + + .. code-block:: bash - .. code-block:: bash + uv pip install -U torch==2.10.0 torchvision==0.25.0 --index-url https://download.pytorch.org/whl/cu128 - uv pip install -U torch==2.10.0 torchvision==0.25.0 --index-url https://download.pytorch.org/whl/cu128 + .. tab-item:: :icon:`fa-brands fa-windows` Windows (x86_64) + :sync: windows-x86_64 + + .. code-block:: bash + + uv pip install -U torch==2.10.0 torchvision==0.25.0 --index-url https://download.pytorch.org/whl/cu128 + + .. tab-item:: :icon:`fa-brands fa-linux` Linux (aarch64) + :sync: linux-aarch64 + + .. code-block:: bash + + uv pip install -U torch==2.10.0 torchvision==0.25.0 --index-url https://download.pytorch.org/whl/cu130 Before we can install Isaac Sim, we need to make sure pip is updated. To update pip, run @@ -131,9 +151,10 @@ Installation is now as easy as navigating to the repo and then calling the root .. tab-item:: :icon:`fa-brands fa-windows` Windows :sync: windows - .. code:: bash + .. code:: batch - isaaclab.bat --install :: or "isaaclab.bat -i" + isaaclab.bat --install + :: or use "isaaclab.bat -i" Quick Start Using Isaac Launchable @@ -173,11 +194,11 @@ Use the ``presets=`` argument to select the physics backend at runtime: .. code-block:: bash - # Newton (Kit-less) with Newton visualizer + # MJWarp (Newton backend, Kit-less) with Newton visualizer ./isaaclab.sh -p scripts/reinforcement_learning/rsl_rl/train.py \ --task Isaac-Cartpole-Direct-v0 \ --num_envs 4096 \ - presets=newton \ + presets=newton_mjwarp \ --visualizer newton # PhysX (Kit) — requires Isaac Sim installed @@ -186,11 +207,11 @@ Use the ``presets=`` argument to select the physics backend at runtime: --num_envs 4096 \ presets=physx - # Newton with a specific visualizer + # MJWarp with a specific visualizer ./isaaclab.sh -p scripts/reinforcement_learning/rsl_rl/train.py \ --task Isaac-Cartpole-Direct-v0 \ --num_envs 4096 \ - presets=newton \ + presets=newton_mjwarp \ --visualizer viser Kit-less visualizer options are ``newton``, ``rerun``, and ``viser``. diff --git a/docs/source/setup/walkthrough/training_jetbot_reward_exploration.rst b/docs/source/setup/walkthrough/training_jetbot_reward_exploration.rst index efdce4689c99..351189183d40 100644 --- a/docs/source/setup/walkthrough/training_jetbot_reward_exploration.rst +++ b/docs/source/setup/walkthrough/training_jetbot_reward_exploration.rst @@ -43,7 +43,7 @@ we can finally run training! Let's see what happens! .. code-block:: bash - python scripts/skrl/train.py --task=Template-Isaac-Lab-Tutorial-Direct-v0 + python scripts/reinforcement_learning/skrl/train.py --task=Template-Isaac-Lab-Tutorial-Direct-v0 .. figure:: https://download.isaacsim.omniverse.nvidia.com/isaaclab/images/walkthrough_naive_webp.webp diff --git a/docs/source/testing/benchmarks.rst b/docs/source/testing/benchmarks.rst index 0225569f1759..0127f87a3976 100644 --- a/docs/source/testing/benchmarks.rst +++ b/docs/source/testing/benchmarks.rst @@ -154,6 +154,96 @@ Measure asset method and property performance using mock interfaces: For detailed documentation on micro-benchmarks, including available benchmark files, input modes, and how to add new benchmarks, see :ref:`testing_micro_benchmarks`. +Startup Profiling Benchmark +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Profile the startup sequence of an IsaacLab environment using ``cProfile``. Each +startup stage is wrapped in its own profiling session and the top functions by +own-time are reported. This is useful for investigating startup regressions and +understanding where time is spent during initialization. + +.. code-block:: bash + + # Basic usage — reports top 30 functions per phase + ./isaaclab.sh -p scripts/benchmarks/benchmark_startup.py \ + --task Isaac-Ant-v0 \ + --num_envs 4096 \ + --headless \ + --benchmark_backend summary + +The script profiles five phases independently: + +- **app_launch**: ``launch_simulation()`` context entry (Kit/USD/PhysX init) +- **python_imports**: importing gymnasium, torch, isaaclab_tasks, etc. +- **task_config**: ``resolve_task_config()`` (Hydra config resolution) +- **env_creation**: ``gym.make()`` + ``env.reset()`` (scene creation, sim start) +- **first_step**: a single ``env.step()`` call + +Each phase records a wall-clock time plus per-function own-time and cumulative +time as ``SingleMeasurement`` entries. Only IsaacLab functions and first-level +calls into external libraries are included (deep internals of torch, USD, etc. +are filtered out). + +**Whitelist mode** — For dashboard time-series comparisons across runs, use a +YAML whitelist config to report a fixed set of functions instead of top-N. +Patterns use ``fnmatch`` syntax (``*`` and ``?`` wildcards): + +.. code-block:: yaml + + # Example whitelist config + app_launch: + - "isaaclab.utils.configclass:_custom_post_init" + - "isaaclab.sim.*:__init__" + env_creation: + - "isaaclab.cloner.*:usd_replicate" + - "isaaclab.cloner.*:filter_collisions" + - "isaaclab.scene.*:_init_scene" + first_step: + - "isaaclab.actuators.*:compute" + - "warp.*:launch" + +.. code-block:: bash + + ./isaaclab.sh -p scripts/benchmarks/benchmark_startup.py \ + --task Isaac-Ant-v0 \ + --num_envs 4096 \ + --headless \ + --benchmark_backend omniperf \ + --whitelist_config scripts/benchmarks/startup_whitelist.yaml + +Phases listed in the YAML use the whitelist; phases not listed fall back to +``--top_n`` (default: 5 in whitelist mode, 30 otherwise). Patterns that match +no profiled function emit ``0.0`` placeholders so the output always contains +the same keys. + +A default whitelist is provided at ``scripts/benchmarks/startup_whitelist.yaml``. + +.. list-table:: + :header-rows: 1 + :widths: 25 15 60 + + * - Argument + - Default + - Description + * - ``--task`` + - required + - Environment task name + * - ``--num_envs`` + - from config + - Number of parallel environments + * - ``--top_n`` + - 30 (5 with whitelist) + - Max functions per non-whitelisted phase + * - ``--whitelist_config`` + - None + - Path to YAML whitelist file + * - ``--benchmark_backend`` + - ``omniperf`` + - Output backend (``json``, ``osmo``, ``omniperf``, ``summary``) + * - ``--output_path`` + - ``.`` + - Directory for output files + Command Line Arguments ---------------------- @@ -399,9 +489,12 @@ Output structure: Summary Backend ~~~~~~~~~~~~~~~ -Human-readable console report plus JSON file. Prints a formatted summary (runtime, -startup, train, frametime, and system info) to the terminal while also writing -the same data as JSON. Use when you want a quick readout without opening the JSON: +Human-readable console report plus JSON file. Prints a formatted summary to the +terminal while also writing the same data as JSON. Standard phases (runtime, +startup, train, frametime, system info) are rendered with specialized formatting; +any additional phases (e.g., from the startup profiling benchmark) are rendered +automatically with their ``SingleMeasurement`` and ``StatisticalMeasurement`` +entries. Use when you want a quick readout without opening the JSON: .. code-block:: bash diff --git a/docs/source/testing/index.rst b/docs/source/testing/index.rst index ae8494a3ec89..4d875d982797 100644 --- a/docs/source/testing/index.rst +++ b/docs/source/testing/index.rst @@ -1,7 +1,7 @@ .. _testing: Testing -======= +======== This section covers testing utilities and patterns for Isaac Lab development. diff --git a/docs/source/tutorials/00_sim/create_empty.rst b/docs/source/tutorials/00_sim/create_empty.rst index 1a9740ab93af..e65876a0f997 100644 --- a/docs/source/tutorials/00_sim/create_empty.rst +++ b/docs/source/tutorials/00_sim/create_empty.rst @@ -72,8 +72,8 @@ pausing and stepping the simulator. All these operations are handled through the context**. It takes care of various timeline events and also configures the physics scene for simulation. -In Isaac Lab, the :class:`sim.SimulationContext` class inherits from Isaac Sim's -:class:`isaacsim.core.api.simulation_context.SimulationContext` to allow configuring the simulation +In Isaac Lab, the :class:`sim.SimulationContext` class wraps Isaac Sim's simulation stack +to allow configuring the simulation through Python's ``dataclass`` object and handle certain intricacies of the simulation stepping. For this tutorial, we set the physics and rendering time step to 0.01 seconds. This is done @@ -139,7 +139,7 @@ Now that we have gone through the code, let's run the script and see the result: .. code-block:: bash - ./isaaclab.sh -p scripts/tutorials/00_sim/create_empty.py + ./isaaclab.sh -p scripts/tutorials/00_sim/create_empty.py --viz kit The simulation should be playing, and the stage should be rendering. To stop the simulation, @@ -156,7 +156,7 @@ following: .. code-block:: bash - ./isaaclab.sh -p scripts/tutorials/00_sim/create_empty.py --headless + ./isaaclab.sh -p scripts/tutorials/00_sim/create_empty.py --viz none Now that we have a basic understanding of how to run a simulation, let's move on to the diff --git a/docs/source/tutorials/00_sim/launch_app.rst b/docs/source/tutorials/00_sim/launch_app.rst index 62e77c49612c..8c2670e8f605 100644 --- a/docs/source/tutorials/00_sim/launch_app.rst +++ b/docs/source/tutorials/00_sim/launch_app.rst @@ -128,7 +128,7 @@ as we will demonstrate later in this tutorial. These arguments can be used with any script that starts the simulation using :class:`~app.AppLauncher`, with one exception, ``--enable_cameras``. This setting sets the rendering pipeline to use the offscreen renderer. However, this setting is only compatible with the :class:`isaaclab.sim.SimulationContext`. -It will not work with Isaac Sim's :class:`isaacsim.core.api.simulation_context.SimulationContext` class. +It will not work with Isaac Sim's legacy ``SimulationContext`` from deprecated Isaac Sim core extensions. For more information on this flag, please see the :class:`~app.AppLauncher` API documentation. diff --git a/docs/source/tutorials/00_sim/spawn_prims.rst b/docs/source/tutorials/00_sim/spawn_prims.rst index 299f15adbe56..1c4555687a28 100644 --- a/docs/source/tutorials/00_sim/spawn_prims.rst +++ b/docs/source/tutorials/00_sim/spawn_prims.rst @@ -188,5 +188,5 @@ demonstrates the basic concepts of scene designing in Isaac Lab and how to use t we will now look at how to interact with the scene and the simulation. -.. _`USD documentation`: https://openusd.org/docs/index.html +.. _`USD documentation`: https://openusd.org/release/index.html .. _`different light prims`: https://youtu.be/c7qyI8pZvF4?feature=shared diff --git a/docs/source/tutorials/01_assets/run_deformable_object.rst b/docs/source/tutorials/01_assets/run_deformable_object.rst index d8567c953244..61092353cec8 100644 --- a/docs/source/tutorials/01_assets/run_deformable_object.rst +++ b/docs/source/tutorials/01_assets/run_deformable_object.rst @@ -7,10 +7,11 @@ Interacting with a deformable object .. currentmodule:: isaaclab While deformable objects sometimes refer to a broader class of objects, such as cloths, fluids and soft bodies, -in PhysX, deformable objects syntactically correspond to soft bodies. Unlike rigid objects, soft bodies can deform -under external forces and collisions. +in PhysX, deformable objects are represented as either surface or volume deformables. Unlike rigid objects, soft bodies can deform +under external forces and collisions. In this tutorial, we will focus on volume deformable bodies. For an example of surface +deformables (cloth), see the deformable demo at ``scripts/demos/deformables.py``. -Soft bodies are simulated using Finite Element Method (FEM) in PhysX. The soft body comprises of two tetrahedral +Soft bodies are simulated using Finite Element Method (FEM) in PhysX. The volume deformable comprises of two tetrahedral meshes -- a simulation mesh and a collision mesh. The simulation mesh is used to simulate the deformations of the soft body, while the collision mesh is used to detect collisions with other objects in the scene. For more details, please check the `PhysX documentation`_. @@ -30,7 +31,7 @@ The tutorial corresponds to the ``run_deformable_object.py`` script in the ``scr .. literalinclude:: ../../../../scripts/tutorials/01_assets/run_deformable_object.py :language: python - :emphasize-lines: 61-73, 75-77, 102-110, 112-115, 117-118, 123-130, 132-133, 139-140 + :emphasize-lines: 68-82, 110-126, 131-139, 141-149 :linenos: @@ -62,7 +63,7 @@ an instance of the :class:`assets.DeformableObject` class by passing the configu .. literalinclude:: ../../../../scripts/tutorials/01_assets/run_deformable_object.py :language: python - :start-at: # Create separate groups called "Origin1", "Origin2", "Origin3" + :start-at: # Create separate groups called "Origin0", "Origin1", ... :end-at: cube_object = DeformableObject(cfg=cfg) Running the simulation loop @@ -149,7 +150,7 @@ the average position of all the nodes in the mesh. .. literalinclude:: ../../../../scripts/tutorials/01_assets/run_deformable_object.py :language: python :start-at: # update buffers - :end-at: print(f"Root position (in world): {wp.to_torch(cube_object.data.root_pos_w)[:, :3]}") + :end-at: cube_object.data.root_pos_w The Code Execution @@ -159,10 +160,10 @@ Now that we have gone through the code, let's run the script and see the result: .. code-block:: bash - ./isaaclab.sh -p scripts/tutorials/01_assets/run_deformable_object.py + ./isaaclab.sh -p scripts/tutorials/01_assets/run_deformable_object.py --visualizer kit -This should open a stage with a ground plane, lights, and several green cubes. Two of the four cubes must be dropping +This should open a stage with a ground plane, lights, and several cubes. Two of the four cubes must be dropping from a height and settling on to the ground. Meanwhile the other two cubes must be moving along the z-axis. You should see a marker showing the kinematic target position for the nodes at the bottom-left corner of the cubes. To stop the simulation, you can either close the window, or press ``Ctrl+C`` in the terminal @@ -174,7 +175,7 @@ To stop the simulation, you can either close the window, or press ``Ctrl+C`` in This tutorial showed how to spawn deformable objects and wrap them in a :class:`DeformableObject` class to initialize their physics handles which allows setting and obtaining their state. We also saw how to apply kinematic commands to the -deformable object to move the mesh nodes in a controlled manner. In the next tutorial, we will see how to create +deformable object to move the mesh nodes in a controlled manner. An advanced demo of deformable objects, including surface deformables and loading USD assets and applying deformable material on them, can be found in ``scripts/demos/deformables.py``. In the next tutorial, we will see how to create a scene using the :class:`InteractiveScene` class. .. _PhysX documentation: https://nvidia-omniverse.github.io/PhysX/physx/5.4.1/docs/SoftBodies.html diff --git a/docs/source/tutorials/04_sensors/add_sensors_on_robot.rst b/docs/source/tutorials/04_sensors/add_sensors_on_robot.rst index 3d9f40667b62..85383a876ed4 100644 --- a/docs/source/tutorials/04_sensors/add_sensors_on_robot.rst +++ b/docs/source/tutorials/04_sensors/add_sensors_on_robot.rst @@ -93,11 +93,11 @@ Height scanner The height-scanner is implemented as a virtual sensor using the NVIDIA Warp ray-casting kernels. Through the :class:`sensors.RayCasterCfg`, we can specify the pattern of rays to cast and the -meshes against which to cast the rays. Since they are virtual sensors, there is no corresponding -prim created in the scene for them. Instead they are attached to a prim in the scene, which is -used to specify the location of the sensor. +meshes against which to cast the rays. By default, :attr:`~sensors.RayCasterCfg.spawn` creates +a plain USD Xform at :attr:`~sensors.RayCasterCfg.prim_path` to serve as the sensor's +attachment frame, similar to how :class:`sensors.CameraCfg` spawns a Camera prim. -For this tutorial, the ray-cast based height scanner is attached to the base frame of the robot. +For this tutorial, the ray-cast based height scanner is attached under the base frame of the robot. The pattern of rays is specified using the :attr:`~sensors.RayCasterCfg.pattern` attribute. For a uniform grid pattern, we specify the pattern using :class:`~sensors.patterns.GridPatternCfg`. Since we only care about the height information, we do not need to consider the roll and pitch diff --git a/docs/source/tutorials/06_exporting/exporting_direct_workflow_policies_with_leapp.rst b/docs/source/tutorials/06_exporting/exporting_direct_workflow_policies_with_leapp.rst new file mode 100644 index 000000000000..1ce0aa3a82e6 --- /dev/null +++ b/docs/source/tutorials/06_exporting/exporting_direct_workflow_policies_with_leapp.rst @@ -0,0 +1,183 @@ +Exporting Direct Workflow Policies with LEAPP +============================================= + +.. currentmodule:: isaaclab + +This tutorial shows how to prepare a Direct workflow policy for export with +LEAPP. If your policy is manager-based, use the +:doc:`manager-based LEAPP export guide ` +instead. + + +Overview +~~~~~~~~ + +To export a Direct workflow policy with LEAPP, you add LEAPP annotations to the +environment code. During export, LEAPP traces the annotated tensors and builds an +intermediate representation of the full policy pipeline. These annotations remain +dormant during normal environment execution and only add a small amount of +overhead until export time. They are activated by +``scripts/reinforcement_learning/leapp/rsl_rl/export.py`` when you run the export flow. + +This tutorial uses ``scripts/tutorials/06_deploy/anymal_c_env.py`` as the example. +The script is based on the existing ANYmal-C direct environment at +``source/isaaclab_tasks/isaaclab_tasks/direct/anymal_c/anymal_c_env.py`` and adds +the annotations needed to make it compatible with the export script. Once you have added +the annotations to your direct RL environment, you can export a trained policy +with: + +.. code-block:: bash + + ./isaaclab.sh -p scripts/reinforcement_learning/leapp/rsl_rl/export.py \ + --task \ + --checkpoint \ + --export_save_path + +The ``--task`` argument is the registered task name, such as +``Isaac-Velocity-Rough-Anymal-C-Direct-v0``. The ``--checkpoint`` argument +points to the trained RSL-RL checkpoint to export. The optional +``--export_save_path`` argument selects the output directory for the exported +artifacts. If you omit it, the export is written next to the checkpoint. + +.. warning:: + + This tutorial covers exporting Direct workflow policies only. Direct workflow + policies are not currently supported by + ``scripts/reinforcement_learning/leapp/deploy.py``. + +For more information on the export arguments, see the +:doc:`manager-based LEAPP export guide `. + + +.. dropdown:: Full example script + :icon: code + + .. literalinclude:: ../../../../scripts/tutorials/06_deploy/anymal_c_env.py + :language: python + :emphasize-lines: 20, 100-118, 85-88 + :linenos: + + +How the Annotations Work +~~~~~~~~~~~~~~~~~~~~~~~~ + +The main task is to identify the inputs, outputs, and persistent state in the +environment and register them with LEAPP. In this example, the script uses four +annotation helpers: + +- :func:`annotate.input_tensors` marks tensors that enter the policy pipeline. +- :func:`annotate.output_tensors` marks tensors that leave the environment-side + part of the pipeline. +- :func:`annotate.state_tensors` marks tensors that behave like persistent state. +- :func:`annotate.update_state` updates that persistent state after each step. + + +Input Annotations +~~~~~~~~~~~~~~~~~ + +Input annotations usually belong in ``_get_observations()``, because that method +collects the tensors that are passed to the policy. + + +.. literalinclude:: ../../../../scripts/tutorials/06_deploy/anymal_c_env.py + :language: python + :start-at: # start LEAPP annotations for inputs + :end-at: # end LEAPP annotations for inputs + :dedent: 8 + +``annotate.input_tensors()`` wraps a tensor so LEAPP can trace all downstream +operations that depend on it. The function takes two important arguments: + +- ``self.spec.id`` identifies the node that owns the tensor. When you use + ``export.py``, this ID matches the exported policy node. +- The second argument is a dictionary that maps a unique tensor name to the + tensor itself. LEAPP uses these names in the exported metadata and for + debugging. + +In this example, the observation tensors are registered one by one for +readability, but ``annotate.input_tensors()`` can also register multiple tensors +in a single call. + +.. note:: + Any inputs not explicitly annotated will be automatically inlined as a constant. + This may be desired for certain values such as constant transforms or default values. + + +Output Annotations +~~~~~~~~~~~~~~~~~~ + +Output annotations should be placed where the environment has finished preparing +the command that will be applied to the robot. In this example, that happens in +``_pre_physics_step()``. + +.. literalinclude:: ../../../../scripts/tutorials/06_deploy/anymal_c_env.py + :language: python + :start-at: # start LEAPP annotations for outputs + :end-at: # end LEAPP annotations for outputs + :dedent: 8 + +``annotate.output_tensors()`` marks the tensors that leave the environment-side +part of the pipeline. As with input annotations, the call uses ``self.spec.id`` +together with a dictionary that maps tensor names to tensors. + +The ``export_with`` argument restricts an output annotation to specific +export backends. The supported backend names are ``onnx-dynamo``, ``onnx-torchscript``, +``jit-script``, and ``jit-trace``. This argument is needed to actually generate the IR +based on the tracing. + +Unlike ``annotate.input_tensors()``, output annotation should happen once for the +final outputs of the pipeline stage. In this example, ``processed_actions`` is +the tensor that should be exported. After calling +``annotate.output_tensors()``, you do not need to use a return value. + +.. note:: + All tensors passed to ``annotate.output_tensors()`` must be traced tensors. + These tensors are created from inputs or tensors derived from inputs. + +.. warning:: + + Do not place output annotations in ``_apply_action()``. That method may be + called multiple times per environment step, depending on the decimation + setting, which would make the traced pipeline incorrect. + + +State Annotations +~~~~~~~~~~~~~~~~~ + +If your policy depends on internal state or feedback loops, register that data +explicitly with ``annotate.state_tensors()`` and update it with +``annotate.update_state()``. + +In this example, the environment uses the previous action as part of the +observation. That makes ``previous_actions`` a feedback state: + +- ``annotate.state_tensors()`` is called in ``_get_observations()`` so the state + can participate in the traced observation pipeline. +- ``annotate.update_state()`` is called in ``_pre_physics_step()`` so the stored + value is updated for the next step. + +The state name must match across both calls. Here, both functions use the name +``previous_actions``, which lets LEAPP route the feedback tensor correctly. + + +Semantic Annotations +~~~~~~~~~~~~~~~~~~~~ + +This example covers the minimum annotations needed to trace the pipeline. In +more advanced export workflows, you may also want to attach semantic metadata +so downstream runtimes know what each tensor represents. + +For direct environments, semantic annotations are optional and should be +authored explicitly by the user. Unlike the manager-based export path, Isaac Lab +does not infer tensor semantics automatically for direct environments, instead it +is up to the user to provide this data. LEAPP provides this through +``TensorSemantics``. You can use it to describe the meaning of tensors more +precisely and make the exported pipeline easier to inspect, validate, and integrate +into deployment systems. + +.. note:: + + Refer to the `LEAPP semantic annotation guide + `_ + and `LEAPP API reference `_ + for details on authoring semantic annotations. diff --git a/docs/source/tutorials/index.rst b/docs/source/tutorials/index.rst index f1096e6c05b0..41b606e1bf76 100644 --- a/docs/source/tutorials/index.rst +++ b/docs/source/tutorials/index.rst @@ -108,3 +108,14 @@ tutorials show you how to use motion generators to control the robots at the tas 05_controllers/run_diff_ik 05_controllers/run_osc + +Exporting Policies +------------------ + +The following tutorial shows how to prepare a Direct workflow policy for export with LEAPP. + +.. toctree:: + :maxdepth: 1 + :titlesonly: + + 06_exporting/exporting_direct_workflow_policies_with_leapp diff --git a/isaaclab.bat b/isaaclab.bat index 077e9a4b1abd..1d8fb8275467 100644 --- a/isaaclab.bat +++ b/isaaclab.bat @@ -26,6 +26,13 @@ if defined VIRTUAL_ENV ( rem Add source/isaaclab to PYTHONPATH so we can import isaaclab.cli. set "PYTHONPATH=%ISAACLAB_PATH%\source\isaaclab;%PYTHONPATH%" +rem If a local Isaac Sim binary is present, source its env setup so that +rem PYTHONPATH/PATH/EXP_PATH are correct without depending on a conda +rem activate.d hook (those don't fire under e.g. `conda run` on Windows). +if exist "%ISAACLAB_PATH%\_isaac_sim\setup_conda_env.bat" ( + call "%ISAACLAB_PATH%\_isaac_sim\setup_conda_env.bat" >NUL +) + rem Execute CLI. "%python_exe%" -c "from isaaclab.cli import cli; cli()" %* diff --git a/isaaclab.sh b/isaaclab.sh index 8d535a10b307..d4042353e88f 100755 --- a/isaaclab.sh +++ b/isaaclab.sh @@ -28,5 +28,13 @@ fi # Add source/isaaclab to PYTHONPATH so we can import isaaclab.cli. export PYTHONPATH="$ISAACLAB_PATH/source/isaaclab:$PYTHONPATH" +# If a local Isaac Sim binary is present, source its env setup so that +# PYTHONPATH/PATH/EXP_PATH are correct without depending on a conda +# activate.d hook (those don't fire reliably under e.g. `conda run`). +if [ -f "$ISAACLAB_PATH/_isaac_sim/setup_conda_env.sh" ]; then + # shellcheck disable=SC1091 + . "$ISAACLAB_PATH/_isaac_sim/setup_conda_env.sh" >/dev/null 2>&1 || true +fi + # Execute CLI. exec "$python_exe" -c "from isaaclab.cli import cli; cli()" "$@" diff --git a/pyproject.toml b/pyproject.toml index b34726f1eaed..513ce684d93f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -154,6 +154,7 @@ explicit = false [tool.uv] index-strategy = "unsafe-best-match" prerelease = "allow" +override-dependencies = ["numpy>=2"] [tool.uv.pip] index-strategy = "unsafe-best-match" diff --git a/scripts/benchmarks/benchmark_cameras.py b/scripts/benchmarks/benchmark_cameras.py index 47bea5469b2b..835fb980be0d 100644 --- a/scripts/benchmarks/benchmark_cameras.py +++ b/scripts/benchmarks/benchmark_cameras.py @@ -265,8 +265,6 @@ CameraCfg, RayCasterCamera, RayCasterCameraCfg, - TiledCamera, - TiledCameraCfg, patterns, ) from isaaclab.test.benchmark import BaseIsaacLabBenchmark, DictMeasurement, SingleMeasurement @@ -280,14 +278,14 @@ def create_camera_base( - camera_cfg: type[CameraCfg | TiledCameraCfg], + camera_cfg: type[CameraCfg], num_cams: int, data_types: list[str], height: int, width: int, prim_path: str | None = None, instantiate: bool = True, -) -> Camera | TiledCamera | CameraCfg | TiledCameraCfg | None: +) -> Camera | CameraCfg | None: """Generalized function to create a camera or tiled camera sensor.""" # Determine prim prefix based on the camera class name = camera_cfg.class_type.__name__ @@ -320,12 +318,12 @@ def create_camera_base( def create_tiled_cameras( num_cams: int = 2, data_types: list[str] | None = None, height: int = 100, width: int = 120 -) -> TiledCamera | None: +) -> Camera | None: if data_types is None: data_types = ["rgb", "depth"] - """Defines the tiled camera sensor to add to the scene.""" + """Defines the camera sensor to add to the scene.""" return create_camera_base( - camera_cfg=TiledCameraCfg, + camera_cfg=CameraCfg, num_cams=num_cams, data_types=data_types, height=height, @@ -381,10 +379,10 @@ def create_ray_caster_cameras( return None -def create_tiled_camera_cfg(prim_path: str) -> TiledCameraCfg: - """Grab a simple tiled camera config for injecting into task environments.""" +def create_tiled_camera_cfg(prim_path: str) -> CameraCfg: + """Grab a simple camera config for injecting into task environments.""" return create_camera_base( - TiledCameraCfg, + CameraCfg, num_cams=args_cli.num_tiled_cameras, data_types=args_cli.tiled_camera_data_types, width=args_cli.width, diff --git a/scripts/benchmarks/benchmark_load_robot.py b/scripts/benchmarks/benchmark_load_robot.py index 1e8dc1f737e9..490a8bd0a064 100644 --- a/scripts/benchmarks/benchmark_load_robot.py +++ b/scripts/benchmarks/benchmark_load_robot.py @@ -57,7 +57,6 @@ imports_time_begin = time.perf_counter_ns() import torch -import warp as wp import isaaclab.sim as sim_utils from isaaclab.assets import ArticulationCfg, AssetBaseCfg @@ -136,15 +135,15 @@ def run_simulator(sim: sim_utils.SimulationContext, scene: InteractiveScene): # root state # we offset the root state by the origin since the states are written in simulation world frame # if this is not done, then the robots will be spawned at the (0, 0, 0) of the simulation world - root_pose = wp.to_torch(robot.data.default_root_pose).clone() + root_pose = robot.data.default_root_pose.torch.clone() root_pose[:, :3] += scene.env_origins robot.write_root_pose_to_sim_index(root_pose=root_pose) - root_vel = wp.to_torch(robot.data.default_root_vel).clone() + root_vel = robot.data.default_root_vel.torch.clone() robot.write_root_velocity_to_sim_index(root_velocity=root_vel) # set joint positions with some noise joint_pos, joint_vel = ( - wp.to_torch(robot.data.default_joint_pos).clone(), - wp.to_torch(robot.data.default_joint_vel).clone(), + robot.data.default_joint_pos.torch.clone(), + robot.data.default_joint_vel.torch.clone(), ) joint_pos += torch.rand_like(joint_pos) * 0.1 robot.write_joint_position_to_sim_index(position=joint_pos) @@ -153,7 +152,7 @@ def run_simulator(sim: sim_utils.SimulationContext, scene: InteractiveScene): scene.reset() # Apply random action # -- generate random joint efforts - efforts = torch.randn_like(wp.to_torch(robot.data.joint_pos)) * 5.0 + efforts = torch.randn_like(robot.data.joint_pos.torch) * 5.0 # -- apply action to the robot robot.set_joint_effort_target_index(target=efforts) # -- write data to sim diff --git a/scripts/benchmarks/benchmark_non_rl.py b/scripts/benchmarks/benchmark_non_rl.py index aee3be21a40e..4a4ffc700974 100644 --- a/scripts/benchmarks/benchmark_non_rl.py +++ b/scripts/benchmarks/benchmark_non_rl.py @@ -120,7 +120,12 @@ def main( # override configurations with non-hydra CLI arguments env_cfg.scene.num_envs = args_cli.num_envs if args_cli.num_envs is not None else env_cfg.scene.num_envs - env_cfg.sim.device = args_cli.device if args_cli.device is not None else env_cfg.sim.device + # For distributed training, launch_simulation() already resolved the + # correct per-rank device; only apply a CLI --device override for + # non-distributed runs (the default "cuda:0" would clobber the + # per-rank device otherwise). + if not args_cli.distributed: + env_cfg.sim.device = args_cli.device if args_cli.device is not None else env_cfg.sim.device env_cfg.seed = args_cli.seed # check for invalid combination of CPU device with distributed training @@ -131,10 +136,10 @@ def main( ) # process distributed + # env_cfg.sim.device is already resolved by launch_simulation(). world_size = 1 world_rank = 0 if args_cli.distributed: - env_cfg.sim.device = f"cuda:{int(os.getenv('LOCAL_RANK', '0'))}" world_size = int(os.getenv("WORLD_SIZE", 1)) world_rank = int(os.getenv("RANK", "0")) diff --git a/scripts/benchmarks/benchmark_rlgames.py b/scripts/benchmarks/benchmark_rlgames.py index f6c000a8fce9..ab1d625d5aaf 100644 --- a/scripts/benchmarks/benchmark_rlgames.py +++ b/scripts/benchmarks/benchmark_rlgames.py @@ -14,6 +14,13 @@ from isaaclab.app import AppLauncher +from scripts.benchmarks.early_stop import ( + RlGamesEarlyStopObserver, + add_success_cli_args, + build_success_kwargs, + get_success_tracker, +) + # add argparse arguments parser = argparse.ArgumentParser(description="Train an RL agent with RL-Games.") parser.add_argument("--video", action="store_true", default=False, help="Record videos during training.") @@ -52,6 +59,7 @@ parser.add_argument( "--convergence_config", type=str, default="full", help="Config mode for convergence thresholds (default: full)." ) +add_success_cli_args(parser) # append AppLauncher cli args AppLauncher.add_app_launcher_args(parser) @@ -95,14 +103,17 @@ from scripts.benchmarks.utils import ( get_backend_type, get_preset_string, + get_success_rate_log, log_app_start_time, log_convergence, log_python_imports_time, log_rl_policy_episode_lengths, log_rl_policy_rewards, + log_rl_policy_success_rates, log_runtime_step_times, log_scene_creation_time, log_simulation_start_time, + log_success, log_task_start_time, log_total_start_time, parse_tf_logs, @@ -145,7 +156,12 @@ def main( # override configurations with non-hydra CLI arguments env_cfg.scene.num_envs = args_cli.num_envs if args_cli.num_envs is not None else env_cfg.scene.num_envs - env_cfg.sim.device = args_cli.device if args_cli.device is not None else env_cfg.sim.device + # For distributed training, launch_simulation() already resolved the + # correct per-rank device; only apply a CLI --device override for + # non-distributed runs (the default "cuda:0" would clobber the + # per-rank device otherwise). + if not args_cli.distributed: + env_cfg.sim.device = args_cli.device if args_cli.device is not None else env_cfg.sim.device # check for invalid combination of CPU device with distributed training if args_cli.distributed and args_cli.device is not None and "cpu" in args_cli.device: raise ValueError( @@ -153,8 +169,9 @@ def main( "Please use GPU device (e.g., --device cuda) for distributed training." ) - # update agent device to match simulation device - if args_cli.device is not None: + # update agent device to match simulation device (skip for distributed — + # the per-rank device is resolved by launch_simulation) + if args_cli.device is not None and not args_cli.distributed: agent_cfg["params"]["config"]["device"] = args_cli.device agent_cfg["params"]["config"]["device_name"] = args_cli.device @@ -164,10 +181,10 @@ def main( agent_cfg["params"]["seed"] = args_cli.seed if args_cli.seed is not None else agent_cfg["params"]["seed"] # process distributed + # env_cfg.sim.device is already resolved by launch_simulation(). world_rank = 0 if args_cli.distributed: - env_cfg.sim.device = f"cuda:{int(os.getenv('LOCAL_RANK', '0'))}" - agent_cfg["params"]["config"]["device"] = f"cuda:{int(os.getenv('LOCAL_RANK', '0'))}" + agent_cfg["params"]["config"]["device"] = env_cfg.sim.device world_rank = int(os.getenv("RANK", "0")) # specify directory for logging experiments @@ -184,11 +201,9 @@ def main( # multi-gpu training config if args_cli.distributed: agent_cfg["params"]["seed"] += int(os.getenv("RANK", "0")) - agent_cfg["params"]["config"]["device"] = f"cuda:{int(os.getenv('LOCAL_RANK', '0'))}" - agent_cfg["params"]["config"]["device_name"] = f"cuda:{int(os.getenv('LOCAL_RANK', '0'))}" + agent_cfg["params"]["config"]["device"] = env_cfg.sim.device + agent_cfg["params"]["config"]["device_name"] = env_cfg.sim.device agent_cfg["params"]["config"]["multi_gpu"] = True - # update env config device - env_cfg.sim.device = f"cuda:{int(os.getenv('LOCAL_RANK', '0'))}" # max iterations if args_cli.max_iterations: @@ -233,8 +248,9 @@ def main( # set number of actors into agent config agent_cfg["params"]["config"]["num_actors"] = env.unwrapped.num_envs - # create runner from rl-games - runner = Runner(IsaacAlgoObserver()) + # always track the success metric; early-stop only if --check_success + observer = RlGamesEarlyStopObserver(IsaacAlgoObserver(), **build_success_kwargs(args_cli)) + runner = Runner(observer) runner.load(agent_cfg) # set seed of the env @@ -274,6 +290,9 @@ def main( log_runtime_step_times(benchmark, rl_training_times, compute_stats=True) log_rl_policy_rewards(benchmark, log_data["rewards/iter"]) log_rl_policy_episode_lengths(benchmark, log_data["episode_lengths/iter"]) + success_rates = get_success_rate_log(log_data) + if success_rates is not None: + log_rl_policy_success_rates(benchmark, success_rates) log_convergence( benchmark, log_data["rewards/iter"], @@ -284,6 +303,9 @@ def main( convergence_config=args_cli.convergence_config, ) + tracker = get_success_tracker(args_cli, observer.tracker, log_data) + log_success(benchmark, tracker, framework_iteration_count=observer.framework_iteration_count) + benchmark._finalize_impl() # close the simulator diff --git a/scripts/benchmarks/benchmark_rsl_rl.py b/scripts/benchmarks/benchmark_rsl_rl.py index 596b267e248a..0eef6063fba7 100644 --- a/scripts/benchmarks/benchmark_rsl_rl.py +++ b/scripts/benchmarks/benchmark_rsl_rl.py @@ -14,6 +14,13 @@ from isaaclab.app import AppLauncher +from scripts.benchmarks.early_stop import ( + RslRlEarlyStopWrapper, + add_success_cli_args, + build_success_kwargs, + get_success_tracker, +) + sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "../..")) import scripts.reinforcement_learning.rsl_rl.cli_args as cli_args # isort: skip @@ -55,6 +62,7 @@ parser.add_argument( "--convergence_config", type=str, default="full", help="Config mode for convergence thresholds (default: full)." ) +add_success_cli_args(parser) # append RSL-RL cli arguments cli_args.add_rsl_rl_args(parser) @@ -97,14 +105,17 @@ from scripts.benchmarks.utils import ( get_backend_type, get_preset_string, + get_success_rate_log, log_app_start_time, log_convergence, log_python_imports_time, log_rl_policy_episode_lengths, log_rl_policy_rewards, + log_rl_policy_success_rates, log_runtime_step_times, log_scene_creation_time, log_simulation_start_time, + log_success, log_task_start_time, log_total_start_time, parse_tf_logs, @@ -154,7 +165,12 @@ def main( # set the environment seed # note: certain randomizations occur in the environment initialization so we set the seed here env_cfg.seed = agent_cfg.seed - env_cfg.sim.device = args_cli.device if args_cli.device is not None else env_cfg.sim.device + # For distributed training, launch_simulation() already resolved the + # correct per-rank device; only apply a CLI --device override for + # non-distributed runs (the default "cuda:0" would clobber the + # per-rank device otherwise). + if not args_cli.distributed: + env_cfg.sim.device = args_cli.device if args_cli.device is not None else env_cfg.sim.device # check for invalid combination of CPU device with distributed training if args_cli.distributed and args_cli.device is not None and "cpu" in args_cli.device: raise ValueError( @@ -163,11 +179,11 @@ def main( ) # multi-gpu training configuration + # env_cfg.sim.device is already resolved by launch_simulation(). world_rank = 0 world_size = 1 if args_cli.distributed: - env_cfg.sim.device = f"cuda:{int(os.getenv('LOCAL_RANK', '0'))}" - agent_cfg.device = f"cuda:{int(os.getenv('LOCAL_RANK', '0'))}" + agent_cfg.device = env_cfg.sim.device # use global rank for seed diversity across all nodes world_rank = int(os.getenv("RANK", "0")) @@ -232,8 +248,13 @@ def main( dump_yaml(os.path.join(log_dir, "params", "env.yaml"), env_cfg) dump_yaml(os.path.join(log_dir, "params", "agent.yaml"), agent_cfg) + # always track the success metric; early-stop only if --check_success + early_stop_ctx = RslRlEarlyStopWrapper( + env, runner, num_steps_per_env=agent_cfg.num_steps_per_env, **build_success_kwargs(args_cli) + ) + # run training with continuous benchmark monitoring - with BenchmarkMonitor(benchmark, interval=1.0): + with early_stop_ctx, BenchmarkMonitor(benchmark, interval=1.0): runner.learn(num_learning_iterations=agent_cfg.max_iterations, init_at_random_ep_len=True) if world_rank == 0: @@ -268,6 +289,9 @@ def main( log_runtime_step_times(benchmark, rl_training_times, compute_stats=True) log_rl_policy_rewards(benchmark, log_data["Train/mean_reward"]) log_rl_policy_episode_lengths(benchmark, log_data["Train/mean_episode_length"]) + success_rates = get_success_rate_log(log_data) + if success_rates is not None: + log_rl_policy_success_rates(benchmark, success_rates) log_convergence( benchmark, @@ -279,6 +303,9 @@ def main( convergence_config=args_cli.convergence_config, ) + tracker = get_success_tracker(args_cli, early_stop_ctx.tracker, log_data) + log_success(benchmark, tracker, framework_iteration_count=early_stop_ctx.framework_iteration_count) + benchmark._finalize_impl() # close the simulator diff --git a/scripts/benchmarks/benchmark_startup.py b/scripts/benchmarks/benchmark_startup.py new file mode 100644 index 000000000000..e47f6e8c066d --- /dev/null +++ b/scripts/benchmarks/benchmark_startup.py @@ -0,0 +1,352 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Script to profile IsaacLab startup phases with cProfile. + +Each startup stage (app launch, python imports, env creation, first step) is +wrapped in its own cProfile session. The top functions by own-time are emitted +as SingleMeasurement entries (both own-time and cumulative time) via the +standard benchmark backend. +""" + +import argparse +import cProfile +import os +import sys +import time + +from isaaclab.app import AppLauncher + +# -- CLI arguments ----------------------------------------------------------- + +parser = argparse.ArgumentParser(description="Profile IsaacLab startup phases.") +parser.add_argument("--num_envs", type=int, default=None, help="Number of environments to simulate.") +parser.add_argument("--task", type=str, required=True, help="Name of the task.") +parser.add_argument("--seed", type=int, default=None, help="Seed used for the environment") +parser.add_argument( + "--top_n", + type=int, + default=None, + help="Number of top functions per phase (default: 30, or 5 with --whitelist_config).", +) +parser.add_argument( + "--benchmark_backend", + type=str, + default="omniperf", + choices=[ + "json", + "osmo", + "omniperf", + "summary", + "LocalLogMetrics", + "JSONFileMetrics", + "OsmoKPIFile", + "OmniPerfKPIFile", + ], + help="Benchmarking backend options, defaults omniperf", +) +parser.add_argument("--output_path", type=str, default=".", help="Path to output benchmark results.") +parser.add_argument( + "--whitelist_config", + type=str, + default=None, + help="Path to YAML file with per-phase function whitelist patterns. Overrides --top_n for listed phases.", +) + +# append AppLauncher cli args (provides --device, --headless, etc.) +AppLauncher.add_app_launcher_args(parser) +# parse the arguments +args_cli, hydra_args = parser.parse_known_args() + +# clear out sys.argv for Hydra +sys.argv = [sys.argv[0]] + hydra_args + +sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "../..")) + +from isaaclab.test.benchmark import BaseIsaacLabBenchmark, SingleMeasurement +from isaaclab.utils.timer import Timer, TimerError + +from scripts.benchmarks.utils import ( + get_backend_type, + get_preset_string, + parse_cprofile_stats, +) + +# -- Python imports (profiled) ------------------------------------------------ + +imports_profile = cProfile.Profile() +imports_time_begin = time.perf_counter_ns() +imports_profile.enable() + +import gymnasium as gym # noqa: E402 +import numpy as np # noqa: E402 +import torch # noqa: E402 + +from isaaclab.envs import DirectMARLEnvCfg, DirectRLEnvCfg, ManagerBasedRLEnvCfg # noqa: E402 + +from isaaclab_tasks.utils import launch_simulation, resolve_task_config # noqa: E402 + +imports_profile.disable() + +if torch.cuda.is_available() and torch.cuda.is_initialized(): + torch.cuda.synchronize() +imports_time_end = time.perf_counter_ns() + +# -- Resolve task config (profiled) ------------------------------------------ + +task_config_profile = cProfile.Profile() +task_config_time_begin = time.perf_counter_ns() +task_config_profile.enable() + +env_cfg, _agent_cfg = resolve_task_config(args_cli.task, None) + +task_config_profile.disable() +task_config_time_end = time.perf_counter_ns() + +# -- Detect IsaacLab source prefixes for filtering --------------------------- + +_REPO_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "../..")) +_source_dir = os.path.join(_REPO_ROOT, "source") +if os.path.isdir(_source_dir): + _ISAACLAB_PREFIXES = [ + os.path.join(_source_dir, d) for d in os.listdir(_source_dir) if os.path.isdir(os.path.join(_source_dir, d)) + ] +else: + print(f"[WARNING] IsaacLab source directory not found at '{_source_dir}'. Function-level profiling will be empty.") + _ISAACLAB_PREFIXES = [] + +# -- Load whitelist config if provided --------------------------------------- + +_WHITELIST: dict[str, list[str]] = {} +if args_cli.whitelist_config is not None: + import yaml + + try: + with open(args_cli.whitelist_config) as f: + raw = yaml.safe_load(f) + except OSError as e: + print(f"[ERROR] Cannot read whitelist config '{args_cli.whitelist_config}': {e}") + sys.exit(1) + except yaml.YAMLError as e: + print(f"[ERROR] Invalid YAML in whitelist config '{args_cli.whitelist_config}': {e}") + sys.exit(1) + + if raw is None: + _WHITELIST = {} + elif not isinstance(raw, dict): + print( + f"[ERROR] Whitelist config must be a YAML mapping (got {type(raw).__name__})." + " Expected format: phase_name: [pattern, ...]" + ) + sys.exit(1) + else: + _VALID_PHASES = {"app_launch", "python_imports", "task_config", "env_creation", "first_step"} + unknown_phases = set(raw.keys()) - _VALID_PHASES + if unknown_phases: + print( + f"[WARNING] Whitelist config contains unknown phase(s): {unknown_phases}. " + f"Valid phases: {_VALID_PHASES}. Check for typos." + ) + for phase_name, patterns in raw.items(): + if not isinstance(patterns, list) or not all(isinstance(p, str) for p in patterns): + print( + f"[ERROR] Whitelist phase '{phase_name}' must be a list of strings, " + f"got {type(patterns).__name__}. Check YAML formatting (use '- pattern' syntax)." + ) + sys.exit(1) + _WHITELIST = raw + +# Resolve top_n default: 5 when using whitelist (fallback phases stay compact), 30 otherwise +if args_cli.top_n is None: + args_cli.top_n = 5 if _WHITELIST else 30 + +# -- Create the benchmark instance ------------------------------------------ + +env_cfg.seed = args_cli.seed if args_cli.seed is not None else env_cfg.seed + +backend_type = get_backend_type(args_cli.benchmark_backend) +benchmark = BaseIsaacLabBenchmark( + benchmark_name="benchmark_startup", + backend_type=backend_type, + output_path=args_cli.output_path, + use_recorders=True, + output_prefix=f"benchmark_startup_{args_cli.task}", + workflow_metadata={ + "metadata": [ + {"name": "task", "data": args_cli.task}, + {"name": "seed", "data": args_cli.seed}, + {"name": "num_envs", "data": args_cli.num_envs}, + {"name": "top_n", "data": args_cli.top_n}, + {"name": "presets", "data": get_preset_string(hydra_args)}, + ] + }, +) + + +# -- Main profiling logic --------------------------------------------------- + + +def main( + env_cfg: ManagerBasedRLEnvCfg | DirectRLEnvCfg | DirectMARLEnvCfg, + app_launch_profile: cProfile.Profile, + app_launch_wall_ms: float, +): + """Profile env creation and first step, then log all phase measurements. + + Args: + env_cfg: Resolved environment configuration for the task. + app_launch_profile: cProfile session from the app-launch phase. + app_launch_wall_ms: Wall-clock duration of the app-launch phase [ms]. + """ + + # Override config with CLI args + env_cfg.scene.num_envs = args_cli.num_envs if args_cli.num_envs is not None else env_cfg.scene.num_envs + env_cfg.sim.device = args_cli.device if args_cli.device is not None else env_cfg.sim.device + env_cfg.seed = args_cli.seed if args_cli.seed is not None else env_cfg.seed + + # -- Env creation (gym.make + env.reset) profiled --------------------------- + + env = None + env_creation_profile = cProfile.Profile() + env_creation_time_begin = time.perf_counter_ns() + env_creation_profile.enable() + try: + env = gym.make(args_cli.task, cfg=env_cfg) + env.reset() + finally: + env_creation_profile.disable() + + try: + if torch.cuda.is_available() and torch.cuda.is_initialized(): + torch.cuda.synchronize() + env_creation_time_end = time.perf_counter_ns() + # -- First step profiled ------------------------------------------------ + + # Sample random actions from the action space directly to support + # Box, Discrete, MultiDiscrete, and Dict spaces. + np_actions = np.stack([env.unwrapped.single_action_space.sample() for _ in range(env.unwrapped.num_envs)]) + actions = torch.as_tensor(np_actions, dtype=torch.float32, device=env.unwrapped.device) + + first_step_profile = cProfile.Profile() + first_step_time_begin = time.perf_counter_ns() + first_step_profile.enable() + try: + env.step(actions) + finally: + first_step_profile.disable() + + if torch.cuda.is_available() and torch.cuda.is_initialized(): + torch.cuda.synchronize() + first_step_time_end = time.perf_counter_ns() + + # -- Parse all profiles and log measurements ---------------------------- + + imports_wall_ms = (imports_time_end - imports_time_begin) / 1e6 + task_config_wall_ms = (task_config_time_end - task_config_time_begin) / 1e6 + env_creation_wall_ms = (env_creation_time_end - env_creation_time_begin) / 1e6 + first_step_wall_ms = (first_step_time_end - first_step_time_begin) / 1e6 + + # Collect Timer-based sub-timings for env_creation phase (may not exist for all environment types) + scene_creation_ms = None + try: + scene_creation_ms = Timer.get_timer_info("scene_creation") * 1000 + except TimerError: + print("[INFO] Timer 'scene_creation' not available; sub-timing will be omitted.") + + simulation_start_ms = None + try: + simulation_start_ms = Timer.get_timer_info("simulation_start") * 1000 + except TimerError: + print("[INFO] Timer 'simulation_start' not available; sub-timing will be omitted.") + + phases = { + "app_launch": { + "profile": app_launch_profile, + "wall_clock_ms": app_launch_wall_ms, + "extra_measurements": [], + }, + "python_imports": { + "profile": imports_profile, + "wall_clock_ms": imports_wall_ms, + "extra_measurements": [], + }, + "task_config": { + "profile": task_config_profile, + "wall_clock_ms": task_config_wall_ms, + "extra_measurements": [], + }, + "env_creation": { + "profile": env_creation_profile, + "wall_clock_ms": env_creation_wall_ms, + "extra_measurements": [ + (name, val) + for name, val in [ + ("Scene Creation Time", scene_creation_ms), + ("Simulation Start Time", simulation_start_ms), + ] + if val is not None + ], + }, + "first_step": { + "profile": first_step_profile, + "wall_clock_ms": first_step_wall_ms, + "extra_measurements": [], + }, + } + + # Parse profiles and log measurements to benchmark + for phase_name, phase_data in phases.items(): + phase_whitelist = _WHITELIST.get(phase_name) + functions = parse_cprofile_stats( + phase_data["profile"], _ISAACLAB_PREFIXES, top_n=args_cli.top_n, whitelist=phase_whitelist + ) + wall_ms = phase_data["wall_clock_ms"] + extras = phase_data["extra_measurements"] + + # Log wall-clock time + benchmark.add_measurement( + phase_name, measurement=SingleMeasurement(name="Wall Clock Time", value=wall_ms, unit="ms") + ) + + # Log extra sub-timings + for extra_name, extra_val in extras: + benchmark.add_measurement( + phase_name, measurement=SingleMeasurement(name=extra_name, value=extra_val, unit="ms") + ) + + # Log per-function measurements (tottime + cumtime) + for label, tottime_ms, cumtime_ms in functions: + benchmark.add_measurement( + phase_name, measurement=SingleMeasurement(name=label, value=round(tottime_ms, 2), unit="ms") + ) + benchmark.add_measurement( + phase_name, + measurement=SingleMeasurement(name=f"{label} (cumtime)", value=round(cumtime_ms, 2), unit="ms"), + ) + + # Finalize benchmark output + benchmark.update_manual_recorders() + benchmark._finalize_impl() + finally: + if env is not None: + env.close() + + +if __name__ == "__main__": + # -- App launch (profiled) -------------------------------------------------- + + app_launch_profile = cProfile.Profile() + app_launch_time_begin = time.perf_counter_ns() + app_launch_profile.enable() + + with launch_simulation(env_cfg, args_cli): + app_launch_profile.disable() + + if torch.cuda.is_available() and torch.cuda.is_initialized(): + torch.cuda.synchronize() + app_launch_time_end = time.perf_counter_ns() + + app_launch_wall_ms = (app_launch_time_end - app_launch_time_begin) / 1e6 + main(env_cfg, app_launch_profile, app_launch_wall_ms) diff --git a/scripts/benchmarks/benchmark_view_comparison.py b/scripts/benchmarks/benchmark_view_comparison.py index 8f2b60c49077..a637f687803e 100644 --- a/scripts/benchmarks/benchmark_view_comparison.py +++ b/scripts/benchmarks/benchmark_view_comparison.py @@ -3,54 +3,50 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""Benchmark script comparing XformPrimView vs PhysX RigidBodyView for transform operations. +"""Benchmark script comparing FrameView backends and PhysX RigidBodyView. -This script tests the performance of batched transform operations using: +Compares batched transform operation performance across: -- Isaac Lab's XformPrimView (USD-based) -- Isaac Lab's XformPrimView (Fabric-based) -- PhysX RigidBodyView (PhysX tensors-based, as used in RigidObject) - -Note: - XformPrimView operates on USD attributes directly (useful for non-physics prims), - or on Fabric attributes when Fabric is enabled. - while RigidBodyView requires rigid body physics components and operates on PhysX tensors. - This benchmark helps understand the performance trade-offs between the two approaches. +- **USD** (baseline): Isaac Lab's FrameView via USD XformCache +- **Fabric**: Isaac Lab's FrameView via Fabric GPU arrays +- **Newton**: Isaac Lab's Newton FrameView via Warp site kernels +- **PhysX**: PhysX RigidBodyView via PhysX tensor API (reference) Usage: - # Basic benchmark + # All backends ./isaaclab.sh -p scripts/benchmarks/benchmark_view_comparison.py --num_envs 1024 --device cuda:0 --headless - # With profiling enabled (for snakeviz visualization) - ./isaaclab.sh -p scripts/benchmarks/benchmark_view_comparison.py --num_envs 1024 --profile --headless + # Select specific backends + ./isaaclab.sh -p scripts/benchmarks/benchmark_view_comparison.py --backends usd fabric newton --headless - # Then visualize with snakeviz: - snakeviz profile_results/xform_view_benchmark.prof - snakeviz profile_results/physx_view_benchmark.prof + # With profiling + ./isaaclab.sh -p scripts/benchmarks/benchmark_view_comparison.py --num_envs 1024 --profile --headless """ from __future__ import annotations -"""Launch Isaac Sim Simulator first.""" - import argparse from isaaclab.app import AppLauncher -# parse the arguments -args_cli = argparse.Namespace() - -parser = argparse.ArgumentParser(description="Benchmark XformPrimView vs PhysX RigidBodyView performance.") +parser = argparse.ArgumentParser(description="Benchmark FrameView backends and PhysX RigidBodyView.") parser.add_argument("--num_envs", type=int, default=1000, help="Number of environments to simulate.") parser.add_argument("--num_iterations", type=int, default=50, help="Number of iterations for each test.") +parser.add_argument( + "--backends", + nargs="+", + default=["usd", "fabric", "newton", "physx"], + choices=["usd", "fabric", "newton", "physx"], + help="Backends to benchmark. Default: all four.", +) parser.add_argument( "--profile", action="store_true", help="Enable profiling with cProfile. Results saved as .prof files for snakeviz visualization.", ) parser.add_argument( - "--profile-dir", + "--profile_dir", type=str, default="./profile_results", help="Directory to save profile results. Default: ./profile_results", @@ -59,7 +55,6 @@ AppLauncher.add_app_launcher_args(parser) args_cli = parser.parse_args() -# launch omniverse app app_launcher = AppLauncher(args_cli) simulation_app = app_launcher.app @@ -69,40 +64,40 @@ import time import torch +import warp as wp + +from pxr import Gf import isaaclab.sim as sim_utils -from isaaclab.sim.views import XformPrimView +from isaaclab.sim.views import FrameView + +try: + from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg + from isaaclab_newton.sim.views import NewtonSiteFrameView + + HAS_NEWTON = True +except ImportError: + HAS_NEWTON = False + + +# ------------------------------------------------------------------ +# Benchmark functions +# ------------------------------------------------------------------ @torch.no_grad() -def benchmark_view(view_type: str, num_iterations: int) -> tuple[dict[str, float], dict[str, torch.Tensor]]: - """Benchmark the specified view class. - - Args: - view_type: Type of view to benchmark ("xform", "xform_fabric", or "physx"). - num_iterations: Number of iterations to run. - - Returns: - A tuple of (timing_results, computed_results) where: - - timing_results: Dictionary containing timing results for various operations - - computed_results: Dictionary containing the computed values for validation - """ +def benchmark_usd_or_fabric(view_type: str, num_iterations: int) -> dict[str, float]: + """Benchmark USD or Fabric FrameView.""" timing_results = {} - computed_results = {} - # Setup scene print(" Setting up scene") - # Clear stage sim_utils.create_new_stage() - # Create simulation context start_time = time.perf_counter() - sim_cfg = sim_utils.SimulationCfg(dt=0.01, device=args_cli.device, use_fabric=(view_type == "xform_fabric")) + sim_cfg = sim_utils.SimulationCfg(dt=0.01, device=args_cli.device, use_fabric=(view_type == "fabric")) sim = sim_utils.SimulationContext(sim_cfg) stage = sim_utils.get_current_stage() + print(f" SimulationContext: {time.perf_counter() - start_time:.4f}s") - print(f" Time taken to create simulation context: {time.perf_counter() - start_time:.4f} seconds") - - # create a rigid object object_cfg = sim_utils.ConeCfg( radius=0.15, height=0.5, @@ -111,222 +106,223 @@ def benchmark_view(view_type: str, num_iterations: int) -> tuple[dict[str, float collision_props=sim_utils.CollisionPropertiesCfg(), visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(0.0, 1.0, 0.0)), ) - # Create prims for i in range(args_cli.num_envs): sim_utils.create_prim(f"/World/Env_{i}", "Xform", stage=stage, translation=(i * 2.0, 0.0, 0.0)) object_cfg.func(f"/World/Env_{i}/Object", object_cfg, translation=(0.0, 0.0, 1.0)) + prim = stage.DefinePrim(f"/World/Env_{i}/Object/Sensor", "Xform") + sim_utils.standardize_xform_ops(prim) + prim.GetAttribute("xformOp:translate").Set(Gf.Vec3d(0.1, 0.0, 0.05)) + prim.GetAttribute("xformOp:orient").Set(Gf.Quatd(1.0, 0.0, 0.0, 0.0)) - # Play simulation sim.reset() - # Pattern to match all prims - pattern = "/World/Env_.*/Object" if view_type == "xform" else "/World/Env_*/Object" - print(f" Pattern: {pattern}") + pattern = "/World/Env_.*/Object/Sensor" - # Create view based on type start_time = time.perf_counter() - if view_type == "xform": - view = XformPrimView(pattern, device=args_cli.device, validate_xform_ops=False) - num_prims = view.count - view_name = "XformPrimView (USD)" - elif view_type == "xform_fabric": - if "cuda" not in args_cli.device: - raise ValueError("Fabric backend requires CUDA. Please use --device cuda:0 for this benchmark.") - view = XformPrimView(pattern, device=args_cli.device, validate_xform_ops=False) - num_prims = view.count - view_name = "XformPrimView (Fabric)" - else: # physx - physics_sim_view = sim.physics_manager.get_physics_sim_view() - view = physics_sim_view.create_rigid_body_view(pattern) - num_prims = view.count - view_name = "PhysX RigidBodyView" + if view_type == "fabric" and "cuda" not in args_cli.device: + raise ValueError("Fabric backend requires CUDA.") + view = FrameView(pattern, device=args_cli.device, validate_xform_ops=False) + num_prims = view.count timing_results["init"] = time.perf_counter() - start_time - # prepare indices for benchmarking - all_indices = torch.arange(num_prims, device=args_cli.device) - - print(f" {view_name} managing {num_prims} prims") - - # Fabric is write-first: initialize it to match USD before benchmarking reads. - if view_type == "xform_fabric" and num_prims > 0: - init_positions = torch.zeros((num_prims, 3), dtype=torch.float32, device=args_cli.device) - init_positions[:, 0] = 2.0 * torch.arange(num_prims, device=args_cli.device, dtype=torch.float32) - init_positions[:, 2] = 1.0 - init_orientations = torch.tensor( - [[1.0, 0.0, 0.0, 0.0]] * num_prims, dtype=torch.float32, device=args_cli.device + + print(f" FrameView ({view_type.upper()}) managing {num_prims} prims") + + positions, orientations = view.get_world_poses() + + _run_pose_benchmarks(view, num_prims, num_iterations, timing_results, positions, orientations) + + sim.clear_instance() + return timing_results + + +@torch.no_grad() +def benchmark_newton(num_iterations: int) -> dict[str, float]: + """Benchmark Newton FrameView.""" + from isaaclab.assets import RigidObjectCfg + from isaaclab.scene import InteractiveScene, InteractiveSceneCfg + from isaaclab.sim import SimulationCfg, build_simulation_context + from isaaclab.utils import configclass + + timing_results = {} + + @configclass + class _SceneCfg(InteractiveSceneCfg): + cube: RigidObjectCfg = RigidObjectCfg( + prim_path="{ENV_REGEX_NS}/Cube", + spawn=sim_utils.CuboidCfg( + size=(0.2, 0.2, 0.2), + rigid_props=sim_utils.RigidBodyPropertiesCfg(), + mass_props=sim_utils.MassPropertiesCfg(mass=1.0), + collision_props=sim_utils.CollisionPropertiesCfg(), + ), + init_state=RigidObjectCfg.InitialStateCfg(pos=(0.0, 0.0, 1.0)), ) - view.set_world_poses(init_positions, init_orientations) - # Benchmark get_world_poses + print(" Setting up Newton scene") + newton_cfg = SimulationCfg(physics=NewtonCfg(solver_cfg=MJWarpSolverCfg()), device=args_cli.device) start_time = time.perf_counter() - for _ in range(num_iterations): - if view_type in ("xform", "xform_fabric"): - positions, orientations = view.get_world_poses() - else: # physx - transforms = view.get_transforms() - positions = transforms[:, :3] - orientations = transforms[:, 3:7] - timing_results["get_world_poses"] = (time.perf_counter() - start_time) / num_iterations + ctx = build_simulation_context(device=args_cli.device, sim_cfg=newton_cfg, add_ground_plane=True) + sim = ctx.__enter__() + sim._app_control_on_stop_handle = None + InteractiveScene(_SceneCfg(num_envs=args_cli.num_envs, env_spacing=2.0)) - # Store initial world poses - computed_results["initial_world_positions"] = positions.clone() - computed_results["initial_world_orientations"] = orientations.clone() + stage = sim_utils.get_current_stage() + for i in range(args_cli.num_envs): + prim = stage.DefinePrim(f"/World/envs/env_{i}/Cube/Sensor", "Xform") + sim_utils.standardize_xform_ops(prim) + prim.GetAttribute("xformOp:translate").Set(Gf.Vec3d(0.1, 0.0, 0.05)) + prim.GetAttribute("xformOp:orient").Set(Gf.Quatd(1.0, 0.0, 0.0, 0.0)) + + sim.reset() + print(f" Newton scene setup: {time.perf_counter() - start_time:.4f}s") - # Benchmark set_world_poses - new_positions = positions.clone() - new_positions[:, 2] += 0.5 start_time = time.perf_counter() - for _ in range(num_iterations): - if view_type in ("xform", "xform_fabric"): - view.set_world_poses(new_positions, orientations) - else: # physx - new_transforms = torch.cat([new_positions, orientations], dim=-1) - view.set_transforms(new_transforms, indices=all_indices) - timing_results["set_world_poses"] = (time.perf_counter() - start_time) / num_iterations + view = NewtonSiteFrameView("/World/envs/env_.*/Cube/Sensor", device=args_cli.device) + num_prims = view.count + timing_results["init"] = time.perf_counter() - start_time - # Get world poses after setting to verify - if view_type in ("xform", "xform_fabric"): - positions_after_set, orientations_after_set = view.get_world_poses() - else: # physx - transforms_after = view.get_transforms() - positions_after_set = transforms_after[:, :3] - orientations_after_set = transforms_after[:, 3:7] - computed_results["world_positions_after_set"] = positions_after_set.clone() - computed_results["world_orientations_after_set"] = orientations_after_set.clone() - - # close simulation - sim.clear_instance() + print(f" Newton FrameView managing {num_prims} prims") - return timing_results, computed_results + positions, orientations = view.get_world_poses() + _run_pose_benchmarks(view, num_prims, num_iterations, timing_results, positions, orientations) -def compare_results( - results_dict: dict[str, dict[str, torch.Tensor]], tolerance: float = 1e-4 -) -> dict[str, dict[str, dict[str, float]]]: - """Compare computed results across implementations. + ctx.__exit__(None, None, None) + return timing_results - Args: - results_dict: Dictionary mapping implementation names to their computed values. - tolerance: Tolerance for numerical comparison. - Returns: - Nested dictionary: {comparison_pair: {metric: {stats}}} - """ - comparison_stats = {} - impl_names = list(results_dict.keys()) +@torch.no_grad() +def benchmark_physx(num_iterations: int) -> dict[str, float]: + """Benchmark PhysX RigidBodyView.""" + timing_results = {} - # Compare each pair of implementations - for i, impl1 in enumerate(impl_names): - for impl2 in impl_names[i + 1 :]: - pair_key = f"{impl1}_vs_{impl2}" - comparison_stats[pair_key] = {} + print(" Setting up scene") + sim_utils.create_new_stage() + start_time = time.perf_counter() + sim_cfg = sim_utils.SimulationCfg(dt=0.01, device=args_cli.device, use_fabric=False) + sim = sim_utils.SimulationContext(sim_cfg) + stage = sim_utils.get_current_stage() + print(f" SimulationContext: {time.perf_counter() - start_time:.4f}s") - computed1 = results_dict[impl1] - computed2 = results_dict[impl2] + object_cfg = sim_utils.ConeCfg( + radius=0.15, + height=0.5, + rigid_props=sim_utils.RigidBodyPropertiesCfg(), + mass_props=sim_utils.MassPropertiesCfg(mass=1.0), + collision_props=sim_utils.CollisionPropertiesCfg(), + visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(0.0, 1.0, 0.0)), + ) + for i in range(args_cli.num_envs): + sim_utils.create_prim(f"/World/Env_{i}", "Xform", stage=stage, translation=(i * 2.0, 0.0, 0.0)) + object_cfg.func(f"/World/Env_{i}/Object", object_cfg, translation=(0.0, 0.0, 1.0)) - for key in computed1.keys(): - if key not in computed2: - continue + sim.reset() - val1 = computed1[key] - val2 = computed2[key] + pattern = "/World/Env_*/Object" + start_time = time.perf_counter() + physics_sim_view = sim.physics_manager.get_physics_sim_view() + view = physics_sim_view.create_rigid_body_view(pattern) + num_prims = view.count + timing_results["init"] = time.perf_counter() - start_time - # Skip zero tensors (not applicable tests) - if torch.all(val1 == 0) or torch.all(val2 == 0): - continue + print(f" PhysX RigidBodyView managing {num_prims} prims") - # Compute differences - diff = torch.abs(val1 - val2) - max_diff = torch.max(diff).item() - mean_diff = torch.mean(diff).item() + all_indices = wp.from_torch(torch.arange(num_prims, dtype=torch.int32, device=args_cli.device)) - # Check if within tolerance - all_close = torch.allclose(val1, val2, atol=tolerance, rtol=0) + transforms = view.get_transforms() + transforms_t = wp.to_torch(transforms) if isinstance(transforms, wp.array) else transforms + positions_t = transforms_t[:, :3] + orientations_t = transforms_t[:, 3:7] - comparison_stats[pair_key][key] = { - "max_diff": max_diff, - "mean_diff": mean_diff, - "all_close": all_close, - } + start_time = time.perf_counter() + for _ in range(num_iterations): + transforms = view.get_transforms() + timing_results["get_world_poses"] = (time.perf_counter() - start_time) / num_iterations - return comparison_stats + new_positions = positions_t.clone() + new_positions[:, 2] += 0.5 + expected_positions = new_positions.clone() + new_transforms = wp.from_torch(torch.cat([new_positions, orientations_t], dim=-1).contiguous()) + start_time = time.perf_counter() + for _ in range(num_iterations): + view.set_transforms(new_transforms, indices=all_indices) + timing_results["set_world_poses"] = (time.perf_counter() - start_time) / num_iterations + transforms_after = view.get_transforms() + ta = wp.to_torch(transforms_after) if isinstance(transforms_after, wp.array) else transforms_after + pos_ok = torch.allclose(ta[:, :3], expected_positions, atol=1e-4, rtol=0) + quat_ok = torch.allclose(ta[:, 3:7], orientations_t, atol=1e-4, rtol=0) + if pos_ok and quat_ok: + print(" Round-trip verification: PASS") + else: + pos_diff = (ta[:, :3] - expected_positions).abs().max().item() + quat_diff = (ta[:, 3:7] - orientations_t).abs().max().item() + print(f" Round-trip verification: FAIL (pos max_diff={pos_diff:.6e}, quat max_diff={quat_diff:.6e})") -def print_comparison_results(comparison_stats: dict[str, dict[str, dict[str, float]]], tolerance: float): - """Print comparison results. + sim.clear_instance() + return timing_results + + +def _run_pose_benchmarks( + view, + num_prims: int, + num_iterations: int, + timing_results: dict, + positions: wp.array, + orientations: wp.array, +): + """Shared benchmark loop for get/set world poses on any FrameView.""" + start_time = time.perf_counter() + for _ in range(num_iterations): + view.get_world_poses() + timing_results["get_world_poses"] = (time.perf_counter() - start_time) / num_iterations - Args: - comparison_stats: Nested dictionary containing comparison statistics. - tolerance: Tolerance used for comparison. - """ - for pair_key, pair_stats in comparison_stats.items(): - if not pair_stats: # Skip if no comparable results - continue + new_positions = wp.clone(positions) + new_positions_t = wp.to_torch(new_positions) + new_positions_t[:, 2] += 0.5 + expected_positions = new_positions_t.clone() - # Format the pair key for display - impl1, impl2 = pair_key.split("_vs_") - display_impl1 = impl1.replace("_", " ").title() - display_impl2 = impl2.replace("_", " ").title() - comparison_title = f"{display_impl1} vs {display_impl2}" - - # Check if all results match - all_match = all(stats["all_close"] for stats in pair_stats.values()) - - if all_match: - # Compact output when everything matches - print("\n" + "=" * 100) - print(f"RESULT COMPARISON: {comparison_title}") - print("=" * 100) - print(f"✓ All computed values match within tolerance ({tolerance})") - print("=" * 100) - else: - # Detailed output when there are mismatches - print("\n" + "=" * 100) - print(f"RESULT COMPARISON: {comparison_title}") - print("=" * 100) - print(f"{'Computed Value':<40} {'Max Diff':<15} {'Mean Diff':<15} {'Match':<10}") - print("-" * 100) - - for key, stats in pair_stats.items(): - # Format the key for display - display_key = key.replace("_", " ").title() - match_str = "✓ Yes" if stats["all_close"] else "✗ No" - - print(f"{display_key:<40} {stats['max_diff']:<15.6e} {stats['mean_diff']:<15.6e} {match_str:<10}") - - print("=" * 100) - print(f"\n✗ Some results differ beyond tolerance ({tolerance})") - print(f" This may indicate implementation differences between {display_impl1} and {display_impl2}") + start_time = time.perf_counter() + for _ in range(num_iterations): + view.set_world_poses(new_positions, orientations) + timing_results["set_world_poses"] = (time.perf_counter() - start_time) / num_iterations + + ret_pos, ret_quat = view.get_world_poses() + ret_pos_t = wp.to_torch(ret_pos) + ret_quat_t = wp.to_torch(ret_quat) + ori_t = wp.to_torch(orientations) + + pos_ok = torch.allclose(ret_pos_t, expected_positions, atol=1e-4, rtol=0) + quat_ok = torch.allclose(ret_quat_t, ori_t, atol=1e-4, rtol=0) + if pos_ok and quat_ok: + print(" Round-trip verification: PASS") + else: + pos_diff = (ret_pos_t - expected_positions).abs().max().item() + quat_diff = (ret_quat_t - ori_t).abs().max().item() + print(f" Round-trip verification: FAIL (pos max_diff={pos_diff:.6e}, quat max_diff={quat_diff:.6e})") - print() + +# ------------------------------------------------------------------ +# Reporting +# ------------------------------------------------------------------ def print_results(results_dict: dict[str, dict[str, float]], num_prims: int, num_iterations: int): - """Print benchmark results in a formatted table. - - Args: - results_dict: Dictionary mapping implementation names to their timing results. - num_prims: Number of prims tested. - num_iterations: Number of iterations run. - """ - print("\n" + "=" * 100) + """Print benchmark results in a formatted table.""" + print("\n" + "=" * 120) print(f"BENCHMARK RESULTS: {num_prims} prims, {num_iterations} iterations") - print("=" * 100) + print("=" * 120) impl_names = list(results_dict.keys()) - # Format names for display - display_names = [name.replace("_", " ").title() for name in impl_names] - - # Calculate column width - col_width = 20 + display_names = {n: n.replace("_", " ").title() for n in impl_names} + col_width = 22 - # Print header - header = f"{'Operation':<30}" - for display_name in display_names: - header += f" {display_name + ' (ms)':<{col_width}}" + header = f"{'Operation':<25}" + for name in impl_names: + header += f" {display_names[name] + ' (ms)':>{col_width}}" print(header) - print("-" * 100) + print("-" * 120) - # Print each operation operations = [ ("Initialization", "init"), ("Get World Poses", "get_world_poses"), @@ -334,168 +330,117 @@ def print_results(results_dict: dict[str, dict[str, float]], num_prims: int, num ] for op_name, op_key in operations: - row = f"{op_name:<30}" - for impl_name in impl_names: - impl_time = results_dict[impl_name].get(op_key, 0) * 1000 # Convert to ms - row += f" {impl_time:>{col_width - 1}.4f}" + row = f"{op_name:<25}" + for name in impl_names: + val = results_dict[name].get(op_key, 0) * 1000 + row += f" {val:>{col_width}.4f}" print(row) - print("=" * 100) - - # Calculate and print total time (excluding N/A operations) - total_row = f"{'Total Time':<30}" - for impl_name in impl_names: - if impl_name == "physx_view": - # Exclude local pose operations for PhysX - total_time = ( - results_dict[impl_name].get("init", 0) * 1000 - + results_dict[impl_name].get("get_world_poses", 0) * 1000 - + results_dict[impl_name].get("set_world_poses", 0) * 1000 - ) - else: - total_time = sum(results_dict[impl_name].values()) * 1000 - total_row += f" {total_time:>{col_width - 1}.4f}" - print(f"\n{total_row}") - - # Calculate speedups relative to XformPrimView (USD baseline) - if "xform_view" in impl_names: - print("\n" + "=" * 100) - print("SPEEDUP vs XformPrimView (USD)") - print("=" * 100) - print(f"{'Operation':<30}", end="") - for impl_name, display_name in zip(impl_names, display_names): - if impl_name != "xform_view": - print(f" {display_name + ' Speedup':<{col_width}}", end="") - print() - print("-" * 100) - - xform_results = results_dict["xform_view"] + print("=" * 120) + + total_row = f"{'Total':<25}" + for name in impl_names: + total = sum(results_dict[name].values()) * 1000 + total_row += f" {total:>{col_width}.4f}" + print(total_row) + + baseline = "usd" + if baseline in results_dict and len(impl_names) > 1: + print("\n" + "=" * 120) + print(f"SPEEDUP vs {display_names[baseline]}") + print("=" * 120) + header = f"{'Operation':<25}" + for name in impl_names: + if name != baseline: + header += f" {display_names[name]:>{col_width}}" + print(header) + print("-" * 120) + + base = results_dict[baseline] for op_name, op_key in operations: - print(f"{op_name:<30}", end="") - xform_time = xform_results.get(op_key, 0) - for impl_name, display_name in zip(impl_names, display_names): - if impl_name != "xform_view": - impl_time = results_dict[impl_name].get(op_key, 0) - if xform_time > 0 and impl_time > 0: - speedup = impl_time / xform_time - print(f" {speedup:>{col_width - 1}.2f}x", end="") + row = f"{op_name:<25}" + base_t = base.get(op_key, 0) + for name in impl_names: + if name != baseline: + impl_t = results_dict[name].get(op_key, 0) + if base_t > 0 and impl_t > 0: + row += f" {base_t / impl_t:>{col_width}.2f}x" else: - print(f" {'N/A':>{col_width}}", end="") - print() + row += f" {'N/A':>{col_width}}" + print(row) + print("=" * 120) - # Overall speedup (only world pose operations) - print("=" * 100) - print(f"{'Overall Speedup (World Ops)':<30}", end="") - total_xform = ( - xform_results.get("init", 0) - + xform_results.get("get_world_poses", 0) - + xform_results.get("set_world_poses", 0) - ) - for impl_name, display_name in zip(impl_names, display_names): - if impl_name != "xform_view": - total_impl = ( - results_dict[impl_name].get("init", 0) - + results_dict[impl_name].get("get_world_poses", 0) - + results_dict[impl_name].get("set_world_poses", 0) - ) - if total_xform > 0 and total_impl > 0: - overall_speedup = total_impl / total_xform - print(f" {overall_speedup:>{col_width - 1}.2f}x", end="") - else: - print(f" {'N/A':>{col_width}}", end="") - print() - - print("\n" + "=" * 100) print("\nNotes:") print(" - Times are averaged over all iterations") - print(" - Speedup = (Implementation time) / (XformPrimView USD time)") - print(" - Speedup > 1.0 means USD XformPrimView is faster") - print(" - Speedup < 1.0 means the implementation is faster than USD") - print(" - PhysX View requires rigid body physics components") - print(" - XformPrimView works with any Xform prim (physics or non-physics)") - print(" - PhysX View does not support local pose operations directly") + print(" - Speedup > 1.0 means faster than USD baseline") + print(" - PhysX RigidBodyView requires rigid body physics; FrameView works with any Xformable prim") print() +# ------------------------------------------------------------------ +# Main +# ------------------------------------------------------------------ + + def main(): - """Main benchmark function.""" - print("=" * 100) - print("View Comparison Benchmark - XformPrimView vs PhysX RigidBodyView") - print("=" * 100) - print("Configuration:") - print(f" Number of environments: {args_cli.num_envs}") - print(f" Iterations per test: {args_cli.num_iterations}") - print(f" Device: {args_cli.device}") - print(f" Profiling: {'Enabled' if args_cli.profile else 'Disabled'}") - if args_cli.profile: - print(f" Profile directory: {args_cli.profile_dir}") + print("=" * 120) + print("FrameView Benchmark: USD vs Fabric vs Newton vs PhysX") + print("=" * 120) + print(f" Environments: {args_cli.num_envs}") + print(f" Iterations: {args_cli.num_iterations}") + print(f" Device: {args_cli.device}") + print(f" Backends: {', '.join(args_cli.backends)}") print() - # Create profile directory if profiling is enabled if args_cli.profile: import os os.makedirs(args_cli.profile_dir, exist_ok=True) - # Dictionary to store all results - all_timing_results = {} - all_computed_results = {} + all_timing = {} profile_files = {} - # Implementations to benchmark - implementations = [ - ("xform_view", "XformPrimView (USD)", "xform"), - ("xform_fabric_view", "XformPrimView (Fabric)", "xform_fabric"), - ("physx_view", "PhysX RigidBodyView", "physx"), - ] + dispatch = { + "usd": ("usd", "FrameView (USD)", lambda n: benchmark_usd_or_fabric("usd", n)), + "fabric": ("fabric", "FrameView (Fabric)", lambda n: benchmark_usd_or_fabric("fabric", n)), + "newton": ("newton", "FrameView (Newton)", lambda n: benchmark_newton(n)), + "physx": ("physx", "PhysX RigidBodyView", lambda n: benchmark_physx(n)), + } - # Benchmark each implementation - for impl_key, impl_name, view_type in implementations: - print(f"Benchmarking {impl_name}...") + for backend in args_cli.backends: + if backend == "newton" and not HAS_NEWTON: + print(f"Skipping {backend}: isaaclab_newton not installed") + continue + + key, display_name, bench_fn = dispatch[backend] + print(f"Benchmarking {display_name}...") if args_cli.profile: profiler = cProfile.Profile() profiler.enable() - timing, computed = benchmark_view(view_type=view_type, num_iterations=args_cli.num_iterations) + timing = bench_fn(args_cli.num_iterations) if args_cli.profile: profiler.disable() - profile_file = f"{args_cli.profile_dir}/{impl_key}_benchmark.prof" - profiler.dump_stats(profile_file) - profile_files[impl_key] = profile_file - print(f" Profile saved to: {profile_file}") - - all_timing_results[impl_key] = timing - all_computed_results[impl_key] = computed + pf = f"{args_cli.profile_dir}/{key}_benchmark.prof" + profiler.dump_stats(pf) + profile_files[key] = pf + print(f" Profile saved to: {pf}") - print(" Done!") - print() + all_timing[key] = timing + print(" Done!\n") - # Print timing results - print_results(all_timing_results, args_cli.num_envs, args_cli.num_iterations) + print_results(all_timing, args_cli.num_envs, args_cli.num_iterations) - # Compare computed results - print("\nComparing computed results across implementations...") - comparison_stats = compare_results(all_computed_results, tolerance=1e-4) - print_comparison_results(comparison_stats, tolerance=1e-4) - - # Print profiling instructions if enabled if args_cli.profile: print("\n" + "=" * 100) print("PROFILING RESULTS") print("=" * 100) - print("Profile files have been saved. To visualize with snakeviz, run:") - for impl_key, profile_file in profile_files.items(): - impl_display = impl_key.replace("_", " ").title() - print(f" # {impl_display}") - print(f" snakeviz {profile_file}") - print("\nAlternatively, use pstats to analyze in terminal:") - print(" python -m pstats ") - print("=" * 100) + for key, pf in profile_files.items(): + print(f" snakeviz {pf}") print() - # Clean up sim_utils.SimulationContext.clear_instance() diff --git a/scripts/benchmarks/benchmark_xform_prim_view.py b/scripts/benchmarks/benchmark_xform_prim_view.py index e76796e20271..b682c03f71fc 100644 --- a/scripts/benchmarks/benchmark_xform_prim_view.py +++ b/scripts/benchmarks/benchmark_xform_prim_view.py @@ -3,59 +3,35 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""Benchmark script comparing XformPrimView implementations across different APIs. +"""Benchmark script comparing FrameView implementations across backends. -This script tests the performance of batched transform operations using: -- Isaac Lab's XformPrimView implementation with USD backend -- Isaac Lab's XformPrimView implementation with Fabric backend -- Isaac Sim's XformPrimView implementation (legacy) -- Isaac Sim Experimental's XformPrim implementation (latest) +Compares batched transform operation performance across: +- Isaac Lab FrameView (USD backend) -- baseline +- Isaac Lab FrameView (Fabric backend) +- Isaac Lab FrameView (Newton backend) Usage: - # Basic benchmark (all APIs) ./isaaclab.sh -p scripts/benchmarks/benchmark_xform_prim_view.py --num_envs 1024 --device cuda:0 --headless - # With profiling enabled (for snakeviz visualization) + # With profiling ./isaaclab.sh -p scripts/benchmarks/benchmark_xform_prim_view.py --num_envs 1024 --profile --headless - - # Then visualize with snakeviz: - snakeviz profile_results/isaaclab_usd_benchmark.prof - snakeviz profile_results/isaaclab_fabric_benchmark.prof - snakeviz profile_results/isaacsim_benchmark.prof - snakeviz profile_results/isaacsim_exp_benchmark.prof """ from __future__ import annotations -"""Launch Isaac Sim Simulator first.""" - import argparse from isaaclab.app import AppLauncher -# parse the arguments -args_cli = argparse.Namespace() - -parser = argparse.ArgumentParser(description="This script can help you benchmark the performance of XformPrimView.") - +parser = argparse.ArgumentParser(description="Benchmark FrameView performance across backends.") parser.add_argument("--num_envs", type=int, default=100, help="Number of environments to simulate.") parser.add_argument("--num_iterations", type=int, default=50, help="Number of iterations for each test.") -parser.add_argument( - "--profile", - action="store_true", - help="Enable profiling with cProfile. Results saved as .prof files for snakeviz visualization.", -) -parser.add_argument( - "--profile-dir", - type=str, - default="./profile_results", - help="Directory to save profile results. Default: ./profile_results", -) +parser.add_argument("--profile", action="store_true", help="Enable cProfile profiling.") +parser.add_argument("--profile_dir", type=str, default="./profile_results", help="Directory for .prof files.") AppLauncher.add_app_launcher_args(parser) args_cli = parser.parse_args() -# launch omniverse app app_launcher = AppLauncher(args_cli) simulation_app = app_launcher.app @@ -66,402 +42,231 @@ from typing import Literal import torch +import warp as wp +from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg +from isaaclab_newton.sim.views import NewtonSiteFrameView +from isaaclab_physx.sim.views import FabricFrameView -from isaacsim.core.prims import XFormPrim as IsaacSimXformPrimView -from isaacsim.core.utils.extensions import enable_extension - -# compare against latest Isaac Sim implementation -enable_extension("isaacsim.core.experimental.prims") -from isaacsim.core.experimental.prims import XformPrim as IsaacSimExperimentalXformPrimView +from pxr import Gf import isaaclab.sim as sim_utils -from isaaclab.sim.views import XformPrimView as IsaacLabXformPrimView +from isaaclab.assets import RigidObjectCfg +from isaaclab.scene import InteractiveScene, InteractiveSceneCfg +from isaaclab.sim import SimulationCfg, build_simulation_context +from isaaclab.sim.views import UsdFrameView +from isaaclab.utils import configclass + + +@configclass +class _NewtonSceneCfg(InteractiveSceneCfg): + cube: RigidObjectCfg = RigidObjectCfg( + prim_path="{ENV_REGEX_NS}/Object", + spawn=sim_utils.CuboidCfg( + size=(0.2, 0.2, 0.2), + rigid_props=sim_utils.RigidBodyPropertiesCfg(), + mass_props=sim_utils.MassPropertiesCfg(mass=1.0), + collision_props=sim_utils.CollisionPropertiesCfg(), + ), + init_state=RigidObjectCfg.InitialStateCfg(pos=(0.0, 0.0, 1.0)), + ) + + +# ------------------------------------------------------------------ +# Benchmark +# ------------------------------------------------------------------ @torch.no_grad() -def benchmark_xform_prim_view( # noqa: C901 - api: Literal["isaaclab-usd", "isaaclab-fabric", "isaacsim-usd", "isaacsim-fabric", "isaacsim-exp"], +def benchmark_frame_view( # noqa: C901 + api: Literal["isaaclab-usd", "isaaclab-fabric", "isaaclab-newton-site"], num_iterations: int, ) -> tuple[dict[str, float], dict[str, torch.Tensor]]: - """Benchmark the Xform view class from Isaac Lab, Isaac Sim, or Isaac Sim Experimental. - - Args: - api: Which API to benchmark: - - "isaaclab-usd": Isaac Lab XformPrimView with USD backend - - "isaaclab-fabric": Isaac Lab XformPrimView with Fabric backend - - "isaacsim-usd": Isaac Sim legacy XformPrimView with USD (usd=True) - - "isaacsim-fabric": Isaac Sim legacy XformPrimView with Fabric (usd=False) - - "isaacsim-exp": Isaac Sim Experimental XformPrim - num_iterations: Number of iterations to run. - - Returns: - A tuple of (timing_results, computed_results) where: - - timing_results: Dictionary containing timing results for various operations - - computed_results: Dictionary containing the computed values for validation - """ - timing_results = {} - computed_results = {} - - # Setup scene + """Benchmark get/set world/local poses for the given FrameView backend.""" + timing_results: dict[str, float] = {} + computed_results: dict[str, torch.Tensor] = {} + device = args_cli.device + num_envs = args_cli.num_envs + + # -- Scene setup (backend-specific) -------------------------------- + print(" Setting up scene") - # Clear stage - sim_utils.create_new_stage() - # Create simulation context - start_time = time.perf_counter() - sim_cfg = sim_utils.SimulationCfg( - dt=0.01, - device=args_cli.device, - use_fabric=api in ("isaaclab-fabric", "isaacsim-fabric"), - ) - sim = sim_utils.SimulationContext(sim_cfg) - stage = sim_utils.get_current_stage() - - print(f" Time taken to create simulation context: {time.perf_counter() - start_time} seconds") - - # Create prims - prim_paths = [] - for i in range(args_cli.num_envs): - sim_utils.create_prim(f"/World/Env_{i}", "Xform", stage=stage, translation=(i * 2.0, 0.0, 1.0)) - sim_utils.create_prim(f"/World/Env_{i}/Object", "Xform", stage=stage, translation=(0.0, 0.0, 0.0)) - prim_paths.append(f"/World/Env_{i}/Object") - # Play simulation - sim.reset() - - # Pattern to match all prims - pattern = "/World/Env_.*/Object" - print(f" Pattern: {pattern}") - - # Create view - start_time = time.perf_counter() - if api == "isaaclab-usd" or api == "isaaclab-fabric": - xform_view = IsaacLabXformPrimView(pattern, device=args_cli.device, validate_xform_ops=False) - elif api == "isaacsim-usd": - xform_view = IsaacSimXformPrimView(pattern, reset_xform_properties=False, usd=True) - elif api == "isaacsim-fabric": - xform_view = IsaacSimXformPrimView(pattern, reset_xform_properties=False, usd=False) - elif api == "isaacsim-exp": - xform_view = IsaacSimExperimentalXformPrimView(pattern) + cleanup = None + + if api == "isaaclab-newton-site": + newton_cfg = SimulationCfg(device=device, physics=NewtonCfg(solver_cfg=MJWarpSolverCfg())) + ctx = build_simulation_context(device=device, sim_cfg=newton_cfg, add_ground_plane=True) + sim = ctx.__enter__() + sim._app_control_on_stop_handle = None + InteractiveScene(_NewtonSceneCfg(num_envs=num_envs, env_spacing=2.0)) + + stage = sim_utils.get_current_stage() + for i in range(num_envs): + prim = stage.DefinePrim(f"/World/envs/env_{i}/Object/Sensor", "Xform") + sim_utils.standardize_xform_ops(prim) + prim.GetAttribute("xformOp:translate").Set(Gf.Vec3d(0.1, 0.0, 0.05)) + prim.GetAttribute("xformOp:orient").Set(Gf.Quatd(1.0, 0.0, 0.0, 0.0)) + + sim.reset() + + start_time = time.perf_counter() + xform_view = NewtonSiteFrameView("/World/envs/env_.*/Object/Sensor", device=device) + timing_results["init"] = time.perf_counter() - start_time + cleanup = lambda: ctx.__exit__(None, None, None) # noqa: E731 + else: - raise ValueError(f"Invalid API: {api}") - timing_results["init"] = time.perf_counter() - start_time - - if api in ("isaaclab-usd", "isaaclab-fabric", "isaacsim-usd", "isaacsim-fabric"): - num_prims = xform_view.count - elif api == "isaacsim-exp": - num_prims = len(xform_view.prims) - print(f" XformView managing {num_prims} prims") - - # Benchmark get_world_poses - # Warmup call to initialize Fabric (if needed) - excluded from timing - positions, orientations = xform_view.get_world_poses() - - # Now time the actual iterations (steady-state performance) - start_time = time.perf_counter() - for _ in range(num_iterations): - positions, orientations = xform_view.get_world_poses() - - # Ensure tensors are torch tensors (do this AFTER timing) - if not isinstance(positions, torch.Tensor): - positions = torch.tensor(positions, dtype=torch.float32) - if not isinstance(orientations, torch.Tensor): - orientations = torch.tensor(orientations, dtype=torch.float32) - - timing_results["get_world_poses"] = (time.perf_counter() - start_time) / num_iterations - - # Store initial world poses - computed_results["initial_world_positions"] = positions.clone() - computed_results["initial_world_orientations"] = orientations.clone() - - # Benchmark set_world_poses - new_positions = positions.clone() - new_positions[:, 2] += 0.1 - start_time = time.perf_counter() - for _ in range(num_iterations): - if api in ("isaaclab-usd", "isaaclab-fabric", "isaacsim-usd", "isaacsim-fabric"): + sim_utils.create_new_stage() + start_time = time.perf_counter() + use_fabric = api == "isaaclab-fabric" + sim = sim_utils.SimulationContext(sim_utils.SimulationCfg(dt=0.01, device=device, use_fabric=use_fabric)) + stage = sim_utils.get_current_stage() + + for i in range(num_envs): + sim_utils.create_prim(f"/World/Env_{i}", "Xform", stage=stage, translation=(i * 2.0, 0.0, 1.0)) + sim_utils.create_prim(f"/World/Env_{i}/Object", "Xform", stage=stage, translation=(0.0, 0.0, 0.0)) + + sim.reset() + + pattern = "/World/Env_.*/Object" + start_time = time.perf_counter() + ViewClass = FabricFrameView if use_fabric else UsdFrameView + xform_view = ViewClass(pattern, device=device, validate_xform_ops=False) + timing_results["init"] = time.perf_counter() - start_time + cleanup = lambda: sim.clear_instance() # noqa: E731 + + num_prims = xform_view.count + print(f" {api} managing {num_prims} prims") + + is_newton = api == "isaaclab-newton-site" + + def to_torch(a): + return wp.to_torch(a) if isinstance(a, wp.array) else a + + try: + # -- Warmup -------------------------------------------------------- + xform_view.get_world_poses() + + # -- get_world_poses ----------------------------------------------- + if is_newton: + torch.cuda.synchronize() + start_time = time.perf_counter() + for _ in range(num_iterations): + positions, orientations = xform_view.get_world_poses() + if is_newton: + torch.cuda.synchronize() + timing_results["get_world_poses"] = (time.perf_counter() - start_time) / num_iterations + + positions_t = to_torch(positions) + orientations_t = to_torch(orientations) + computed_results["initial_world_positions"] = positions_t.clone() + computed_results["initial_world_orientations"] = orientations_t.clone() + + # -- set_world_poses ----------------------------------------------- + if is_newton: + new_positions = wp.clone(positions) + wp.to_torch(new_positions)[:, 2] += 0.1 + else: + new_positions = positions_t.clone() + new_positions[:, 2] += 0.1 + + if is_newton: + torch.cuda.synchronize() + start_time = time.perf_counter() + for _ in range(num_iterations): xform_view.set_world_poses(new_positions, orientations) - elif api == "isaacsim-exp": - xform_view.set_world_poses(new_positions.cpu().numpy(), orientations.cpu().numpy()) - timing_results["set_world_poses"] = (time.perf_counter() - start_time) / num_iterations - - # Get world poses after setting to verify - positions_after_set, orientations_after_set = xform_view.get_world_poses() - if not isinstance(positions_after_set, torch.Tensor): - positions_after_set = torch.tensor(positions_after_set, dtype=torch.float32) - if not isinstance(orientations_after_set, torch.Tensor): - orientations_after_set = torch.tensor(orientations_after_set, dtype=torch.float32) - computed_results["world_positions_after_set"] = positions_after_set.clone() - computed_results["world_orientations_after_set"] = orientations_after_set.clone() - - # Benchmark get_local_poses - # Warmup call (though local poses use USD, so minimal overhead) - translations, orientations_local = xform_view.get_local_poses() - - # Now time the actual iterations - start_time = time.perf_counter() - for _ in range(num_iterations): - translations, orientations_local = xform_view.get_local_poses() - # Ensure tensors are torch tensors (do this AFTER timing) - if not isinstance(translations, torch.Tensor): - translations = torch.tensor(translations, dtype=torch.float32, device=args_cli.device) - if not isinstance(orientations_local, torch.Tensor): - orientations_local = torch.tensor(orientations_local, dtype=torch.float32, device=args_cli.device) - - timing_results["get_local_poses"] = (time.perf_counter() - start_time) / num_iterations - - # Store initial local poses - computed_results["initial_local_translations"] = translations.clone() - computed_results["initial_local_orientations"] = orientations_local.clone() - - # Benchmark set_local_poses - new_translations = translations.clone() - new_translations[:, 2] += 0.1 - start_time = time.perf_counter() - for _ in range(num_iterations): - if api in ("isaaclab-usd", "isaaclab-fabric", "isaacsim-usd", "isaacsim-fabric"): + if is_newton: + torch.cuda.synchronize() + timing_results["set_world_poses"] = (time.perf_counter() - start_time) / num_iterations + + pa, oa = xform_view.get_world_poses() + computed_results["world_positions_after_set"] = to_torch(pa).clone() + computed_results["world_orientations_after_set"] = to_torch(oa).clone() + + # -- get_local_poses ----------------------------------------------- + if is_newton: + torch.cuda.synchronize() + start_time = time.perf_counter() + for _ in range(num_iterations): + translations, orientations_local = xform_view.get_local_poses() + if is_newton: + torch.cuda.synchronize() + timing_results["get_local_poses"] = (time.perf_counter() - start_time) / num_iterations + + translations_t = to_torch(translations) + orientations_local_t = to_torch(orientations_local) + computed_results["initial_local_translations"] = translations_t.clone() + computed_results["initial_local_orientations"] = orientations_local_t.clone() + + # -- set_local_poses ----------------------------------------------- + if is_newton: + new_translations = wp.clone(translations) + wp.to_torch(new_translations)[:, 2] += 0.1 + else: + new_translations = translations_t.clone() + new_translations[:, 2] += 0.1 + + if is_newton: + torch.cuda.synchronize() + start_time = time.perf_counter() + for _ in range(num_iterations): xform_view.set_local_poses(new_translations, orientations_local) - elif api == "isaacsim-exp": - xform_view.set_local_poses(new_translations.cpu().numpy(), orientations_local.cpu().numpy()) - timing_results["set_local_poses"] = (time.perf_counter() - start_time) / num_iterations - - # Get local poses after setting to verify - translations_after_set, orientations_local_after_set = xform_view.get_local_poses() - if not isinstance(translations_after_set, torch.Tensor): - translations_after_set = torch.tensor(translations_after_set, dtype=torch.float32) - if not isinstance(orientations_local_after_set, torch.Tensor): - orientations_local_after_set = torch.tensor(orientations_local_after_set, dtype=torch.float32) - computed_results["local_translations_after_set"] = translations_after_set.clone() - computed_results["local_orientations_after_set"] = orientations_local_after_set.clone() - - # Benchmark combined get operation - # Warmup call (Fabric should already be initialized by now, but for consistency) - positions, orientations = xform_view.get_world_poses() - translations, local_orientations = xform_view.get_local_poses() - - # Now time the actual iterations - start_time = time.perf_counter() - for _ in range(num_iterations): - positions, orientations = xform_view.get_world_poses() - translations, local_orientations = xform_view.get_local_poses() - timing_results["get_both"] = (time.perf_counter() - start_time) / num_iterations - - # Benchmark interleaved set/get (realistic workflow pattern) - # Pre-convert tensors for experimental API to avoid conversion overhead in loop - if api == "isaacsim-exp": - new_positions_np = new_positions.cpu().numpy() - orientations_np = orientations - - # Warmup - if api in ("isaaclab-usd", "isaaclab-fabric", "isaacsim-usd", "isaacsim-fabric"): - xform_view.set_world_poses(new_positions, orientations) - positions, orientations = xform_view.get_world_poses() - elif api == "isaacsim-exp": - xform_view.set_world_poses(new_positions_np, orientations_np) - positions, orientations = xform_view.get_world_poses() - positions = torch.tensor(positions, dtype=torch.float32) - orientations = torch.tensor(orientations, dtype=torch.float32) - - # Now time the actual interleaved iterations - start_time = time.perf_counter() - for _ in range(num_iterations): - # Write then immediately read (common pattern: set pose, verify/query result) - if api in ("isaaclab-usd", "isaaclab-fabric", "isaacsim-usd", "isaacsim-fabric"): + if is_newton: + torch.cuda.synchronize() + timing_results["set_local_poses"] = (time.perf_counter() - start_time) / num_iterations + + ta, ola = xform_view.get_local_poses() + computed_results["local_translations_after_set"] = to_torch(ta).clone() + computed_results["local_orientations_after_set"] = to_torch(ola).clone() + + # -- get_both (world + local) -------------------------------------- + if is_newton: + torch.cuda.synchronize() + start_time = time.perf_counter() + for _ in range(num_iterations): + xform_view.get_world_poses() + xform_view.get_local_poses() + if is_newton: + torch.cuda.synchronize() + timing_results["get_both"] = (time.perf_counter() - start_time) / num_iterations + + # -- interleaved set -> get ---------------------------------------- + if is_newton: + torch.cuda.synchronize() + start_time = time.perf_counter() + for _ in range(num_iterations): xform_view.set_world_poses(new_positions, orientations) - positions, orientations = xform_view.get_world_poses() - elif api == "isaacsim-exp": - xform_view.set_world_poses(new_positions_np, orientations_np) - positions, orientations = xform_view.get_world_poses() + xform_view.get_world_poses() + if is_newton: + torch.cuda.synchronize() + timing_results["interleaved_world_set_get"] = (time.perf_counter() - start_time) / num_iterations - timing_results["interleaved_world_set_get"] = (time.perf_counter() - start_time) / num_iterations - - # close simulation - sim.clear_instance() + finally: + if cleanup: + cleanup() return timing_results, computed_results -def compare_results( - results_dict: dict[str, dict[str, torch.Tensor]], tolerance: float = 1e-4 -) -> dict[str, dict[str, dict[str, float]]]: - """Compare computed results across multiple implementations. - - Only compares implementations using the same data path: - - USD implementations (isaaclab-usd, isaacsim-usd) are compared with each other - - Fabric implementations (isaaclab-fabric, isaacsim-fabric) are compared with each other - - This is because Fabric is designed for write-first workflows and may not match - USD reads on initialization. - - Args: - results_dict: Dictionary mapping API names to their computed values. - tolerance: Tolerance for numerical comparison. - - Returns: - Nested dictionary: {comparison_pair: {metric: {stats}}}, e.g., - {"isaaclab-usd_vs_isaacsim-usd": {"initial_world_positions": {"max_diff": 0.001, ...}}} - """ - comparison_stats = {} - - # Group APIs by their data path (USD vs Fabric) - usd_apis = [api for api in results_dict.keys() if "usd" in api and "fabric" not in api] - fabric_apis = [api for api in results_dict.keys() if "fabric" in api] - - # Compare within USD group - for i, api1 in enumerate(usd_apis): - for api2 in usd_apis[i + 1 :]: - pair_key = f"{api1}_vs_{api2}" - comparison_stats[pair_key] = {} - - computed1 = results_dict[api1] - computed2 = results_dict[api2] - - for key in computed1.keys(): - if key not in computed2: - print(f" Warning: Key '{key}' not found in {api2} results") - continue - - val1 = computed1[key] - val2 = computed2[key] - - # Compute differences - diff = torch.abs(val1 - val2) - max_diff = torch.max(diff).item() - mean_diff = torch.mean(diff).item() - - # Check if within tolerance - all_close = torch.allclose(val1, val2, atol=tolerance, rtol=0) - - comparison_stats[pair_key][key] = { - "max_diff": max_diff, - "mean_diff": mean_diff, - "all_close": all_close, - } - - # Compare within Fabric group - for i, api1 in enumerate(fabric_apis): - for api2 in fabric_apis[i + 1 :]: - pair_key = f"{api1}_vs_{api2}" - comparison_stats[pair_key] = {} - - computed1 = results_dict[api1] - computed2 = results_dict[api2] - - for key in computed1.keys(): - if key not in computed2: - print(f" Warning: Key '{key}' not found in {api2} results") - continue - - val1 = computed1[key] - val2 = computed2[key] - - # Compute differences - diff = torch.abs(val1 - val2) - max_diff = torch.max(diff).item() - mean_diff = torch.mean(diff).item() - - # Check if within tolerance - all_close = torch.allclose(val1, val2, atol=tolerance, rtol=0) - - comparison_stats[pair_key][key] = { - "max_diff": max_diff, - "mean_diff": mean_diff, - "all_close": all_close, - } - - return comparison_stats - - -def print_comparison_results(comparison_stats: dict[str, dict[str, dict[str, float]]], tolerance: float): - """Print comparison results across implementations. - - Args: - comparison_stats: Nested dictionary containing comparison statistics for each API pair. - tolerance: Tolerance used for comparison. - """ - if not comparison_stats: - print("\n" + "=" * 100) - print("RESULT COMPARISON") - print("=" * 100) - print("ℹ️ No comparisons performed.") - print(" USD and Fabric implementations are not compared because Fabric uses a") - print(" write-first workflow and may not match USD reads on initialization.") - print("=" * 100) - print() - return - - for pair_key, pair_stats in comparison_stats.items(): - # Format the pair key for display (e.g., "isaaclab_vs_isaacsim" -> "Isaac Lab vs Isaac Sim") - api1, api2 = pair_key.split("_vs_") - display_api1 = api1.replace("-", " ").title() - display_api2 = api2.replace("-", " ").title() - comparison_title = f"{display_api1} vs {display_api2}" - - # Check if all results match - all_match = all(stats["all_close"] for stats in pair_stats.values()) - - if all_match: - # Compact output when everything matches - print("\n" + "=" * 100) - print(f"RESULT COMPARISON: {comparison_title}") - print("=" * 100) - print(f"✓ All computed values match within tolerance ({tolerance})") - print("=" * 100) - else: - # Detailed output when there are mismatches - print("\n" + "=" * 100) - print(f"RESULT COMPARISON: {comparison_title}") - print("=" * 100) - print(f"{'Computed Value':<40} {'Max Diff':<15} {'Mean Diff':<15} {'Match':<10}") - print("-" * 100) - - for key, stats in pair_stats.items(): - # Format the key for display - display_key = key.replace("_", " ").title() - match_str = "✓ Yes" if stats["all_close"] else "✗ No" - - print(f"{display_key:<40} {stats['max_diff']:<15.6e} {stats['mean_diff']:<15.6e} {match_str:<10}") - - print("=" * 100) - print(f"\n✗ Some results differ beyond tolerance ({tolerance})") - - # Special note for Isaac Sim Fabric local pose bug - if "isaacsim-fabric" in pair_key and any("local_translations_after_set" in k for k in pair_stats.keys()): - if not pair_stats.get("local_translations_after_set", {}).get("all_close", True): - print("\n ⚠️ Known Issue: Isaac Sim Fabric has a bug where get_local_poses() returns stale") - print(" values after set_local_poses(). Isaac Lab Fabric correctly returns updated values.") - print(" This is a correctness issue in Isaac Sim's implementation, not Isaac Lab's.") - else: - print(f" This may indicate implementation differences between {display_api1} and {display_api2}") - - print() +# ------------------------------------------------------------------ +# Reporting +# ------------------------------------------------------------------ def print_results(results_dict: dict[str, dict[str, float]], num_prims: int, num_iterations: int): - """Print benchmark results in a formatted table. - - Args: - results_dict: Dictionary mapping API names to their timing results. - num_prims: Number of prims tested. - num_iterations: Number of iterations run. - """ - print("\n" + "=" * 100) + """Print benchmark results in a formatted table.""" + print("\n" + "=" * 120) print(f"BENCHMARK RESULTS: {num_prims} prims, {num_iterations} iterations") - print("=" * 100) + print("=" * 120) api_names = list(results_dict.keys()) - # Format API names for display - display_names = [name.replace("-", " ").replace("_", " ").title() for name in api_names] - - # Calculate column width based on number of APIs - col_width = 20 + display_names = [name.replace("-", " ").title() for name in api_names] + col_width = 22 - # Print header - header = f"{'Operation':<25}" - for display_name in display_names: - header += f" {display_name + ' (ms)':<{col_width}}" + header = f"{'Operation':<28}" + for dn in display_names: + header += f" {dn + ' (ms)':>{col_width}}" print(header) - print("-" * 100) + print("-" * 120) - # Print each operation operations = [ ("Initialization", "init"), ("Get World Poses", "get_world_poses"), @@ -469,159 +274,119 @@ def print_results(results_dict: dict[str, dict[str, float]], num_prims: int, num ("Get Local Poses", "get_local_poses"), ("Set Local Poses", "set_local_poses"), ("Get Both (World+Local)", "get_both"), - ("Interleaved World Set→Get", "interleaved_world_set_get"), + ("Interleaved World Set->Get", "interleaved_world_set_get"), ] for op_name, op_key in operations: - row = f"{op_name:<25}" - for api_name in api_names: - api_time = results_dict[api_name].get(op_key, 0) * 1000 # Convert to ms - row += f" {api_time:>{col_width - 1}.4f}" + row = f"{op_name:<28}" + for name in api_names: + val = results_dict[name].get(op_key, 0) * 1000 + row += f" {val:>{col_width}.4f}" print(row) - print("=" * 100) + print("=" * 120) - # Calculate and print total time - total_row = f"{'Total Time':<25}" - for api_name in api_names: - total_time = sum(results_dict[api_name].values()) * 1000 - total_row += f" {total_time:>{col_width - 1}.4f}" + total_row = f"{'Total':<28}" + for name in api_names: + total_row += f" {sum(results_dict[name].values()) * 1000:>{col_width}.4f}" print(f"\n{total_row}") - # Calculate speedups relative to Isaac Lab USD (baseline) - if "isaaclab-usd" in api_names: - print("\n" + "=" * 100) - print("SPEEDUP vs Isaac Lab USD (Baseline)") - print("=" * 100) - print(f"{'Operation':<25}", end="") - for api_name, display_name in zip(api_names, display_names): - if api_name != "isaaclab-usd": - print(f" {display_name:<{col_width}}", end="") - print() - print("-" * 100) - - isaaclab_usd_results = results_dict["isaaclab-usd"] + baseline = "isaaclab-usd" + if baseline in results_dict and len(api_names) > 1: + print("\n" + "=" * 120) + print(f"SPEEDUP vs {baseline.replace('-', ' ').title()}") + print("=" * 120) + header = f"{'Operation':<28}" + for name in api_names: + if name != baseline: + header += f" {name.replace('-', ' ').title():>{col_width}}" + print(header) + print("-" * 120) + + base = results_dict[baseline] for op_name, op_key in operations: - print(f"{op_name:<25}", end="") - isaaclab_usd_time = isaaclab_usd_results.get(op_key, 0) - for api_name, display_name in zip(api_names, display_names): - if api_name != "isaaclab-usd": - api_time = results_dict[api_name].get(op_key, 0) - if isaaclab_usd_time > 0 and api_time > 0: - speedup = isaaclab_usd_time / api_time - print(f" {speedup:>{col_width - 1}.2f}x", end="") + row = f"{op_name:<28}" + base_t = base.get(op_key, 0) + for name in api_names: + if name != baseline: + impl_t = results_dict[name].get(op_key, 0) + if base_t > 0 and impl_t > 0: + row += f" {base_t / impl_t:>{col_width}.2f}x" else: - print(f" {'N/A':>{col_width}}", end="") - print() - - # Overall speedup - print("=" * 100) - print(f"{'Overall Speedup':<25}", end="") - total_isaaclab_usd = sum(isaaclab_usd_results.values()) - for api_name, display_name in zip(api_names, display_names): - if api_name != "isaaclab-usd": - total_api = sum(results_dict[api_name].values()) - if total_isaaclab_usd > 0 and total_api > 0: - overall_speedup = total_isaaclab_usd / total_api - print(f" {overall_speedup:>{col_width - 1}.2f}x", end="") + row += f" {'N/A':>{col_width}}" + print(row) + + print("=" * 120) + print(f"{'Overall':>28}", end="") + total_base = sum(base.values()) + for name in api_names: + if name != baseline: + total_impl = sum(results_dict[name].values()) + if total_base > 0 and total_impl > 0: + print(f" {total_base / total_impl:>{col_width}.2f}x", end="") else: print(f" {'N/A':>{col_width}}", end="") print() - print("\n" + "=" * 100) + print("\n" + "=" * 120) print("\nNotes:") print(" - Times are averaged over all iterations") - print(" - Speedup = (Isaac Lab USD time) / (Other API time)") - print(" - Speedup > 1.0 means the other API is faster than Isaac Lab USD") - print(" - Speedup < 1.0 means the other API is slower than Isaac Lab USD") + print(" - Speedup > 1.0 means faster than USD baseline") print() def main(): - """Main benchmark function.""" - print("=" * 100) - print("XformPrimView Benchmark - Comparing Multiple APIs") - print("=" * 100) - print("Configuration:") - print(f" Number of environments: {args_cli.num_envs}") - print(f" Iterations per test: {args_cli.num_iterations}") - print(f" Device: {args_cli.device}") - print(f" Profiling: {'Enabled' if args_cli.profile else 'Disabled'}") - if args_cli.profile: - print(f" Profile directory: {args_cli.profile_dir}") + print("=" * 120) + print("FrameView Benchmark") + print("=" * 120) + print(f" Environments: {args_cli.num_envs}") + print(f" Iterations: {args_cli.num_iterations}") + print(f" Device: {args_cli.device}") print() - # Create profile directory if profiling is enabled if args_cli.profile: import os os.makedirs(args_cli.profile_dir, exist_ok=True) - # Dictionary to store all results - all_timing_results = {} - all_computed_results = {} + all_timing = {} + all_computed = {} profile_files = {} - # APIs to benchmark - apis_to_test = [ - ("isaaclab-usd", "Isaac Lab XformPrimView (USD)"), - ("isaaclab-fabric", "Isaac Lab XformPrimView (Fabric)"), - ("isaacsim-usd", "Isaac Sim XformPrimView (USD)"), - ("isaacsim-fabric", "Isaac Sim XformPrimView (Fabric)"), - ("isaacsim-exp", "Isaac Sim Experimental XformPrim"), + apis = [ + ("isaaclab-usd", "Isaac Lab FrameView (USD)"), + ("isaaclab-fabric", "Isaac Lab FrameView (Fabric)"), + ("isaaclab-newton-site", "Isaac Lab FrameView (Newton Site)"), ] - # Benchmark each API - for api_key, api_name in apis_to_test: + for api_key, api_name in apis: print(f"Benchmarking {api_name}...") if args_cli.profile: profiler = cProfile.Profile() profiler.enable() - # Cast api_key to Literal type for type checker - timing, computed = benchmark_xform_prim_view( - api=api_key, # type: ignore[arg-type] - num_iterations=args_cli.num_iterations, - ) + timing, computed = benchmark_frame_view(api=api_key, num_iterations=args_cli.num_iterations) if args_cli.profile: profiler.disable() - profile_file = f"{args_cli.profile_dir}/{api_key.replace('-', '_')}_benchmark.prof" - profiler.dump_stats(profile_file) - profile_files[api_key] = profile_file - print(f" Profile saved to: {profile_file}") - - all_timing_results[api_key] = timing - all_computed_results[api_key] = computed - - print(" Done!") - print() + pf = f"{args_cli.profile_dir}/{api_key.replace('-', '_')}_benchmark.prof" + profiler.dump_stats(pf) + profile_files[api_key] = pf + print(f" Profile saved to: {pf}") - # Print timing results - print_results(all_timing_results, args_cli.num_envs, args_cli.num_iterations) + all_timing[api_key] = timing + all_computed[api_key] = computed + print(" Done!\n") - # Compare computed results - print("\nComparing computed results across APIs...") - comparison_stats = compare_results(all_computed_results, tolerance=1e-6) - print_comparison_results(comparison_stats, tolerance=1e-4) + print_results(all_timing, args_cli.num_envs, args_cli.num_iterations) - # Print profiling instructions if enabled if args_cli.profile: - print("\n" + "=" * 100) - print("PROFILING RESULTS") - print("=" * 100) - print("Profile files have been saved. To visualize with snakeviz, run:") - for api_key, profile_file in profile_files.items(): - api_display = api_key.replace("-", " ").title() - print(f" # {api_display}") - print(f" snakeviz {profile_file}") - print("\nAlternatively, use pstats to analyze in terminal:") - print(" python -m pstats ") - print("=" * 100) + print("\nProfile files:") + for key, pf in profile_files.items(): + print(f" snakeviz {pf}") print() - # Clean up sim_utils.SimulationContext.clear_instance() diff --git a/scripts/benchmarks/early_stop.py b/scripts/benchmarks/early_stop.py new file mode 100644 index 000000000000..38dabe3b67cd --- /dev/null +++ b/scripts/benchmarks/early_stop.py @@ -0,0 +1,321 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Early stopping for benchmark training based on a success metric. + +Framework-specific implementations that monitor a metric from ``extras["log"]`` +and stop training when it stabilizes above a threshold: + +- **rsl_rl**: ``env.step`` wrapper + exception (no callback API in rsl_rl). +- **rl_games**: ``AlgoObserver`` subclass, sets ``max_epochs`` for clean exit. +""" + +from __future__ import annotations + +import argparse +import os +import statistics +from typing import TYPE_CHECKING + +from scripts.benchmarks.utils import get_success_rate_log + +if TYPE_CHECKING: + from rl_games.common.algo_observer import AlgoObserver + from rsl_rl.runners import OnPolicyRunner + + from isaaclab_rl.rsl_rl import RslRlVecEnvWrapper + +DEFAULT_SUCCESS_THRESHOLD = 0.3 +DEFAULT_SUCCESS_WINDOW = 20 + + +class EarlyStopConverged(Exception): + """Raised by :class:`RslRlEarlyStopWrapper` when the metric has converged.""" + + +class SuccessRateTracker: + """Accumulates a per-iteration success-rate metric and checks trailing-window convergence. + + Args: + threshold: Minimum value to consider a pass. + window: Consecutive iterations above *threshold* to trigger convergence. + num_steps_per_env: Steps per RL iteration (for boundary detection). + """ + + def __init__(self, threshold: float, window: int, num_steps_per_env: int): + self.threshold = threshold + self.window = window + self.num_steps_per_env = num_steps_per_env + + self.history: list[float] = [] + self._step_count = 0 + self._iter_sum = 0.0 + self._iter_count = 0 + + def record_step(self, extras: dict) -> None: + """Record one env step.""" + val = get_success_rate_log(extras.get("log", {})) + if val is not None: + self._iter_sum += val.item() if hasattr(val, "item") else float(val) + self._iter_count += 1 + self._step_count += 1 + + def end_iteration(self) -> float | None: + """Finalize the current iteration. Returns mean metric, or ``None`` if no data.""" + if self._iter_count == 0: + return None + mean = self._iter_sum / self._iter_count + self.history.append(mean) + self._iter_sum = 0.0 + self._iter_count = 0 + return mean + + @property + def at_iteration_boundary(self) -> bool: + """Whether the tracker has seen exactly a full iteration's worth of steps. + + Assumes :meth:`record_step` is called exactly once per env step. This holds for + all current framework integrations (rsl_rl's patched ``env.step`` and rl_games' + ``AlgoObserver.process_infos``) — both pair a single step with a single record. + Integrations that call :meth:`record_step` more or fewer times per env step will + break iteration accounting. + """ + return self.num_steps_per_env > 0 and self._step_count % self.num_steps_per_env == 0 + + @property + def converged(self) -> bool: + if len(self.history) < self.window: + return False + return all(v >= self.threshold for v in self.history[-self.window :]) + + @property + def current_iteration(self) -> int: + return len(self.history) + + @property + def tail_mean(self) -> float: + if not self.history: + return 0.0 + tail = self.history[-self.window :] if len(self.history) >= self.window else self.history + return statistics.mean(tail) + + +class RslRlEarlyStopWrapper: + """Context manager that wraps ``env.step`` to track a success metric during rsl_rl training. + + Always records the metric into :attr:`tracker` so the caller can log the tail mean / converged-at + iteration regardless of whether early stopping is enabled. When ``stop_on_convergence=True``, the + wrapper also raises :class:`EarlyStopConverged` on the first iteration where the trailing window + is above threshold, performs runner cleanup (checkpoint save + logger flush), and suppresses the + exception so the caller sees a normal return from :meth:`rsl_rl.runners.OnPolicyRunner.learn`. + + Args: + env: ``RslRlVecEnvWrapper`` instance. + runner: ``OnPolicyRunner`` instance. + threshold: Minimum metric value to pass. + window: Consecutive iterations above threshold to trigger stop. + num_steps_per_env: Steps per RL iteration. + stop_on_convergence: If ``True``, raise :class:`EarlyStopConverged` when the metric converges. + If ``False``, only track the metric without interrupting training. + """ + + def __init__( + self, + env: RslRlVecEnvWrapper, + runner: OnPolicyRunner, + threshold: float, + window: int, + num_steps_per_env: int, + stop_on_convergence: bool = True, + ): + self.env = env + self.runner = runner + self.tracker = SuccessRateTracker(threshold, window, num_steps_per_env) + self.stop_on_convergence = stop_on_convergence + self._orig_step = env.step + + def __enter__(self): + self.env.step = self._step + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + self.env.step = self._orig_step + if exc_type is EarlyStopConverged: + self._runner_cleanup() + print( + f"[INFO] Early stop: success rate converged at iteration " + f"{self.tracker.current_iteration} (tail mean {self.tracker.tail_mean:.4f})" + ) + return True + return False + + def _step(self, actions): + result = self._orig_step(actions) + self.tracker.record_step(result[3]) # rsl_rl: (obs, rew, dones, extras) + if self.tracker.at_iteration_boundary: + self.tracker.end_iteration() + if self.stop_on_convergence and self.tracker.converged: + # relies on rsl_rl's rollout loop not catching arbitrary exceptions; if upstream + # ever wraps env.step in a broad except, this exception will be swallowed + raise EarlyStopConverged() + return result + + def _runner_cleanup(self): + """Save final checkpoint and flush the TensorBoard writer.""" + if self.runner.logger.writer is not None: + it = self.runner.current_learning_iteration + self.runner.save(os.path.join(self.runner.logger.log_dir, f"model_{it}.pt")) + self.runner.logger.stop_logging_writer() + + @property + def framework_iteration_count(self) -> int: + """Number of training iterations the rsl_rl runner has recorded as completed. + + Note: ``current_learning_iteration`` is set AFTER rollout + policy update, so mid-rollout + (including the instant our early-stop exception fires) this counter lags :attr:`tracker` + by 1 iteration. + """ + return self.runner.current_learning_iteration + 1 + + +class RlGamesEarlyStopObserver: + """``AlgoObserver`` that tracks a success metric during rl_games training. + + Always records the metric into :attr:`tracker` so the caller can log the tail mean / converged-at + iteration regardless of whether early stopping is enabled. When ``stop_on_convergence=True``, the + observer also sets ``algo.max_epochs`` on the first iteration where the trailing window is above + threshold, which forces a clean exit from :meth:`rl_games.torch_runner.Runner.run`. All other + observer calls are delegated to *base_observer*. + + Args: + base_observer: Original ``AlgoObserver`` to delegate to. + threshold: Minimum metric value to pass. + window: Consecutive iterations above threshold to trigger stop. + stop_on_convergence: If ``True``, set ``algo.max_epochs`` when the metric converges. + If ``False``, only track the metric without interrupting training. + """ + + def __init__( + self, + base_observer: AlgoObserver, + threshold: float, + window: int, + stop_on_convergence: bool = True, + ): + self._base = base_observer + self.threshold = threshold + self.window = window + self.stop_on_convergence = stop_on_convergence + self.algo = None + self.tracker: SuccessRateTracker | None = None + + def before_init(self, base_name, config, experiment_name): + self._base.before_init(base_name, config, experiment_name) + + def after_init(self, algo): + self._base.after_init(algo) + self.algo = algo + num_steps = getattr(algo, "horizon_length", algo.config.get("horizon_length", 16)) + self.tracker = SuccessRateTracker(self.threshold, self.window, num_steps) + + def process_infos(self, infos, done_indices): + self._base.process_infos(infos, done_indices) + if self.tracker is not None and isinstance(infos, dict) and "episode" in infos: + # rl_games remaps extras["log"] → extras["episode"] + self.tracker.record_step({"log": infos["episode"]}) + + def after_steps(self): + self._base.after_steps() + if self.tracker is None: + return + self.tracker.end_iteration() + if self.stop_on_convergence and self.tracker.converged and self.algo is not None: + print( + f"[INFO] Early stop: success rate converged at iteration " + f"{self.tracker.current_iteration} (tail mean {self.tracker.tail_mean:.4f})" + ) + self.algo.max_epochs = self.tracker.current_iteration + + def after_clear_stats(self): + self._base.after_clear_stats() + + def after_print_stats(self, frame, epoch_num, total_time): + self._base.after_print_stats(frame, epoch_num, total_time) + + @property + def framework_iteration_count(self) -> int | None: + """Number of training iterations the rl_games algo has recorded. + + rl_games increments ``algo.epoch_num`` at the start of each iteration, so after iter N + completes this value equals N (matching :attr:`tracker`'s count exactly). Returns + ``None`` before :meth:`after_init` has attached to an algo. + """ + return None if self.algo is None else self.algo.epoch_num + + +def add_success_cli_args(parser: argparse.ArgumentParser) -> None: + """Register the success-metric CLI args on *parser*. + + Adds ``--check_success``, ``--success_threshold``, and ``--success_window``. Use + :func:`build_success_kwargs` to resolve the parsed values into a kwargs dict for + the wrapper constructors. + """ + parser.add_argument( + "--check_success", action="store_true", help="Early-stop when the normalized success metric converges." + ) + parser.add_argument( + "--success_threshold", + type=float, + default=None, + help=f"Override the success threshold (default: {DEFAULT_SUCCESS_THRESHOLD}).", + ) + parser.add_argument( + "--success_window", + type=int, + default=None, + help=f"Override the convergence window (default: {DEFAULT_SUCCESS_WINDOW}).", + ) + + +def build_success_kwargs(args_cli: argparse.Namespace) -> dict: + """Resolve success-metric CLI args into kwargs for the wrapper constructors. + + Returns a dict with ``threshold``, ``window``, and ``stop_on_convergence``, suitable + to splat into :class:`RslRlEarlyStopWrapper` or :class:`RlGamesEarlyStopObserver`. + """ + return { + "threshold": ( + args_cli.success_threshold if args_cli.success_threshold is not None else DEFAULT_SUCCESS_THRESHOLD + ), + "window": args_cli.success_window if args_cli.success_window is not None else DEFAULT_SUCCESS_WINDOW, + "stop_on_convergence": args_cli.check_success, + } + + +def get_success_tracker( + args_cli: argparse.Namespace, + live_tracker: SuccessRateTracker | None, + log_data: dict[str, list[float]], +) -> SuccessRateTracker | None: + """Return a tracker with recorded history, or ``None`` if neither source has data. + + Prefers *live_tracker* (from the training wrapper/observer). If it never ran or recorded + no iterations, falls back to building a post-hoc tracker by replaying the success metric + series out of TensorBoard *log_data* (from :func:`scripts.benchmarks.utils.parse_tf_logs`). + + Args: + args_cli: Parsed arg namespace with the ``--success_*`` flags. + live_tracker: Tracker attached to the early-stop wrapper/observer (or ``None``). + log_data: Mapping of TB tag -> list of scalars for the current run. + """ + if live_tracker is not None and live_tracker.history: + return live_tracker + history = get_success_rate_log(log_data) + if not history: + return None + kwargs = build_success_kwargs(args_cli) + tracker = SuccessRateTracker(kwargs["threshold"], kwargs["window"], num_steps_per_env=0) + tracker.history = list(history) + return tracker diff --git a/scripts/benchmarks/nsys_trace.json b/scripts/benchmarks/nsys_trace.json new file mode 100644 index 000000000000..0d04fd1b8546 --- /dev/null +++ b/scripts/benchmarks/nsys_trace.json @@ -0,0 +1,166 @@ +[ + { + "_comment": "=== PYTHON IMPORTS (tracks module loading) ===", + "domain": "Python-Imports", + "color": "0x9E9E9E", + "module": "importlib", + "functions": ["import_module"] + }, + { + "domain": "Python-Imports", + "color": "0x9E9E9E", + "module": "importlib._bootstrap", + "functions": ["_find_and_load", "_load_unlocked"] + }, + { + "_comment": "=== WARP (verified working) ===", + "domain": "Warp", + "color": "0xF44336", + "module": "warp", + "functions": ["launch", "synchronize", "copy", "zeros", "empty"] + }, + { + "_comment": "=== PYTORCH (verified working) ===", + "domain": "PyTorch", + "color": "0x3F51B5", + "module": "torch.autograd", + "functions": ["backward"] + }, + { + "_comment": "=== USD (verified working) ===", + "domain": "USD", + "color": "0x795548", + "module": "pxr.UsdGeom", + "functions": ["Xform", "Mesh", "Sphere", "Cube"] + }, + { + "_comment": "=== ISAACLAB ENVIRONMENTS ===", + "domain": "IsaacLab-Env", + "color": "0x9C27B0", + "module": "isaaclab.envs.manager_based_rl_env", + "functions": [ + {"function": "ManagerBasedRLEnv.__init__", "color": "0x9C27B0"}, + {"function": "ManagerBasedRLEnv.step", "color": "0xAB47BC"} + ] + }, + { + "domain": "IsaacLab-Env", + "color": "0x9C27B0", + "module": "isaaclab.envs.manager_based_env", + "functions": [ + {"function": "ManagerBasedEnv.__init__", "color": "0x9C27B0"}, + {"function": "ManagerBasedEnv.step", "color": "0xAB47BC"}, + {"function": "ManagerBasedEnv.reset", "color": "0xBA68C8"}, + {"function": "ManagerBasedEnv._reset_idx", "color": "0xCE93D8"} + ] + }, + { + "_comment": "=== ISAACLAB SIMULATION ===", + "domain": "IsaacLab-Sim", + "color": "0x4CAF50", + "module": "isaaclab.sim.simulation_context", + "functions": [ + {"function": "SimulationContext.__init__", "color": "0x4CAF50"}, + {"function": "SimulationContext.reset", "color": "0x66BB6A"}, + {"function": "SimulationContext.step", "color": "0x81C784"} + ] + }, + { + "_comment": "=== ISAACLAB SCENE ===", + "domain": "IsaacLab-Scene", + "color": "0x2196F3", + "module": "isaaclab.scene.interactive_scene", + "functions": [ + {"function": "InteractiveScene.__init__", "color": "0x2196F3"}, + {"function": "InteractiveScene.reset", "color": "0x42A5F5"}, + {"function": "InteractiveScene.write_data_to_sim", "color": "0x64B5F6"}, + {"function": "InteractiveScene.update", "color": "0x90CAF9"} + ] + }, + { + "_comment": "=== ISAACLAB MANAGERS ===", + "domain": "IsaacLab-Managers", + "color": "0xFF9800", + "module": "isaaclab.managers.observation_manager", + "functions": [ + {"function": "ObservationManager.__init__", "color": "0xFF9800"}, + {"function": "ObservationManager.reset", "color": "0xFFA726"}, + {"function": "ObservationManager.compute", "color": "0xFFB74D"} + ] + }, + { + "domain": "IsaacLab-Managers", + "color": "0xFF9800", + "module": "isaaclab.managers.action_manager", + "functions": [ + {"function": "ActionManager.__init__", "color": "0xFF9800"}, + {"function": "ActionManager.reset", "color": "0xFFA726"}, + {"function": "ActionManager.process_action", "color": "0xFFB74D"}, + {"function": "ActionManager.apply_action", "color": "0xFFCC80"} + ] + }, + { + "domain": "IsaacLab-Managers", + "color": "0xFF9800", + "module": "isaaclab.managers.reward_manager", + "functions": [ + {"function": "RewardManager.__init__", "color": "0xFF9800"}, + {"function": "RewardManager.reset", "color": "0xFFA726"}, + {"function": "RewardManager.compute", "color": "0xFFB74D"} + ] + }, + { + "_comment": "=== ISAACLAB ASSETS ===", + "domain": "IsaacLab-Assets", + "color": "0x607D8B", + "module": "isaaclab.assets.articulation.articulation", + "functions": [ + {"function": "Articulation.__init__", "color": "0x607D8B"}, + {"function": "Articulation.reset", "color": "0x78909C"}, + {"function": "Articulation.write_data_to_sim", "color": "0x90A4AE"}, + {"function": "Articulation.update", "color": "0xB0BEC5"} + ] + }, + { + "_comment": "=== ISAACLAB SENSORS ===", + "domain": "IsaacLab-Sensors", + "color": "0x00BCD4", + "module": "isaaclab.sensors.camera.camera", + "functions": [ + {"function": "Camera.__init__", "color": "0x00BCD4"}, + {"function": "Camera.reset", "color": "0x26C6DA"}, + {"function": "Camera.update", "color": "0x4DD0E1"} + ] + }, + { + "_comment": "=== RSL-RL ===", + "domain": "RSL-RL", + "color": "0x673AB7", + "module": "rsl_rl.runners.on_policy_runner", + "functions": [ + {"function": "OnPolicyRunner.__init__", "color": "0x673AB7"}, + {"function": "OnPolicyRunner.learn", "color": "0x7E57C2"} + ] + }, + { + "domain": "RSL-RL", + "color": "0x673AB7", + "module": "rsl_rl.algorithms.ppo", + "functions": [ + {"function": "PPO.__init__", "color": "0x673AB7"}, + {"function": "PPO.act", "color": "0x7E57C2"}, + {"function": "PPO.update", "color": "0x9575CD"} + ] + }, + { + "_comment": "=== NEWTON WARP RENDERER ===", + "domain": "NewtonWarpRenderer", + "color": "0xE91E63", + "module": "isaaclab_newton.renderers.newton_warp_renderer", + "functions": [ + {"function": "NewtonWarpRenderer.update_transforms", "color": "0x2196F3"}, + {"function": "NewtonWarpRenderer.render", "color": "0x4CAF50"}, + {"function": "NewtonWarpRenderer.read_output", "color": "0xFF9800"} + ] + } +] diff --git a/scripts/benchmarks/startup_whitelist.yaml b/scripts/benchmarks/startup_whitelist.yaml new file mode 100644 index 000000000000..121718d36b40 --- /dev/null +++ b/scripts/benchmarks/startup_whitelist.yaml @@ -0,0 +1,25 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +app_launch: + - "isaaclab.utils.configclass:_wrap_resolvable_strings" + - "isaaclab.utils.configclass:_custom_post_init" + - "isaaclab.utils.configclass:_field_module_dir" + +env_creation: + - "isaaclab.cloner.*:usd_replicate" + - "isaaclab.cloner.*:filter_collisions" + - "isaaclab_physx.cloner.*:attach_end_fn" + - "isaaclab.scene.*:_init_scene" + - "isaaclab.envs.mdp.observations:*" + - "isaaclab.utils.assets:_find_usd_dependencies" + +first_step: + - "isaaclab.envs.mdp.rewards:*" + - "isaaclab.envs.mdp.terminations:*" + - "isaaclab.envs.mdp.observations:*" + - "isaaclab.actuators.*:compute" + - "warp.*:launch" + - "warp.*:to_torch" diff --git a/scripts/benchmarks/test/test_early_stop.py b/scripts/benchmarks/test/test_early_stop.py new file mode 100644 index 000000000000..b11231481da3 --- /dev/null +++ b/scripts/benchmarks/test/test_early_stop.py @@ -0,0 +1,706 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Unit tests for the benchmark success-metric early-stopping helpers.""" + +from __future__ import annotations + +import argparse + +import pytest + +from scripts.benchmarks.early_stop import ( + DEFAULT_SUCCESS_THRESHOLD, + DEFAULT_SUCCESS_WINDOW, + RlGamesEarlyStopObserver, + RslRlEarlyStopWrapper, + SuccessRateTracker, + add_success_cli_args, + build_success_kwargs, + get_success_tracker, +) +from scripts.benchmarks.utils import SUCCESS_RATE_LOG_TAGS, log_success + +DEFAULT_SUCCESS_TAG = SUCCESS_RATE_LOG_TAGS[0] + +# -- fakes ------------------------------------------------------------------ + + +class _FakeTensor: + """Stand-in for ``torch.Tensor`` with only the ``.item()`` path exercised.""" + + def __init__(self, value: float): + self._value = value + + def item(self) -> float: + return self._value + + +class _FakeBenchmark: + def __init__(self): + self.measurements: list[tuple[str, str, object, str]] = [] + + def add_measurement(self, phase, measurement): + self.measurements.append((phase, measurement.name, measurement.value, measurement.unit)) + + def by_name(self, name: str): + return next(m for m in self.measurements if m[1] == name) + + +class _FakeLogger: + def __init__(self, has_writer: bool = True): + self.writer = object() if has_writer else None + self.log_dir = "/tmp/fake_log_dir" + self.stopped = False + + def stop_logging_writer(self): + self.stopped = True + + +class _FakeRunner: + def __init__(self, has_writer: bool = True): + self.logger = _FakeLogger(has_writer=has_writer) + self.current_learning_iteration = 7 + self.saved: list[str] = [] + + def save(self, path: str): + self.saved.append(path) + + +class _FakeEnv: + def __init__(self, extras_sequence): + self._seq = list(extras_sequence) + self.step_calls = 0 + + def step(self, actions): + extras = self._seq[self.step_calls] if self.step_calls < len(self._seq) else self._seq[-1] + self.step_calls += 1 + return (None, None, None, extras) + + +class _FakeBaseObserver: + def __init__(self): + self.calls: list[str] = [] + + def before_init(self, base_name, config, experiment_name): + self.calls.append("before_init") + + def after_init(self, algo): + self.calls.append("after_init") + + def process_infos(self, infos, done_indices): + self.calls.append("process_infos") + + def after_steps(self): + self.calls.append("after_steps") + + def after_clear_stats(self): + self.calls.append("after_clear_stats") + + def after_print_stats(self, frame, epoch_num, total_time): + self.calls.append("after_print_stats") + + +class _FakeAlgo: + def __init__(self, horizon_length: int | None = None, config_horizon: int | None = 16, epoch_num: int = 0): + self.max_epochs = 999 + self.epoch_num = epoch_num + if horizon_length is not None: + self.horizon_length = horizon_length + self.config = {"horizon_length": config_horizon} if config_horizon is not None else {} + + +def _parser() -> argparse.ArgumentParser: + p = argparse.ArgumentParser() + add_success_cli_args(p) + return p + + +# -- SuccessRateTracker ----------------------------------------------------- + + +class TestSuccessRateTracker: + """Test cases for the per-iteration metric accumulator and convergence check.""" + + def test_records_metric_from_extras_log(self): + """Test that a present metric is accumulated into the iteration sum.""" + t = SuccessRateTracker(0.5, 3, num_steps_per_env=4) + t.record_step({"log": {DEFAULT_SUCCESS_TAG: 0.9}}) + assert t._iter_sum == pytest.approx(0.9) + assert t._iter_count == 1 + + def test_ignores_missing_metric_key(self): + """Test that a foreign key in extras["log"] is ignored.""" + t = SuccessRateTracker(0.5, 3, num_steps_per_env=4) + t.record_step({"log": {"other": 1.0}}) + assert t._iter_count == 0 + + def test_missing_log_subdict_does_not_raise(self): + """Test that an extras dict without a "log" sub-dict is handled gracefully.""" + t = SuccessRateTracker(0.5, 3, num_steps_per_env=4) + t.record_step({}) + assert t._iter_count == 0 + assert t._step_count == 1 + + def test_tensor_value_uses_item_method(self): + """Test that tensor-like values are extracted via ``.item()``.""" + t = SuccessRateTracker(0.5, 3, num_steps_per_env=4) + t.record_step({"log": {DEFAULT_SUCCESS_TAG: _FakeTensor(0.7)}}) + assert t._iter_sum == pytest.approx(0.7) + + def test_step_count_increments_even_without_metric(self): + """Test that ``_step_count`` tracks every call regardless of metric presence.""" + t = SuccessRateTracker(0.5, 3, num_steps_per_env=4) + t.record_step({}) + t.record_step({"log": {"other": 1.0}}) + assert t._step_count == 2 + assert t._iter_count == 0 + + def test_end_iteration_averages_and_resets(self): + """Test that ``end_iteration`` averages recorded values and resets counters.""" + t = SuccessRateTracker(0.5, 3, num_steps_per_env=4) + t.record_step({"log": {DEFAULT_SUCCESS_TAG: 0.4}}) + t.record_step({"log": {DEFAULT_SUCCESS_TAG: 0.6}}) + assert t.end_iteration() == pytest.approx(0.5) + assert t.history == [pytest.approx(0.5)] + assert t._iter_sum == 0.0 + assert t._iter_count == 0 + + def test_end_iteration_no_data_returns_none_without_recording(self): + """Test that ``end_iteration`` returns None and skips history append when no data was seen.""" + t = SuccessRateTracker(0.5, 3, num_steps_per_env=4) + assert t.end_iteration() is None + assert t.history == [] + + def test_at_iteration_boundary_respects_num_steps_per_env(self): + """Test that the boundary flag fires only after exactly ``num_steps_per_env`` calls.""" + t = SuccessRateTracker(0.5, 3, num_steps_per_env=4) + for _ in range(3): + t.record_step({"log": {DEFAULT_SUCCESS_TAG: 0.1}}) + assert t.at_iteration_boundary is False + t.record_step({"log": {DEFAULT_SUCCESS_TAG: 0.1}}) + assert t.at_iteration_boundary is True + + def test_at_iteration_boundary_false_when_num_steps_zero(self): + """Test that a post-hoc tracker (``num_steps_per_env=0``) never reports a boundary.""" + t = SuccessRateTracker(0.5, 3, num_steps_per_env=0) + t.record_step({"log": {DEFAULT_SUCCESS_TAG: 0.1}}) + assert t.at_iteration_boundary is False + + def test_not_converged_when_history_shorter_than_window(self): + """Test that convergence is False when there aren't yet enough history entries.""" + t = SuccessRateTracker(0.5, 3, num_steps_per_env=4) + t.history = [0.9, 0.9] + assert t.converged is False + + def test_not_converged_when_history_empty(self): + """Test that convergence is False on a freshly-created tracker.""" + t = SuccessRateTracker(0.5, 3, num_steps_per_env=4) + assert t.history == [] + assert t.converged is False + + def test_converged_when_window_all_above_threshold(self): + """Test that convergence is True when the trailing window is all above threshold.""" + t = SuccessRateTracker(0.5, 3, num_steps_per_env=4) + t.history = [0.1, 0.9, 0.9, 0.9] + assert t.converged is True + + def test_converged_when_history_length_equals_window(self): + """Test the window boundary: history length == window (minimum qualifying case).""" + t = SuccessRateTracker(0.5, 3, num_steps_per_env=4) + t.history = [0.9, 0.9, 0.9] + assert t.converged is True + + def test_converged_at_exact_threshold(self): + """Test the threshold boundary: values equal to the threshold satisfy ``>= threshold``.""" + t = SuccessRateTracker(0.5, 3, num_steps_per_env=4) + t.history = [0.5, 0.5, 0.5] + assert t.converged is True + + def test_not_converged_when_any_window_value_below(self): + """Test that a single sub-threshold value in the trailing window blocks convergence.""" + t = SuccessRateTracker(0.5, 3, num_steps_per_env=4) + t.history = [0.9, 0.9, 0.4] + assert t.converged is False + + def test_converged_with_window_of_one(self): + """Test the degenerate ``window=1`` case: only the last value matters.""" + t = SuccessRateTracker(0.5, 1, num_steps_per_env=4) + t.history = [0.1, 0.2, 0.9] + assert t.converged is True + t.history = [0.9, 0.9, 0.1] + assert t.converged is False + + def test_tail_mean_empty_history_is_zero(self): + """Test that ``tail_mean`` returns 0.0 for an empty history.""" + t = SuccessRateTracker(0.5, 3, num_steps_per_env=4) + assert t.tail_mean == 0.0 + + def test_tail_mean_shorter_than_window_uses_all_values(self): + """Test that ``tail_mean`` averages the full history when it's shorter than the window.""" + t = SuccessRateTracker(0.5, 3, num_steps_per_env=4) + t.history = [0.2, 0.4] + assert t.tail_mean == pytest.approx(0.3) + + def test_tail_mean_longer_than_window_uses_tail(self): + """Test that ``tail_mean`` averages only the last ``window`` entries.""" + t = SuccessRateTracker(0.5, 3, num_steps_per_env=4) + t.history = [0.9, 0.9, 0.1, 0.2, 0.3] + assert t.tail_mean == pytest.approx(0.2) + + def test_current_iteration_equals_history_length(self): + """Test that ``current_iteration`` reports the history length.""" + t = SuccessRateTracker(0.5, 3, num_steps_per_env=4) + t.history = [0.1, 0.2, 0.3] + assert t.current_iteration == 3 + + +# -- CLI helpers ------------------------------------------------------------ + + +class TestCliHelpers: + """Test cases for the ``--success_*`` CLI registration and kwargs resolution.""" + + def test_defaults_parse_to_none_and_false(self): + """Test that unset args resolve to None / False.""" + args = _parser().parse_args([]) + assert args.check_success is False + assert args.success_threshold is None + assert args.success_window is None + + def test_overrides_parse(self): + """Test that explicit ``--success_*`` values round-trip through argparse.""" + args = _parser().parse_args( + [ + "--check_success", + "--success_threshold", + "0.75", + "--success_window", + "50", + ] + ) + assert args.check_success is True + assert args.success_threshold == 0.75 + assert args.success_window == 50 + + def test_build_success_kwargs_uses_defaults_when_unset(self): + """Test that ``build_success_kwargs`` substitutes library defaults for unset args.""" + kwargs = build_success_kwargs(_parser().parse_args([])) + assert kwargs == { + "threshold": DEFAULT_SUCCESS_THRESHOLD, + "window": DEFAULT_SUCCESS_WINDOW, + "stop_on_convergence": False, + } + + def test_build_success_kwargs_applies_overrides(self): + """Test that CLI overrides flow through into the kwargs dict.""" + args = _parser().parse_args( + [ + "--check_success", + "--success_threshold", + "0.1", + "--success_window", + "5", + ] + ) + kwargs = build_success_kwargs(args) + assert kwargs["threshold"] == pytest.approx(0.1) + assert kwargs["window"] == 5 + assert kwargs["stop_on_convergence"] is True + + def test_zero_threshold_is_respected_not_treated_as_unset(self): + """Test that ``--success_threshold 0`` is preserved (``is not None`` check, not truthy).""" + args = _parser().parse_args(["--success_threshold", "0"]) + assert build_success_kwargs(args)["threshold"] == 0.0 + + +# -- get_success_tracker ---------------------------------------------------- + + +class TestGetSuccessTracker: + """Test cases for the live-vs-post-hoc tracker resolution helper.""" + + def test_prefers_live_tracker_with_history(self): + """Test that a non-empty live tracker is returned as-is.""" + live = SuccessRateTracker(0.5, 3, num_steps_per_env=4) + live.history = [0.9, 0.9] + assert get_success_tracker(_parser().parse_args([]), live, {}) is live + + def test_falls_back_to_post_hoc_when_live_tracker_empty(self): + """Test that an empty live tracker falls back to TensorBoard replay.""" + live = SuccessRateTracker(0.5, 3, num_steps_per_env=4) + log_data = {DEFAULT_SUCCESS_TAG: [0.1, 0.2, 0.3]} + result = get_success_tracker(_parser().parse_args([]), live, log_data) + assert result is not live + assert result.history == [pytest.approx(0.1), pytest.approx(0.2), pytest.approx(0.3)] + + def test_falls_back_to_post_hoc_when_live_tracker_none(self): + """Test that a missing live tracker falls back to TensorBoard replay.""" + log_data = {DEFAULT_SUCCESS_TAG: [0.5, 0.6, 0.7]} + result = get_success_tracker(_parser().parse_args([]), None, log_data) + assert result is not None + assert result.history == [pytest.approx(0.5), pytest.approx(0.6), pytest.approx(0.7)] + + def test_returns_none_when_no_data_anywhere(self): + """Test that both sources missing resolves to ``None``.""" + assert get_success_tracker(_parser().parse_args([]), None, {}) is None + + def test_returns_none_when_tag_absent_from_log_data(self): + """Test that unrelated TensorBoard tags don't satisfy the fallback.""" + assert get_success_tracker(_parser().parse_args([]), None, {"Metrics/other": [1.0]}) is None + + def test_post_hoc_honors_override_threshold_and_window(self): + """Test that CLI threshold/window overrides are applied to the post-hoc tracker.""" + args = _parser().parse_args(["--success_threshold", "0.2", "--success_window", "2"]) + log_data = {DEFAULT_SUCCESS_TAG: [0.3, 0.3]} + result = get_success_tracker(args, None, log_data) + assert result.threshold == pytest.approx(0.2) + assert result.window == 2 + assert result.converged is True + + def test_post_hoc_tracker_has_no_iteration_boundary(self): + """Test that post-hoc trackers use ``num_steps_per_env=0`` so ``at_iteration_boundary`` never fires.""" + result = get_success_tracker(_parser().parse_args([]), None, {DEFAULT_SUCCESS_TAG: [0.9]}) + assert result.num_steps_per_env == 0 + assert result.at_iteration_boundary is False + + +# -- RslRlEarlyStopWrapper -------------------------------------------------- + + +class TestRslRlEarlyStopWrapper: + """Test cases for the rsl_rl env.step monkey-patch context manager.""" + + def test_records_every_step_and_restores_on_exit(self): + """Test that wrapped env.step records, and original step is restored on normal exit.""" + env = _FakeEnv([{"log": {DEFAULT_SUCCESS_TAG: 0.9}}] * 5) + runner = _FakeRunner() + with RslRlEarlyStopWrapper(env, runner, 0.5, 3, num_steps_per_env=2) as ctx: + env.step(None) + assert ctx.tracker._iter_sum == pytest.approx(0.9) + # after exit, env.step no longer routes through the tracker + env.step(None) + assert ctx.tracker._iter_sum == pytest.approx(0.9) + assert env.step_calls == 2 + + def test_raises_and_cleans_up_on_convergence_by_default(self): + """Test that convergence triggers cleanup (checkpoint + flush) and suppresses the exception.""" + env = _FakeEnv([{"log": {DEFAULT_SUCCESS_TAG: 0.9}}] * 100) + runner = _FakeRunner() + # num_steps_per_env=2, window=2 -> converges on step 4 (iter 2) + with RslRlEarlyStopWrapper(env, runner, 0.5, 2, num_steps_per_env=2) as ctx: + for _ in range(10): + env.step(None) + assert ctx.tracker.converged is True + assert env.step_calls == 4 + assert len(runner.saved) == 1 + assert runner.logger.stopped is True + + def test_does_not_raise_when_stop_on_convergence_false(self): + """Test that ``stop_on_convergence=False`` lets training run past convergence.""" + env = _FakeEnv([{"log": {DEFAULT_SUCCESS_TAG: 0.9}}] * 100) + runner = _FakeRunner() + with RslRlEarlyStopWrapper( + env, + runner, + 0.5, + 2, + num_steps_per_env=2, + stop_on_convergence=False, + ) as ctx: + for _ in range(10): + env.step(None) + assert env.step_calls == 10 + assert ctx.tracker.converged is True + assert runner.saved == [] + assert runner.logger.stopped is False + + def test_does_not_suppress_other_exceptions(self): + """Test that non-EarlyStopConverged exceptions propagate out of the ``with`` block.""" + env = _FakeEnv([{"log": {}}]) + runner = _FakeRunner() + with pytest.raises(ValueError): + with RslRlEarlyStopWrapper(env, runner, 0.5, 2, num_steps_per_env=2): + raise ValueError("not an early stop") + + def test_env_step_restored_after_early_stop_exception(self): + """Test that env.step is unwrapped after an early-stop exception suppressed by __exit__.""" + env = _FakeEnv([{"log": {DEFAULT_SUCCESS_TAG: 0.9}}] * 100) + runner = _FakeRunner() + with RslRlEarlyStopWrapper(env, runner, 0.5, 2, num_steps_per_env=2) as ctx: + for _ in range(10): + env.step(None) # converges & raises at step 4, suppressed + sum_at_exit = ctx.tracker._iter_sum + env.step(None) + assert ctx.tracker._iter_sum == sum_at_exit # post-exit step bypassed the tracker + + def test_env_step_restored_after_unrelated_exception(self): + """Test that env.step is unwrapped even when a non-EarlyStopConverged exception propagates.""" + env = _FakeEnv([{"log": {DEFAULT_SUCCESS_TAG: 0.9}}] * 10) + runner = _FakeRunner() + try: + with RslRlEarlyStopWrapper(env, runner, 0.5, 2, num_steps_per_env=2) as ctx: + env.step(None) + raise ValueError("boom") + except ValueError: + pass + sum_at_exit = ctx.tracker._iter_sum + env.step(None) + assert ctx.tracker._iter_sum == sum_at_exit + + def test_cleanup_not_called_on_unrelated_exceptions(self): + """Test that only EarlyStopConverged triggers checkpoint save + logger flush.""" + env = _FakeEnv([{"log": {}}]) + runner = _FakeRunner() + try: + with RslRlEarlyStopWrapper(env, runner, 0.5, 2, num_steps_per_env=2): + raise ValueError("boom") + except ValueError: + pass + assert runner.saved == [] + assert runner.logger.stopped is False + + def test_cleanup_skipped_when_runner_has_no_writer(self): + """Test that cleanup skips both save and flush when ``runner.logger.writer`` is ``None``.""" + env = _FakeEnv([{"log": {DEFAULT_SUCCESS_TAG: 0.9}}] * 100) + runner = _FakeRunner(has_writer=False) + with RslRlEarlyStopWrapper(env, runner, 0.5, 2, num_steps_per_env=2): + for _ in range(10): + env.step(None) + assert runner.saved == [] + assert runner.logger.stopped is False + + def test_framework_iteration_count_reflects_runner(self): + """Test that the framework-counter property reports ``current_learning_iteration + 1``.""" + env = _FakeEnv([{"log": {DEFAULT_SUCCESS_TAG: 0.0}}]) + runner = _FakeRunner() + runner.current_learning_iteration = 42 + wrapper = RslRlEarlyStopWrapper(env, runner, 0.5, 3, num_steps_per_env=2) + assert wrapper.framework_iteration_count == 43 + + +# -- RlGamesEarlyStopObserver ----------------------------------------------- + + +class TestRlGamesEarlyStopObserver: + """Test cases for the rl_games AlgoObserver that tracks success and forces max_epochs.""" + + def test_delegates_every_call_to_base(self): + """Test that all observer lifecycle calls are forwarded to the wrapped base observer.""" + base = _FakeBaseObserver() + obs = RlGamesEarlyStopObserver(base, 0.5, 3) + obs.before_init("name", {}, "exp") + obs.after_init(_FakeAlgo(horizon_length=8)) + obs.process_infos({"episode": {}}, []) + obs.after_steps() + obs.after_clear_stats() + obs.after_print_stats(0, 0, 0) + assert base.calls == [ + "before_init", + "after_init", + "process_infos", + "after_steps", + "after_clear_stats", + "after_print_stats", + ] + + def test_tracker_uses_horizon_length_attribute(self): + """Test that the tracker pulls ``num_steps_per_env`` from ``algo.horizon_length`` when present.""" + obs = RlGamesEarlyStopObserver(_FakeBaseObserver(), 0.5, 3) + obs.after_init(_FakeAlgo(horizon_length=24)) + assert obs.tracker.num_steps_per_env == 24 + + def test_tracker_falls_back_to_config_horizon_length(self): + """Test that the tracker falls back to ``algo.config['horizon_length']`` when the attr is missing.""" + obs = RlGamesEarlyStopObserver(_FakeBaseObserver(), 0.5, 3) + obs.after_init(_FakeAlgo(horizon_length=None, config_horizon=32)) + assert obs.tracker.num_steps_per_env == 32 + + def test_process_infos_records_from_episode_key(self): + """Test that ``infos["episode"]`` is remapped to the tracker's extras["log"] shape.""" + obs = RlGamesEarlyStopObserver(_FakeBaseObserver(), 0.5, 3) + obs.after_init(_FakeAlgo(horizon_length=2)) + obs.process_infos({"episode": {DEFAULT_SUCCESS_TAG: 0.8}}, []) + assert obs.tracker._iter_sum == pytest.approx(0.8) + + def test_process_infos_is_noop_before_after_init(self): + """Test that ``process_infos`` before ``after_init`` does not raise (tracker is None).""" + obs = RlGamesEarlyStopObserver(_FakeBaseObserver(), 0.5, 3) + obs.process_infos({"episode": {DEFAULT_SUCCESS_TAG: 0.8}}, []) + assert obs.tracker is None + + def test_process_infos_ignores_non_dict_infos(self): + """Test that non-dict ``infos`` are skipped gracefully without mutating the tracker.""" + obs = RlGamesEarlyStopObserver(_FakeBaseObserver(), 0.5, 3) + obs.after_init(_FakeAlgo(horizon_length=2)) + obs.process_infos([], []) + assert obs.tracker._iter_sum == 0.0 + + def test_after_steps_sets_max_epochs_on_convergence(self): + """Test that convergence on iteration N sets ``algo.max_epochs = N`` for clean exit.""" + obs = RlGamesEarlyStopObserver(_FakeBaseObserver(), 0.5, 2) + algo = _FakeAlgo(horizon_length=1) + obs.after_init(algo) + obs.process_infos({"episode": {DEFAULT_SUCCESS_TAG: 0.9}}, []) + obs.after_steps() + obs.process_infos({"episode": {DEFAULT_SUCCESS_TAG: 0.9}}, []) + obs.after_steps() + assert algo.max_epochs == 2 + + def test_after_steps_leaves_max_epochs_alone_when_stop_disabled(self): + """Test that ``stop_on_convergence=False`` preserves the caller's ``algo.max_epochs``.""" + obs = RlGamesEarlyStopObserver( + _FakeBaseObserver(), + 0.5, + 2, + stop_on_convergence=False, + ) + algo = _FakeAlgo(horizon_length=1) + original_max_epochs = algo.max_epochs + obs.after_init(algo) + obs.process_infos({"episode": {DEFAULT_SUCCESS_TAG: 0.9}}, []) + obs.after_steps() + obs.process_infos({"episode": {DEFAULT_SUCCESS_TAG: 0.9}}, []) + obs.after_steps() + assert algo.max_epochs == original_max_epochs + + def test_after_steps_noop_before_after_init(self): + """Test that ``after_steps`` before ``after_init`` does not raise (tracker is None).""" + obs = RlGamesEarlyStopObserver(_FakeBaseObserver(), 0.5, 2) + obs.after_steps() + assert obs.tracker is None + + def test_each_after_steps_appends_one_iteration(self): + """Test that each ``after_steps`` call finalizes exactly one iteration in the tracker.""" + obs = RlGamesEarlyStopObserver(_FakeBaseObserver(), 0.5, 5) + obs.after_init(_FakeAlgo(horizon_length=1)) + for i in range(4): + obs.process_infos({"episode": {DEFAULT_SUCCESS_TAG: 0.9}}, []) + obs.after_steps() + assert obs.tracker.current_iteration == i + 1 + + def test_after_steps_does_not_converge_with_insufficient_history(self): + """Test that a trailing window shorter than ``window`` does not trigger early stop.""" + obs = RlGamesEarlyStopObserver(_FakeBaseObserver(), 0.5, 5) + algo = _FakeAlgo(horizon_length=1) + obs.after_init(algo) + for _ in range(4): + obs.process_infos({"episode": {DEFAULT_SUCCESS_TAG: 0.9}}, []) + obs.after_steps() + assert algo.max_epochs == 999 # unchanged: tracker.converged is still False + + def test_framework_iteration_count_returns_none_before_after_init(self): + """Test that the framework-counter property returns ``None`` before an algo is attached.""" + obs = RlGamesEarlyStopObserver(_FakeBaseObserver(), 0.5, 2) + assert obs.framework_iteration_count is None + + def test_framework_iteration_count_reflects_algo_epoch_num(self): + """Test that the framework-counter property mirrors ``algo.epoch_num``.""" + obs = RlGamesEarlyStopObserver(_FakeBaseObserver(), 0.5, 2) + obs.after_init(_FakeAlgo(horizon_length=1, epoch_num=7)) + assert obs.framework_iteration_count == 7 + + +# -- log_success (scripts.benchmarks.utils) --------------------------------- + + +class TestLogSuccess: + """Test cases for the benchmark-side success-metric logging helper.""" + + def _tracker_with(self, history: list[float]) -> SuccessRateTracker: + """Build a tracker with a pre-populated history for testing.""" + t = SuccessRateTracker(0.5, 3, num_steps_per_env=4) + t.history = history + return t + + def test_noop_when_tracker_is_none(self): + """Test that ``log_success`` emits nothing when no tracker is supplied.""" + bench = _FakeBenchmark() + log_success(bench, None) + assert bench.measurements == [] + + def test_noop_when_history_empty(self): + """Test that an empty tracker history is a silent no-op.""" + bench = _FakeBenchmark() + log_success(bench, self._tracker_with([])) + assert bench.measurements == [] + + def test_logs_full_measurement_set(self): + """Test that a populated tracker produces the full measurement set.""" + bench = _FakeBenchmark() + log_success(bench, self._tracker_with([0.9, 0.9, 0.9])) + names = {m[1] for m in bench.measurements} + assert names == {"Success Rate (tail mean)", "Success Converged At Iter", "Success Passed"} + + def test_converged_path(self): + """Test that a converged run reports ``Passed=1`` with the true converged iter + tail mean.""" + bench = _FakeBenchmark() + log_success(bench, self._tracker_with([0.9, 0.9, 0.9])) + assert bench.by_name("Success Passed")[2] == 1 + assert bench.by_name("Success Converged At Iter")[2] == 3 + assert bench.by_name("Success Rate (tail mean)")[2] == pytest.approx(0.9) + + def test_failed_path(self): + """Test that a non-converged run reports ``Passed=0`` and ``Converged At Iter=-1``.""" + bench = _FakeBenchmark() + log_success(bench, self._tracker_with([0.1, 0.2, 0.3])) + assert bench.by_name("Success Passed")[2] == 0 + assert bench.by_name("Success Converged At Iter")[2] == -1 + + def test_cadence_warning_fires_on_cadence_violation(self, capsys): + """Test that a 2x tracker/framework ratio triggers the cadence warning.""" + bench = _FakeBenchmark() + log_success(bench, self._tracker_with([0.5] * 100), framework_iteration_count=50) + captured = capsys.readouterr().out + assert "[WARN]" in captured + assert "check record_step cadence" in captured + + def test_no_cadence_warning_on_exact_agreement(self, capsys): + """Test that an exact tracker-vs-framework match (rl_games case) is silent.""" + bench = _FakeBenchmark() + log_success(bench, self._tracker_with([0.5] * 50), framework_iteration_count=50) + assert "[WARN]" not in capsys.readouterr().out + + def test_no_cadence_warning_on_rsl_rl_early_stop_offset(self, capsys): + """Test that the rsl_rl early-stop +1 offset (tracker=51, framework=50) is within slack.""" + bench = _FakeBenchmark() + log_success(bench, self._tracker_with([0.5] * 51), framework_iteration_count=50) + assert "[WARN]" not in capsys.readouterr().out + + def test_no_cadence_warning_when_framework_count_not_provided(self, capsys): + """Test that the cadence check is skipped entirely when no framework count is supplied.""" + bench = _FakeBenchmark() + log_success(bench, self._tracker_with([0.5] * 999)) + assert "[WARN]" not in capsys.readouterr().out + + def test_cadence_violation_end_to_end_via_wrapper(self, capsys): + """Test that a simulated 2x env.step bug manifests as an overcounted tracker and is caught. + + The wrapper can't distinguish "2 env.step calls that should have been 1" from normal + traffic — but the tracker overcounts iterations by 2x, and comparing against the + runner's independent counter catches the discrepancy. + """ + env = _FakeEnv([{"log": {DEFAULT_SUCCESS_TAG: 0.5}}] * 100) + runner = _FakeRunner() + runner.current_learning_iteration = 9 # rsl_rl thinks 10 iterations completed + with RslRlEarlyStopWrapper( + env, + runner, + 0.5, + 3, + num_steps_per_env=2, + stop_on_convergence=False, + ) as ctx: + # simulate the bug: upstream calls env.step 2x per real rollout step + for _ in range(10 * 2 * 2): # 10 iters * 2 steps/iter * 2x-bug + env.step(None) + # 40 calls with num_steps_per_env=2 => tracker.current_iteration = 20 + assert ctx.tracker.current_iteration == 20 + # framework's counter is independent: reports 10 iterations actually ran + assert ctx.framework_iteration_count == 10 + bench = _FakeBenchmark() + log_success(bench, ctx.tracker, framework_iteration_count=ctx.framework_iteration_count) + captured = capsys.readouterr().out + assert "[WARN]" in captured diff --git a/scripts/benchmarks/test/test_nsys_trace.py b/scripts/benchmarks/test/test_nsys_trace.py new file mode 100644 index 000000000000..e39f372da380 --- /dev/null +++ b/scripts/benchmarks/test/test_nsys_trace.py @@ -0,0 +1,153 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Sync tests for ``scripts/benchmarks/nsys_trace.json``. + +The JSON lists Python functions that nsys annotates during profiling via the +``--python-functions-trace`` flag. Entries reference IsaacLab (and adjacent) +source by dotted paths. These tests catch two kinds of drift: + +* Referenced functions that no longer resolve (hard failure) +* Covered classes that have public methods not listed in the JSON (warning — + signals that new coverage may need to be added) +""" + +from isaaclab.app import AppLauncher + +simulation_app = AppLauncher(headless=True).app + +"""Rest everything follows.""" + +import importlib +import inspect +import json +import warnings +from collections import defaultdict +from pathlib import Path + +import pytest + +TRACE_JSON_PATH = Path(__file__).resolve().parents[1] / "nsys_trace.json" + + +def _load_trace_entries() -> list[dict]: + """Return the parsed JSON entries from the trace file.""" + if not TRACE_JSON_PATH.exists(): + raise RuntimeError(f"nsys trace JSON not found at {TRACE_JSON_PATH}") + try: + with TRACE_JSON_PATH.open() as f: + return json.load(f) + except json.JSONDecodeError as exc: + raise RuntimeError(f"nsys trace JSON at {TRACE_JSON_PATH} is malformed: {exc}") from exc + + +def _function_name_and_module(entry_module: str, func_spec) -> tuple[str, str]: + """Normalize a function spec to ``(module, dotted_name)``. + + ``func_spec`` may be a bare string or a dict that optionally overrides + ``module`` (per the nsys --python-functions-trace schema). + """ + if isinstance(func_spec, str): + return entry_module, func_spec + return func_spec.get("module", entry_module), func_spec["function"] + + +def _iter_function_pairs(entries: list[dict]) -> list[tuple[str, str]]: + """Yield ``(module, dotted_function_path)`` for every function in the JSON.""" + pairs: list[tuple[str, str]] = [] + for entry in entries: + entry_module = entry["module"] + for func_spec in entry["functions"]: + pairs.append(_function_name_and_module(entry_module, func_spec)) + return pairs + + +def _resolve(module_name: str, dotted_path: str): + """Import ``module_name`` and walk ``dotted_path`` via getattr.""" + obj = importlib.import_module(module_name) + for attr in dotted_path.split("."): + obj = getattr(obj, attr) + return obj + + +def _group_methods_by_class(pairs: list[tuple[str, str]]) -> dict[tuple[str, str], set[str]]: + """Group referenced method names by ``(module, class_name)``. + + Top-level functions (paths without a dot) are skipped — no class context. + """ + grouped: dict[tuple[str, str], set[str]] = defaultdict(set) + for module_name, dotted_path in pairs: + parts = dotted_path.split(".") + if len(parts) >= 2: + class_name, method_name = parts[0], parts[-1] + grouped[(module_name, class_name)].add(method_name) + return grouped + + +def _is_own_public_method(cls: type, name: str, member: object) -> bool: + """True if ``member`` is a public method defined directly on ``cls``.""" + if not inspect.isfunction(member): + return False + if name not in cls.__dict__: + return False + # Skip dunders and private helpers from the unreferenced-method check; the JSON curates inclusions explicitly. + if name.startswith("_"): + return False + return True + + +_FUNCTION_PAIRS = _iter_function_pairs(_load_trace_entries()) + + +@pytest.mark.parametrize( + "module_name, dotted_path", + _FUNCTION_PAIRS, + ids=[f"{m}:{p}" for m, p in _FUNCTION_PAIRS], +) +def test_function_resolves(module_name: str, dotted_path: str): + """Every function referenced in the trace JSON must resolve to a callable. + + A missing reference silently loses profiling coverage, so this fails loudly. + Modules that aren't importable in the current environment (e.g. optional + RL frameworks) are skipped rather than failed. + """ + try: + importlib.import_module(module_name) + except ImportError as exc: + pytest.skip(f"Module '{module_name}' not importable here: {exc}") + + try: + resolved = _resolve(module_name, dotted_path) + except AttributeError as exc: + pytest.fail(f"'{module_name}.{dotted_path}' not found: {exc}") + + assert callable(resolved), f"'{module_name}.{dotted_path}' resolved but is not callable" + + +def test_warn_unreferenced_methods_on_covered_classes(): + """Emit a warning for each public method that isn't listed in the JSON. + + Scope: classes that already have at least one method referenced. If the + class gained a new public method since the JSON was last updated, it shows + up here as a nudge to add (or intentionally omit) it. Inherited, dunder, + and private methods are excluded to keep the signal actionable. + """ + grouped = _group_methods_by_class(_FUNCTION_PAIRS) + + for (module_name, class_name), referenced in sorted(grouped.items()): + try: + cls = _resolve(module_name, class_name) + except (ImportError, AttributeError): + continue + if not inspect.isclass(cls): + continue + + own_public = {name for name, member in inspect.getmembers(cls) if _is_own_public_method(cls, name, member)} + unreferenced = own_public - referenced + if unreferenced: + warnings.warn( + f"{module_name}.{class_name} has public methods not listed in nsys_trace.json: {sorted(unreferenced)}", + stacklevel=2, + ) diff --git a/scripts/benchmarks/utils.py b/scripts/benchmarks/utils.py index ff3ab78efb68..e157765adb0e 100644 --- a/scripts/benchmarks/utils.py +++ b/scripts/benchmarks/utils.py @@ -4,6 +4,7 @@ # SPDX-License-Identifier: BSD-3-Clause +import cProfile import glob import os import statistics @@ -18,6 +19,7 @@ os.path.dirname(__file__), "..", "..", "source", "isaaclab_tasks", "test", "benchmarking" ) _CONFIGS_YAML = os.path.join(_BENCHMARKING_DIR, "configs.yaml") +SUCCESS_RATE_LOG_TAGS = ("Metrics/success_rate", "Episode/Metrics/success_rate") def get_backend_type(cli_backend: str) -> str: @@ -150,6 +152,23 @@ def log_rl_policy_episode_lengths(benchmark: BaseIsaacLabBenchmark, value: list) benchmark.add_measurement("train", measurement=measurement) +def log_rl_policy_success_rates(benchmark: BaseIsaacLabBenchmark, value: list): + if not value: + return + measurement = ListMeasurement(name="Success Rates", value=value) + benchmark.add_measurement("train", measurement=measurement) + # Log the best observed success rate as a scalar for benchmark JSON backends. + measurement = SingleMeasurement(name="success_rate", value=max(value), unit="float") + benchmark.add_measurement("train", measurement=measurement) + + +def get_success_rate_log(log_data: dict) -> list | None: + for tag in SUCCESS_RATE_LOG_TAGS: + if tag in log_data: + return log_data[tag] + return None + + def check_convergence( rewards: list[float], threshold: float, @@ -235,3 +254,154 @@ def log_convergence( benchmark.add_measurement( "train", SingleMeasurement(name="Convergence Passed", value=int(result["passed"]), unit="bool") ) + + +def log_success(benchmark, tracker, framework_iteration_count: int | None = None): + """Log success-metric results to the benchmark backend. + + Always logs the tag, tail mean, converged-at-iter, and pass/fail whenever the tracker holds + data (useful for historical comparison across runs). No-op when the tracker is ``None`` or + never recorded anything. + + Args: + benchmark: Benchmark instance. + tracker: :class:`SuccessRateTracker` from early_stop (or ``None`` if no tracker ran). + framework_iteration_count: Iterations the RL framework actually ran. When provided, emits a warning + if the tracker's count exceeds the framework's by more than 1. + """ + if tracker is None or not tracker.history: + return + + converged = tracker.converged + benchmark.add_measurement( + "train", SingleMeasurement(name="Success Rate (tail mean)", value=round(tracker.tail_mean, 4), unit="float") + ) + benchmark.add_measurement( + "train", + SingleMeasurement( + name="Success Converged At Iter", + value=tracker.current_iteration if converged else -1, + unit="int", + ), + ) + benchmark.add_measurement("train", SingleMeasurement(name="Success Passed", value=int(converged), unit="bool")) + + # +1 slack handles counters that lag behind during early-stop. + # Anything larger signals a broken record_step cadence (see SuccessRateTracker.at_iteration_boundary). + if framework_iteration_count is not None and tracker.current_iteration > framework_iteration_count + 1: + print( + f"[WARN] Success tracker logged {tracker.current_iteration} iterations vs framework's " + f"{framework_iteration_count}; check record_step cadence assumption." + ) + + +def parse_cprofile_stats( + profile: cProfile.Profile, + isaaclab_prefixes: list[str], + top_n: int = 30, + whitelist: list[str] | None = None, +) -> list[tuple[str, float, float]]: + """Parse cProfile stats, filtering to IsaacLab + first-level external calls. + + Walks the pstats data and keeps functions that are either (a) inside an + IsaacLab source directory, or (b) directly called by an IsaacLab function. + Results are sorted by own-time (tottime) descending. + + When *whitelist* is provided, only functions whose labels match at least one + ``fnmatch`` pattern are returned. Patterns that match no profiled function + emit a ``(pattern, 0.0, 0.0)`` placeholder so dashboards always receive + consistent keys. The *top_n* parameter is ignored in whitelist mode. + + Args: + profile: A completed cProfile.Profile instance (after .disable()). + isaaclab_prefixes: Absolute file path prefixes identifying IsaacLab source + (e.g. ["/home/user/IsaacLab/source/isaaclab", ...]). + top_n: Maximum number of functions to return. Ignored when + *whitelist* is provided. + whitelist: Optional list of ``fnmatch`` patterns to select specific + functions (e.g. ``["isaaclab.cloner.*:usd_replicate"]``). + + Returns: + List of (function_label, tottime_ms, cumtime_ms) tuples sorted by + tottime descending. + """ + import fnmatch + import io + import pstats + + stats = pstats.Stats(profile, stream=io.StringIO()) + + def _is_isaaclab(filename: str) -> bool: + return any(filename.startswith(prefix) for prefix in isaaclab_prefixes) + + def _make_label(filename: str, funcname: str) -> str: + # For builtins/C-extensions the filename is something like "~" or "" + if not filename or filename.startswith("<") or filename == "~": + return funcname + # Convert absolute path to dotted module-style label + for prefix in isaaclab_prefixes: + if filename.startswith(prefix): + rel = os.path.relpath(filename, prefix) + # Strip .py, replace os.sep with dot + rel = rel.replace(os.sep, ".").removesuffix(".py") + return f"{rel}:{funcname}" + # External function — try to find the top-level package name + # e.g. ".../site-packages/torch/nn/modules/linear.py" -> "torch.nn.modules.linear" + parts = filename.replace(os.sep, "/").removesuffix(".py").split("/") + # Find "site-packages" anchor or fall back to last 3 components + try: + sp_idx = parts.index("site-packages") + short = ".".join(parts[sp_idx + 1 :]) + except ValueError: + short = ".".join(parts[-3:]) if len(parts) >= 3 else ".".join(parts) + return f"{short}:{funcname}" + + # NOTE: stats.stats is an internal CPython dict, not part of the public pstats API. + # The public get_stats_profile() (Python 3.9+) doesn't expose caller info, which + # we need for the first-level external call filter. If a future Python release + # breaks this, switch to get_stats_profile() and drop the caller-based filtering. + # stats.stats: dict[(filename, lineno, funcname)] -> (pcalls, ncalls, tottime, cumtime, callers) + # callers: dict[(filename, lineno, funcname)] -> (pcalls, ncalls, tottime, cumtime) + results = [] + for func_key, (_, _, tottime, cumtime, callers) in stats.stats.items(): + filename, _, funcname = func_key + if _is_isaaclab(filename): + label = _make_label(filename, funcname) + results.append((label, tottime * 1000.0, cumtime * 1000.0)) + else: + # Check if any direct caller is an IsaacLab function + for caller_key in callers: + caller_filename = caller_key[0] + if _is_isaaclab(caller_filename): + label = _make_label(filename, funcname) + results.append((label, tottime * 1000.0, cumtime * 1000.0)) + break + + # Sort by tottime (own-time) descending + results.sort(key=lambda x: x[1], reverse=True) + + if whitelist is None: + return results[:top_n] + + # Whitelist mode: filter by fnmatch patterns, emit placeholders for unmatched patterns + matched: dict[str, tuple[str, float, float]] = {} + matched_patterns: set[str] = set() + for label, tottime, cumtime in results: + for pattern in whitelist: + if fnmatch.fnmatch(label, pattern): + if label not in matched: + matched[label] = (label, tottime, cumtime) + matched_patterns.add(pattern) + + # Add 0.0 placeholders for patterns that matched nothing + for pattern in whitelist: + if pattern not in matched_patterns: + print( + f"[WARNING] Whitelist pattern '{pattern}' matched no profiled functions. " + "Check for typos or verify the function ran during this phase." + ) + matched[pattern] = (pattern, 0.0, 0.0) + + filtered = list(matched.values()) + filtered.sort(key=lambda x: x[1], reverse=True) + return filtered diff --git a/scripts/demos/arms.py b/scripts/demos/arms.py index a224a44b3703..b08686a8e52c 100644 --- a/scripts/demos/arms.py +++ b/scripts/demos/arms.py @@ -36,7 +36,6 @@ import numpy as np import torch -import warp as wp import isaaclab.sim as sim_utils from isaaclab.assets import Articulation @@ -178,15 +177,15 @@ def run_simulator(sim: sim_utils.SimulationContext, entities: dict[str, Articula # reset the scene entities for index, robot in enumerate(entities.values()): # root state - root_pose = wp.to_torch(robot.data.default_root_pose).clone() + root_pose = robot.data.default_root_pose.torch.clone() root_pose[:, :3] += origins[index] robot.write_root_pose_to_sim_index(root_pose=root_pose) - root_vel = wp.to_torch(robot.data.default_root_vel).clone() + root_vel = robot.data.default_root_vel.torch.clone() robot.write_root_velocity_to_sim_index(root_velocity=root_vel) # set joint positions joint_pos, joint_vel = ( - wp.to_torch(robot.data.default_joint_pos).clone(), - wp.to_torch(robot.data.default_joint_vel).clone(), + robot.data.default_joint_pos.torch.clone(), + robot.data.default_joint_vel.torch.clone(), ) robot.write_joint_position_to_sim_index(position=joint_pos) robot.write_joint_velocity_to_sim_index(velocity=joint_vel) @@ -196,10 +195,8 @@ def run_simulator(sim: sim_utils.SimulationContext, entities: dict[str, Articula # apply random actions to the robots for robot in entities.values(): # generate random joint positions - joint_pos_target = ( - wp.to_torch(robot.data.default_joint_pos) + torch.randn_like(wp.to_torch(robot.data.joint_pos)) * 0.1 - ) - soft_limits = wp.to_torch(robot.data.soft_joint_pos_limits) + joint_pos_target = robot.data.default_joint_pos.torch + torch.randn_like(robot.data.joint_pos.torch) * 0.1 + soft_limits = robot.data.soft_joint_pos_limits.torch joint_pos_target = joint_pos_target.clamp_(soft_limits[..., 0], soft_limits[..., 1]) # apply action to the robot robot.set_joint_position_target_index(target=joint_pos_target) diff --git a/scripts/demos/bin_packing.py b/scripts/demos/bin_packing.py index 05da86396a1c..20d2d656cd86 100644 --- a/scripts/demos/bin_packing.py +++ b/scripts/demos/bin_packing.py @@ -46,7 +46,6 @@ import math import torch -import warp as wp import isaaclab.sim as sim_utils import isaaclab.utils.math as math_utils @@ -267,9 +266,9 @@ def run_simulator(sim: SimulationContext, scene: InteractiveScene) -> None: num_envs = scene.num_envs device = scene.device view_indices = torch.arange(num_envs * num_objects, device=device) - default_pose_w = wp.to_torch(groceries.data.default_body_pose).clone() + default_pose_w = groceries.data.default_body_pose.torch.clone() default_pose_w[..., :3] = default_pose_w[..., :3] + scene.env_origins.unsqueeze(1) - default_vel_w = wp.to_torch(groceries.data.default_body_vel).clone() + default_vel_w = groceries.data.default_body_vel.torch.clone() default_state_w = torch.cat([default_pose_w, default_vel_w], dim=-1) # Define simulation stepping sim_dt = sim.get_physics_dt() diff --git a/scripts/demos/bipeds.py b/scripts/demos/bipeds.py index a8dfdf693962..68f79db14fcb 100644 --- a/scripts/demos/bipeds.py +++ b/scripts/demos/bipeds.py @@ -35,7 +35,6 @@ """Rest everything follows.""" import torch -import warp as wp import isaaclab.sim as sim_utils from isaaclab.assets import Articulation @@ -92,22 +91,22 @@ def run_simulator(sim: sim_utils.SimulationContext, robots: list[Articulation], for index, robot in enumerate(robots): # reset dof state joint_pos, joint_vel = ( - wp.to_torch(robot.data.default_joint_pos), - wp.to_torch(robot.data.default_joint_vel), + robot.data.default_joint_pos.torch, + robot.data.default_joint_vel.torch, ) robot.write_joint_position_to_sim_index(position=joint_pos) robot.write_joint_velocity_to_sim_index(velocity=joint_vel) - root_pose = wp.to_torch(robot.data.default_root_pose).clone() + root_pose = robot.data.default_root_pose.torch.clone() root_pose[:, :3] += origins[index] robot.write_root_pose_to_sim_index(root_pose=root_pose) - root_vel = wp.to_torch(robot.data.default_root_vel).clone() + root_vel = robot.data.default_root_vel.torch.clone() robot.write_root_velocity_to_sim_index(root_velocity=root_vel) robot.reset() # reset command print(">>>>>>>> Reset!") # apply action to the robot for robot in robots: - robot.set_joint_position_target_index(target=wp.to_torch(robot.data.default_joint_pos).clone()) + robot.set_joint_position_target_index(target=robot.data.default_joint_pos.torch.clone()) robot.write_data_to_sim() # perform step sim.step() diff --git a/scripts/demos/deformables.py b/scripts/demos/deformables.py index fc759a3142d1..71f40b5f9c4a 100644 --- a/scripts/demos/deformables.py +++ b/scripts/demos/deformables.py @@ -38,24 +38,31 @@ import numpy as np import torch import tqdm -import warp as wp + +# deformables supported in PhysX +from isaaclab_physx.assets import DeformableObject, DeformableObjectCfg +from isaaclab_physx.sim import DeformableBodyMaterialCfg, DeformableBodyPropertiesCfg, SurfaceDeformableBodyMaterialCfg import isaaclab.sim as sim_utils -from isaaclab.assets import DeformableObject, DeformableObjectCfg +from isaaclab.utils.assets import ISAACLAB_NUCLEUS_DIR + +def define_origins(num_origins: int, radius: float = 2.0, center_height: float = 3.0) -> list[list[float]]: + """Defines origins distributed on the surface of a sphere, sampled according to a Fibonacci lattice. -def define_origins(num_origins: int, spacing: float) -> list[list[float]]: - """Defines the origins of the the scene.""" - # create tensor based on number of environments + Args: + num_origins: Number of points to place. + radius: Radius of the sphere [m]. + center_height: Height of the sphere center above ground [m]. + """ + golden_ratio = (1 + np.sqrt(5)) / 2 env_origins = torch.zeros(num_origins, 3) - # create a grid of origins - num_cols = np.floor(np.sqrt(num_origins)) - num_rows = np.ceil(num_origins / num_cols) - xx, yy = torch.meshgrid(torch.arange(num_rows), torch.arange(num_cols), indexing="xy") - env_origins[:, 0] = spacing * xx.flatten()[:num_origins] - spacing * (num_rows - 1) / 2 - env_origins[:, 1] = spacing * yy.flatten()[:num_origins] - spacing * (num_cols - 1) / 2 - env_origins[:, 2] = torch.rand(num_origins) + 1.0 - # return the origins + for i in range(num_origins): + theta = 2 * np.pi * i / golden_ratio + phi = np.arccos(1 - 2 * (i + 0.5) / num_origins) + env_origins[i, 0] = radius * np.cos(theta) * np.sin(phi) + env_origins[i, 1] = radius * np.sin(theta) * np.sin(phi) + env_origins[i, 2] = radius * np.cos(phi) + center_height return env_origins.tolist() @@ -74,37 +81,51 @@ def design_scene() -> tuple[dict, list[list[float]]]: # spawn a red cone cfg_sphere = sim_utils.MeshSphereCfg( - radius=0.25, - deformable_props=sim_utils.DeformableBodyPropertiesCfg(rest_offset=0.0), + radius=0.4, + deformable_props=DeformableBodyPropertiesCfg(), visual_material=sim_utils.PreviewSurfaceCfg(), - physics_material=sim_utils.DeformableBodyMaterialCfg(), + physics_material=DeformableBodyMaterialCfg(), ) cfg_cuboid = sim_utils.MeshCuboidCfg( - size=(0.2, 0.2, 0.2), - deformable_props=sim_utils.DeformableBodyPropertiesCfg(rest_offset=0.0), + size=(0.6, 0.6, 0.6), + deformable_props=DeformableBodyPropertiesCfg(), visual_material=sim_utils.PreviewSurfaceCfg(), - physics_material=sim_utils.DeformableBodyMaterialCfg(), + physics_material=DeformableBodyMaterialCfg(), ) cfg_cylinder = sim_utils.MeshCylinderCfg( - radius=0.15, + radius=0.25, height=0.5, - deformable_props=sim_utils.DeformableBodyPropertiesCfg(rest_offset=0.0), + deformable_props=DeformableBodyPropertiesCfg(), visual_material=sim_utils.PreviewSurfaceCfg(), - physics_material=sim_utils.DeformableBodyMaterialCfg(), + physics_material=DeformableBodyMaterialCfg(), ) cfg_capsule = sim_utils.MeshCapsuleCfg( - radius=0.15, + radius=0.35, height=0.5, - deformable_props=sim_utils.DeformableBodyPropertiesCfg(rest_offset=0.0), + deformable_props=DeformableBodyPropertiesCfg(), visual_material=sim_utils.PreviewSurfaceCfg(), - physics_material=sim_utils.DeformableBodyMaterialCfg(), + physics_material=DeformableBodyMaterialCfg(), ) cfg_cone = sim_utils.MeshConeCfg( - radius=0.15, - height=0.5, - deformable_props=sim_utils.DeformableBodyPropertiesCfg(rest_offset=0.0), + radius=0.35, + height=0.75, + deformable_props=DeformableBodyPropertiesCfg(), + visual_material=sim_utils.PreviewSurfaceCfg(), + physics_material=DeformableBodyMaterialCfg(), + ) + cfg_cloth = sim_utils.MeshSquareCfg( + size=1.5, + resolution=(21, 21), + deformable_props=DeformableBodyPropertiesCfg(), visual_material=sim_utils.PreviewSurfaceCfg(), - physics_material=sim_utils.DeformableBodyMaterialCfg(), + physics_material=SurfaceDeformableBodyMaterialCfg(), + ) + cfg_usd = sim_utils.UsdFileCfg( + usd_path=f"{ISAACLAB_NUCLEUS_DIR}/Objects/Teddy_Bear/teddy_bear.usd", + deformable_props=DeformableBodyPropertiesCfg(), + visual_material=sim_utils.PreviewSurfaceCfg(), + physics_material=DeformableBodyMaterialCfg(), + scale=[0.05, 0.05, 0.05], ) # create a dictionary of all the objects to be spawned objects_cfg = { @@ -113,58 +134,80 @@ def design_scene() -> tuple[dict, list[list[float]]]: "cylinder": cfg_cylinder, "capsule": cfg_capsule, "cone": cfg_cone, + "cloth": cfg_cloth, + "usd": cfg_usd, } # Create separate groups of deformable objects - origins = define_origins(num_origins=64, spacing=0.6) + origins = define_origins(num_origins=12, radius=1.5, center_height=2.0) print("[INFO]: Spawning objects...") + num_volumes = 0 + num_surfaces = 0 # Iterate over all the origins and randomly spawn objects for idx, origin in tqdm.tqdm(enumerate(origins), total=len(origins)): # randomly select an object to spawn obj_name = random.choice(list(objects_cfg.keys())) obj_cfg = objects_cfg[obj_name] - # randomize the young modulus (somewhere between a Silicone 30 and Silicone 70) - obj_cfg.physics_material.youngs_modulus = random.uniform(0.7e6, 3.3e6) + # randomize the young modulus + obj_cfg.physics_material.youngs_modulus = random.uniform(5e5, 1e8) + # higher mesh resolution causes instability at low stiffness + if obj_name in ["sphere", "capsule", "cloth", "usd"]: + obj_cfg.physics_material.youngs_modulus = random.uniform(1e8, 5e9) # randomize the poisson's ratio - obj_cfg.physics_material.poissons_ratio = random.uniform(0.25, 0.5) + obj_cfg.physics_material.poissons_ratio = random.uniform(0.25, 0.45) # randomize the color obj_cfg.visual_material.diffuse_color = (random.random(), random.random(), random.random()) - # spawn the object - obj_cfg.func(f"/World/Origin/Object{idx:02d}", obj_cfg, translation=origin) - - # create a view for all the deformables + # spawn the object, separate groups for surface and volume deformables + if obj_name in ["cloth"]: + obj_cfg.func(f"/World/Origin/Surface{idx:02d}", obj_cfg, translation=origin) + num_surfaces += 1 + else: + obj_cfg.func(f"/World/Origin/Volume{idx:02d}", obj_cfg, translation=origin) + num_volumes += 1 + + # create a view for all the deformables, separate views for volume and surface deformables # note: since we manually spawned random deformable meshes above, we don't need to # specify the spawn configuration for the deformable object - cfg = DeformableObjectCfg( - prim_path="/World/Origin/Object.*", - spawn=None, - init_state=DeformableObjectCfg.InitialStateCfg(), - ) - deformable_object = DeformableObject(cfg=cfg) + scene_entities = {} + if num_volumes > 0: + cfg = DeformableObjectCfg( + prim_path="/World/Origin/Volume.*", + spawn=None, + init_state=DeformableObjectCfg.InitialStateCfg(), + ) + volume_deformable_object = DeformableObject(cfg=cfg) + scene_entities["volume_deformable_object"] = volume_deformable_object + if num_surfaces > 0: + cfg = DeformableObjectCfg( + prim_path="/World/Origin/Surface.*", + spawn=None, + init_state=DeformableObjectCfg.InitialStateCfg(), + ) + surface_deformable_object = DeformableObject(cfg=cfg) + scene_entities["surface_deformable_object"] = surface_deformable_object # return the scene information - scene_entities = {"deformable_object": deformable_object} return scene_entities, origins -def run_simulator(sim: sim_utils.SimulationContext, entities: dict[str, DeformableObject], origins: torch.Tensor): +def run_simulator(sim: sim_utils.SimulationContext, entities: dict[str, DeformableObject]): """Runs the simulation loop.""" # Define simulation stepping sim_dt = sim.get_physics_dt() sim_time = 0.0 count = 0 + # Simulate physics while simulation_app.is_running(): # reset - if count % 400 == 0: + if count % int(3.0 / sim_dt) == 0: # reset counters - sim_time = 0.0 count = 0 # reset deformable object state for _, deform_body in enumerate(entities.values()): # root state - nodal_state = wp.to_torch(deform_body.data.default_nodal_state_w).clone() - deform_body.write_nodal_state_to_sim(nodal_state) + nodal_state = deform_body.data.default_nodal_state_w.torch.clone() + deform_body.write_nodal_state_to_sim_index(nodal_state) # reset the internal state deform_body.reset() print("[INFO]: Resetting deformable object state...") @@ -187,15 +230,13 @@ def main(): sim.set_camera_view([4.0, 4.0, 3.0], [0.5, 0.5, 0.0]) # Design scene by adding assets to it - scene_entities, scene_origins = design_scene() - scene_origins = torch.tensor(scene_origins, device=sim.device) + scene_entities, _ = design_scene() # Play the simulator sim.reset() # Now we are ready! print("[INFO]: Setup complete...") - - # Run the simulator - run_simulator(sim, scene_entities, scene_origins) + run_simulator(sim, scene_entities) + print("[INFO]: Simulation complete...") if __name__ == "__main__": diff --git a/scripts/demos/h1_locomotion.py b/scripts/demos/h1_locomotion.py index 2a48828a425d..7e7429c35b0d 100644 --- a/scripts/demos/h1_locomotion.py +++ b/scripts/demos/h1_locomotion.py @@ -45,7 +45,6 @@ """Rest everything follows.""" import torch -import warp as wp from rsl_rl.runners import OnPolicyRunner import carb @@ -199,10 +198,10 @@ def _update_camera(self): """Updates the per-frame transform of the third-person view camera to follow the selected robot's torso transform.""" - base_pos = wp.to_torch(self.env.unwrapped.scene["robot"].data.root_pos_w)[ + base_pos = self.env.unwrapped.scene["robot"].data.root_pos_w.torch[ self._selected_id, : ] # - env.scene.env_origins - base_quat = wp.to_torch(self.env.unwrapped.scene["robot"].data.root_quat_w)[self._selected_id, :] + base_quat = self.env.unwrapped.scene["robot"].data.root_quat_w.torch[self._selected_id, :] camera_pos = quat_apply(base_quat, self._camera_local_transform) + base_pos diff --git a/scripts/demos/hands.py b/scripts/demos/hands.py index 2199d7f5401c..4b9a12d7b433 100644 --- a/scripts/demos/hands.py +++ b/scripts/demos/hands.py @@ -36,7 +36,6 @@ import numpy as np import torch -import warp as wp import isaaclab.sim as sim_utils from isaaclab.assets import Articulation @@ -112,15 +111,15 @@ def run_simulator(sim: sim_utils.SimulationContext, entities: dict[str, Articula # reset robots for index, robot in enumerate(entities.values()): # root state - root_pose = wp.to_torch(robot.data.default_root_pose).clone() + root_pose = robot.data.default_root_pose.torch.clone() root_pose[:, :3] += origins[index] robot.write_root_pose_to_sim_index(root_pose=root_pose) - root_vel = wp.to_torch(robot.data.default_root_vel).clone() + root_vel = robot.data.default_root_vel.torch.clone() robot.write_root_velocity_to_sim_index(root_velocity=root_vel) # joint state joint_pos, joint_vel = ( - wp.to_torch(robot.data.default_joint_pos).clone(), - wp.to_torch(robot.data.default_joint_vel).clone(), + robot.data.default_joint_pos.torch.clone(), + robot.data.default_joint_vel.torch.clone(), ) robot.write_joint_position_to_sim_index(position=joint_pos) robot.write_joint_velocity_to_sim_index(velocity=joint_vel) @@ -133,7 +132,7 @@ def run_simulator(sim: sim_utils.SimulationContext, entities: dict[str, Articula # apply default actions to the hands robots for robot in entities.values(): # generate joint positions - joint_pos_target = wp.to_torch(robot.data.soft_joint_pos_limits)[..., grasp_mode] + joint_pos_target = robot.data.soft_joint_pos_limits.torch[..., grasp_mode] # apply action to the robot robot.set_joint_position_target_index(target=joint_pos_target) # write data to sim diff --git a/scripts/demos/haply_teleoperation.py b/scripts/demos/haply_teleoperation.py index 928d04506e9c..a1c5a7cec677 100644 --- a/scripts/demos/haply_teleoperation.py +++ b/scripts/demos/haply_teleoperation.py @@ -59,7 +59,6 @@ import numpy as np import torch -import warp as wp import isaaclab.sim as sim_utils from isaaclab.assets import Articulation, AssetBaseCfg, RigidObject, RigidObjectCfg @@ -193,9 +192,9 @@ def run_simulator( ee_body_name = "panda_hand" ee_body_idx = robot.body_names.index(ee_body_name) - joint_pos = wp.to_torch(robot.data.default_joint_pos).clone() + joint_pos = robot.data.default_joint_pos.torch.clone() joint_pos[0, :7] = torch.tensor([0.0, -0.569, 0.0, -2.81, 0.0, 3.037, 0.741], device=robot.device) - joint_vel = wp.to_torch(robot.data.default_joint_vel).clone() + joint_vel = robot.data.default_joint_vel.torch.clone() robot.write_joint_position_to_sim_index(position=joint_pos) robot.write_joint_velocity_to_sim_index(velocity=joint_vel) @@ -205,7 +204,7 @@ def run_simulator( scene.update(sim_dt) # Initialize the position of franka - robot_initial_pos = wp.to_torch(robot.data.body_pos_w)[0, ee_body_idx].cpu().numpy() + robot_initial_pos = robot.data.body_pos_w.torch[0, ee_body_idx].cpu().numpy() haply_initial_pos = np.array([0.0, 0.0, 0.0], dtype=np.float32) ik_controller_cfg = DifferentialIKControllerCfg( @@ -228,7 +227,7 @@ def run_simulator( # Initialize IK controller ik_controller = DifferentialIKController(cfg=ik_controller_cfg, num_envs=scene.num_envs, device=sim.device) - initial_ee_quat = wp.to_torch(robot.data.body_quat_w)[:, ee_body_idx] + initial_ee_quat = robot.data.body_quat_w.torch[:, ee_body_idx] ik_controller.set_command(command=torch.zeros(scene.num_envs, 3, device=sim.device), ee_quat=initial_ee_quat) prev_button_a = False @@ -237,7 +236,7 @@ def run_simulator( gripper_target = 0.04 # Initialize the rotation of franka end-effector - ee_rotation_angle = wp.to_torch(robot.data.joint_pos)[0, 6].item() + ee_rotation_angle = robot.data.joint_pos.torch[0, 6].item() rotation_step = np.pi / 3 print("\n[INFO] Teleoperation ready!") @@ -247,22 +246,22 @@ def run_simulator( while simulation_app.is_running(): if count % 10000 == 0: count = 1 - root_pose = wp.to_torch(robot.data.default_root_pose).clone() + root_pose = robot.data.default_root_pose.torch.clone() root_pose[:, :3] += scene.env_origins robot.write_root_pose_to_sim_index(root_pose=root_pose) - root_vel = wp.to_torch(robot.data.default_root_vel).clone() + root_vel = robot.data.default_root_vel.torch.clone() robot.write_root_velocity_to_sim_index(root_velocity=root_vel) - joint_pos = wp.to_torch(robot.data.default_joint_pos).clone() + joint_pos = robot.data.default_joint_pos.torch.clone() joint_pos[0, :7] = torch.tensor([0.0, -0.569, 0.0, -2.81, 0.0, 3.037, 0.741], device=robot.device) - joint_vel = wp.to_torch(robot.data.default_joint_vel).clone() + joint_vel = robot.data.default_joint_vel.torch.clone() robot.write_joint_position_to_sim_index(position=joint_pos) robot.write_joint_velocity_to_sim_index(velocity=joint_vel) - cube_pose = wp.to_torch(cube.data.default_root_pose).clone() + cube_pose = cube.data.default_root_pose.torch.clone() cube_pose[:, :3] += scene.env_origins cube.write_root_pose_to_sim_index(root_pose=cube_pose) - cube_vel = wp.to_torch(cube.data.default_root_vel).clone() + cube_vel = cube.data.default_root_vel.torch.clone() cube.write_root_velocity_to_sim_index(root_velocity=cube_vel) scene.reset() @@ -304,16 +303,16 @@ def run_simulator( target_pos_tensor = torch.tensor(target_pos, dtype=torch.float32, device=sim.device).unsqueeze(0) - current_joint_pos = wp.to_torch(robot.data.joint_pos)[:, arm_joint_indices] - ee_pos_w = wp.to_torch(robot.data.body_pos_w)[:, ee_body_idx] - ee_quat_w = wp.to_torch(robot.data.body_quat_w)[:, ee_body_idx] + current_joint_pos = robot.data.joint_pos.torch[:, arm_joint_indices] + ee_pos_w = robot.data.body_pos_w.torch[:, ee_body_idx] + ee_quat_w = robot.data.body_quat_w.torch[:, ee_body_idx] # get jacobian to IK controller jacobian = robot.root_view.get_jacobians()[:, ee_body_idx, :, arm_joint_indices] ik_controller.set_command(command=target_pos_tensor, ee_quat=ee_quat_w) joint_pos_des = ik_controller.compute(ee_pos_w, ee_quat_w, jacobian, current_joint_pos) - joint_pos_target = wp.to_torch(robot.data.joint_pos)[0].clone() + joint_pos_target = robot.data.joint_pos.torch[0].clone() # Update joints: 6 from IK + 1 from button control (correct by design) joint_pos_target[arm_joint_indices] = joint_pos_des[0] # panda_joint1-6 from IK diff --git a/scripts/demos/multi_asset.py b/scripts/demos/multi_asset.py index 05412f327c39..8091c71afe0e 100644 --- a/scripts/demos/multi_asset.py +++ b/scripts/demos/multi_asset.py @@ -39,8 +39,6 @@ import random -import warp as wp - from pxr import Gf, Sdf import isaaclab.sim as sim_utils @@ -242,28 +240,28 @@ def run_simulator(sim: SimulationContext, scene: InteractiveScene): count = 0 # reset the scene entities # object - root_pose = wp.to_torch(rigid_object.data.default_root_pose).clone() + root_pose = rigid_object.data.default_root_pose.torch.clone() root_pose[:, :3] += scene.env_origins rigid_object.write_root_pose_to_sim_index(root_pose=root_pose) - root_vel = wp.to_torch(rigid_object.data.default_root_vel).clone() + root_vel = rigid_object.data.default_root_vel.torch.clone() rigid_object.write_root_velocity_to_sim_index(root_velocity=root_vel) # object collection - default_pose_w = wp.to_torch(rigid_object_collection.data.default_body_pose).clone() + default_pose_w = rigid_object_collection.data.default_body_pose.torch.clone() default_pose_w[..., :3] += scene.env_origins.unsqueeze(1) rigid_object_collection.write_body_pose_to_sim_index(body_poses=default_pose_w) - default_vel_w = wp.to_torch(rigid_object_collection.data.default_body_vel).clone() + default_vel_w = rigid_object_collection.data.default_body_vel.torch.clone() rigid_object_collection.write_body_com_velocity_to_sim_index(body_velocities=default_vel_w) # robot # -- root state - root_pose = wp.to_torch(robot.data.default_root_pose).clone() + root_pose = robot.data.default_root_pose.torch.clone() root_pose[:, :3] += scene.env_origins robot.write_root_pose_to_sim_index(root_pose=root_pose) - root_vel = wp.to_torch(robot.data.default_root_vel).clone() + root_vel = robot.data.default_root_vel.torch.clone() robot.write_root_velocity_to_sim_index(root_velocity=root_vel) # -- joint state joint_pos, joint_vel = ( - wp.to_torch(robot.data.default_joint_pos).clone(), - wp.to_torch(robot.data.default_joint_vel).clone(), + robot.data.default_joint_pos.torch.clone(), + robot.data.default_joint_vel.torch.clone(), ) robot.write_joint_position_to_sim_index(position=joint_pos) robot.write_joint_velocity_to_sim_index(velocity=joint_vel) @@ -272,7 +270,7 @@ def run_simulator(sim: SimulationContext, scene: InteractiveScene): print("[INFO]: Resetting scene state...") # Apply action to robot - robot.set_joint_position_target_index(target=wp.to_torch(robot.data.default_joint_pos)) + robot.set_joint_position_target_index(target=robot.data.default_joint_pos.torch) # Write data to sim scene.write_data_to_sim() # Perform step diff --git a/scripts/demos/pick_and_place.py b/scripts/demos/pick_and_place.py index af7d54d1cc13..0308706ce38d 100644 --- a/scripts/demos/pick_and_place.py +++ b/scripts/demos/pick_and_place.py @@ -143,8 +143,8 @@ def __init__(self, cfg: PickAndPlaceEnvCfg, render_mode: str | None = None, **kw self._z_dof_idx, _ = self.pick_and_place.find_joints(self.cfg.z_dof_name) # joints info - self.joint_pos = wp.to_torch(self.pick_and_place.data.joint_pos) - self.joint_vel = wp.to_torch(self.pick_and_place.data.joint_vel) + self.joint_pos = self.pick_and_place.data.joint_pos.torch + self.joint_vel = self.pick_and_place.data.joint_vel.torch # Buffers self.go_to_cube = torch.zeros(self.num_envs, dtype=torch.bool, device=self.device) @@ -240,13 +240,13 @@ def _apply_action(self) -> None: # Process each environment independently if self.go_to_cube.any(): # Effort based proportional controller to track the cube position - head_pos_x = wp.to_torch(self.pick_and_place.data.joint_pos)[self.go_to_cube, self._x_dof_idx[0]] - head_pos_y = wp.to_torch(self.pick_and_place.data.joint_pos)[self.go_to_cube, self._y_dof_idx[0]] + head_pos_x = self.pick_and_place.data.joint_pos.torch[self.go_to_cube, self._x_dof_idx[0]] + head_pos_y = self.pick_and_place.data.joint_pos.torch[self.go_to_cube, self._y_dof_idx[0]] cube_pos_x = ( - wp.to_torch(self.cube.data.root_pos_w)[self.go_to_cube, 0] - self.scene.env_origins[self.go_to_cube, 0] + self.cube.data.root_pos_w.torch[self.go_to_cube, 0] - self.scene.env_origins[self.go_to_cube, 0] ) cube_pos_y = ( - wp.to_torch(self.cube.data.root_pos_w)[self.go_to_cube, 1] - self.scene.env_origins[self.go_to_cube, 1] + self.cube.data.root_pos_w.torch[self.go_to_cube, 1] - self.scene.env_origins[self.go_to_cube, 1] ) d_cube_robot_x = cube_pos_x - head_pos_x d_cube_robot_y = cube_pos_y - head_pos_y @@ -255,8 +255,8 @@ def _apply_action(self) -> None: ) if self.go_to_target.any(): # Effort based proportional controller to track the target position - head_pos_x = wp.to_torch(self.pick_and_place.data.joint_pos)[self.go_to_target, self._x_dof_idx[0]] - head_pos_y = wp.to_torch(self.pick_and_place.data.joint_pos)[self.go_to_target, self._y_dof_idx[0]] + head_pos_x = self.pick_and_place.data.joint_pos.torch[self.go_to_target, self._x_dof_idx[0]] + head_pos_y = self.pick_and_place.data.joint_pos.torch[self.go_to_target, self._y_dof_idx[0]] target_pos_x = self.target_pos[self.go_to_target, 0] target_pos_y = self.target_pos[self.go_to_target, 1] d_target_robot_x = target_pos_x - head_pos_x @@ -304,12 +304,12 @@ def _get_rewards(self) -> torch.Tensor: def _get_dones(self) -> tuple[torch.Tensor, torch.Tensor]: # Dones - self.joint_pos = wp.to_torch(self.pick_and_place.data.joint_pos) - self.joint_vel = wp.to_torch(self.pick_and_place.data.joint_vel) + self.joint_pos = self.pick_and_place.data.joint_pos.torch + self.joint_vel = self.pick_and_place.data.joint_vel.torch # Check for time out time_out = self.episode_length_buf >= self.max_episode_length - 1 # Check if the cube reached the target - cube_root_pos_w = wp.to_torch(self.cube.data.root_pos_w) + cube_root_pos_w = self.cube.data.root_pos_w.torch cube_to_target_x_dist = cube_root_pos_w[:, 0] - self.target_pos[:, 0] - self.scene.env_origins[:, 0] cube_to_target_y_dist = cube_root_pos_w[:, 1] - self.target_pos[:, 1] - self.scene.env_origins[:, 1] cube_to_target_z_dist = cube_root_pos_w[:, 2] - self.target_pos[:, 2] - self.scene.env_origins[:, 2] @@ -350,7 +350,7 @@ def _reset_idx(self, env_ids: Sequence[int] | None): self.target_pos[env_ids, 2] = self.cfg.target_z_pos # Set the initial position of the cube - cube_pos = wp.to_torch(self.cube.data.default_root_pose)[env_ids] + cube_pos = self.cube.data.default_root_pose.torch[env_ids] cube_pos[:, 0] = sample_uniform( self.cfg.initial_object_x_pos_range[0], self.cfg.initial_object_x_pos_range[1], @@ -368,7 +368,7 @@ def _reset_idx(self, env_ids: Sequence[int] | None): self.cube.write_root_pose_to_sim_index(root_pose=cube_pos, env_ids=env_ids) # Set the initial position of the robot - joint_pos = wp.to_torch(self.pick_and_place.data.default_joint_pos)[env_ids] + joint_pos = self.pick_and_place.data.default_joint_pos.torch[env_ids] joint_pos[:, self._x_dof_idx] += sample_uniform( self.cfg.initial_x_pos_range[0], self.cfg.initial_x_pos_range[1], @@ -387,7 +387,7 @@ def _reset_idx(self, env_ids: Sequence[int] | None): joint_pos[:, self._z_dof_idx].shape, self.device, ) - joint_vel = wp.to_torch(self.pick_and_place.data.default_joint_vel)[env_ids] + joint_vel = self.pick_and_place.data.default_joint_vel.torch[env_ids] self.joint_pos[env_ids] = joint_pos self.joint_vel[env_ids] = joint_vel diff --git a/scripts/demos/quadcopter.py b/scripts/demos/quadcopter.py index 0e665596e71d..4cc9e1a27095 100644 --- a/scripts/demos/quadcopter.py +++ b/scripts/demos/quadcopter.py @@ -35,7 +35,6 @@ """Rest everything follows.""" import torch -import warp as wp import isaaclab.sim as sim_utils from isaaclab.assets import Articulation @@ -93,12 +92,12 @@ def main(): sim_time = 0.0 count = 0 # reset dof state - joint_pos, joint_vel = wp.to_torch(robot.data.default_joint_pos), wp.to_torch(robot.data.default_joint_vel) + joint_pos, joint_vel = robot.data.default_joint_pos.torch, robot.data.default_joint_vel.torch robot.write_joint_position_to_sim_index(position=joint_pos) robot.write_joint_velocity_to_sim_index(velocity=joint_vel) - default_root_pose = wp.to_torch(robot.data.default_root_pose) + default_root_pose = robot.data.default_root_pose.torch robot.write_root_pose_to_sim_index(root_pose=default_root_pose) - default_root_vel = wp.to_torch(robot.data.default_root_vel) + default_root_vel = robot.data.default_root_vel.torch robot.write_root_velocity_to_sim_index(root_velocity=default_root_vel) robot.reset() # reset command diff --git a/scripts/demos/quadrupeds.py b/scripts/demos/quadrupeds.py index 28cc64074bff..59551a3738a2 100644 --- a/scripts/demos/quadrupeds.py +++ b/scripts/demos/quadrupeds.py @@ -36,7 +36,6 @@ import numpy as np import torch -import warp as wp import isaaclab.sim as sim_utils from isaaclab.assets import Articulation @@ -141,15 +140,15 @@ def run_simulator(sim: sim_utils.SimulationContext, entities: dict[str, Articula # reset robots for index, robot in enumerate(entities.values()): # root state - root_pose = wp.to_torch(robot.data.default_root_pose).clone() + root_pose = robot.data.default_root_pose.torch.clone() root_pose[:, :3] += origins[index] robot.write_root_pose_to_sim_index(root_pose=root_pose) - root_vel = wp.to_torch(robot.data.default_root_vel).clone() + root_vel = robot.data.default_root_vel.torch.clone() robot.write_root_velocity_to_sim_index(root_velocity=root_vel) # joint state joint_pos, joint_vel = ( - wp.to_torch(robot.data.default_joint_pos).clone(), - wp.to_torch(robot.data.default_joint_vel).clone(), + robot.data.default_joint_pos.torch.clone(), + robot.data.default_joint_vel.torch.clone(), ) robot.write_joint_position_to_sim_index(position=joint_pos) robot.write_joint_velocity_to_sim_index(velocity=joint_vel) @@ -159,9 +158,7 @@ def run_simulator(sim: sim_utils.SimulationContext, entities: dict[str, Articula # apply default actions to the quadrupedal robots for robot in entities.values(): # generate random joint positions - joint_pos_target = ( - wp.to_torch(robot.data.default_joint_pos) + torch.randn_like(wp.to_torch(robot.data.joint_pos)) * 0.1 - ) + joint_pos_target = robot.data.default_joint_pos.torch + torch.randn_like(robot.data.joint_pos.torch) * 0.1 # apply action to the robot robot.set_joint_position_target_index(target=joint_pos_target) # write data to sim diff --git a/scripts/demos/sensors/cameras.py b/scripts/demos/sensors/cameras.py index f96f7226039f..400881ac5d62 100644 --- a/scripts/demos/sensors/cameras.py +++ b/scripts/demos/sensors/cameras.py @@ -44,12 +44,11 @@ import matplotlib.pyplot as plt import numpy as np import torch -import warp as wp import isaaclab.sim as sim_utils from isaaclab.assets import ArticulationCfg, AssetBaseCfg from isaaclab.scene import InteractiveScene, InteractiveSceneCfg -from isaaclab.sensors import CameraCfg, RayCasterCameraCfg, TiledCameraCfg +from isaaclab.sensors import CameraCfg, RayCasterCameraCfg from isaaclab.sensors.ray_caster import patterns from isaaclab.terrains import TerrainImporterCfg from isaaclab.utils import configclass @@ -95,14 +94,14 @@ class SensorsSceneCfg(InteractiveSceneCfg): ), offset=CameraCfg.OffsetCfg(pos=(0.510, 0.0, 0.015), rot=(0.5, -0.5, 0.5, -0.5), convention="ros"), ) - tiled_camera = TiledCameraCfg( + tiled_camera = CameraCfg( prim_path="{ENV_REGEX_NS}/Robot/base/front_cam", update_period=0.1, height=480, width=640, data_types=["rgb", "distance_to_image_plane"], spawn=None, # the camera is already spawned in the scene - offset=TiledCameraCfg.OffsetCfg(pos=(0.510, 0.0, 0.015), rot=(0.5, -0.5, 0.5, -0.5), convention="ros"), + offset=CameraCfg.OffsetCfg(pos=(0.510, 0.0, 0.015), rot=(0.5, -0.5, 0.5, -0.5), convention="ros"), ) raycast_camera = RayCasterCameraCfg( prim_path="{ENV_REGEX_NS}/Robot/base", @@ -192,15 +191,15 @@ def run_simulator(sim: sim_utils.SimulationContext, scene: InteractiveScene): # root state # we offset the root state by the origin since the states are written in simulation world frame # if this is not done, then the robots will be spawned at the (0, 0, 0) of the simulation world - root_pose = wp.to_torch(scene["robot"].data.default_root_pose).clone() + root_pose = scene["robot"].data.default_root_pose.torch.clone() root_pose[:, :3] += scene.env_origins scene["robot"].write_root_pose_to_sim_index(root_pose=root_pose) - root_vel = wp.to_torch(scene["robot"].data.default_root_vel).clone() + root_vel = scene["robot"].data.default_root_vel.torch.clone() scene["robot"].write_root_velocity_to_sim_index(root_velocity=root_vel) # set joint positions with some noise joint_pos, joint_vel = ( - wp.to_torch(scene["robot"].data.default_joint_pos).clone(), - wp.to_torch(scene["robot"].data.default_joint_vel).clone(), + scene["robot"].data.default_joint_pos.torch.clone(), + scene["robot"].data.default_joint_vel.torch.clone(), ) joint_pos += torch.rand_like(joint_pos) * 0.1 scene["robot"].write_joint_position_to_sim_index(position=joint_pos) @@ -210,7 +209,7 @@ def run_simulator(sim: sim_utils.SimulationContext, scene: InteractiveScene): print("[INFO]: Resetting robot state...") # Apply default actions to the robot # -- generate actions/commands - targets = wp.to_torch(scene["robot"].data.default_joint_pos) + targets = scene["robot"].data.default_joint_pos.torch # -- apply action to the robot scene["robot"].set_joint_position_target_index(target=targets) # -- write data to sim @@ -244,7 +243,7 @@ def run_simulator(sim: sim_utils.SimulationContext, scene: InteractiveScene): rgb_images = [scene["camera"].data.output["rgb"][0, ..., :3], scene["tiled_camera"].data.output["rgb"][0]] save_images_grid( rgb_images, - subtitles=["Camera", "TiledCamera"], + subtitles=["Camera"], title="RGB Image: Cam0", filename=os.path.join(output_dir, "rgb", f"{count:04d}.jpg"), ) @@ -258,7 +257,7 @@ def run_simulator(sim: sim_utils.SimulationContext, scene: InteractiveScene): save_images_grid( depth_images, cmap="turbo", - subtitles=["Camera", "TiledCamera", "RaycasterCamera"], + subtitles=["Camera", "RaycasterCamera"], title="Depth Image: Cam0", filename=os.path.join(output_dir, "distance_to_camera", f"{count:04d}.jpg"), ) diff --git a/scripts/demos/sensors/contact_sensor.py b/scripts/demos/sensors/contact_sensor.py index 0c1a72126e90..37ddd14e28a6 100644 --- a/scripts/demos/sensors/contact_sensor.py +++ b/scripts/demos/sensors/contact_sensor.py @@ -26,7 +26,6 @@ """Rest everything follows.""" import torch -import warp as wp import isaaclab.sim as sim_utils from isaaclab.assets import AssetBaseCfg, RigidObjectCfg @@ -109,15 +108,15 @@ def run_simulator(sim: sim_utils.SimulationContext, scene: InteractiveScene): # root state # we offset the root state by the origin since the states are written in simulation world frame # if this is not done, then the robots will be spawned at the (0, 0, 0) of the simulation world - root_pose = wp.to_torch(scene["robot"].data.default_root_pose).clone() + root_pose = scene["robot"].data.default_root_pose.torch.clone() root_pose[:, :3] += scene.env_origins scene["robot"].write_root_pose_to_sim_index(root_pose=root_pose) - root_vel = wp.to_torch(scene["robot"].data.default_root_vel).clone() + root_vel = scene["robot"].data.default_root_vel.torch.clone() scene["robot"].write_root_velocity_to_sim_index(root_velocity=root_vel) # set joint positions with some noise joint_pos, joint_vel = ( - wp.to_torch(scene["robot"].data.default_joint_pos).clone(), - wp.to_torch(scene["robot"].data.default_joint_vel).clone(), + scene["robot"].data.default_joint_pos.torch.clone(), + scene["robot"].data.default_joint_vel.torch.clone(), ) joint_pos += torch.rand_like(joint_pos) * 0.1 scene["robot"].write_joint_position_to_sim_index(position=joint_pos) @@ -127,7 +126,7 @@ def run_simulator(sim: sim_utils.SimulationContext, scene: InteractiveScene): print("[INFO]: Resetting robot state...") # Apply default actions to the robot # -- generate actions/commands - targets = wp.to_torch(scene["robot"].data.default_joint_pos) + targets = scene["robot"].data.default_joint_pos.torch # -- apply action to the robot scene["robot"].set_joint_position_target_index(target=targets) # -- write data to sim diff --git a/scripts/demos/sensors/frame_transformer_sensor.py b/scripts/demos/sensors/frame_transformer_sensor.py index e8a8760219a9..039e38935547 100644 --- a/scripts/demos/sensors/frame_transformer_sensor.py +++ b/scripts/demos/sensors/frame_transformer_sensor.py @@ -24,7 +24,6 @@ """Rest everything follows.""" import torch -import warp as wp import isaaclab.sim as sim_utils from isaaclab.assets import AssetBaseCfg, RigidObjectCfg @@ -105,15 +104,15 @@ def run_simulator(sim: sim_utils.SimulationContext, scene: InteractiveScene): # root state # we offset the root state by the origin since the states are written in simulation world frame # if this is not done, then the robots will be spawned at the (0, 0, 0) of the simulation world - root_pose = wp.to_torch(scene["robot"].data.default_root_pose).clone() + root_pose = scene["robot"].data.default_root_pose.torch.clone() root_pose[:, :3] += scene.env_origins scene["robot"].write_root_pose_to_sim_index(root_pose=root_pose) - root_vel = wp.to_torch(scene["robot"].data.default_root_vel).clone() + root_vel = scene["robot"].data.default_root_vel.torch.clone() scene["robot"].write_root_velocity_to_sim_index(root_velocity=root_vel) # set joint positions with some noise joint_pos, joint_vel = ( - wp.to_torch(scene["robot"].data.default_joint_pos).clone(), - wp.to_torch(scene["robot"].data.default_joint_vel).clone(), + scene["robot"].data.default_joint_pos.torch.clone(), + scene["robot"].data.default_joint_vel.torch.clone(), ) joint_pos += torch.rand_like(joint_pos) * 0.1 scene["robot"].write_joint_position_to_sim_index(position=joint_pos) @@ -123,7 +122,7 @@ def run_simulator(sim: sim_utils.SimulationContext, scene: InteractiveScene): print("[INFO]: Resetting robot state...") # Apply default actions to the robot # -- generate actions/commands - targets = wp.to_torch(scene["robot"].data.default_joint_pos) + targets = scene["robot"].data.default_joint_pos.torch # -- apply action to the robot scene["robot"].set_joint_position_target_index(target=targets) # -- write data to sim diff --git a/scripts/demos/sensors/imu_sensor.py b/scripts/demos/sensors/imu_sensor.py index 9990648ee40f..beb701d62074 100644 --- a/scripts/demos/sensors/imu_sensor.py +++ b/scripts/demos/sensors/imu_sensor.py @@ -26,7 +26,6 @@ """Rest everything follows.""" import torch -import warp as wp import isaaclab.sim as sim_utils from isaaclab.assets import AssetBaseCfg @@ -42,7 +41,7 @@ @configclass class ImuSensorSceneCfg(InteractiveSceneCfg): - """Design the scene with sensors on the robot.""" + """Design the scene with IMU sensors on the robot.""" # ground plane ground = AssetBaseCfg(prim_path="/World/defaultGroundPlane", spawn=sim_utils.GroundPlaneCfg()) @@ -55,9 +54,9 @@ class ImuSensorSceneCfg(InteractiveSceneCfg): # robot robot = ANYMAL_C_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") - imu_RF = ImuCfg(prim_path="{ENV_REGEX_NS}/Robot/LF_FOOT", debug_vis=True) + imu_RF = ImuCfg(prim_path="{ENV_REGEX_NS}/Robot/LF_FOOT") - imu_LF = ImuCfg(prim_path="{ENV_REGEX_NS}/Robot/RF_FOOT", gravity_bias=(0, 0, 0), debug_vis=True) + imu_LF = ImuCfg(prim_path="{ENV_REGEX_NS}/Robot/RF_FOOT") def run_simulator(sim: sim_utils.SimulationContext, scene: InteractiveScene): @@ -73,18 +72,15 @@ def run_simulator(sim: sim_utils.SimulationContext, scene: InteractiveScene): # reset counter count = 0 # reset the scene entities - # root state - # we offset the root state by the origin since the states are written in simulation world frame - # if this is not done, then the robots will be spawned at the (0, 0, 0) of the simulation world - root_pose = wp.to_torch(scene["robot"].data.default_root_pose).clone() + root_pose = scene["robot"].data.default_root_pose.torch.clone() root_pose[:, :3] += scene.env_origins scene["robot"].write_root_link_pose_to_sim_index(root_pose=root_pose) - root_vel = wp.to_torch(scene["robot"].data.default_root_vel).clone() + root_vel = scene["robot"].data.default_root_vel.torch.clone() scene["robot"].write_root_com_velocity_to_sim_index(root_velocity=root_vel) # set joint positions with some noise joint_pos, joint_vel = ( - wp.to_torch(scene["robot"].data.default_joint_pos).clone(), - wp.to_torch(scene["robot"].data.default_joint_vel).clone(), + scene["robot"].data.default_joint_pos.torch.clone(), + scene["robot"].data.default_joint_vel.torch.clone(), ) joint_pos += torch.rand_like(joint_pos) * 0.1 scene["robot"].write_joint_position_to_sim_index(position=joint_pos) @@ -93,11 +89,8 @@ def run_simulator(sim: sim_utils.SimulationContext, scene: InteractiveScene): scene.reset() print("[INFO]: Resetting robot state...") # Apply default actions to the robot - # -- generate actions/commands - targets = wp.to_torch(scene["robot"].data.default_joint_pos) - # -- apply action to the robot + targets = scene["robot"].data.default_joint_pos.torch scene["robot"].set_joint_position_target_index(target=targets) - # -- write data to sim scene.write_data_to_sim() # perform step sim.step() @@ -110,16 +103,12 @@ def run_simulator(sim: sim_utils.SimulationContext, scene: InteractiveScene): # print information from the sensors print("-------------------------------") print(scene["imu_LF"]) - print("Received linear velocity: ", scene["imu_LF"].data.lin_vel_b) print("Received angular velocity: ", scene["imu_LF"].data.ang_vel_b) print("Received linear acceleration: ", scene["imu_LF"].data.lin_acc_b) - print("Received angular acceleration: ", scene["imu_LF"].data.ang_acc_b) print("-------------------------------") print(scene["imu_RF"]) - print("Received linear velocity: ", scene["imu_RF"].data.lin_vel_b) print("Received angular velocity: ", scene["imu_RF"].data.ang_vel_b) print("Received linear acceleration: ", scene["imu_RF"].data.lin_acc_b) - print("Received angular acceleration: ", scene["imu_RF"].data.ang_acc_b) def main(): diff --git a/scripts/demos/sensors/multi_mesh_raycaster.py b/scripts/demos/sensors/multi_mesh_raycaster.py index 1a586a8aa2d1..c154a6181763 100644 --- a/scripts/demos/sensors/multi_mesh_raycaster.py +++ b/scripts/demos/sensors/multi_mesh_raycaster.py @@ -49,7 +49,6 @@ import random import torch -import warp as wp from pxr import Gf, Sdf @@ -239,17 +238,17 @@ def run_simulator(sim: sim_utils.SimulationContext, scene: InteractiveScene): count = 0 # reset the scene entities # root state - root_pose = wp.to_torch(scene["asset"].data.default_root_pose).clone() + root_pose = scene["asset"].data.default_root_pose.torch.clone() root_pose[:, :3] += scene.env_origins scene["asset"].write_root_pose_to_sim_index(root_pose=root_pose) - root_vel = wp.to_torch(scene["asset"].data.default_root_vel).clone() + root_vel = scene["asset"].data.default_root_vel.torch.clone() scene["asset"].write_root_velocity_to_sim_index(root_velocity=root_vel) if isinstance(scene["asset"], Articulation): # set joint positions with some noise joint_pos, joint_vel = ( - wp.to_torch(scene["asset"].data.default_joint_pos).clone(), - wp.to_torch(scene["asset"].data.default_joint_vel).clone(), + scene["asset"].data.default_joint_pos.torch.clone(), + scene["asset"].data.default_joint_vel.torch.clone(), ) joint_pos += torch.rand_like(joint_pos) * 0.1 scene["asset"].write_joint_position_to_sim_index(position=joint_pos) @@ -260,7 +259,7 @@ def run_simulator(sim: sim_utils.SimulationContext, scene: InteractiveScene): if isinstance(scene["asset"], Articulation): # -- generate actions/commands - default_joint_pos = wp.to_torch(scene["asset"].data.default_joint_pos) + default_joint_pos = scene["asset"].data.default_joint_pos.torch targets = default_joint_pos + 5 * (torch.rand_like(default_joint_pos) - 0.5) # -- apply action to the asset scene["asset"].set_joint_position_target_index(target=targets) diff --git a/scripts/demos/sensors/multi_mesh_raycaster_camera.py b/scripts/demos/sensors/multi_mesh_raycaster_camera.py index 6c61a2a4c4dd..5d1dfd39a07d 100644 --- a/scripts/demos/sensors/multi_mesh_raycaster_camera.py +++ b/scripts/demos/sensors/multi_mesh_raycaster_camera.py @@ -49,7 +49,6 @@ import random import torch -import warp as wp from pxr import Gf, Sdf @@ -255,17 +254,17 @@ def run_simulator(sim: sim_utils.SimulationContext, scene: InteractiveScene): count = 0 # reset the scene entities # root state - root_pose = wp.to_torch(scene["asset"].data.default_root_pose).clone() + root_pose = scene["asset"].data.default_root_pose.torch.clone() root_pose[:, :3] += scene.env_origins scene["asset"].write_root_pose_to_sim_index(root_pose=root_pose) - root_vel = wp.to_torch(scene["asset"].data.default_root_vel).clone() + root_vel = scene["asset"].data.default_root_vel.torch.clone() scene["asset"].write_root_velocity_to_sim_index(root_velocity=root_vel) if isinstance(scene["asset"], Articulation): # set joint positions with some noise joint_pos, joint_vel = ( - wp.to_torch(scene["asset"].data.default_joint_pos).clone(), - wp.to_torch(scene["asset"].data.default_joint_vel).clone(), + scene["asset"].data.default_joint_pos.torch.clone(), + scene["asset"].data.default_joint_vel.torch.clone(), ) joint_pos += torch.rand_like(joint_pos) * 0.1 scene["asset"].write_joint_position_to_sim_index(position=joint_pos) @@ -276,7 +275,7 @@ def run_simulator(sim: sim_utils.SimulationContext, scene: InteractiveScene): if isinstance(scene["asset"], Articulation): # -- generate actions/commands - default_joint_pos = wp.to_torch(scene["asset"].data.default_joint_pos) + default_joint_pos = scene["asset"].data.default_joint_pos.torch targets = default_joint_pos + 5 * (torch.rand_like(default_joint_pos) - 0.5) # -- apply action to the asset scene["asset"].set_joint_position_target_index(target=targets) @@ -295,7 +294,7 @@ def run_simulator(sim: sim_utils.SimulationContext, scene: InteractiveScene): countdown -= 1 continue - data = scene["ray_caster"].data.ray_hits_w.cpu().numpy() # noqa: F841 + data = scene["ray_caster"].data.ray_hits_w.torch.cpu().numpy() # noqa: F841 triggered = True else: continue diff --git a/scripts/demos/sensors/pva_sensor.py b/scripts/demos/sensors/pva_sensor.py new file mode 100644 index 000000000000..a51ea7c17cc9 --- /dev/null +++ b/scripts/demos/sensors/pva_sensor.py @@ -0,0 +1,147 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Launch Isaac Sim Simulator first.""" + +import argparse + +from isaaclab.app import AppLauncher + +# add argparse arguments +parser = argparse.ArgumentParser(description="Example on using the PVA sensor.") +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) +# demos should open Kit visualizer by default +parser.set_defaults(visualizer=["kit"]) +# 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 torch + +import isaaclab.sim as sim_utils +from isaaclab.assets import AssetBaseCfg +from isaaclab.scene import InteractiveScene, InteractiveSceneCfg +from isaaclab.sensors import PvaCfg +from isaaclab.utils import configclass + +## +# Pre-defined configs +## +from isaaclab_assets.robots.anymal import ANYMAL_C_CFG # isort: skip + + +@configclass +class PvaSensorSceneCfg(InteractiveSceneCfg): + """Design the scene with sensors on the robot.""" + + # ground plane + 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)) + ) + + # robot + robot = ANYMAL_C_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") + + pva_RF = PvaCfg(prim_path="{ENV_REGEX_NS}/Robot/LF_FOOT", debug_vis=True) + + pva_LF = PvaCfg(prim_path="{ENV_REGEX_NS}/Robot/RF_FOOT", debug_vis=True) + + +def run_simulator(sim: sim_utils.SimulationContext, scene: InteractiveScene): + """Run the simulator.""" + # Define simulation stepping + sim_dt = sim.get_physics_dt() + sim_time = 0.0 + count = 0 + + # Simulate physics + while simulation_app.is_running(): + if count % 500 == 0: + # reset counter + count = 0 + # reset the scene entities + # root state + # we offset the root state by the origin since the states are written in simulation world frame + # if this is not done, then the robots will be spawned at the (0, 0, 0) of the simulation world + root_pose = scene["robot"].data.default_root_pose.torch.clone() + root_pose[:, :3] += scene.env_origins + scene["robot"].write_root_link_pose_to_sim_index(root_pose=root_pose) + root_vel = scene["robot"].data.default_root_vel.torch.clone() + scene["robot"].write_root_com_velocity_to_sim_index(root_velocity=root_vel) + # set joint positions with some noise + joint_pos, joint_vel = ( + scene["robot"].data.default_joint_pos.torch.clone(), + scene["robot"].data.default_joint_vel.torch.clone(), + ) + joint_pos += torch.rand_like(joint_pos) * 0.1 + scene["robot"].write_joint_position_to_sim_index(position=joint_pos) + scene["robot"].write_joint_velocity_to_sim_index(velocity=joint_vel) + # clear internal buffers + scene.reset() + print("[INFO]: Resetting robot state...") + # Apply default actions to the robot + # -- generate actions/commands + targets = scene["robot"].data.default_joint_pos.torch + # -- apply action to the robot + scene["robot"].set_joint_position_target_index(target=targets) + # -- write data to sim + scene.write_data_to_sim() + # perform step + sim.step() + # update sim-time + sim_time += sim_dt + count += 1 + # update buffers + scene.update(sim_dt) + + # print information from the sensors + print("-------------------------------") + print(scene["pva_LF"]) + print("Received linear velocity: ", scene["pva_LF"].data.lin_vel_b) + print("Received angular velocity: ", scene["pva_LF"].data.ang_vel_b) + print("Received linear acceleration: ", scene["pva_LF"].data.lin_acc_b) + print("Received angular acceleration: ", scene["pva_LF"].data.ang_acc_b) + print("-------------------------------") + print(scene["pva_RF"]) + print("Received linear velocity: ", scene["pva_RF"].data.lin_vel_b) + print("Received angular velocity: ", scene["pva_RF"].data.ang_vel_b) + print("Received linear acceleration: ", scene["pva_RF"].data.lin_acc_b) + print("Received angular acceleration: ", scene["pva_RF"].data.ang_acc_b) + + +def main(): + """Main function.""" + + # Initialize the simulation context + sim_cfg = sim_utils.SimulationCfg(dt=0.005, device=args_cli.device) + sim = sim_utils.SimulationContext(sim_cfg) + # Set main camera + sim.set_camera_view(eye=[3.5, 3.5, 3.5], target=[0.0, 0.0, 0.0]) + # design scene + scene_cfg = PvaSensorSceneCfg(num_envs=args_cli.num_envs, env_spacing=2.0) + scene = InteractiveScene(scene_cfg) + # Play the simulator + sim.reset() + # Now we are ready! + print("[INFO]: Setup complete...") + # Run the simulator + run_simulator(sim, scene) + + +if __name__ == "__main__": + # run the main function + main() + # close sim app + simulation_app.close() diff --git a/scripts/demos/sensors/raycaster_sensor.py b/scripts/demos/sensors/raycaster_sensor.py index 43c6eb6911e0..25073af40487 100644 --- a/scripts/demos/sensors/raycaster_sensor.py +++ b/scripts/demos/sensors/raycaster_sensor.py @@ -25,7 +25,6 @@ import numpy as np import torch -import warp as wp import isaaclab.sim as sim_utils from isaaclab.assets import AssetBaseCfg @@ -62,7 +61,7 @@ class RaycasterSensorSceneCfg(InteractiveSceneCfg): robot = ANYMAL_C_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") ray_caster = RayCasterCfg( - prim_path="{ENV_REGEX_NS}/Robot/base/lidar_cage", + prim_path="{ENV_REGEX_NS}/Robot/base", update_period=1 / 60, offset=RayCasterCfg.OffsetCfg(pos=(0, 0, 0.5)), mesh_prim_paths=["/World/Ground"], @@ -93,15 +92,15 @@ def run_simulator(sim: sim_utils.SimulationContext, scene: InteractiveScene): # root state # we offset the root state by the origin since the states are written in simulation world frame # if this is not done, then the robots will be spawned at the (0, 0, 0) of the simulation world - root_pose = wp.to_torch(scene["robot"].data.default_root_pose).clone() + root_pose = scene["robot"].data.default_root_pose.torch.clone() root_pose[:, :3] += scene.env_origins scene["robot"].write_root_pose_to_sim_index(root_pose=root_pose) - root_vel = wp.to_torch(scene["robot"].data.default_root_vel).clone() + root_vel = scene["robot"].data.default_root_vel.torch.clone() scene["robot"].write_root_velocity_to_sim_index(root_velocity=root_vel) # set joint positions with some noise joint_pos, joint_vel = ( - wp.to_torch(scene["robot"].data.default_joint_pos).clone(), - wp.to_torch(scene["robot"].data.default_joint_vel).clone(), + scene["robot"].data.default_joint_pos.torch.clone(), + scene["robot"].data.default_joint_vel.torch.clone(), ) joint_pos += torch.rand_like(joint_pos) * 0.1 scene["robot"].write_joint_position_to_sim_index(position=joint_pos) @@ -111,7 +110,7 @@ def run_simulator(sim: sim_utils.SimulationContext, scene: InteractiveScene): print("[INFO]: Resetting robot state...") # Apply default actions to the robot # -- generate actions/commands - targets = wp.to_torch(scene["robot"].data.default_joint_pos) + targets = scene["robot"].data.default_joint_pos.torch # -- apply action to the robot scene["robot"].set_joint_position_target_index(target=targets) # -- write data to sim @@ -127,13 +126,13 @@ def run_simulator(sim: sim_utils.SimulationContext, scene: InteractiveScene): # print information from the sensors print("-------------------------------") print(scene["ray_caster"]) - print("Ray cast hit results: ", scene["ray_caster"].data.ray_hits_w) + print("Ray cast hit results: ", scene["ray_caster"].data.ray_hits_w.torch) if not triggered: if countdown > 0: countdown -= 1 continue - data = scene["ray_caster"].data.ray_hits_w.cpu().numpy() + data = scene["ray_caster"].data.ray_hits_w.torch.cpu().numpy() np.save("cast_data.npy", data) triggered = True else: diff --git a/scripts/demos/sensors/tacsl_sensor.py b/scripts/demos/sensors/tacsl_sensor.py index 97f59589fa3d..22f40e8c9ff2 100644 --- a/scripts/demos/sensors/tacsl_sensor.py +++ b/scripts/demos/sensors/tacsl_sensor.py @@ -30,7 +30,6 @@ import cv2 import numpy as np import torch -import warp as wp from isaaclab.app import AppLauncher @@ -83,7 +82,7 @@ import isaaclab.sim as sim_utils from isaaclab.assets import ArticulationCfg, AssetBaseCfg, RigidObjectCfg from isaaclab.scene import InteractiveScene, InteractiveSceneCfg -from isaaclab.sensors import TiledCameraCfg +from isaaclab.sensors import CameraCfg from isaaclab.utils import configclass from isaaclab.utils.assets import ISAACLAB_NUCLEUS_DIR from isaaclab.utils.timer import Timer @@ -158,7 +157,7 @@ class TactileSensorsSceneCfg(InteractiveSceneCfg): # Camera configuration # Note: the camera is already spawned in the scene, properties are set in the # 'gelsight_r15_finger.usd' USD file - camera_cfg=TiledCameraCfg( + camera_cfg=CameraCfg( prim_path="{ENV_REGEX_NS}/Robot/elastomer_tip/cam", height=GELSIGHT_R15_CFG.image_height, width=GELSIGHT_R15_CFG.image_width, @@ -333,10 +332,10 @@ def run_simulator(sim: sim_utils.SimulationContext, scene: InteractiveScene): # Reset robot and contact object positions count = 0 for entity in entity_list: - root_pose = wp.to_torch(scene[entity].data.default_root_pose).clone() + root_pose = scene[entity].data.default_root_pose.torch.clone() root_pose[:, :3] += scene.env_origins scene[entity].write_root_pose_to_sim_index(root_pose=root_pose) - root_vel = wp.to_torch(scene[entity].data.default_root_vel).clone() + root_vel = scene[entity].data.default_root_vel.torch.clone() scene[entity].write_root_velocity_to_sim_index(root_velocity=root_vel) scene.reset() diff --git a/scripts/environments/random_agent.py b/scripts/environments/random_agent.py index e98bd17f951e..bd6671f00969 100644 --- a/scripts/environments/random_agent.py +++ b/scripts/environments/random_agent.py @@ -37,7 +37,7 @@ def main(): torch.manual_seed(42) - # parse configuration via Hydra (supports preset selection, e.g. env.sim.physics=newton) + # parse configuration via Hydra (supports preset selection, e.g. env.sim.physics=newton_mjwarp) env_cfg, _ = resolve_task_config(args_cli.task, "") with launch_simulation(env_cfg, args_cli): diff --git a/scripts/environments/state_machine/lift_cube_sm.py b/scripts/environments/state_machine/lift_cube_sm.py index 003304089055..ff7734a69e1a 100644 --- a/scripts/environments/state_machine/lift_cube_sm.py +++ b/scripts/environments/state_machine/lift_cube_sm.py @@ -284,12 +284,12 @@ def main(): # -- end-effector frame ee_frame_sensor = env.unwrapped.scene["ee_frame"] tcp_rest_position = ( - wp.to_torch(ee_frame_sensor.data.target_pos_w)[..., 0, :].clone() - env.unwrapped.scene.env_origins + ee_frame_sensor.data.target_pos_w.torch[..., 0, :].clone() - env.unwrapped.scene.env_origins ) - tcp_rest_orientation = wp.to_torch(ee_frame_sensor.data.target_quat_w)[..., 0, :].clone() + tcp_rest_orientation = ee_frame_sensor.data.target_quat_w.torch[..., 0, :].clone() # -- object frame object_data: RigidObjectData = env.unwrapped.scene["object"].data - object_position = wp.to_torch(object_data.root_pos_w) - env.unwrapped.scene.env_origins + object_position = object_data.root_pos_w.torch - env.unwrapped.scene.env_origins # -- target object frame desired_position = env.unwrapped.command_manager.get_command("object_pose")[..., :3] diff --git a/scripts/environments/state_machine/lift_teddy_bear.py b/scripts/environments/state_machine/lift_teddy_bear.py index 47a6c91cd197..0aa8e0c33504 100644 --- a/scripts/environments/state_machine/lift_teddy_bear.py +++ b/scripts/environments/state_machine/lift_teddy_bear.py @@ -34,9 +34,9 @@ simulation_app = app_launcher.app # disable metrics assembler due to scene graph instancing -from isaacsim.core.utils.extensions import disable_extension +from isaacsim.core.experimental.utils.app import enable_extension -disable_extension("omni.usd.metrics.assembler.ui") +enable_extension("omni.usd.metrics.assembler.ui", enabled=False) """Rest everything else.""" @@ -304,12 +304,12 @@ def main(): # -- end-effector frame ee_frame_sensor = env.unwrapped.scene["ee_frame"] tcp_rest_position = ( - wp.to_torch(ee_frame_sensor.data.target_pos_w)[..., 0, :].clone() - env.unwrapped.scene.env_origins + ee_frame_sensor.data.target_pos_w.torch[..., 0, :].clone() - env.unwrapped.scene.env_origins ) - tcp_rest_orientation = wp.to_torch(ee_frame_sensor.data.target_quat_w)[..., 0, :].clone() + tcp_rest_orientation = ee_frame_sensor.data.target_quat_w.torch[..., 0, :].clone() # -- object frame object_data: RigidObjectData = env.unwrapped.scene["object"].data - object_position = wp.to_torch(object_data.root_pos_w) - env.unwrapped.scene.env_origins + object_position = object_data.root_pos_w.torch - env.unwrapped.scene.env_origins object_position += object_local_grasp_position # -- target object frame diff --git a/scripts/environments/state_machine/open_cabinet_sm.py b/scripts/environments/state_machine/open_cabinet_sm.py index 4b2d52ebe243..39cae64bce07 100644 --- a/scripts/environments/state_machine/open_cabinet_sm.py +++ b/scripts/environments/state_machine/open_cabinet_sm.py @@ -300,16 +300,14 @@ def main(): # observations # -- end-effector frame ee_frame_tf: FrameTransformer = env.unwrapped.scene["ee_frame"] - tcp_rest_position = ( - wp.to_torch(ee_frame_tf.data.target_pos_w)[..., 0, :].clone() - env.unwrapped.scene.env_origins - ) - tcp_rest_orientation = wp.to_torch(ee_frame_tf.data.target_quat_w)[..., 0, :].clone() + tcp_rest_position = ee_frame_tf.data.target_pos_w.torch[..., 0, :].clone() - env.unwrapped.scene.env_origins + tcp_rest_orientation = ee_frame_tf.data.target_quat_w.torch[..., 0, :].clone() # -- handle frame cabinet_frame_tf: FrameTransformer = env.unwrapped.scene["cabinet_frame"] cabinet_position = ( - wp.to_torch(cabinet_frame_tf.data.target_pos_w)[..., 0, :].clone() - env.unwrapped.scene.env_origins + cabinet_frame_tf.data.target_pos_w.torch[..., 0, :].clone() - env.unwrapped.scene.env_origins ) - cabinet_orientation = wp.to_torch(cabinet_frame_tf.data.target_quat_w)[..., 0, :].clone() + cabinet_orientation = cabinet_frame_tf.data.target_quat_w.torch[..., 0, :].clone() # advance state machine actions = open_sm.compute( diff --git a/scripts/environments/teleoperation/teleop_se3_agent.py b/scripts/environments/teleoperation/teleop_se3_agent.py index c4821c86b9be..3f1f4ac477fc 100644 --- a/scripts/environments/teleoperation/teleop_se3_agent.py +++ b/scripts/environments/teleoperation/teleop_se3_agent.py @@ -29,16 +29,30 @@ parser.add_argument( "--teleop_device", type=str, - default="keyboard", + default=None, help=( - "Teleop device. Set here (legacy) or via the environment config. If using the environment config, pass the" - " device key/name defined under 'teleop_devices' (it can be a custom name, not necessarily 'handtracking')." - " Built-ins: keyboard, spacemouse, gamepad. Not all tasks support all built-ins." - " If env_cfg has isaac_teleop configured, this argument is ignored and IsaacTeleop stack is used." + "Legacy teleop device name. When omitted, the IsaacTeleop pipeline is used if configured in the env," + " otherwise keyboard is used as fallback. When explicitly provided, the script uses the legacy" + " teleop_devices path and looks up this name in env_cfg.teleop_devices.devices." ), ) parser.add_argument("--task", type=str, default=None, help="Name of the task.") parser.add_argument("--sensitivity", type=float, default=1.0, help="Sensitivity factor.") +parser.add_argument( + "--cloudxr_env", + type=str, + default="cloudxrjs", + help=( + "Path to a CloudXR .env file, or a shorthand: 'cloudxrjs' (Quest/Pico, default) or 'avp' (Apple Vision Pro)." + " Set to 'none' to disable CloudXR auto-launch entirely." + ), +) +parser.add_argument( + "--auto_launch_cloudxr", + action=argparse.BooleanOptionalAction, + default=True, + help="Auto-launch the CloudXR runtime when --cloudxr_env is set. Use --no-auto_launch_cloudxr to disable.", +) # append AppLauncher cli args AppLauncher.add_app_launcher_args(parser) # parse the arguments @@ -46,9 +60,6 @@ app_launcher_args = vars(args_cli) -if "handtracking" in args_cli.teleop_device.lower(): - app_launcher_args["xr"] = True - # launch omniverse app app_launcher = AppLauncher(app_launcher_args) simulation_app = app_launcher.app @@ -71,9 +82,38 @@ from isaaclab_tasks.manager_based.manipulation.lift import mdp from isaaclab_tasks.utils import parse_env_cfg -# import logger logger = logging.getLogger(__name__) +_CLOUDXR_ENV_SHORTHANDS: dict[str, str] = {} + + +def _resolve_cloudxr_env(value: str | None) -> str | None: + """Resolve ``--cloudxr_env`` shorthands to absolute ``.env`` file paths. + + Accepts ``"cloudxrjs"`` (Quest/Pico), ``"avp"`` (Apple Vision Pro), + ``"none"`` / ``None`` (disable), or an arbitrary file path. + """ + if value is None or value.strip() == "" or value.lower() == "none": + return None + if not _CLOUDXR_ENV_SHORTHANDS: + from isaaclab_teleop import CLOUDXR_AVP_ENV, CLOUDXR_JS_ENV + + _CLOUDXR_ENV_SHORTHANDS["cloudxrjs"] = CLOUDXR_JS_ENV + _CLOUDXR_ENV_SHORTHANDS["avp"] = CLOUDXR_AVP_ENV + return _CLOUDXR_ENV_SHORTHANDS.get(value.lower(), value) + + +def _create_builtin_device(device_name: str, sensitivity: float) -> object | None: + """Create a built-in teleop device by name, or return None if unrecognized.""" + name = device_name.lower() + if name == "keyboard": + return Se3Keyboard(Se3KeyboardCfg(pos_sensitivity=0.05 * sensitivity, rot_sensitivity=0.05 * sensitivity)) + elif name == "spacemouse": + return Se3SpaceMouse(Se3SpaceMouseCfg(pos_sensitivity=0.05 * sensitivity, rot_sensitivity=0.05 * sensitivity)) + elif name == "gamepad": + return Se3Gamepad(Se3GamepadCfg(pos_sensitivity=0.1 * sensitivity, rot_sensitivity=0.1 * sensitivity)) + return None + def main() -> None: """ @@ -101,8 +141,12 @@ def main() -> None: # add termination condition for reaching the goal otherwise the environment won't reset env_cfg.terminations.object_reached_goal = DoneTerm(func=mdp.object_reached_goal) - # Check if IsaacTeleop is configured in the environment - use_isaac_teleop = hasattr(env_cfg, "isaac_teleop") and env_cfg.isaac_teleop is not None + # When --teleop_device is explicitly provided, use the legacy teleop_devices path + # even if isaac_teleop is configured. Otherwise prefer isaac_teleop when available. + teleop_device_explicitly_set = args_cli.teleop_device is not None + use_isaac_teleop = ( + not teleop_device_explicitly_set and hasattr(env_cfg, "isaac_teleop") and env_cfg.isaac_teleop is not None + ) if use_isaac_teleop or args_cli.xr: env_cfg = remove_camera_configs(env_cfg) @@ -186,45 +230,46 @@ def stop_teleoperation() -> None: try: if use_isaac_teleop: - from isaaclab_teleop import create_isaac_teleop_device + from isaaclab_teleop import create_isaac_teleop_device, poll_control_events teleop_interface = create_isaac_teleop_device( env_cfg.isaac_teleop, sim_device=args_cli.device, callbacks=teleoperation_callbacks, + cloudxr_env_file=_resolve_cloudxr_env(args_cli.cloudxr_env), + auto_launch_cloudxr=args_cli.auto_launch_cloudxr, ) - elif hasattr(env_cfg, "teleop_devices") and args_cli.teleop_device in env_cfg.teleop_devices.devices: - # Use native Isaac Lab teleop stack - teleop_interface = create_teleop_device( - args_cli.teleop_device, env_cfg.teleop_devices.devices, teleoperation_callbacks - ) - else: - logger.warning( - f"No teleop device '{args_cli.teleop_device}' found in environment config. Creating default." - ) - # Create fallback teleop device - sensitivity = args_cli.sensitivity - if args_cli.teleop_device.lower() == "keyboard": - teleop_interface = Se3Keyboard( - Se3KeyboardCfg(pos_sensitivity=0.05 * sensitivity, rot_sensitivity=0.05 * sensitivity) - ) - elif args_cli.teleop_device.lower() == "spacemouse": - teleop_interface = Se3SpaceMouse( - Se3SpaceMouseCfg(pos_sensitivity=0.05 * sensitivity, rot_sensitivity=0.05 * sensitivity) - ) - elif args_cli.teleop_device.lower() == "gamepad": - teleop_interface = Se3Gamepad( - Se3GamepadCfg(pos_sensitivity=0.1 * sensitivity, rot_sensitivity=0.1 * sensitivity) + elif teleop_device_explicitly_set: + device_name = args_cli.teleop_device + if hasattr(env_cfg, "teleop_devices") and device_name in env_cfg.teleop_devices.devices: + teleop_interface = create_teleop_device( + device_name, env_cfg.teleop_devices.devices, teleoperation_callbacks ) else: - logger.error(f"Unsupported teleop device: {args_cli.teleop_device}") - logger.error("Configure the teleop device in the environment config.") - env.close() - simulation_app.close() - return - - # Add callbacks to fallback device + teleop_interface = _create_builtin_device(device_name, args_cli.sensitivity) + if teleop_interface is None: + logger.error( + f"--teleop_device={device_name} was passed but no matching entry exists in" + " env_cfg.teleop_devices and it is not a built-in device name. Either remove" + " --teleop_device to use the IsaacTeleop pipeline, or add a" + f" '{device_name}' entry under teleop_devices in the environment config." + " Built-in devices: keyboard, spacemouse, gamepad." + ) + env.close() + simulation_app.close() + return + for key, callback in teleoperation_callbacks.items(): + try: + teleop_interface.add_callback(key, callback) + except (ValueError, TypeError) as e: + logger.warning(f"Failed to add callback for key {key}: {e}") + else: + # No --teleop_device and no isaac_teleop: fall back to keyboard + sensitivity = args_cli.sensitivity + teleop_interface = Se3Keyboard( + Se3KeyboardCfg(pos_sensitivity=0.05 * sensitivity, rot_sensitivity=0.05 * sensitivity) + ) for key, callback in teleoperation_callbacks.items(): try: teleop_interface.add_callback(key, callback) @@ -263,6 +308,13 @@ def run_loop(): # get device command action = teleop_interface.advance() + if use_isaac_teleop: + ctrl = poll_control_events(teleop_interface) + if ctrl.is_active is not None: + teleoperation_active = ctrl.is_active + if ctrl.should_reset: + should_reset_recording_instance = True + # action is None when IsaacTeleop session hasn't started yet # (e.g. waiting for user to click "Start AR") if action is None: diff --git a/scripts/environments/zero_agent.py b/scripts/environments/zero_agent.py index f2a64bd29d9a..3979a11d7fa8 100644 --- a/scripts/environments/zero_agent.py +++ b/scripts/environments/zero_agent.py @@ -38,7 +38,7 @@ def main(): torch.manual_seed(42) - # parse configuration via Hydra (supports preset selection, e.g. env.sim.physics=newton) + # parse configuration via Hydra (supports preset selection, e.g. env.sim.physics=newton_mjwarp) env_cfg, _ = resolve_task_config(args_cli.task, "") with launch_simulation(env_cfg, args_cli): diff --git a/scripts/imitation_learning/isaaclab_mimic/generate_dataset.py b/scripts/imitation_learning/isaaclab_mimic/generate_dataset.py index fabbd286c2fe..6752e4b82912 100644 --- a/scripts/imitation_learning/isaaclab_mimic/generate_dataset.py +++ b/scripts/imitation_learning/isaaclab_mimic/generate_dataset.py @@ -30,14 +30,21 @@ parser.add_argument( "--pause_subtask", action="store_true", - help="pause after every subtask during generation for debugging - only useful with render flag", + help="Pause after every subtask during generation for debugging - only useful with render flag", ) parser.add_argument( "--use_skillgen", action="store_true", default=False, - help="use skillgen to generate motion trajectories", + help="Use skillgen to generate motion trajectories", ) +parser.add_argument( + "--disable_dataset_compression", + action="store_true", + default=False, + help="Disables dataset compression", +) + # append AppLauncher cli args AppLauncher.add_app_launcher_args(parser) # parse the arguments @@ -88,6 +95,7 @@ def main(): num_envs=num_envs, device=args_cli.device, generation_num_trials=args_cli.generation_num_trials, + dataset_compression=not args_cli.disable_dataset_compression, ) # Create environment @@ -158,6 +166,7 @@ def main(): async_components["action_queue"], async_components["info_pool"], async_components["event_loop"], + data_gen_tasks=data_gen_tasks, ) except asyncio.CancelledError: print("Tasks were cancelled.") diff --git a/scripts/imitation_learning/locomanipulation_sdg/generate_data.py b/scripts/imitation_learning/locomanipulation_sdg/generate_data.py index 2b3af68914c2..bbae0689ff65 100644 --- a/scripts/imitation_learning/locomanipulation_sdg/generate_data.py +++ b/scripts/imitation_learning/locomanipulation_sdg/generate_data.py @@ -350,26 +350,26 @@ def project_robot_state_into_env(env: LocomanipulationSDGEnv, input_episode_data root_velocity=torch.zeros((1, 6), device=env.device), env_ids=[0] ) # Update default root pose and velocity for correct state on reset - default_pose = wp.to_torch(env.scene["robot"].data.default_root_pose).clone() + default_pose = env.scene["robot"].data.default_root_pose.torch.clone() default_pose[0] = new_robot_pose[0] - env.scene["robot"].data.default_root_pose.assign( + env.scene["robot"].data.default_root_pose.warp.assign( wp.from_torch(default_pose.to(env.device).contiguous()).view(wp.transformf) ) - default_vel = wp.to_torch(env.scene["robot"].data.default_root_vel).clone() + default_vel = env.scene["robot"].data.default_root_vel.torch.clone() default_vel[0] = torch.zeros(6, device=env.device) - env.scene["robot"].data.default_root_vel.assign(wp.from_torch(default_vel.to(env.device).contiguous())) + env.scene["robot"].data.default_root_vel.warp.assign(wp.from_torch(default_vel.to(env.device).contiguous())) robot_state = recording_initial_state["articulation"]["robot"] joint_position = robot_state["joint_position"][0].to(env.device) joint_velocity = robot_state["joint_velocity"][0].to(env.device) # Update default joint positions and velocities for correct state on reset - default_joint_pos = wp.to_torch(env.scene["robot"].data.default_joint_pos).clone() + default_joint_pos = env.scene["robot"].data.default_joint_pos.torch.clone() default_joint_pos[0] = joint_position - env.scene["robot"].data.default_joint_pos.assign(wp.from_torch(default_joint_pos.to(env.device).contiguous())) - default_joint_vel = wp.to_torch(env.scene["robot"].data.default_joint_vel).clone() + env.scene["robot"].data.default_joint_pos.warp.assign(wp.from_torch(default_joint_pos.to(env.device).contiguous())) + default_joint_vel = env.scene["robot"].data.default_joint_vel.torch.clone() default_joint_vel[0] = joint_velocity - env.scene["robot"].data.default_joint_vel.assign(wp.from_torch(default_joint_vel.to(env.device).contiguous())) + env.scene["robot"].data.default_joint_vel.warp.assign(wp.from_torch(default_joint_vel.to(env.device).contiguous())) env.scene["robot"].write_joint_position_to_sim_index(position=joint_position[None, :], env_ids=[0]) env.scene["robot"].write_joint_velocity_to_sim_index(velocity=joint_velocity[None, :], env_ids=[0]) @@ -401,14 +401,14 @@ def project_object_state_into_env(env: LocomanipulationSDGEnv, input_episode_dat root_velocity=torch.zeros((1, 6), device=env.device), env_ids=[0] ) # Update default root pose and velocity for correct state on reset - default_pose = wp.to_torch(env.scene["object"].data.default_root_pose).clone() + default_pose = env.scene["object"].data.default_root_pose.torch.clone() default_pose[0] = new_object_pose[0] - env.scene["object"].data.default_root_pose.assign( + env.scene["object"].data.default_root_pose.warp.assign( wp.from_torch(default_pose.to(env.device).contiguous()).view(wp.transformf) ) - default_vel = wp.to_torch(env.scene["object"].data.default_root_vel).clone() + default_vel = env.scene["object"].data.default_root_vel.torch.clone() default_vel[0] = torch.zeros(6, device=env.device) - env.scene["object"].data.default_root_vel.assign(wp.from_torch(default_vel.to(env.device).contiguous())) + env.scene["object"].data.default_root_vel.warp.assign(wp.from_torch(default_vel.to(env.device).contiguous())) return new_object_pose diff --git a/scripts/reinforcement_learning/leapp/deploy.py b/scripts/reinforcement_learning/leapp/deploy.py new file mode 100644 index 000000000000..5b032daa9dda --- /dev/null +++ b/scripts/reinforcement_learning/leapp/deploy.py @@ -0,0 +1,82 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Deploy a LEAPP-exported policy in an Isaac Lab simulation.""" + +"""Launch Isaac Sim Simulator first.""" + +import argparse +import sys + +from isaaclab.app import AppLauncher + +parser = argparse.ArgumentParser(description="Deploy a LEAPP-exported policy in simulation.") +parser.add_argument("--task", type=str, default=None, help="Name of the registered Isaac Lab task.") +parser.add_argument("--leapp_model", type=str, default=None, help="Path to the LEAPP .yaml pipeline description.") +parser.add_argument("--seed", type=int, default=None, help="Seed for the environment.") +AppLauncher.add_app_launcher_args(parser) +args_cli, hydra_args = parser.parse_known_args() + +if args_cli.task is None or args_cli.leapp_model is None: + missing_args = [] + if args_cli.task is None: + missing_args.append("--task") + if args_cli.leapp_model is None: + missing_args.append("--leapp_model") + parser.error(f"the following arguments are required: {', '.join(missing_args)}") + +sys.argv = [sys.argv[0]] + hydra_args + +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +"""Rest everything follows.""" + +import torch + +from isaaclab.envs.leapp_deployment_env import LeappDeploymentEnv + +import isaaclab_tasks # noqa: F401 +from isaaclab_tasks.utils.parse_cfg import load_cfg_from_registry + + +def main(): + # ── Load env config from gym registry ───────────────────────── + task_name = args_cli.task.split(":")[-1] + env_cfg = load_cfg_from_registry(task_name, "env_cfg_entry_point") + + if args_cli.seed is not None: + env_cfg.seed = args_cli.seed + if args_cli.device is not None: + env_cfg.sim.device = args_cli.device + + # ── Create deploy env ───────────────────────────────────────── + env = LeappDeploymentEnv(env_cfg, args_cli.leapp_model) + + if getattr(args_cli, "headless", False): + print( + "[WARN]: Running deploy without a viewport. This happens when headless mode is active, " + "including the default case where no visualizer was selected. The policy may be " + "stepping normally, but no viewport will appear unless you specify the " + "`--visualizer` field." + ) + + print(f"[INFO]: Deploying task '{task_name}' with LEAPP model: {args_cli.leapp_model}") + print(f"[INFO]: Num envs: {env.num_envs}, decimation: {env.cfg.decimation}, step_dt: {env.step_dt:.4f}s") + + # ── Run loop ────────────────────────────────────────────────── + env.reset() + try: + with torch.inference_mode(): + while simulation_app.is_running(): + env.step() + env.close() + except KeyboardInterrupt: + pass + + +if __name__ == "__main__": + main() + simulation_app.close() diff --git a/scripts/reinforcement_learning/leapp/rsl_rl/export.py b/scripts/reinforcement_learning/leapp/rsl_rl/export.py new file mode 100644 index 000000000000..65bab2f9c221 --- /dev/null +++ b/scripts/reinforcement_learning/leapp/rsl_rl/export.py @@ -0,0 +1,282 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +# ruff: noqa: E402 + +"""Script to export a checkpoint if an RL agent from RSL-RL.""" + +"""Launch Isaac Sim Simulator first.""" + +import argparse +import importlib.metadata as metadata +import sys +import time +from collections.abc import Mapping +from pathlib import Path + +import torch + +try: + import leapp + from leapp import annotate +except ImportError as e: + raise ImportError("LEAPP package is required for policy export. Install with: pip install leapp") from e + +# Disable TorchScript before importing task/environment modules so any +# @torch.jit.script helpers resolve to plain Python functions during export. +torch.jit._state.disable() + +from isaaclab.app import AppLauncher + +_RSL_RL_SCRIPTS_DIR = Path(__file__).resolve().parents[2] / "rsl_rl" +if str(_RSL_RL_SCRIPTS_DIR) not in sys.path: + sys.path.insert(0, str(_RSL_RL_SCRIPTS_DIR)) +import cli_args # isort: skip + + +parser = argparse.ArgumentParser(description="Train an RL agent with RSL-RL.") +parser.add_argument( + "--disable_fabric", action="store_true", default=False, help="Disable fabric and use USD I/O operations." +) +parser.add_argument("--task", type=str, default=None, help="Name of the task.") +parser.add_argument( + "--agent", type=str, default="rsl_rl_cfg_entry_point", help="Name of the RL agent configuration entry point." +) +parser.add_argument("--seed", type=int, default=None, help="Seed used for the environment") +parser.add_argument( + "--use_pretrained_checkpoint", + action="store_true", + help="Use the pre-trained checkpoint from Nucleus.", +) + +# LEAPP arguments +parser.add_argument( + "--export_task_name", + type=str, + default=None, + help="Name of the exported graph. Defaults to the task name.", +) +parser.add_argument( + "--export_method", + type=str, + default="onnx-dynamo", + choices=["onnx-dynamo", "onnx-torchscript", "jit-script", "jit-trace"], + help="Method to export the policy", +) +parser.add_argument( + "--export_save_path", + type=str, + default=None, + help="Path to save the exported model", +) +parser.add_argument( + "--validation_steps", + type=int, + default=5, + help="Number of steps to validate the exported model", +) +parser.add_argument( + "--disable_graph_visualization", + action="store_true", + default=False, + help="Disable LEAPP graph visualization during compile_graph().", +) + +cli_args.add_rsl_rl_args(parser) +AppLauncher.add_app_launcher_args(parser) +args_cli, hydra_args = parser.parse_known_args() +args_cli.headless = True + +# clear out sys.argv for Hydra +sys.argv = [sys.argv[0]] + hydra_args + +installed_version = metadata.version("rsl-rl-lib") + +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +"""Rest everything follows.""" + +import os + +import gymnasium as gym +from rsl_rl.runners import DistillationRunner, OnPolicyRunner + +from isaaclab.envs import ManagerBasedRLEnv, ManagerBasedRLEnvCfg +from isaaclab.utils.assets import retrieve_file_path +from isaaclab.utils.leapp import patch_env_for_export +from isaaclab.utils.leapp.utils import ensure_env_spec_id + +from isaaclab_rl.rsl_rl import RslRlBaseRunnerCfg, RslRlVecEnvWrapper, handle_deprecated_rsl_rl_cfg +from isaaclab_rl.utils.pretrained_checkpoint import get_published_pretrained_checkpoint + +import isaaclab_tasks # noqa: F401 +from isaaclab_tasks.utils import get_checkpoint_path +from isaaclab_tasks.utils.hydra import hydra_task_config + + +def get_actor_memory_module(policy_nn): + """Return the actor-side recurrent memory module when the policy exposes one.""" + if hasattr(policy_nn, "memory_a"): + return policy_nn.memory_a + if hasattr(policy_nn, "memory_s"): + return policy_nn.memory_s + return None + + +def ensure_actor_hidden_state_initialized(policy_nn, batch_size: int, device: torch.device, dtype: torch.dtype): + """Initialize and return the actor hidden state when a recurrent policy has not created it yet.""" + actor_state, _ = policy_nn.get_hidden_states() + if actor_state is not None: + return actor_state + + memory = get_actor_memory_module(policy_nn) + if memory is None or not hasattr(memory, "rnn"): + return None + + num_layers = memory.rnn.num_layers + hidden_size = memory.rnn.hidden_size + zeros = torch.zeros(num_layers, batch_size, hidden_size, device=device, dtype=dtype) + if isinstance(memory.rnn, torch.nn.LSTM): + actor_state = (zeros.clone(), zeros.clone()) + else: + actor_state = zeros + memory.hidden_state = actor_state + return actor_state + + +def state_dict_from_actor_hidden(actor_hidden): + """Convert the actor hidden state into the named tensor mapping expected by LEAPP state APIs.""" + if actor_hidden is None: + return {} + if isinstance(actor_hidden, tuple): + return {f"actor_state_{idx}": tensor for idx, tensor in enumerate(actor_hidden)} + return {"actor_state": actor_hidden} + + +def actor_hidden_from_registered(registered_state, original_hidden): + """Restore the registered LEAPP state to the hidden-state structure expected by the actor memory module.""" + if isinstance(original_hidden, tuple): + if isinstance(registered_state, tuple): + return registered_state + return (registered_state,) + return registered_state + + +@hydra_task_config(args_cli.task, args_cli.agent) +def main(env_cfg: ManagerBasedRLEnvCfg, agent_cfg: RslRlBaseRunnerCfg): + """Export a RSL-RL agent.""" + task_name = args_cli.task.split(":")[-1] + train_task_name = task_name.replace("-Play", "") + + agent_cfg: RslRlBaseRunnerCfg = cli_args.update_rsl_rl_cfg(agent_cfg, args_cli) + env_cfg.scene.num_envs = 1 + + agent_cfg = handle_deprecated_rsl_rl_cfg(agent_cfg, installed_version) + + # note: certain randomizations occur in the environment initialization so we set the seed here + env_cfg.seed = agent_cfg.seed + env_cfg.sim.device = args_cli.device if args_cli.device is not None else env_cfg.sim.device + + log_root_path = os.path.join("logs", "rsl_rl", agent_cfg.experiment_name) + log_root_path = os.path.abspath(log_root_path) + print(f"[INFO] Loading experiment from directory: {log_root_path}") + if args_cli.use_pretrained_checkpoint: + resume_path = get_published_pretrained_checkpoint("rsl_rl", train_task_name) + if not resume_path: + print("[INFO] Unfortunately a pre-trained checkpoint is currently unavailable for this task.") + return + elif args_cli.checkpoint: + resume_path = retrieve_file_path(args_cli.checkpoint) + else: + resume_path = get_checkpoint_path(log_root_path, agent_cfg.load_run, agent_cfg.load_checkpoint) + + log_dir = os.path.dirname(resume_path) + + env_cfg.log_dir = log_dir + + env = gym.make(args_cli.task, cfg=env_cfg, render_mode=None) + policy_node_name = ensure_env_spec_id(env) + + graph_name = args_cli.export_task_name if args_cli.export_task_name is not None else task_name + + if isinstance(env.unwrapped, ManagerBasedRLEnv): + # Patch only the observation groups consumed by the actor policy. + # This filters out the critic and teacher observation groups. + obs_groups_cfg = getattr(agent_cfg, "obs_groups", None) + if isinstance(obs_groups_cfg, Mapping): + required_obs_groups = set(obs_groups_cfg.get("actor", ["policy"])) + else: + required_obs_groups = {"policy"} + patch_env_for_export( + env, + export_method=args_cli.export_method, + required_obs_groups=required_obs_groups, + ) + + env = RslRlVecEnvWrapper(env, clip_actions=agent_cfg.clip_actions) + + print(f"[INFO]: Loading model checkpoint from: {resume_path}") + if agent_cfg.class_name == "OnPolicyRunner": + runner = OnPolicyRunner(env, agent_cfg.to_dict(), log_dir=None, device=agent_cfg.device) + elif agent_cfg.class_name == "DistillationRunner": + runner = DistillationRunner(env, agent_cfg.to_dict(), log_dir=None, device=agent_cfg.device) + else: + raise ValueError(f"Unsupported runner class: {agent_cfg.class_name}") + runner.load(resume_path) + + policy = runner.get_inference_policy(device=env.unwrapped.device) + policy_nn = getattr(policy, "__self__", None) + + if args_cli.export_save_path is not None: + save_path = args_cli.export_save_path + elif args_cli.use_pretrained_checkpoint: + # Use a predictable path independent of the Nucleus mirror directory structure. + save_path = os.path.join(".pretrained_checkpoints", "rsl_rl", train_task_name) + else: + save_path = log_dir + leapp.start(graph_name, save_path=save_path, max_cached_io=max(args_cli.validation_steps, 2)) + obs = env.reset()[0] + while not simulation_app.is_running(): + time.sleep(0.5) + + for _ in range(max(args_cli.validation_steps, 2)): + with torch.inference_mode(): + if policy_nn is not None and getattr(policy_nn, "is_recurrent", False): + actor_hidden = ensure_actor_hidden_state_initialized( + policy_nn, + batch_size=env.num_envs, + device=env.unwrapped.device, + dtype=next(policy_nn.parameters()).dtype, + ) + registered_state = annotate.state_tensors( + policy_node_name, + state_dict_from_actor_hidden(actor_hidden), + ) + actor_memory = get_actor_memory_module(policy_nn) + if actor_memory is not None: + actor_memory.hidden_state = actor_hidden_from_registered(registered_state, actor_hidden) + + actions = policy(obs) + + if policy_nn is not None and getattr(policy_nn, "is_recurrent", False): + actor_hidden_after = policy_nn.get_hidden_states()[0] + annotate.update_state( + policy_node_name, + state_dict_from_actor_hidden(actor_hidden_after), + ) + + obs, _, _, _ = env.step(actions) + + leapp.stop() + validate = args_cli.validation_steps > 0 + leapp.compile_graph(visualize=not args_cli.disable_graph_visualization, validate=validate) + + env.close() + + +if __name__ == "__main__": + main() + simulation_app.close() diff --git a/scripts/reinforcement_learning/rl_games/train.py b/scripts/reinforcement_learning/rl_games/train.py index 4de23c19246a..697ca06660a3 100644 --- a/scripts/reinforcement_learning/rl_games/train.py +++ b/scripts/reinforcement_learning/rl_games/train.py @@ -84,7 +84,12 @@ def main(): with launch_simulation(env_cfg, args_cli): # override configurations with non-hydra CLI arguments env_cfg.scene.num_envs = args_cli.num_envs if args_cli.num_envs is not None else env_cfg.scene.num_envs - env_cfg.sim.device = args_cli.device if args_cli.device is not None else env_cfg.sim.device + # For distributed training, launch_simulation() already resolved the + # correct per-rank device; only apply a CLI --device override for + # non-distributed runs (the default "cuda:0" would clobber the + # per-rank device otherwise). + if not args_cli.distributed: + env_cfg.sim.device = args_cli.device if args_cli.device is not None else env_cfg.sim.device if args_cli.distributed and args_cli.device is not None and "cpu" in args_cli.device: raise ValueError( "Distributed training is not supported when using CPU device. " @@ -110,12 +115,12 @@ def main(): # multi-gpu training config if args_cli.distributed: - local_rank = int(os.getenv("LOCAL_RANK", "0")) agent_cfg["params"]["seed"] += int(os.getenv("RANK", "0")) - agent_cfg["params"]["config"]["device"] = f"cuda:{local_rank}" - agent_cfg["params"]["config"]["device_name"] = f"cuda:{local_rank}" + # env_cfg.sim.device is resolved by launch_simulation() which + # accounts for CUDA_VISIBLE_DEVICES restrictions. + agent_cfg["params"]["config"]["device"] = env_cfg.sim.device + agent_cfg["params"]["config"]["device_name"] = env_cfg.sim.device agent_cfg["params"]["config"]["multi_gpu"] = True - env_cfg.sim.device = f"cuda:{local_rank}" # set the environment seed (after multi-gpu config for updated rank from agent seed) env_cfg.seed = agent_cfg["params"]["seed"] diff --git a/scripts/reinforcement_learning/rsl_rl/train.py b/scripts/reinforcement_learning/rsl_rl/train.py index da865153b398..eefc13a8aa2c 100644 --- a/scripts/reinforcement_learning/rsl_rl/train.py +++ b/scripts/reinforcement_learning/rsl_rl/train.py @@ -120,7 +120,12 @@ def main(env_cfg: ManagerBasedRLEnvCfg | DirectRLEnvCfg | DirectMARLEnvCfg, agen # set the environment seed # note: certain randomizations occur in the environment initialization so we set the seed here env_cfg.seed = agent_cfg.seed - env_cfg.sim.device = args_cli.device if args_cli.device is not None else env_cfg.sim.device + # For distributed training, launch_simulation() already resolved the + # correct per-rank device; only apply a CLI --device override for + # non-distributed runs (the default "cuda:0" would clobber the + # per-rank device otherwise). + if not args_cli.distributed: + env_cfg.sim.device = args_cli.device if args_cli.device is not None else env_cfg.sim.device # check for invalid combination of CPU device with distributed training if args_cli.distributed and args_cli.device is not None and "cpu" in args_cli.device: raise ValueError( @@ -130,10 +135,10 @@ def main(env_cfg: ManagerBasedRLEnvCfg | DirectRLEnvCfg | DirectMARLEnvCfg, agen # multi-gpu training configuration if args_cli.distributed: - local_rank = int(os.getenv("LOCAL_RANK", "0")) global_rank = int(os.getenv("RANK", "0")) - env_cfg.sim.device = f"cuda:{local_rank}" - agent_cfg.device = f"cuda:{local_rank}" + # env_cfg.sim.device is resolved by launch_simulation() which + # accounts for CUDA_VISIBLE_DEVICES restrictions. + agent_cfg.device = env_cfg.sim.device # use global rank for seed diversity across all nodes seed = agent_cfg.seed + global_rank diff --git a/scripts/reinforcement_learning/skrl/play.py b/scripts/reinforcement_learning/skrl/play.py index 3857c095150b..8663d0561941 100644 --- a/scripts/reinforcement_learning/skrl/play.py +++ b/scripts/reinforcement_learning/skrl/play.py @@ -34,7 +34,7 @@ with contextlib.suppress(ImportError): import isaaclab_tasks_experimental # noqa: F401 -SKRL_VERSION = "1.4.3" +SKRL_VERSION = "2.0.0" # -- argparse ---------------------------------------------------------------- parser = argparse.ArgumentParser(description="Play a checkpoint of an RL agent from skrl.") @@ -65,7 +65,7 @@ "--ml_framework", type=str, default="torch", - choices=["torch", "jax", "jax-numpy"], + choices=["torch", "jax"], help="The ML framework used for training the skrl agent.", ) parser.add_argument( @@ -191,10 +191,11 @@ def main(): print(f"[INFO] Loading model checkpoint from: {resume_path}") runner.agent.load(resume_path) - runner.agent.set_running_mode("eval") + runner.agent.enable_training_mode(False, apply_to_models=True) # reset environment obs, _ = env.reset() + states = env.state() timestep = 0 # simulate environment try: @@ -202,12 +203,13 @@ def main(): start_time = time.time() with torch.inference_mode(): - outputs = runner.agent.act(obs, timestep=0, timesteps=0) + outputs = runner.agent.act(obs, states, timestep=0, timesteps=0) if hasattr(env, "possible_agents"): actions = {a: outputs[-1][a].get("mean_actions", outputs[0][a]) for a in env.possible_agents} else: actions = outputs[-1].get("mean_actions", outputs[0]) obs, _, _, _, _ = env.step(actions) + states = env.state() if args_cli.video: timestep += 1 if timestep == args_cli.video_length: diff --git a/scripts/reinforcement_learning/skrl/train.py b/scripts/reinforcement_learning/skrl/train.py index 37beb7510be9..535403e5a105 100644 --- a/scripts/reinforcement_learning/skrl/train.py +++ b/scripts/reinforcement_learning/skrl/train.py @@ -39,7 +39,7 @@ with contextlib.suppress(ImportError): import isaaclab_tasks_experimental # noqa: F401 -SKRL_VERSION = "1.4.3" +SKRL_VERSION = "2.0.0" # -- argparse ---------------------------------------------------------------- parser = argparse.ArgumentParser(description="Train an RL agent with skrl.") @@ -68,7 +68,7 @@ "--ml_framework", type=str, default="torch", - choices=["torch", "jax", "jax-numpy"], + choices=["torch", "jax"], help="The ML framework used for training the skrl agent.", ) parser.add_argument( @@ -117,7 +117,12 @@ def main(): # override configurations with non-hydra CLI arguments env_cfg.scene.num_envs = args_cli.num_envs if args_cli.num_envs is not None else env_cfg.scene.num_envs - env_cfg.sim.device = args_cli.device if args_cli.device is not None else env_cfg.sim.device + # For distributed training, launch_simulation() already resolved the + # correct per-rank device; only apply a CLI --device override for + # non-distributed runs (the default "cuda:0" would clobber the + # per-rank device otherwise). + if not args_cli.distributed: + env_cfg.sim.device = args_cli.device if args_cli.device is not None else env_cfg.sim.device if args_cli.distributed and args_cli.device is not None and "cpu" in args_cli.device: raise ValueError( @@ -127,9 +132,9 @@ def main(): # multi-gpu training config if args_cli.distributed: - local_rank = int(os.getenv("LOCAL_RANK", "0")) global_rank = int(os.getenv("RANK", "0")) - env_cfg.sim.device = f"cuda:{local_rank}" + # env_cfg.sim.device is resolved by launch_simulation() which + # accounts for CUDA_VISIBLE_DEVICES restrictions. # max iterations for training if args_cli.max_iterations: agent_cfg["trainer"]["timesteps"] = args_cli.max_iterations * agent_cfg["agent"]["rollouts"] diff --git a/scripts/run_ovphysx.sh b/scripts/run_ovphysx.sh new file mode 100755 index 000000000000..72d18a1bec82 --- /dev/null +++ b/scripts/run_ovphysx.sh @@ -0,0 +1,71 @@ +#!/bin/bash +# Run ovphysx in Kit's Python with its bundled libcarb.so preloaded. +# Use when ovphysx is installed into Kit's Python. +# +# Usage: ./scripts/run_ovphysx.sh [your_script.py or -m pytest ...] +set -e + +ISAACLAB_PATH="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +ISAAC_DIR="${ISAACLAB_PATH}/_isaac_sim" + +# Match python.sh so Kit extensions/resources resolve during training too. +export CARB_APP_PATH="${CARB_APP_PATH:-${ISAAC_DIR}/kit}" +export ISAAC_PATH="${ISAAC_PATH:-${ISAAC_DIR}}" +export EXP_PATH="${EXP_PATH:-${ISAAC_DIR}/apps}" + +# Source the Python environment setup (sets PYTHONPATH, LD_LIBRARY_PATH) +# but do NOT use python.sh which sets LD_PRELOAD +source "${ISAAC_DIR}/setup_python_env.sh" + +# Preload ovphysx's own libcarb.so so its Carbonite framework wins the +# SONAME race against any other libcarb.so present in the process. +_ovphysx_libcarb="" +for _sp in "${ISAAC_DIR}"/kit/python/lib/python3.*/site-packages/ovphysx/plugins/libcarb.so; do + if [ -f "${_sp}" ]; then + _ovphysx_libcarb="${_sp}" + break + fi +done +if [ -n "${_ovphysx_libcarb}" ]; then + export LD_PRELOAD="${_ovphysx_libcarb}" +else + export LD_PRELOAD="" +fi +unset _ovphysx_libcarb + +# Ensure pxr (OpenUSD Python bindings) is on PYTHONPATH. +# setup_python_env.sh may not include the packman USD path after rebuilds. +# Search order: IsaacSim's bundled site-packages first, then the Python +# environment's own site-packages (covers pip-installed OpenUSD). +_pxr_found=false +for usd_dir in "${ISAAC_DIR}"/kit/python/lib/python3.*/site-packages/usd_core.libs/../.. \ + "${ISAAC_DIR}"/kit/python/lib/python3.*/site-packages; do + if [ -d "${usd_dir}/pxr" ]; then + export PYTHONPATH="${usd_dir}:${PYTHONPATH}" + _pxr_found=true + break + fi +done +if [ "${_pxr_found}" = false ]; then + # Last resort: ask Python itself where pxr lives + _pxr_path=$("${ISAAC_DIR}/kit/python/bin/python3" -c "import pxr, os; print(os.path.dirname(os.path.dirname(pxr.__file__)))" 2>/dev/null) + if [ -n "${_pxr_path}" ] && [ -d "${_pxr_path}/pxr" ]; then + export PYTHONPATH="${_pxr_path}:${PYTHONPATH}" + fi +fi +unset _pxr_found _pxr_path + +# Add all isaaclab source packages to PYTHONPATH so editable installs work +for pkg in isaaclab isaaclab_ovphysx isaaclab_tasks isaaclab_rl isaaclab_physx isaaclab_newton isaaclab_assets isaaclab_contrib; do + if [ -d "${ISAACLAB_PATH}/source/${pkg}" ]; then + export PYTHONPATH="${ISAACLAB_PATH}/source/${pkg}:${PYTHONPATH}" + fi +done + +# Match python.sh default for Kit app resource discovery. +export RESOURCE_NAME="${RESOURCE_NAME:-IsaacSim}" + +# Use the Python binary directly +PYTHON_EXE="${ISAAC_DIR}/kit/python/bin/python3" + +exec "${PYTHON_EXE}" "$@" diff --git a/scripts/tools/record_demos.py b/scripts/tools/record_demos.py index 875e8906402b..0cac0b59284b 100644 --- a/scripts/tools/record_demos.py +++ b/scripts/tools/record_demos.py @@ -20,8 +20,8 @@ optional arguments: -h, --help Show this help message and exit - --teleop_device Device for interacting with environment. (default: keyboard) - If env_cfg has isaac_teleop configured, this argument is ignored. + --teleop_device Legacy teleop device name. When omitted, IsaacTeleop is used if + configured, otherwise keyboard. When set, forces the legacy path. --dataset_file File path to export recorded demos. (default: "./datasets/dataset.hdf5") --step_hz Environment stepping rate in Hz. (default: 30) --num_demos Number of demonstrations to record. (default: 0) @@ -44,11 +44,11 @@ parser.add_argument( "--teleop_device", type=str, - default="keyboard", + default=None, help=( - "Teleop device. Set here (legacy) or via the environment config. If using the environment config, pass the" - " device key/name defined under 'teleop_devices' (it can be a custom name, not necessarily 'handtracking')." - " Built-ins: keyboard, spacemouse, gamepad. Not all tasks support all built-ins." + "Legacy teleop device name. When omitted, the IsaacTeleop pipeline is used if configured in the env," + " otherwise keyboard is used as fallback. When explicitly provided, the script uses the legacy" + " teleop_devices path and looks up this name in env_cfg.teleop_devices.devices." ), ) parser.add_argument( @@ -64,6 +64,21 @@ default=10, help="Number of continuous steps with task success for concluding a demo as successful. Default is 10.", ) +parser.add_argument( + "--cloudxr_env", + type=str, + default="cloudxrjs", + help=( + "Path to a CloudXR .env file, or a shorthand: 'cloudxrjs' (Quest/Pico, default) or 'avp' (Apple Vision Pro)." + " Set to 'none' to disable CloudXR auto-launch entirely." + ), +) +parser.add_argument( + "--auto_launch_cloudxr", + action=argparse.BooleanOptionalAction, + default=True, + help="Auto-launch the CloudXR runtime when --cloudxr_env is set. Use --no-auto_launch_cloudxr to disable.", +) # append AppLauncher cli args AppLauncher.add_app_launcher_args(parser) @@ -76,9 +91,6 @@ app_launcher_args = vars(args_cli) -if "handtracking" in args_cli.teleop_device.lower(): - app_launcher_args["xr"] = True - # launch the simulator app_launcher = AppLauncher(args_cli) simulation_app = app_launcher.app @@ -111,9 +123,26 @@ import isaaclab_tasks # noqa: F401 from isaaclab_tasks.utils.parse_cfg import parse_env_cfg -# import logger logger = logging.getLogger(__name__) +_CLOUDXR_ENV_SHORTHANDS: dict[str, str] = {} + + +def _resolve_cloudxr_env(value: str | None) -> str | None: + """Resolve ``--cloudxr_env`` shorthands to absolute ``.env`` file paths. + + Accepts ``"cloudxrjs"`` (Quest/Pico), ``"avp"`` (Apple Vision Pro), + ``"none"`` / ``None`` (disable), or an arbitrary file path. + """ + if value is None or value.strip() == "" or value.lower() == "none": + return None + if not _CLOUDXR_ENV_SHORTHANDS: + from isaaclab_teleop import CLOUDXR_AVP_ENV, CLOUDXR_JS_ENV + + _CLOUDXR_ENV_SHORTHANDS["cloudxrjs"] = CLOUDXR_JS_ENV + _CLOUDXR_ENV_SHORTHANDS["avp"] = CLOUDXR_AVP_ENV + return _CLOUDXR_ENV_SHORTHANDS.get(value.lower(), value) + class RateLimiter: """Convenience class for enforcing rates in loops.""" @@ -200,8 +229,12 @@ def create_environment_config( logger.error(f"Failed to parse environment configuration: {e}") exit(1) - # Check if IsaacTeleop is configured - use_isaac_teleop = hasattr(env_cfg, "isaac_teleop") and env_cfg.isaac_teleop is not None + # When --teleop_device is explicitly provided, use the legacy teleop_devices path + # even if isaac_teleop is configured. Otherwise prefer isaac_teleop when available. + teleop_device_explicitly_set = args_cli.teleop_device is not None + use_isaac_teleop = ( + not teleop_device_explicitly_set and hasattr(env_cfg, "isaac_teleop") and env_cfg.isaac_teleop is not None + ) # extract success checking function to invoke in the main loop success_term = None @@ -254,6 +287,16 @@ def create_environment(env_cfg: ManagerBasedRLEnvCfg | DirectRLEnvCfg) -> gym.En exit(1) +def _create_builtin_device(device_name: str) -> object | None: + """Create a built-in teleop device by name, or return None if unrecognized.""" + name = device_name.lower() + if name == "keyboard": + return Se3Keyboard(Se3KeyboardCfg(pos_sensitivity=0.2, rot_sensitivity=0.5)) + elif name == "spacemouse": + return Se3SpaceMouse(Se3SpaceMouseCfg(pos_sensitivity=0.2, rot_sensitivity=0.5)) + return None + + def setup_teleop_device(callbacks: dict[str, Callable], use_isaac_teleop: bool = False) -> object: """Set up the teleoperation device based on configuration. @@ -271,6 +314,7 @@ def setup_teleop_device(callbacks: dict[str, Callable], use_isaac_teleop: bool = Raises: Exception: If teleop device creation fails """ + teleop_device_explicitly_set = args_cli.teleop_device is not None teleop_interface = None try: if use_isaac_teleop: @@ -280,25 +324,30 @@ def setup_teleop_device(callbacks: dict[str, Callable], use_isaac_teleop: bool = env_cfg.isaac_teleop, sim_device=args_cli.device, callbacks=callbacks, + cloudxr_env_file=_resolve_cloudxr_env(args_cli.cloudxr_env), + auto_launch_cloudxr=args_cli.auto_launch_cloudxr, ) - elif hasattr(env_cfg, "teleop_devices") and args_cli.teleop_device in env_cfg.teleop_devices.devices: - teleop_interface = create_teleop_device(args_cli.teleop_device, env_cfg.teleop_devices.devices, callbacks) - else: - logger.warning( - f"No teleop device '{args_cli.teleop_device}' found in environment config. Creating default." - ) - # Create fallback teleop device - if args_cli.teleop_device.lower() == "keyboard": - teleop_interface = Se3Keyboard(Se3KeyboardCfg(pos_sensitivity=0.2, rot_sensitivity=0.5)) - elif args_cli.teleop_device.lower() == "spacemouse": - teleop_interface = Se3SpaceMouse(Se3SpaceMouseCfg(pos_sensitivity=0.2, rot_sensitivity=0.5)) + elif teleop_device_explicitly_set: + device_name = args_cli.teleop_device + if hasattr(env_cfg, "teleop_devices") and device_name in env_cfg.teleop_devices.devices: + teleop_interface = create_teleop_device(device_name, env_cfg.teleop_devices.devices, callbacks) else: - logger.error(f"Unsupported teleop device: {args_cli.teleop_device}") - logger.error("Supported devices: keyboard, spacemouse, handtracking") - exit(1) - - # Add callbacks to fallback device + teleop_interface = _create_builtin_device(device_name) + if teleop_interface is None: + logger.error( + f"--teleop_device={device_name} was passed but no matching entry exists in" + " env_cfg.teleop_devices and it is not a built-in device name. Either remove" + " --teleop_device to use the IsaacTeleop pipeline, or add a" + f" '{device_name}' entry under teleop_devices in the environment config." + " Built-in devices: keyboard, spacemouse." + ) + exit(1) + for key, callback in callbacks.items(): + teleop_interface.add_callback(key, callback) + else: + # No --teleop_device and no isaac_teleop: fall back to keyboard + teleop_interface = Se3Keyboard(Se3KeyboardCfg(pos_sensitivity=0.2, rot_sensitivity=0.5)) for key, callback in callbacks.items(): teleop_interface.add_callback(key, callback) except Exception as e: @@ -372,26 +421,34 @@ def process_success_condition(env: gym.Env, success_term: object | None, success def handle_reset( - env: gym.Env, success_step_count: int, instruction_display: InstructionDisplay, label_text: str + env: gym.Env, + success_step_count: int, + instruction_display: InstructionDisplay, + label_text: str, + teleop_interface: object | None = None, ) -> int: """Handle resetting the environment. - Resets the environment, recorder manager, and related state variables. - Updates the instruction display with current status. + Resets the environment, recorder manager, teleop device, and related + state variables. Updates the instruction display with current status. Args: - env: The environment instance to reset - success_step_count: Current count of consecutive successful steps - instruction_display: The display object to update - label_text: Text to display showing current recording status + env: The environment instance to reset. + success_step_count: Current count of consecutive successful steps. + instruction_display: The display object to update. + label_text: Text to display showing current recording status. + teleop_interface: Optional teleop device to reset (resets XR anchor + and retargeter cross-step state). Returns: - int: Reset success step count (0) + Reset success step count (0). """ print("Resetting environment...") env.sim.reset() env.recorder_manager.reset() env.reset() + if teleop_interface is not None and hasattr(teleop_interface, "reset"): + teleop_interface.reset() success_step_count = 0 instruction_display.show_demo(label_text) return success_step_count @@ -442,7 +499,9 @@ def stop_recording_instance(): running_recording_instance = False print("Recording paused") - # Set up teleoperation callbacks + # Set up teleoperation callbacks. For IsaacTeleop the primary control + # path is poll_control_events(); these callbacks are bridged automatically + # and also serve native (keyboard / spacemouse) devices. teleoperation_callbacks = { "R": reset_recording_instance, "START": start_recording_instance, @@ -451,7 +510,6 @@ def stop_recording_instance(): } teleop_interface = setup_teleop_device(teleoperation_callbacks, use_isaac_teleop) - teleop_interface.add_callback("R", reset_recording_instance) label_text = f"Recorded {current_recorded_demo_count} successful demonstrations." instruction_display = setup_ui(label_text, env) @@ -470,10 +528,21 @@ def inner_loop(): stack_name = "IsaacTeleop" if use_isaac_teleop else "native" print(f"{stack_name} recording started.") + if use_isaac_teleop: + from isaaclab_teleop import poll_control_events + with contextlib.suppress(KeyboardInterrupt), torch.inference_mode(): while simulation_app.is_running(): # Get teleop command (may be None while waiting for session start) action = teleop_interface.advance() + + if use_isaac_teleop: + ctrl = poll_control_events(teleop_interface) + if ctrl.is_active is not None: + running_recording_instance = ctrl.is_active + if ctrl.should_reset: + should_reset_recording_instance = True + if action is None: env.sim.render() continue @@ -524,7 +593,9 @@ def inner_loop(): # Handle reset if requested if should_reset_recording_instance: - success_step_count = handle_reset(env, success_step_count, instruction_display, label_text) + success_step_count = handle_reset( + env, success_step_count, instruction_display, label_text, teleop_interface + ) should_reset_recording_instance = False # Check if simulation is stopped diff --git a/scripts/tools/replay_demos.py b/scripts/tools/replay_demos.py index 58be11ac81be..9a8ccf1f419c 100644 --- a/scripts/tools/replay_demos.py +++ b/scripts/tools/replay_demos.py @@ -38,6 +38,15 @@ default=False, help="Validate the replay success rate using the task environment termination criteria", ) +parser.add_argument( + "--reset_sim_buffer_each_episode", + action="store_true", + default=False, + help=( + "Before loading each episode's initial state, call env.sim.reset() to clear" + " simulation buffers. Only valid with --num_envs 1." + ), +) # append AppLauncher cli args AppLauncher.add_app_launcher_args(parser) @@ -106,86 +115,27 @@ def compare_states(state_from_dataset, runtime_state, runtime_env_index) -> (boo return states_matched, output_log -def main(): - """Replay episodes loaded from a file.""" - global is_paused - - # Load dataset - if not os.path.exists(args_cli.dataset_file): - raise FileNotFoundError(f"The dataset file {args_cli.dataset_file} does not exist.") - dataset_file_handler = HDF5DatasetFileHandler() - dataset_file_handler.open(args_cli.dataset_file) - env_name = dataset_file_handler.get_env_name() - episode_count = dataset_file_handler.get_num_episodes() - - if episode_count == 0: - print("No episodes found in the dataset.") - exit() - - episode_indices_to_replay = args_cli.select_episodes - if len(episode_indices_to_replay) == 0: - episode_indices_to_replay = list(range(episode_count)) - - if args_cli.task is not None: - env_name = args_cli.task.split(":")[-1] - if env_name is None: - raise ValueError("Task/env name was not specified nor found in the dataset.") - - num_envs = args_cli.num_envs - - env_cfg = parse_env_cfg(env_name, device=args_cli.device, num_envs=num_envs) - - # extract success checking function to invoke in the main loop - success_term = None - if args_cli.validate_success_rate: - if hasattr(env_cfg.terminations, "success"): - success_term = env_cfg.terminations.success - env_cfg.terminations.success = None - else: - print( - "No success termination term was found in the environment." - " Will not be able to mark recorded demos as successful." - ) - - # Disable all recorders and terminations - env_cfg.recorders = {} - env_cfg.terminations = {} - - # create environment from loaded config - env = gym.make(args_cli.task, cfg=env_cfg).unwrapped - - teleop_interface = Se3Keyboard(Se3KeyboardCfg(pos_sensitivity=0.1, rot_sensitivity=0.1)) - teleop_interface.add_callback("N", play_cb) - teleop_interface.add_callback("B", pause_cb) - print('Press "B" to pause and "N" to resume the replayed actions.') - - # Determine if state validation should be conducted - state_validation_enabled = False - if args_cli.validate_states and num_envs == 1: - state_validation_enabled = True - elif args_cli.validate_states and num_envs > 1: - print("Warning: State validation is only supported with a single environment. Skipping state validation.") - - # Get idle action (idle actions are applied to envs without next action) - if hasattr(env_cfg, "idle_action"): - idle_action = env_cfg.idle_action.repeat(num_envs, 1) - else: - idle_action = torch.zeros(env.action_space.shape) +def replay_episodes_loop( # noqa: C901 + env, + dataset_file_handler: HDF5DatasetFileHandler, + episode_names: list[str], + episode_count: int, + episode_indices_to_replay: list[int], + num_envs: int, + success_term, + state_validation_enabled: bool, + idle_action: torch.Tensor, + reset_sim_buffer_each_episode: bool, +) -> tuple[int, int, list[int]]: + """Run the replay loop until all selected episodes finish or the app exits. - # reset before starting - env.reset() - teleop_interface.reset() - - # simulate environment -- run everything in inference mode - episode_names = list(dataset_file_handler.get_episode_names()) + Returns: + Tuple of (replayed_episode_count, recorded_episode_count, failed_demo_ids). + """ replayed_episode_count = 0 recorded_episode_count = 0 - - # Track current episode indices for each environment - current_episode_indices = [None] * num_envs - - # Track failed demo IDs - failed_demo_ids = [] + current_episode_indices: list[int | None] = [None] * num_envs + failed_demo_ids: list[int] = [] with contextlib.suppress(KeyboardInterrupt) and torch.inference_mode(): while simulation_app.is_running() and not simulation_app.is_exiting(): @@ -195,7 +145,7 @@ def main(): episode_ended = [False] * num_envs while has_next_action: # initialize actions with idle action so those without next action will not move - actions = idle_action + actions = idle_action.clone() has_next_action = False for env_id in range(num_envs): env_next_action = env_episode_data_map[env_id].get_next_action() @@ -216,11 +166,9 @@ def main(): ) else: # if not successful, add to failed demo IDs list - if ( - current_episode_indices[env_id] is not None - and current_episode_indices[env_id] not in failed_demo_ids - ): - failed_demo_ids.append(current_episode_indices[env_id]) + cid = current_episode_indices[env_id] + if cid is not None and cid not in failed_demo_ids: + failed_demo_ids.append(cid) episode_ended[env_id] = True @@ -243,6 +191,8 @@ def main(): env_episode_data_map[env_id] = episode_data # Set initial state for the new episode initial_state = episode_data.get_initial_state() + if reset_sim_buffer_each_episode: + env.sim.reset() env.reset_to(initial_state, torch.tensor([env_id], device=env.device), is_relative=True) # Get the first action for the new episode env_next_action = env_episode_data_map[env_id].get_next_action() @@ -275,6 +225,99 @@ def main(): print("\t- mismatched.") print(comparison_log) break + + return replayed_episode_count, recorded_episode_count, failed_demo_ids + + +def main(): + """Replay episodes loaded from a file.""" + global is_paused + + # Load dataset + if not os.path.exists(args_cli.dataset_file): + raise FileNotFoundError(f"The dataset file {args_cli.dataset_file} does not exist.") + dataset_file_handler = HDF5DatasetFileHandler() + dataset_file_handler.open(args_cli.dataset_file) + env_name = dataset_file_handler.get_env_name() + episode_count = dataset_file_handler.get_num_episodes() + + if episode_count == 0: + print("No episodes found in the dataset.") + exit() + + episode_indices_to_replay = list(args_cli.select_episodes) + if len(episode_indices_to_replay) == 0: + episode_indices_to_replay = list(range(episode_count)) + + if args_cli.task is not None: + env_name = args_cli.task.split(":")[-1] + if env_name is None: + raise ValueError("Task/env name was not specified nor found in the dataset.") + + num_envs = args_cli.num_envs + if args_cli.reset_sim_buffer_each_episode and num_envs != 1: + raise ValueError( + "--reset_sim_buffer_each_episode is only supported with a single environment (--num_envs 1). " + f"Got num_envs={num_envs}. Use --num_envs 1 or disable --reset_sim_buffer_each_episode." + ) + + env_cfg = parse_env_cfg(env_name, device=args_cli.device, num_envs=num_envs) + + # extract success checking function to invoke in the main loop + success_term = None + if args_cli.validate_success_rate: + if hasattr(env_cfg.terminations, "success"): + success_term = env_cfg.terminations.success + env_cfg.terminations.success = None + else: + print( + "No success termination term was found in the environment." + " Will not be able to mark recorded demos as successful." + ) + + # Disable all recorders and terminations + env_cfg.recorders = {} + env_cfg.terminations = {} + + # create environment from loaded config + env = gym.make(args_cli.task, cfg=env_cfg).unwrapped + + teleop_interface = Se3Keyboard(Se3KeyboardCfg(pos_sensitivity=0.1, rot_sensitivity=0.1)) + teleop_interface.add_callback("N", play_cb) + teleop_interface.add_callback("B", pause_cb) + print('Press "B" to pause and "N" to resume the replayed actions.') + + # Determine if state validation should be conducted + state_validation_enabled = False + if args_cli.validate_states and num_envs == 1: + state_validation_enabled = True + elif args_cli.validate_states and num_envs > 1: + print("Warning: State validation is only supported with a single environment. Skipping state validation.") + + # Get idle action (idle actions are applied to envs without next action) + if hasattr(env_cfg, "idle_action"): + idle_action = torch.tensor(env_cfg.idle_action, device=env.unwrapped.device).repeat(num_envs, 1) + else: + idle_action = torch.zeros(env.action_space.shape) + + # reset before starting + env.reset() + teleop_interface.reset() + + episode_names = list(dataset_file_handler.get_episode_names()) + replayed_episode_count, recorded_episode_count, failed_demo_ids = replay_episodes_loop( + env, + dataset_file_handler, + episode_names, + episode_count, + episode_indices_to_replay, + num_envs, + success_term, + state_validation_enabled, + idle_action, + args_cli.reset_sim_buffer_each_episode, + ) + # Close environment after replay in complete plural_trailing_s = "s" if replayed_episode_count > 1 else "" print(f"Finished replaying {replayed_episode_count} episode{plural_trailing_s}.") diff --git a/scripts/tutorials/01_assets/add_new_robot.py b/scripts/tutorials/01_assets/add_new_robot.py index 087aa865a84c..cbc1e9ab5f03 100644 --- a/scripts/tutorials/01_assets/add_new_robot.py +++ b/scripts/tutorials/01_assets/add_new_robot.py @@ -23,7 +23,6 @@ import numpy as np import torch -import warp as wp import isaaclab.sim as sim_utils from isaaclab.actuators import ImplicitActuatorCfg @@ -110,29 +109,29 @@ def run_simulator(sim: sim_utils.SimulationContext, scene: InteractiveScene): # reset counters count = 0 # reset the scene entities to their initial positions offset by the environment origins - root_jetbot_pose = wp.to_torch(scene["Jetbot"].data.default_root_pose).clone() + root_jetbot_pose = scene["Jetbot"].data.default_root_pose.torch.clone() root_jetbot_pose[:, :3] += scene.env_origins - root_dofbot_pose = wp.to_torch(scene["Dofbot"].data.default_root_pose).clone() + root_dofbot_pose = scene["Dofbot"].data.default_root_pose.torch.clone() root_dofbot_pose[:, :3] += scene.env_origins # copy the default root state to the sim for the jetbot's orientation and velocity scene["Jetbot"].write_root_pose_to_sim_index(root_pose=root_jetbot_pose) - root_jetbot_vel = wp.to_torch(scene["Jetbot"].data.default_root_vel).clone() + root_jetbot_vel = scene["Jetbot"].data.default_root_vel.torch.clone() scene["Jetbot"].write_root_velocity_to_sim_index(root_velocity=root_jetbot_vel) scene["Dofbot"].write_root_pose_to_sim_index(root_pose=root_dofbot_pose) - root_dofbot_vel = wp.to_torch(scene["Dofbot"].data.default_root_vel).clone() + root_dofbot_vel = scene["Dofbot"].data.default_root_vel.torch.clone() scene["Dofbot"].write_root_velocity_to_sim_index(root_velocity=root_dofbot_vel) # copy the default joint states to the sim joint_pos, joint_vel = ( - wp.to_torch(scene["Jetbot"].data.default_joint_pos).clone(), - wp.to_torch(scene["Jetbot"].data.default_joint_vel).clone(), + scene["Jetbot"].data.default_joint_pos.torch.clone(), + scene["Jetbot"].data.default_joint_vel.torch.clone(), ) scene["Jetbot"].write_joint_position_to_sim_index(position=joint_pos) scene["Jetbot"].write_joint_velocity_to_sim_index(velocity=joint_vel) joint_pos, joint_vel = ( - wp.to_torch(scene["Dofbot"].data.default_joint_pos).clone(), - wp.to_torch(scene["Dofbot"].data.default_joint_vel).clone(), + scene["Dofbot"].data.default_joint_pos.torch.clone(), + scene["Dofbot"].data.default_joint_vel.torch.clone(), ) scene["Dofbot"].write_joint_position_to_sim_index(position=joint_pos) scene["Dofbot"].write_joint_velocity_to_sim_index(velocity=joint_vel) @@ -151,7 +150,7 @@ def run_simulator(sim: sim_utils.SimulationContext, scene: InteractiveScene): scene["Jetbot"].set_joint_velocity_target(action) # wave - wave_action = wp.to_torch(scene["Dofbot"].data.default_joint_pos) + wave_action = scene["Dofbot"].data.default_joint_pos.torch wave_action[:, 0:4] = 0.25 * np.sin(2 * np.pi * 0.5 * sim_time) scene["Dofbot"].set_joint_position_target_index(target=wave_action) diff --git a/scripts/tutorials/01_assets/run_articulation.py b/scripts/tutorials/01_assets/run_articulation.py index b6413b0be006..944edf943d4e 100644 --- a/scripts/tutorials/01_assets/run_articulation.py +++ b/scripts/tutorials/01_assets/run_articulation.py @@ -33,7 +33,6 @@ """Rest everything follows.""" import torch -import warp as wp import isaaclab.sim as sim_utils from isaaclab.assets import Articulation @@ -91,15 +90,15 @@ def run_simulator(sim: sim_utils.SimulationContext, entities: dict[str, Articula # root state # we offset the root state by the origin since the states are written in simulation world frame # if this is not done, then the robots will be spawned at the (0, 0, 0) of the simulation world - root_pose = wp.to_torch(robot.data.default_root_pose).clone() + root_pose = robot.data.default_root_pose.torch.clone() root_pose[:, :3] += origins robot.write_root_pose_to_sim_index(root_pose=root_pose) - root_vel = wp.to_torch(robot.data.default_root_vel).clone() + root_vel = robot.data.default_root_vel.torch.clone() robot.write_root_velocity_to_sim_index(root_velocity=root_vel) # set joint positions with some noise joint_pos, joint_vel = ( - wp.to_torch(robot.data.default_joint_pos).clone(), - wp.to_torch(robot.data.default_joint_vel).clone(), + robot.data.default_joint_pos.torch.clone(), + robot.data.default_joint_vel.torch.clone(), ) joint_pos += torch.rand_like(joint_pos) * 0.1 robot.write_joint_position_to_sim_index(position=joint_pos) @@ -109,7 +108,7 @@ def run_simulator(sim: sim_utils.SimulationContext, entities: dict[str, Articula print("[INFO]: Resetting robot state...") # Apply random action # -- generate random joint efforts - efforts = torch.randn_like(wp.to_torch(robot.data.joint_pos)) * 5.0 + efforts = torch.randn_like(robot.data.joint_pos.torch) * 5.0 # -- apply action to the robot robot.set_joint_effort_target_index(target=efforts) # -- write data to sim diff --git a/scripts/tutorials/01_assets/run_deformable_object.py b/scripts/tutorials/01_assets/run_deformable_object.py index 873566534e29..368fe7c3358e 100644 --- a/scripts/tutorials/01_assets/run_deformable_object.py +++ b/scripts/tutorials/01_assets/run_deformable_object.py @@ -15,8 +15,8 @@ """Launch Isaac Sim Simulator first.""" - import argparse +import os from isaaclab.app import AppLauncher @@ -24,6 +24,8 @@ parser = argparse.ArgumentParser(description="Tutorial on interacting with a deformable object.") # append AppLauncher cli args AppLauncher.add_app_launcher_args(parser) +# demos should open Kit visualizer by default +parser.set_defaults(visualizer=["kit"]) # parse the arguments args_cli = parser.parse_args() @@ -34,9 +36,11 @@ """Rest everything follows.""" import torch -import warp as wp from isaaclab_physx.assets import DeformableObject, DeformableObjectCfg +# deformables supported in PhysX +from isaaclab_physx.sim import DeformableBodyMaterialCfg, DeformableBodyPropertiesCfg + import isaaclab.sim as sim_utils import isaaclab.utils.math as math_utils from isaaclab.sim import SimulationContext @@ -51,55 +55,59 @@ def design_scene(): cfg = sim_utils.DomeLightCfg(intensity=2000.0, color=(0.8, 0.8, 0.8)) cfg.func("/World/Light", cfg) - # Create separate groups called "Origin1", "Origin2", "Origin3" + # Create a dictionary for the scene entities + scene_entities = {} + + # Create separate groups called "Origin0", "Origin1", ... # Each group will have a robot in it origins = [[0.25, 0.25, 0.0], [-0.25, 0.25, 0.0], [0.25, -0.25, 0.0], [-0.25, -0.25, 0.0]] for i, origin in enumerate(origins): sim_utils.create_prim(f"/World/Origin{i}", "Xform", translation=origin) - # Deformable Object + # 3D Deformable Object cfg = DeformableObjectCfg( prim_path="/World/Origin.*/Cube", spawn=sim_utils.MeshCuboidCfg( size=(0.2, 0.2, 0.2), - deformable_props=sim_utils.DeformableBodyPropertiesCfg(rest_offset=0.0, contact_offset=0.001), + deformable_props=DeformableBodyPropertiesCfg(), visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(0.5, 0.1, 0.0)), - physics_material=sim_utils.DeformableBodyMaterialCfg(poissons_ratio=0.4, youngs_modulus=1e5), + physics_material=DeformableBodyMaterialCfg(poissons_ratio=0.4, youngs_modulus=1e5), ), init_state=DeformableObjectCfg.InitialStateCfg(pos=(0.0, 0.0, 1.0)), debug_vis=True, ) + cube_object = DeformableObject(cfg=cfg) + scene_entities["cube_object"] = cube_object # return the scene information - scene_entities = {"cube_object": cube_object} return scene_entities, origins -def run_simulator(sim: sim_utils.SimulationContext, entities: dict[str, DeformableObject], origins: torch.Tensor): +def run_simulator(sim: sim_utils.SimulationContext, entities: dict, origins: torch.Tensor, output_dir: str): """Runs the simulation loop.""" # Extract scene entities # note: we only do this here for readability. In general, it is better to access the entities directly from # the dictionary. This dictionary is replaced by the InteractiveScene class in the next tutorial. - cube_object = entities["cube_object"] + cube_object: DeformableObject = entities["cube_object"] + # Define simulation stepping sim_dt = sim.get_physics_dt() sim_time = 0.0 count = 0 # Nodal kinematic targets of the deformable bodies - nodal_kinematic_target = wp.to_torch(cube_object.data.nodal_kinematic_target).clone() + nodal_kinematic_target = cube_object.data.nodal_kinematic_target.torch.clone() # Simulate physics while simulation_app.is_running(): - # reset - if count % 250 == 0: + # reset at start and after 3 seconds + if count % int(3.0 / sim_dt) == 0: # reset counters - sim_time = 0.0 count = 0 # reset the nodal state of the object - nodal_state = wp.to_torch(cube_object.data.default_nodal_state_w).clone() + nodal_state = cube_object.data.default_nodal_state_w.torch.clone() # apply random pose to the object pos_w = torch.rand(cube_object.num_instances, 3, device=sim.device) * 0.1 + origins quat_w = math_utils.random_orientation(cube_object.num_instances, device=sim.device) @@ -120,11 +128,12 @@ def run_simulator(sim: sim_utils.SimulationContext, entities: dict[str, Deformab print("[INFO]: Resetting object state...") # update the kinematic target for cubes at index 0 and 3 + kinematic_cubes = [0, 3] # we slightly move the cube in the z-direction by picking the vertex at index 0 - nodal_kinematic_target[[0, 3], 0, 2] += 0.001 + nodal_kinematic_target[kinematic_cubes, 0, 2] += 0.2 * sim_dt # set vertex at index 0 to be kinematically constrained # 0: constrained, 1: free - nodal_kinematic_target[[0, 3], 0, 3] = 0.0 + nodal_kinematic_target[kinematic_cubes, 0, 3] = 0.0 # write kinematic target to simulation cube_object.write_nodal_kinematic_target_to_sim_index(nodal_kinematic_target) @@ -137,18 +146,19 @@ def run_simulator(sim: sim_utils.SimulationContext, entities: dict[str, Deformab count += 1 # update buffers cube_object.update(sim_dt) - # print the root position - if count % 50 == 0: - print(f"Root position (in world): {wp.to_torch(cube_object.data.root_pos_w)[:, :3]}") + + # print the root positions every second + if count % int(1.0 / sim_dt) == 0: + print(f"Time {sim_time:.2f}s: \tRoot position (in world): {cube_object.data.root_pos_w.torch[:, :3]}") def main(): """Main function.""" # Load kit helper - sim_cfg = sim_utils.SimulationCfg(device=args_cli.device) + sim_cfg = sim_utils.SimulationCfg(dt=0.01, device=args_cli.device) sim = SimulationContext(sim_cfg) # Set main camera - sim.set_camera_view(eye=[3.0, 0.0, 1.0], target=[0.0, 0.0, 0.5]) + sim.set_camera_view(eye=[2.0, 2.0, 2.0], target=[0.0, 0.0, 0.75]) # Design scene scene_entities, scene_origins = design_scene() scene_origins = torch.tensor(scene_origins, device=sim.device) @@ -157,7 +167,9 @@ def main(): # Now we are ready! print("[INFO]: Setup complete...") # Run the simulator - run_simulator(sim, scene_entities, scene_origins) + camera_output = os.path.join(os.path.dirname(os.path.realpath(__file__)), "output", "camera") + run_simulator(sim, scene_entities, scene_origins, camera_output) + print("[INFO]: Simulation complete...") if __name__ == "__main__": diff --git a/scripts/tutorials/01_assets/run_rigid_object.py b/scripts/tutorials/01_assets/run_rigid_object.py index 6cce62d774bf..232e24f9743f 100644 --- a/scripts/tutorials/01_assets/run_rigid_object.py +++ b/scripts/tutorials/01_assets/run_rigid_object.py @@ -34,7 +34,6 @@ """Rest everything follows.""" import torch -import warp as wp import isaaclab.sim as sim_utils import isaaclab.utils.math as math_utils @@ -95,7 +94,7 @@ def run_simulator(sim: sim_utils.SimulationContext, entities: dict[str, RigidObj sim_time = 0.0 count = 0 # reset root state - root_pose = wp.to_torch(cone_object.data.default_root_pose).clone() + root_pose = cone_object.data.default_root_pose.torch.clone() # sample a random position on a cylinder around the origins root_pose[:, :3] += origins root_pose[:, :3] += math_utils.sample_cylinder( @@ -103,7 +102,7 @@ def run_simulator(sim: sim_utils.SimulationContext, entities: dict[str, RigidObj ) # write root state to simulation cone_object.write_root_pose_to_sim_index(root_pose=root_pose) - root_vel = wp.to_torch(cone_object.data.default_root_vel).clone() + root_vel = cone_object.data.default_root_vel.torch.clone() cone_object.write_root_velocity_to_sim_index(root_velocity=root_vel) # reset buffers cone_object.reset() @@ -120,7 +119,7 @@ def run_simulator(sim: sim_utils.SimulationContext, entities: dict[str, RigidObj cone_object.update(sim_dt) # print the root position if count % 50 == 0: - print(f"Root position (in world): {wp.to_torch(cone_object.data.root_pos_w)}") + print(f"Root position (in world): {cone_object.data.root_pos_w.torch}") def main(): diff --git a/scripts/tutorials/01_assets/run_surface_gripper.py b/scripts/tutorials/01_assets/run_surface_gripper.py index cb334f851e4c..5488232a5d42 100644 --- a/scripts/tutorials/01_assets/run_surface_gripper.py +++ b/scripts/tutorials/01_assets/run_surface_gripper.py @@ -108,15 +108,15 @@ def run_simulator( # root state # we offset the root state by the origin since the states are written in simulation world frame # if this is not done, then the robots will be spawned at the (0, 0, 0) of the simulation world - root_pose = wp.to_torch(robot.data.default_root_pose).clone() + root_pose = robot.data.default_root_pose.torch.clone() root_pose[:, :3] += origins robot.write_root_pose_to_sim_index(root_pose=root_pose) - root_vel = wp.to_torch(robot.data.default_root_vel).clone() + root_vel = robot.data.default_root_vel.torch.clone() robot.write_root_velocity_to_sim_index(root_velocity=root_vel) # set joint positions with some noise joint_pos, joint_vel = ( - wp.to_torch(robot.data.default_joint_pos).clone(), - wp.to_torch(robot.data.default_joint_vel).clone(), + robot.data.default_joint_pos.torch.clone(), + robot.data.default_joint_vel.torch.clone(), ) joint_pos += torch.rand_like(joint_pos) * 0.1 robot.write_joint_position_to_sim_index(position=joint_pos) diff --git a/scripts/tutorials/02_scene/create_scene.py b/scripts/tutorials/02_scene/create_scene.py index 7c578e4366b3..1d4578ca256c 100644 --- a/scripts/tutorials/02_scene/create_scene.py +++ b/scripts/tutorials/02_scene/create_scene.py @@ -34,7 +34,6 @@ """Rest everything follows.""" import torch -import warp as wp import isaaclab.sim as sim_utils from isaaclab.assets import ArticulationCfg, AssetBaseCfg @@ -82,15 +81,15 @@ def run_simulator(sim: sim_utils.SimulationContext, scene: InteractiveScene): # root state # we offset the root state by the origin since the states are written in simulation world frame # if this is not done, then the robots will be spawned at the (0, 0, 0) of the simulation world - root_pose = wp.to_torch(robot.data.default_root_pose).clone() + root_pose = robot.data.default_root_pose.torch.clone() root_pose[:, :3] += scene.env_origins robot.write_root_pose_to_sim_index(root_pose=root_pose) - root_vel = wp.to_torch(robot.data.default_root_vel).clone() + root_vel = robot.data.default_root_vel.torch.clone() robot.write_root_velocity_to_sim_index(root_velocity=root_vel) # set joint positions with some noise joint_pos, joint_vel = ( - wp.to_torch(robot.data.default_joint_pos).clone(), - wp.to_torch(robot.data.default_joint_vel).clone(), + robot.data.default_joint_pos.torch.clone(), + robot.data.default_joint_vel.torch.clone(), ) joint_pos += torch.rand_like(joint_pos) * 0.1 robot.write_joint_position_to_sim_index(position=joint_pos) @@ -100,7 +99,7 @@ def run_simulator(sim: sim_utils.SimulationContext, scene: InteractiveScene): print("[INFO]: Resetting robot state...") # Apply random action # -- generate random joint efforts - efforts = torch.randn_like(wp.to_torch(robot.data.joint_pos)) * 5.0 + efforts = torch.randn_like(robot.data.joint_pos.torch) * 5.0 # -- apply action to the robot robot.set_joint_effort_target_index(target=efforts) # -- write data to sim diff --git a/scripts/tutorials/03_envs/create_cube_base_env.py b/scripts/tutorials/03_envs/create_cube_base_env.py index c5850905bd3b..f6629c6bbb82 100644 --- a/scripts/tutorials/03_envs/create_cube_base_env.py +++ b/scripts/tutorials/03_envs/create_cube_base_env.py @@ -51,7 +51,6 @@ """Rest everything follows.""" import torch -import warp as wp import isaaclab.envs.mdp as mdp import isaaclab.sim as sim_utils @@ -129,8 +128,8 @@ def process_actions(self, actions: torch.Tensor): def apply_actions(self): # implement a PD controller to track the target position - pos_error = self._processed_actions - (wp.to_torch(self._asset.data.root_pos_w) - self._env.scene.env_origins) - vel_error = -wp.to_torch(self._asset.data.root_lin_vel_w) + pos_error = self._processed_actions - (self._asset.data.root_pos_w.torch - self._env.scene.env_origins) + vel_error = -self._asset.data.root_lin_vel_w.torch # set velocity targets self._vel_command[:, :3] = self.p_gain * pos_error + self.d_gain * vel_error self._asset.write_root_velocity_to_sim_index(root_velocity=self._vel_command) @@ -158,7 +157,7 @@ def base_position(env: ManagerBasedEnv, asset_cfg: SceneEntityCfg) -> torch.Tens """Root linear velocity in the asset's root frame.""" # extract the used quantities (to enable type-hinting) asset: RigidObject = env.scene[asset_cfg.name] - return wp.to_torch(asset.data.root_pos_w) - env.scene.env_origins + return asset.data.root_pos_w.torch - env.scene.env_origins ## diff --git a/scripts/tutorials/04_sensors/add_sensors_on_robot.py b/scripts/tutorials/04_sensors/add_sensors_on_robot.py index 31f9a2bcefcb..4c143318f27a 100644 --- a/scripts/tutorials/04_sensors/add_sensors_on_robot.py +++ b/scripts/tutorials/04_sensors/add_sensors_on_robot.py @@ -40,7 +40,6 @@ """Rest everything follows.""" import torch -import warp as wp import isaaclab.sim as sim_utils from isaaclab.assets import ArticulationCfg, AssetBaseCfg @@ -112,15 +111,15 @@ def run_simulator(sim: sim_utils.SimulationContext, scene: InteractiveScene): # root state # we offset the root state by the origin since the states are written in simulation world frame # if this is not done, then the robots will be spawned at the (0, 0, 0) of the simulation world - root_pose = wp.to_torch(scene["robot"].data.default_root_pose).clone() + root_pose = scene["robot"].data.default_root_pose.torch.clone() root_pose[:, :3] += scene.env_origins scene["robot"].write_root_pose_to_sim_index(root_pose=root_pose) - root_vel = wp.to_torch(scene["robot"].data.default_root_vel).clone() + root_vel = scene["robot"].data.default_root_vel.torch.clone() scene["robot"].write_root_velocity_to_sim_index(root_velocity=root_vel) # set joint positions with some noise joint_pos, joint_vel = ( - wp.to_torch(scene["robot"].data.default_joint_pos).clone(), - wp.to_torch(scene["robot"].data.default_joint_vel).clone(), + scene["robot"].data.default_joint_pos.torch.clone(), + scene["robot"].data.default_joint_vel.torch.clone(), ) joint_pos += torch.rand_like(joint_pos) * 0.1 scene["robot"].write_joint_position_to_sim_index(position=joint_pos) @@ -130,7 +129,7 @@ def run_simulator(sim: sim_utils.SimulationContext, scene: InteractiveScene): print("[INFO]: Resetting robot state...") # Apply default actions to the robot # -- generate actions/commands - targets = wp.to_torch(scene["robot"].data.default_joint_pos) + targets = scene["robot"].data.default_joint_pos.torch # -- apply action to the robot scene["robot"].set_joint_position_target_index(target=targets) # -- write data to sim @@ -150,7 +149,10 @@ def run_simulator(sim: sim_utils.SimulationContext, scene: InteractiveScene): print("Received shape of depth image: ", scene["camera"].data.output["distance_to_image_plane"].shape) print("-------------------------------") print(scene["height_scanner"]) - print("Received max height value: ", torch.max(scene["height_scanner"].data.ray_hits_w[..., -1]).item()) + print( + "Received max height value: ", + torch.max(scene["height_scanner"].data.ray_hits_w.torch[..., -1]).item(), + ) print("-------------------------------") print(scene["contact_forces"]) print("Received max contact force of: ", torch.max(scene["contact_forces"].data.net_forces_w).item()) diff --git a/scripts/tutorials/04_sensors/run_frame_transformer.py b/scripts/tutorials/04_sensors/run_frame_transformer.py index 9370179cb213..980ced307621 100644 --- a/scripts/tutorials/04_sensors/run_frame_transformer.py +++ b/scripts/tutorials/04_sensors/run_frame_transformer.py @@ -35,7 +35,6 @@ import math import torch -import warp as wp import isaacsim.util.debug_draw._debug_draw as omni_debug_draw @@ -124,7 +123,7 @@ def run_simulator(sim: sim_utils.SimulationContext, scene_entities: dict): # Simulate physics while simulation_app.is_running(): # perform this loop at policy control freq (50 Hz) - robot.set_joint_position_target_index(target=wp.to_torch(robot.data.default_joint_pos).clone()) + robot.set_joint_position_target_index(target=robot.data.default_joint_pos.torch.clone()) robot.write_data_to_sim() # perform step sim.step() @@ -147,10 +146,10 @@ def run_simulator(sim: sim_utils.SimulationContext, scene_entities: dict): print(f"Displaying Frame ID {frame_index}: {frame_names[frame_index]}") # visualize frame - source_pos = wp.to_torch(frame_transformer.data.source_pos_w) - source_quat = wp.to_torch(frame_transformer.data.source_quat_w) - target_pos = wp.to_torch(frame_transformer.data.target_pos_w)[:, frame_index] - target_quat = wp.to_torch(frame_transformer.data.target_quat_w)[:, frame_index] + source_pos = frame_transformer.data.source_pos_w.torch + source_quat = frame_transformer.data.source_quat_w.torch + target_pos = frame_transformer.data.target_pos_w.torch[:, frame_index] + target_quat = frame_transformer.data.target_quat_w.torch[:, frame_index] # draw the frames transform_visualizer.visualize( torch.cat([source_pos, target_pos], dim=0), torch.cat([source_quat, target_quat], dim=0) diff --git a/scripts/tutorials/04_sensors/run_ray_caster.py b/scripts/tutorials/04_sensors/run_ray_caster.py index 3e46ef1a08fd..ea6f946d8c5f 100644 --- a/scripts/tutorials/04_sensors/run_ray_caster.py +++ b/scripts/tutorials/04_sensors/run_ray_caster.py @@ -32,7 +32,6 @@ """Rest everything follows.""" import torch -import warp as wp import isaaclab.sim as sim_utils from isaaclab.assets import RigidObject, RigidObjectCfg @@ -98,9 +97,9 @@ def run_simulator(sim: sim_utils.SimulationContext, scene_entities: dict): balls: RigidObject = scene_entities["balls"] # define an initial position of the sensor - ball_default_pose = wp.to_torch(balls.data.default_root_pose).clone() + ball_default_pose = balls.data.default_root_pose.torch.clone() ball_default_pose[:, :3] = torch.rand_like(ball_default_pose[:, :3]) * 10 - ball_default_vel = wp.to_torch(balls.data.default_root_vel).clone() + ball_default_vel = balls.data.default_root_vel.torch.clone() # Create a counter for resetting the scene step_count = 0 @@ -120,7 +119,7 @@ def run_simulator(sim: sim_utils.SimulationContext, scene_entities: dict): # Update the ray-caster with Timer( f"Ray-caster update with {4} x {ray_caster.num_rays} rays with max height of" - f" {torch.max(ray_caster.data.pos_w).item():.2f}" + f" {torch.max(ray_caster.data.pos_w.torch).item():.2f}" ): ray_caster.update(dt=sim.get_physics_dt(), force_recompute=True) # Update counter diff --git a/scripts/tutorials/04_sensors/run_ray_caster_camera.py b/scripts/tutorials/04_sensors/run_ray_caster_camera.py index 375a0cf8f08b..e19b0ebfa4df 100644 --- a/scripts/tutorials/04_sensors/run_ray_caster_camera.py +++ b/scripts/tutorials/04_sensors/run_ray_caster_camera.py @@ -132,12 +132,10 @@ def run_simulator(sim: sim_utils.SimulationContext, scene_entities: dict): single_cam_data = convert_dict_to_backend( {k: v[camera_index] for k, v in camera.data.output.items()}, backend="numpy" ) - # Extract the other information - single_cam_info = camera.data.info[camera_index] - # Pack data back into replicator format to save them using its writer rep_output = {"annotators": {}} - for key, data, info in zip(single_cam_data.keys(), single_cam_data.values(), single_cam_info.values()): + for key, data in single_cam_data.items(): + info = camera.data.info.get(key) if info is not None: rep_output["annotators"][key] = {"render_product": {"data": data, **info}} else: diff --git a/scripts/tutorials/04_sensors/run_usd_camera.py b/scripts/tutorials/04_sensors/run_usd_camera.py index c2523695566a..5c041d737c5d 100644 --- a/scripts/tutorials/04_sensors/run_usd_camera.py +++ b/scripts/tutorials/04_sensors/run_usd_camera.py @@ -65,6 +65,7 @@ import numpy as np import torch +from isaaclab_physx.renderers import IsaacRtxRendererCfg import omni.replicator.core as rep @@ -97,9 +98,11 @@ def define_sensor() -> Camera: "instance_segmentation_fast", "instance_id_segmentation_fast", ], - colorize_semantic_segmentation=True, - colorize_instance_id_segmentation=True, - colorize_instance_segmentation=True, + renderer_cfg=IsaacRtxRendererCfg( + colorize_semantic_segmentation=True, + colorize_instance_id_segmentation=True, + colorize_instance_segmentation=True, + ), spawn=sim_utils.PinholeCameraCfg( focal_length=24.0, focus_distance=400.0, horizontal_aperture=20.955, clipping_range=(0.1, 1.0e5) ), @@ -173,9 +176,9 @@ def run_simulator(sim: sim_utils.SimulationContext, scene_entities: dict): rep_writer = rep.BasicWriter( output_dir=output_dir, frame_padding=0, - colorize_instance_id_segmentation=camera.cfg.colorize_instance_id_segmentation, - colorize_instance_segmentation=camera.cfg.colorize_instance_segmentation, - colorize_semantic_segmentation=camera.cfg.colorize_semantic_segmentation, + colorize_instance_id_segmentation=camera.cfg.renderer_cfg.colorize_instance_id_segmentation, + colorize_instance_segmentation=camera.cfg.renderer_cfg.colorize_instance_segmentation, + colorize_semantic_segmentation=camera.cfg.renderer_cfg.colorize_semantic_segmentation, ) # Camera positions, targets, orientations @@ -232,12 +235,10 @@ def run_simulator(sim: sim_utils.SimulationContext, scene_entities: dict): {k: v[camera_index] for k, v in camera.data.output.items()}, backend="numpy" ) - # Extract the other information - single_cam_info = camera.data.info[camera_index] - # Pack data back into replicator format to save them using its writer rep_output = {"annotators": {}} - for key, data, info in zip(single_cam_data.keys(), single_cam_data.values(), single_cam_info.values()): + for key, data in single_cam_data.items(): + info = camera.data.info.get(key) if info is not None: rep_output["annotators"][key] = {"render_product": {"data": data, **info}} else: diff --git a/scripts/tutorials/05_controllers/run_diff_ik.py b/scripts/tutorials/05_controllers/run_diff_ik.py index f4a5c7dcf603..2922265e7b9b 100644 --- a/scripts/tutorials/05_controllers/run_diff_ik.py +++ b/scripts/tutorials/05_controllers/run_diff_ik.py @@ -20,8 +20,6 @@ import argparse -import warp as wp - from isaaclab.app import AppLauncher # add argparse arguments @@ -147,8 +145,8 @@ def run_simulator(sim: sim_utils.SimulationContext, scene: InteractiveScene): # reset time count = 0 # reset joint state - joint_pos = wp.to_torch(robot.data.default_joint_pos).clone() - joint_vel = wp.to_torch(robot.data.default_joint_vel).clone() + joint_pos = robot.data.default_joint_pos.torch.clone() + joint_vel = robot.data.default_joint_vel.torch.clone() robot.write_joint_position_to_sim_index(position=joint_pos) robot.write_joint_velocity_to_sim_index(velocity=joint_vel) robot.reset() @@ -163,9 +161,9 @@ def run_simulator(sim: sim_utils.SimulationContext, scene: InteractiveScene): else: # obtain quantities from simulation jacobian = robot.root_view.get_jacobians()[:, ee_jacobi_idx, :, robot_entity_cfg.joint_ids] - ee_pose_w = wp.to_torch(robot.data.body_pose_w)[:, robot_entity_cfg.body_ids[0]] - root_pose_w = wp.to_torch(robot.data.root_pose_w) - joint_pos = wp.to_torch(robot.data.joint_pos)[:, robot_entity_cfg.joint_ids] + ee_pose_w = robot.data.body_pose_w.torch[:, robot_entity_cfg.body_ids[0]] + root_pose_w = robot.data.root_pose_w.torch + joint_pos = robot.data.joint_pos.torch[:, robot_entity_cfg.joint_ids] # compute frame in root frame ee_pos_b, ee_quat_b = subtract_frame_transforms( root_pose_w[:, 0:3], root_pose_w[:, 3:7], ee_pose_w[:, 0:3], ee_pose_w[:, 3:7] @@ -184,7 +182,7 @@ def run_simulator(sim: sim_utils.SimulationContext, scene: InteractiveScene): scene.update(sim_dt) # obtain quantities from simulation - ee_pose_w = wp.to_torch(robot.data.body_state_w)[:, robot_entity_cfg.body_ids[0], 0:7] + ee_pose_w = robot.data.body_state_w.torch[:, robot_entity_cfg.body_ids[0], 0:7] # update marker positions ee_marker.visualize(ee_pose_w[:, 0:3], ee_pose_w[:, 3:7]) goal_marker.visualize(ik_commands[:, 0:3] + scene.env_origins, ik_commands[:, 3:7]) diff --git a/scripts/tutorials/05_controllers/run_osc.py b/scripts/tutorials/05_controllers/run_osc.py index 841ee0c9dd68..09e16c40c70e 100644 --- a/scripts/tutorials/05_controllers/run_osc.py +++ b/scripts/tutorials/05_controllers/run_osc.py @@ -20,8 +20,6 @@ import argparse -import warp as wp - from isaaclab.app import AppLauncher # add argparse arguments @@ -181,7 +179,7 @@ def run_simulator(sim: sim_utils.SimulationContext, scene: InteractiveScene): robot.update(dt=sim_dt) # Get the center of the robot soft joint limits - joint_centers = torch.mean(wp.to_torch(robot.data.soft_joint_pos_limits)[:, arm_joint_ids, :], dim=-1) + joint_centers = torch.mean(robot.data.soft_joint_pos_limits.torch[:, arm_joint_ids, :], dim=-1) # get the updated states ( @@ -215,8 +213,8 @@ def run_simulator(sim: sim_utils.SimulationContext, scene: InteractiveScene): # reset every 500 steps if count % 500 == 0: # reset joint state to default - default_joint_pos = wp.to_torch(robot.data.default_joint_pos).clone() - default_joint_vel = wp.to_torch(robot.data.default_joint_vel).clone() + default_joint_pos = robot.data.default_joint_pos.torch.clone() + default_joint_vel = robot.data.default_joint_vel.torch.clone() robot.write_joint_position_to_sim_index(position=default_joint_pos) robot.write_joint_velocity_to_sim_index(velocity=default_joint_vel) robot.set_joint_effort_target_index(target=zero_joint_efforts) # Set zero torques in the initial step @@ -321,30 +319,26 @@ def update_states( gravity = robot.root_view.get_gravity_compensation_forces()[:, arm_joint_ids] # Convert the Jacobian from world to root frame jacobian_b = jacobian_w.clone() - root_rot_matrix = matrix_from_quat(quat_inv(wp.to_torch(robot.data.root_quat_w))) + root_rot_matrix = matrix_from_quat(quat_inv(robot.data.root_quat_w.torch)) jacobian_b[:, :3, :] = torch.bmm(root_rot_matrix, jacobian_b[:, :3, :]) jacobian_b[:, 3:, :] = torch.bmm(root_rot_matrix, jacobian_b[:, 3:, :]) # Compute current pose of the end-effector - root_pos_w = wp.to_torch(robot.data.root_pos_w) - root_quat_w = wp.to_torch(robot.data.root_quat_w) - ee_pos_w = wp.to_torch(robot.data.body_pos_w)[:, ee_frame_idx] - ee_quat_w = wp.to_torch(robot.data.body_quat_w)[:, ee_frame_idx] + root_pos_w = robot.data.root_pos_w.torch + root_quat_w = robot.data.root_quat_w.torch + ee_pos_w = robot.data.body_pos_w.torch[:, ee_frame_idx] + ee_quat_w = robot.data.body_quat_w.torch[:, ee_frame_idx] ee_pos_b, ee_quat_b = subtract_frame_transforms(root_pos_w, root_quat_w, ee_pos_w, ee_quat_w) root_pose_w = torch.cat([root_pos_w, root_quat_w], dim=-1) ee_pose_w = torch.cat([ee_pos_w, ee_quat_w], dim=-1) ee_pose_b = torch.cat([ee_pos_b, ee_quat_b], dim=-1) # Compute the current velocity of the end-effector - ee_vel_w = wp.to_torch(robot.data.body_vel_w)[ - :, ee_frame_idx, : - ] # Extract end-effector velocity in the world frame - root_vel_w = wp.to_torch(robot.data.root_vel_w) # Extract root velocity in the world frame + ee_vel_w = robot.data.body_vel_w.torch[:, ee_frame_idx, :] # Extract end-effector velocity in the world frame + root_vel_w = robot.data.root_vel_w.torch # Extract root velocity in the world frame relative_vel_w = ee_vel_w - root_vel_w # Compute the relative velocity in the world frame - ee_lin_vel_b = quat_apply_inverse( - wp.to_torch(robot.data.root_quat_w), relative_vel_w[:, 0:3] - ) # From world to root frame - ee_ang_vel_b = quat_apply_inverse(wp.to_torch(robot.data.root_quat_w), relative_vel_w[:, 3:6]) + ee_lin_vel_b = quat_apply_inverse(robot.data.root_quat_w.torch, relative_vel_w[:, 0:3]) # From world to root frame + ee_ang_vel_b = quat_apply_inverse(robot.data.root_quat_w.torch, relative_vel_w[:, 3:6]) ee_vel_b = torch.cat([ee_lin_vel_b, ee_ang_vel_b], dim=-1) # Calculate the contact force @@ -359,8 +353,8 @@ def update_states( ee_force_b = ee_force_w # Get joint positions and velocities - joint_pos = wp.to_torch(robot.data.joint_pos)[:, arm_joint_ids] - joint_vel = wp.to_torch(robot.data.joint_vel)[:, arm_joint_ids] + joint_pos = robot.data.joint_pos.torch[:, arm_joint_ids] + joint_vel = robot.data.joint_vel.torch[:, arm_joint_ids] return ( jacobian_b, diff --git a/scripts/tutorials/06_deploy/anymal_c_env.py b/scripts/tutorials/06_deploy/anymal_c_env.py new file mode 100644 index 000000000000..94022e3a0956 --- /dev/null +++ b/scripts/tutorials/06_deploy/anymal_c_env.py @@ -0,0 +1,208 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +# ruff: noqa: I001 + +from __future__ import annotations + +import gymnasium as gym +import torch +import warp as wp + +import isaaclab.sim as sim_utils +from isaaclab.assets import Articulation +from isaaclab.envs import DirectRLEnv +from isaaclab.sensors import ContactSensor, RayCaster + +from .anymal_c_env_cfg import AnymalCFlatEnvCfg, AnymalCRoughEnvCfg +from leapp import annotate # isort: skip + + +class AnymalCEnv(DirectRLEnv): + cfg: AnymalCFlatEnvCfg | AnymalCRoughEnvCfg + + def __init__(self, cfg: AnymalCFlatEnvCfg | AnymalCRoughEnvCfg, render_mode: str | None = None, **kwargs): + super().__init__(cfg, render_mode, **kwargs) + + self._actions = torch.zeros(self.num_envs, gym.spaces.flatdim(self.single_action_space), device=self.device) + self._previous_actions = torch.zeros( + self.num_envs, gym.spaces.flatdim(self.single_action_space), device=self.device + ) + + self._commands = torch.zeros(self.num_envs, 3, device=self.device) + + self._episode_sums = { + key: torch.zeros(self.num_envs, dtype=torch.float, device=self.device) + for key in [ + "track_lin_vel_xy_exp", + "track_ang_vel_z_exp", + "lin_vel_z_l2", + "ang_vel_xy_l2", + "dof_torques_l2", + "dof_acc_l2", + "action_rate_l2", + "feet_air_time", + "undesired_contacts", + "flat_orientation_l2", + ] + } + self._base_id, _ = self._contact_sensor.find_sensors("base") + self._feet_ids, _ = self._contact_sensor.find_sensors(".*FOOT") + self._undesired_contact_body_ids, _ = self._contact_sensor.find_sensors(".*THIGH") + + def _setup_scene(self): + self._robot = Articulation(self.cfg.robot) + self.scene.articulations["robot"] = self._robot + self._contact_sensor = ContactSensor(self.cfg.contact_sensor) + self.scene.sensors["contact_sensor"] = self._contact_sensor + if isinstance(self.cfg, AnymalCRoughEnvCfg): + self._height_scanner = RayCaster(self.cfg.height_scanner) + self.scene.sensors["height_scanner"] = self._height_scanner + self.cfg.terrain.num_envs = self.scene.cfg.num_envs + self.cfg.terrain.env_spacing = self.scene.cfg.env_spacing + self._terrain = self.cfg.terrain.class_type(self.cfg.terrain) + self.scene.clone_environments(copy_from_source=False) + if self.device == "cpu": + self.scene.filter_collisions(global_prim_paths=[self.cfg.terrain.prim_path]) + light_cfg = sim_utils.DomeLightCfg(intensity=2000.0, color=(0.75, 0.75, 0.75)) + light_cfg.func("/World/Light", light_cfg) + + def _pre_physics_step(self, actions: torch.Tensor): + self._actions = actions.clone() + self._processed_actions = self.cfg.action_scale * self._actions + self._robot.data.default_joint_pos.torch + # start LEAPP annotations for outputs + annotate.update_state(self.spec.id, {"previous_actions": actions}) + annotate.output_tensors(self.spec.id, {"processed_actions": self._processed_actions}, export_with="onnx-dynamo") + # end LEAPP annotations for outputs + + def _apply_action(self): + self._robot.set_joint_position_target_index(target=self._processed_actions) + + def _get_observations(self) -> dict: + self._previous_actions = self._actions.clone() + height_data = None + if isinstance(self.cfg, AnymalCRoughEnvCfg): + height_data = ( + self._height_scanner.data.pos_w.torch[:, 2].unsqueeze(1) + - self._height_scanner.data.ray_hits_w.torch[..., 2] + - 0.5 + ).clip(-1.0, 1.0) + # start LEAPP annotations for inputs + # NOTE: height data is not used by the flat policy. not needed for this example + root_lin_vel_b = annotate.input_tensors(self.spec.id, {"root_lin_vel_b": self._robot.data.root_lin_vel_b.torch}) + root_ang_vel_b = annotate.input_tensors(self.spec.id, {"root_ang_vel_b": self._robot.data.root_ang_vel_b.torch}) + projected_gravity_b = annotate.input_tensors( + self.spec.id, {"projected_gravity_b": self._robot.data.projected_gravity_b.torch} + ) + commands = annotate.input_tensors(self.spec.id, {"commands": self._commands}) + joint_pos = annotate.input_tensors(self.spec.id, {"joint_pos": self._robot.data.joint_pos.torch}) + default_joint_pos = annotate.input_tensors( + self.spec.id, {"default_joint_pos": self._robot.data.default_joint_pos.torch} + ) + joint_vel = annotate.input_tensors(self.spec.id, {"joint_vel": self._robot.data.joint_vel.torch}) + previous_actions = annotate.state_tensors(self.spec.id, {"previous_actions": self._actions}) + # end LEAPP annotations for inputs + + obs = torch.cat( + [ + tensor + for tensor in ( + root_lin_vel_b, + root_ang_vel_b, + projected_gravity_b, + commands, + joint_pos - default_joint_pos, + joint_vel, + height_data, + previous_actions, + ) + if tensor is not None + ], + dim=-1, + ) + observations = {"policy": obs} + return observations + + def _get_rewards(self) -> torch.Tensor: + lin_vel_error = torch.sum( + torch.square(self._commands[:, :2] - self._robot.data.root_lin_vel_b.torch[:, :2]), dim=1 + ) + lin_vel_error_mapped = torch.exp(-lin_vel_error / 0.25) + yaw_rate_error = torch.square(self._commands[:, 2] - self._robot.data.root_ang_vel_b.torch[:, 2]) + yaw_rate_error_mapped = torch.exp(-yaw_rate_error / 0.25) + z_vel_error = torch.square(self._robot.data.root_lin_vel_b.torch[:, 2]) + ang_vel_error = torch.sum(torch.square(self._robot.data.root_ang_vel_b.torch[:, :2]), dim=1) + joint_torques = torch.sum(torch.square(self._robot.data.applied_torque.torch), dim=1) + joint_accel = torch.sum(torch.square(self._robot.data.joint_acc.torch), dim=1) + action_rate = torch.sum(torch.square(self._actions - self._previous_actions), dim=1) + first_contact = self._contact_sensor.compute_first_contact(self.step_dt).torch[:, self._feet_ids] + last_air_time = self._contact_sensor.data.last_air_time.torch[:, self._feet_ids] + air_time = torch.sum((last_air_time - 0.5) * first_contact, dim=1) * ( + torch.linalg.norm(self._commands[:, :2], dim=1) > 0.1 + ) + net_contact_forces = self._contact_sensor.data.net_forces_w_history.torch + is_contact = ( + torch.max(torch.linalg.norm(net_contact_forces[:, :, self._undesired_contact_body_ids], dim=-1), dim=1)[0] + > 1.0 + ) + contacts = torch.sum(is_contact, dim=1) + flat_orientation = torch.sum(torch.square(self._robot.data.projected_gravity_b.torch[:, :2]), dim=1) + + rewards = { + "track_lin_vel_xy_exp": lin_vel_error_mapped * self.cfg.lin_vel_reward_scale * self.step_dt, + "track_ang_vel_z_exp": yaw_rate_error_mapped * self.cfg.yaw_rate_reward_scale * self.step_dt, + "lin_vel_z_l2": z_vel_error * self.cfg.z_vel_reward_scale * self.step_dt, + "ang_vel_xy_l2": ang_vel_error * self.cfg.ang_vel_reward_scale * self.step_dt, + "dof_torques_l2": joint_torques * self.cfg.joint_torque_reward_scale * self.step_dt, + "dof_acc_l2": joint_accel * self.cfg.joint_accel_reward_scale * self.step_dt, + "action_rate_l2": action_rate * self.cfg.action_rate_reward_scale * self.step_dt, + "feet_air_time": air_time * self.cfg.feet_air_time_reward_scale * self.step_dt, + "undesired_contacts": contacts * self.cfg.undesired_contact_reward_scale * self.step_dt, + "flat_orientation_l2": flat_orientation * self.cfg.flat_orientation_reward_scale * self.step_dt, + } + reward = torch.sum(torch.stack(list(rewards.values())), dim=0) + for key, value in rewards.items(): + self._episode_sums[key] += value + return reward + + def _get_dones(self) -> tuple[torch.Tensor, torch.Tensor]: + time_out = self.episode_length_buf >= self.max_episode_length - 1 + net_contact_forces = self._contact_sensor.data.net_forces_w_history.torch + died = torch.any( + torch.max(torch.linalg.norm(net_contact_forces[:, :, self._base_id], dim=-1), dim=1)[0] > 1.0, dim=1 + ) + return died, time_out + + def _reset_idx(self, env_ids: torch.Tensor | None): + if env_ids is None or len(env_ids) == self.num_envs: + env_ids = wp.to_torch(self._robot._ALL_INDICES) + assert env_ids is not None + self._robot.reset(env_ids) + super()._reset_idx(env_ids) + if len(env_ids) == self.num_envs: + self.episode_length_buf[:] = torch.randint_like(self.episode_length_buf, high=int(self.max_episode_length)) + self._actions[env_ids] = 0.0 + self._previous_actions[env_ids] = 0.0 + self._commands[env_ids] = torch.zeros_like(self._commands[env_ids]).uniform_(-1.0, 1.0) + joint_pos = self._robot.data.default_joint_pos.torch[env_ids] + joint_vel = self._robot.data.default_joint_vel.torch[env_ids] + default_root_pose = self._robot.data.default_root_pose.torch[env_ids] + default_root_vel = self._robot.data.default_root_vel.torch[env_ids] + default_root_pose[:, :3] += self._terrain.env_origins[env_ids] + self._robot.write_root_pose_to_sim_index(root_pose=default_root_pose, env_ids=env_ids) + self._robot.write_root_velocity_to_sim_index(root_velocity=default_root_vel, env_ids=env_ids) + self._robot.write_joint_position_to_sim_index(position=joint_pos, env_ids=env_ids) + self._robot.write_joint_velocity_to_sim_index(velocity=joint_vel, env_ids=env_ids) + extras = dict() + for key in self._episode_sums.keys(): + episodic_sum_avg = torch.mean(self._episode_sums[key][env_ids]) + extras["Episode_Reward/" + key] = episodic_sum_avg / self.max_episode_length_s + self._episode_sums[key][env_ids] = 0.0 + self.extras["log"] = dict() + self.extras["log"].update(extras) + extras = dict() + extras["Episode_Termination/base_contact"] = torch.count_nonzero(self.reset_terminated[env_ids]).item() + extras["Episode_Termination/time_out"] = torch.count_nonzero(self.reset_time_outs[env_ids]).item() + self.extras["log"].update(extras) diff --git a/source/isaaclab/changelog.d/.gitkeep b/source/isaaclab/changelog.d/.gitkeep new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/source/isaaclab/changelog.d/antoiner-rename-newton-presets.skip b/source/isaaclab/changelog.d/antoiner-rename-newton-presets.skip new file mode 100644 index 000000000000..e32e76dd5f0e --- /dev/null +++ b/source/isaaclab/changelog.d/antoiner-rename-newton-presets.skip @@ -0,0 +1 @@ +skip diff --git a/source/isaaclab/changelog.d/clone-plan-visualizer-cleanup.minor.rst b/source/isaaclab/changelog.d/clone-plan-visualizer-cleanup.minor.rst new file mode 100644 index 000000000000..8a8a74cb6267 --- /dev/null +++ b/source/isaaclab/changelog.d/clone-plan-visualizer-cleanup.minor.rst @@ -0,0 +1,43 @@ +Added +^^^^^ + +* Added :class:`~isaaclab.cloner.ClonePlan` frozen dataclass capturing per-group + prototype-to-environment mappings (``dest_template``, ``prototype_paths``, + ``clone_mask``). Lets downstream consumers (scene data providers, mesh samplers) + read prototype geometry once and scatter to environments via the per-group mask + instead of walking per-env USD paths. +* Added :meth:`~isaaclab.sim.SimulationContext.get_clone_plans` and + :meth:`~isaaclab.sim.SimulationContext.set_clone_plans` for publishing and + consuming the cloner's per-group plan map. +* Added :attr:`~isaaclab.scene.InteractiveScene.clone_plans` property (forwards to + :meth:`~isaaclab.sim.SimulationContext.get_clone_plans`) so consumers holding a + scene reference can read the published plans without going through the sim + context. + +Changed +^^^^^^^ + +* **Breaking:** :func:`~isaaclab.cloner.clone_from_template` now returns + ``dict[str, ClonePlan]`` instead of ``None``. Bind the result and publish it + through :meth:`~isaaclab.sim.SimulationContext.set_clone_plans` if downstream + consumers (e.g. the PhysX scene data provider's Newton-visualizer build path) + need to read the plan. + +Removed +^^^^^^^ + +* **Breaking:** Removed + :attr:`~isaaclab.cloner.TemplateCloneCfg.visualizer_clone_fn`, + :func:`~isaaclab.cloner.resolve_visualizer_clone_fn`, and + :class:`~isaaclab.physics.scene_data_requirements.VisualizerPrebuiltArtifacts`. + Scene data providers now build backend models from the + :class:`~isaaclab.cloner.ClonePlan` map via + :meth:`~isaaclab.sim.SimulationContext.get_clone_plans` instead of receiving a + prebuilt artifact through a clone-time callback. +* **Breaking:** Removed + :meth:`~isaaclab.sim.SimulationContext.get_scene_data_visualizer_prebuilt_artifact`, + :meth:`~isaaclab.sim.SimulationContext.set_scene_data_visualizer_prebuilt_artifact`, + and + :meth:`~isaaclab.sim.SimulationContext.clear_scene_data_visualizer_prebuilt_artifact`. + Use :meth:`~isaaclab.sim.SimulationContext.get_clone_plans` / + :meth:`~isaaclab.sim.SimulationContext.set_clone_plans` instead. diff --git a/source/isaaclab/changelog.d/leapp_export_integration.rst b/source/isaaclab/changelog.d/leapp_export_integration.rst new file mode 100644 index 000000000000..ea2de5e5d029 --- /dev/null +++ b/source/isaaclab/changelog.d/leapp_export_integration.rst @@ -0,0 +1,15 @@ +Added +^^^^^ + +* Added LEAPP export support for manager-based RSL-RL policies, including + export-time observation/action annotation, recurrent actor-state handling, and + deployment through :mod:`scripts.reinforcement_learning.leapp.deploy`. +* Added a Direct workflow LEAPP export tutorial and annotated ANYmal-C example + script showing how to mark policy inputs, outputs, and persistent state with + LEAPP annotations. Direct workflow policies can be exported with + :mod:`scripts.reinforcement_learning.leapp.rsl_rl.export`, but are not yet + supported by :mod:`scripts.reinforcement_learning.leapp.deploy`. +* Added LEAPP deployment documentation describing the exported-policy validation + flow and linking the manager-based and Direct workflow export paths. +* Added LEAPP export annotations, proxy utilities, and deployment environment + support for Isaac Lab assets, sensors, commands, and manager-based environments. diff --git a/source/isaaclab/changelog.d/mtrepte-expand_viz_markers.minor.rst b/source/isaaclab/changelog.d/mtrepte-expand_viz_markers.minor.rst new file mode 100644 index 000000000000..8975a9178b83 --- /dev/null +++ b/source/isaaclab/changelog.d/mtrepte-expand_viz_markers.minor.rst @@ -0,0 +1,5 @@ +Added +^^^^^ + +* Added backend-agnostic :class:`~isaaclab.markers.VisualizationMarkers` support for + marker-capable Kit, Newton, Rerun, and Viser visualizers. diff --git a/source/isaaclab/changelog.d/omniverseclient-pin.rst b/source/isaaclab/changelog.d/omniverseclient-pin.rst new file mode 100644 index 000000000000..832820b64a47 --- /dev/null +++ b/source/isaaclab/changelog.d/omniverseclient-pin.rst @@ -0,0 +1,4 @@ +Fixed +^^^^^ + +* Pinned ``omniverseclient`` to ``2.71.1.7015``. diff --git a/source/isaaclab/changelog.d/pr-5458-merge-develop.rst b/source/isaaclab/changelog.d/pr-5458-merge-develop.rst new file mode 100644 index 000000000000..c94e6b8921a6 --- /dev/null +++ b/source/isaaclab/changelog.d/pr-5458-merge-develop.rst @@ -0,0 +1,15 @@ +Changed +^^^^^^^ + +* Changed :func:`~isaaclab.envs.mdp.body_incoming_wrench` to read from + :class:`~isaaclab.sensors.JointWrenchSensor`. Pass + ``sensor_cfg=SceneEntityCfg("joint_wrench", body_names=...)`` instead of an + articulation asset config. + +Removed +^^^^^^^ + +* Removed ``BaseArticulationData.body_incoming_joint_wrench_b``. Add + :class:`~isaaclab.sensors.JointWrenchSensorCfg` to the scene and read + :attr:`~isaaclab.sensors.JointWrenchSensorData.force` and + :attr:`~isaaclab.sensors.JointWrenchSensorData.torque` instead. diff --git a/source/isaaclab/changelog.d/rschmitt_decouple_renderer_camera.rst b/source/isaaclab/changelog.d/rschmitt_decouple_renderer_camera.rst new file mode 100644 index 000000000000..337b7f55b6a3 --- /dev/null +++ b/source/isaaclab/changelog.d/rschmitt_decouple_renderer_camera.rst @@ -0,0 +1,33 @@ +Added +^^^^^ + +* Added :class:`~isaaclab.renderers.camera_render_spec.CameraRenderSpec` so render backends + take explicit camera inputs (USD paths, :class:`~isaaclab.sensors.camera.CameraCfg`, device, + counts) instead of the :class:`~isaaclab.sensors.camera.Camera` instance. +* Added :class:`~isaaclab.renderers.render_context.RenderContext` (accessed as + :attr:`~isaaclab.sim.simulation_context.SimulationContext.render_context`) to own one or + more :class:`~isaaclab.renderers.base_renderer.BaseRenderer` instances: configurations that + compare equal under ``==`` and share the same concrete + :class:`~isaaclab.renderers.renderer_cfg.RendererCfg` class reuse a backend; distinct + types (e.g. Isaac RTX and Newton) register separate backends, each with + :meth:`~isaaclab.renderers.base_renderer.BaseRenderer.prepare_stage` the first time a camera + with that configuration initializes. +* Added :meth:`~isaaclab.renderers.render_context.RenderContext.render_into_camera` to run + :meth:`~isaaclab.renderers.render_context.RenderContext.update_transforms` (at most once + per physics step), then :meth:`~isaaclab.renderers.base_renderer.BaseRenderer.render` and + :meth:`~isaaclab.renderers.base_renderer.BaseRenderer.read_output`. +* Added :meth:`~isaaclab.sim.simulation_context.SimulationContext.get_physics_step_count`. + +Changed +^^^^^^^ + +* :class:`~isaaclab.sensors.camera.Camera` obtains a backend via + :meth:`~isaaclab.renderers.render_context.RenderContext.get_renderer` and calls + :meth:`~isaaclab.renderers.base_renderer.BaseRenderer.create_render_data` with + a :class:`~isaaclab.renderers.camera_render_spec.CameraRenderSpec` (no + :class:`~isaaclab.sensors.sensor_base.SensorBase` reference on the public API). +* :class:`~isaaclab.scene.interactive_scene.InteractiveScene` calls + :meth:`~isaaclab.renderers.render_context.RenderContext.update_transforms` once at the start + of :meth:`~isaaclab.scene.interactive_scene.InteractiveScene.update` when + ``lazy_sensor_update`` is false; fetches that render still dedupe the same way via + ``physics_step_count`` in :class:`~isaaclab.renderers.render_context.RenderContext`. diff --git a/source/isaaclab/config/extension.toml b/source/isaaclab/config/extension.toml index 52f92be2364e..95993d71590f 100644 --- a/source/isaaclab/config/extension.toml +++ b/source/isaaclab/config/extension.toml @@ -1,7 +1,7 @@ [package] # Note: Semantic Versioning is used: https://semver.org/ -version = "4.5.25" +version = "4.6.28" # Description title = "Isaac Lab framework for Robot Learning" diff --git a/source/isaaclab/docs/CHANGELOG.rst b/source/isaaclab/docs/CHANGELOG.rst index 5269d6946b01..701f53744f84 100644 --- a/source/isaaclab/docs/CHANGELOG.rst +++ b/source/isaaclab/docs/CHANGELOG.rst @@ -1,6 +1,804 @@ Changelog --------- +4.6.27 (2026-05-01) +~~~~~~~~~~~~~~~~~~~ + +* Added :class:`~isaaclab.sensors.JointWrenchSensor`. + + +4.6.26 (2026-05-01) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added ``Metrics/success_rate`` tracking to benchmark scripts. The result is always logged + to the benchmark artifact; ``--check_success`` additionally early-stops training on convergence. + + +4.6.25 (2026-04-28) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed ``isaaclab.bat --install`` on Windows 11 failing with + ``'"setuptools<82.0.0"': Expected package name at the start of dependency + specifier``. ``extract_python_exe`` now prefers the underlying + ``kit/python/python.exe`` over Isaac Sim's ``python.bat`` so child pip calls + bypass the cmd.exe quoting hop that was preserving the literal double + quotes through to pip's argv. The fallback ``cmd.exe /c`` wrapper for + ``.bat``/``.cmd`` invocations now also uses caret-escaping + (e.g. ``setuptools^<82.0.0``) for metacharacters instead of double-quoting, + so the bat-hop path no longer leaks quotes. + + +4.6.24 (2026-04-28) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed ``./isaaclab.sh -i`` failing to build the ``nlopt`` wheel on ARM Linux + (e.g. DGX Spark) when the host image is missing SWIG. The bare-metal install + path now mirrors ``docker/Dockerfile.base``: on ARM Linux it installs + ``swig`` via apt and pre-installs ``nlopt==2.6.2`` with + ``--no-build-isolation`` so later submodule installs skip the source-build + fallback. + + +4.6.23 (2026-04-30) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :attr:`~isaaclab.assets.AssetBaseCfg.disable_shape_checks` configuration option + to skip shape/dtype validation in setter and writer methods, reducing per-call overhead + in production workloads. + +Fixed +^^^^^ + +* Fixed cross-backend asset interface regression tests to cover tensor views passed to + backend index resolution helpers. + + +4.6.22 (2026-04-27) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* :class:`~isaaclab.renderers.BaseRenderer` now publishes a renderer-owned + output contract via ``supported_output_types() -> {RenderBufferKind: RenderBufferSpec}``. + :class:`~isaaclab.sensors.camera.CameraData` allocates buffers for the + intersection of the requested ``data_types`` and the contract; ``rgb`` is + exposed as a view into ``rgba`` when both are published. Requested types + the active backend cannot produce are dropped with a single warning instead + of being silently discarded later. +* :class:`~isaaclab_ov.renderers.OVRTXRenderer` now writes rendered tiles + directly into the torch storage backing ``camera.data.output``, eliminating + the per-frame ``wp.copy`` bridge. +* Moved Kit/RTX-only logic out of :class:`~isaaclab.sensors.camera.Camera` + into :class:`~isaaclab_physx.renderers.IsaacRtxRenderer`. + +Deprecated +^^^^^^^^^^ + +* Deprecated RTX-flavored fields on :class:`~isaaclab.sensors.camera.CameraCfg` + (``semantic_filter``, ``colorize_semantic_segmentation``, + ``colorize_instance_segmentation``, ``colorize_instance_id_segmentation``, + ``semantic_segmentation_mapping``, ``depth_clipping_behavior``); set them on + :attr:`~isaaclab.sensors.camera.CameraCfg.renderer_cfg` instead. + + +4.6.21 (2026-04-27) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed ProxyArray migration guidance and static regression checks to cover + deprecated ``wp.to_torch(proxy_array)`` usage and direct tensor/wp.array + method calls on data properties. + + +4.6.20 (2026-04-27) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :func:`~isaaclab.utils.checked_apply` for forwarding declared + fields from an Isaac Lab configclass onto an external dataclass + (typically an upstream library config object). Raises + :class:`AttributeError` if the target is missing a declared field, so + upstream renames surface at startup instead of as silent no-ops. +* Added an opt-in runtime detector on :class:`~isaaclab.utils.warp.ProxyArray` + that emits a :class:`UserWarning` with the call site (``stacklevel=2``) on + every ``.torch`` read of a ``wp.quatf``-typed array when the + ``WARN_ON_TORCH_QUATF_ACCESS`` environment variable is set to ``"1"``. + Helps users find code that still assumes Isaac Lab 2.x's ``(w, x, y, z)`` + quaternion convention after the migration to Isaac Lab 3.x's + ``(x, y, z, w)`` convention. Documented in the Isaac Lab 3.0 migration + guide as a complement to the source-level quaternion finder tool. + + +4.6.19 (2026-04-27) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Marked :meth:`~isaaclab.envs.manager_based_rl_mimic_env.ManagerBasedRLMimicEnv.get_subtask_start_signals` and + :meth:`~isaaclab.envs.manager_based_rl_mimic_env.ManagerBasedRLMimicEnv.get_subtask_term_signals` with + ``@optional_method``. + + +4.6.18 (2026-04-27) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Updated the :class:`~isaaclab.cloner.TemplateCloneCfg` docstring example to import + ``get_current_stage`` from :mod:`isaaclab.sim.utils.stage` instead of + ``isaacsim.core.experimental.utils.stage``, aligning with the Isaac Lab API. +* Added a "Migration off Deprecated Isaac Sim APIs" section to the Isaac Lab 3.0 + migration guide (``docs/source/migration/migrating_to_isaaclab_3-0.rst``) that maps + deprecated ``isaacsim.core.*`` paths to their recommended replacements, preferring + Isaac Lab in-tree APIs (``isaaclab.sim.utils.*``, :class:`~isaaclab.sim.views.FrameView`, + :mod:`~isaaclab.cloner`) over the ``isaacsim.core.experimental.*`` fallbacks where + an Isaac Lab API exists. + +Fixed +^^^^^ + +* Fixed :class:`~isaaclab.envs.mdp.randomize_visual_color` and + :class:`~isaaclab.envs.mdp.randomize_visual_texture` failing with + ``'rtx::neuraylib::MdlModuleId' for '' is Invalid`` on Replicator >= 1.13.0. + Kit's ``omni_usd_resolver`` intentionally returns an empty string when resolving + builtin MDL short-names such as ``OmniPBR.mdl`` (``OMNI_USD_RESOLVER_MDL_BUILTIN_BYPASS=1``), + but Replicator's ``create_sdf_spec_material`` now passes that empty resolved path directly + into ``UsdMdl.RegistryUtils.GetSubIdentifiersForAsset``. The fix pre-resolves the absolute + on-disk path via ``carb.tokens`` (``${kit}/mdl/core/Base/OmniPBR.mdl``) before handing it + to Replicator so the resolver returns a valid path. + + +4.6.17 (2026-04-27) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Updated cross-backend asset interface tests to import :class:`~isaaclab_physx.physics.PhysxManager` + (aliased as ``SimulationManager``) instead of ``isaacsim.core.simulation_manager.SimulationManager``. +* Stopped registering deprecated Isaac Sim extension search paths in Isaac Lab Kit experiences and + switched explicit Isaac Sim extension dependencies to non-deprecated ``isaacsim.core.experimental.*``, + ``isaacsim.robot.experimental.wheeled_robots``, ``isaacsim.robot.wheeled_robots.nodes``, and + ``isaacsim.sensors.experimental.*`` equivalents. +* Migrated remaining Isaac Lab imports off deprecated Isaac Sim core utility/prim Python module paths + to their ``isaacsim.core.experimental.*`` replacements. + +Fixed +^^^^^ + +* Fixed ``isaaclab.sh --install`` leaving ``pinocchio`` uninstalled on top of recent Isaac Sim + base images that preinstall ``pin-pink`` in the kit's bundled ``site-packages`` without its + ``pin`` (cmeel pinocchio) dependency. Pip treats the ``pin-pink`` requirement as already + satisfied and skips the transitive ``pin`` resolve, so the pink IK controller and its tests + fail to import. ``isaaclab.cli.commands.install`` now probes ``import pinocchio`` after + installing the Isaac Lab submodules and force-reinstalls the cmeel ``pin``/``pin-pink``/ + ``daqp`` stack when the probe fails. + +Removed +^^^^^^^ + +* Retired several ``source/isaaclab/test/deps/isaacsim`` standalone reproducers that depended on + deprecated Isaac Sim core extensions; use :mod:`isaaclab.sim` and ``isaacsim.core.experimental.*`` + for similar debugging workflows. + + +4.6.16 (2026-04-24) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Renamed the ``TorchArray`` wrapper to + :class:`~isaaclab.utils.warp.ProxyArray` and its module from + ``isaaclab.utils.warp.torch_array`` to + ``isaaclab.utils.warp.proxy_array``. The new name better describes + the class as a proxy around a :class:`wp.array` exposing both + ``.warp`` and ``.torch`` accessors, rather than a torch-first type. + No backward-compatibility alias — downstream code must update + imports and type hints. + +Removed +^^^^^^^ + +* Removed :meth:`~isaaclab.utils.warp.ProxyArray.rebind`. ``ProxyArray`` + instances are now immutable after construction: assigning to any + attribute other than the internal ``_torch_cache`` raises + :class:`AttributeError`. Call sites that previously rebound a + sim-bound wrapper (Newton / PhysX asset data classes when the solver + re-creates its arrays) now assign a fresh + ``ProxyArray(new_buf)`` instead. The old pattern was unsafe — + callers holding a stale ``.torch`` reference read the old memory + silently after ``rebind``. Forcing a new wrapper per rebind makes + the stale-reference hazard local and explicit. + + .. code-block:: python + + # Before (4.6.15) + self._joint_pos_ta.rebind(self._sim_bind_joint_pos) + # After (4.6.16) + self._joint_pos_ta = ProxyArray(self._sim_bind_joint_pos) + + +4.6.15 (2026-04-24) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* :meth:`~isaaclab.sim.views.BaseFrameView.get_world_poses` and + :meth:`~isaaclab.sim.views.BaseFrameView.get_local_poses` now return + a pair of :class:`~isaaclab.utils.warp.ProxyArray` wrappers instead + of raw ``wp.array``. :class:`~isaaclab.sim.views.UsdFrameView`, + :class:`~isaaclab_physx.sim.views.FabricFrameView`, and + :class:`~isaaclab_newton.sim.views.NewtonSiteFrameView` were updated + accordingly. Calls without ``indices`` reuse a cached ProxyArray + wrapping the backend's stable buffer (Fabric/Newton); calls with + ``indices`` and all calls on USD construct a fresh ProxyArray per + invocation. + + **Breaking change** — call sites that wrapped the return in + ``wp.to_torch(...)`` or passed the result directly to a kernel must + migrate: + + .. code-block:: python + + # Before (4.6.14) + pos_wp, quat_wp = view.get_world_poses(indices) + tensor = wp.to_torch(pos_wp) + # After (4.6.15) + pos_w, quat_w = view.get_world_poses(indices) + tensor = pos_w.torch + # ... and when passing to a warp kernel: + wp.launch(..., inputs=[pos_w.warp, ...]) + + +4.6.14 (2026-04-24) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* :class:`~isaaclab.sensors.RayCasterData` and + :class:`~isaaclab.sensors.MultiMeshRayCasterData` properties + :attr:`~isaaclab.sensors.RayCasterData.pos_w`, + :attr:`~isaaclab.sensors.RayCasterData.quat_w`, and + :attr:`~isaaclab.sensors.RayCasterData.ray_hits_w` now return + :class:`~isaaclab.utils.warp.ProxyArray` instead of raw ``wp.array``. + Use ``.torch`` for a cached zero-copy ``torch.Tensor`` view or ``.warp`` + for the underlying ``wp.array``. + + **Breaking change** — call sites that previously wrapped these in + ``wp.to_torch(...)`` must migrate to the ``.torch`` accessor: + + .. code-block:: python + + # Before (4.6.13) + hits = wp.to_torch(sensor.data.ray_hits_w) + # After (4.6.14) + hits = sensor.data.ray_hits_w.torch + + +4.6.13 (2026-04-23) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :class:`~isaaclab.utils.warp.ProxyArray`, a warp-first dual-access array + that provides explicit ``.torch`` and ``.warp`` accessors for seamless + interoperability between warp and PyTorch workflows. + +Changed +^^^^^^^ + +* All properties on the following base data classes now return + :class:`~isaaclab.utils.warp.ProxyArray` instead of raw ``wp.array``: + :class:`~isaaclab.assets.articulation.BaseArticulationData`, + :class:`~isaaclab.assets.rigid_object.BaseRigidObjectData`, + :class:`~isaaclab.assets.rigid_object_collection.BaseRigidObjectCollectionData`, + :class:`~isaaclab.sensors.contact_sensor.BaseContactSensorData`, + :class:`~isaaclab.sensors.frame_transformer.BaseFrameTransformerData`, + :class:`~isaaclab.sensors.imu.BaseImuData`, and + :class:`~isaaclab.sensors.pva.BasePvaData`. + Use ``.torch`` for a cached zero-copy ``torch.Tensor`` view, or ``.warp`` for + the underlying ``wp.array``. Implicit torch operations (arithmetic, + ``torch.*`` functions) work during the deprecation period but emit a warning. + + +4.6.12 (2026-04-23) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added caching to :func:`~isaaclab.utils.string.resolve_matching_names`, + avoiding repeated regex matching across ``find_bodies``, ``find_joints``, + and related calls. + + +4.6.11 (2026-04-22) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Changed :class:`~isaaclab.sensors.RayCaster` to spawn its own non-physics Xform prim via + the new :attr:`~isaaclab.sensors.RayCasterCfg.spawn` attribute. ``prim_path`` should now + point to a child under the parent link (e.g. ``{ENV_REGEX_NS}/Robot/base/raycaster``). +* Renamed :class:`~isaaclab.sim.views.XformPrimView` to :class:`~isaaclab.sim.views.FrameView`, + ``BaseXformPrimView`` to :class:`~isaaclab.sim.views.BaseFrameView`, + and ``UsdXformPrimView`` to :class:`~isaaclab.sim.views.UsdFrameView`. + ``XformPrimView`` is kept as a deprecated alias. +* Moved :class:`~isaaclab.sensors.RayCasterCfg` offset into the spawned prim's local transform + instead of applying it at runtime. The :class:`~isaaclab.sim.views.FrameView` world pose now + includes the offset directly. +* Unified sensor prim path resolution in :class:`~isaaclab.sensors.SensorBase`. When + ``prim_path`` points at a physics body and a spawner is configured, a child prim is + automatically created underneath. + +Deprecated +^^^^^^^^^^ + +* Deprecated passing a ``prim_path`` with ``ArticulationRootAPI`` or ``RigidBodyAPI`` to + :class:`~isaaclab.sensors.RayCasterCfg`. The path is automatically extended with + ``/raycaster``; users should migrate to the child-path convention. + +Removed +^^^^^^^ + +* Removed :attr:`~isaaclab.sensors.RayCasterCfg.attach_yaw_only` (deprecated since 2.1.1). + Use ``ray_alignment="yaw"`` or ``ray_alignment="base"`` instead. + + +4.6.10 (2026-04-22) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :meth:`~isaaclab.utils.wrench_composer.WrenchComposer.add_raw_buffers_from` to merge one composer's raw + input buffers into another. +* Added ``render_enabled`` property to all environment base classes + (:class:`~isaaclab.envs.ManagerBasedEnv`, :class:`~isaaclab.envs.ManagerBasedRLEnv`, + :class:`~isaaclab.envs.DirectRLEnv`, :class:`~isaaclab.envs.DirectMARLEnv`). + Setting ``env.render_enabled = False`` before calling ``step()`` skips the Kit app loop + (``app.update()``) and camera/RTX sensor rendering, while standalone visualizers (Newton, + Rerun, Viser) continue to update normally. Kit bundles camera rendering with its app loop + so the two cannot be separated; non-Kit visualizers have independent ``step()`` methods and + are unaffected by this flag. Post-reset re-renders for RTX sensors are also skipped when + disabled. The property can be toggled between steps for per-step control. Defaults to + ``True`` for full backward compatibility. +* Added ``skip_app_pumping`` parameter to + :meth:`~isaaclab.sim.SimulationContext.render` and + :meth:`~isaaclab.sim.SimulationContext.update_visualizers` to selectively skip + visualizers that pump the Kit app loop (``pumps_app_update() == True``). + +Changed +^^^^^^^ + +* Refactored :class:`~isaaclab.utils.wrench_composer.WrenchComposer` to a dual-buffer architecture with separate + global (world-frame) and local (body-frame) buffers. A new + :meth:`~isaaclab.utils.wrench_composer.WrenchComposer.compose_to_body_frame` method rotates global forces/torques + into the body frame at apply time using the current body orientation, then sums with local forces/torques. +* Updated imports of the PhysX tensors API in the ray caster sensors from + ``omni.physics.tensors.impl.api`` to ``omni.physics.tensors.api`` to track the upstream + Isaac Sim module relocation (the ``impl`` submodule was removed). + +Deprecated +^^^^^^^^^^ + +* Deprecated :attr:`~isaaclab.utils.wrench_composer.WrenchComposer.composed_force` and + :attr:`~isaaclab.utils.wrench_composer.WrenchComposer.composed_torque` in favor of + :attr:`~isaaclab.utils.wrench_composer.WrenchComposer.out_force_b` and + :attr:`~isaaclab.utils.wrench_composer.WrenchComposer.out_torque_b`. + +Fixed +^^^^^ + +* Fixed :class:`~isaaclab.utils.wrench_composer.WrenchComposer` not correctly updating the composed torque from global + positional forces when the body moves. +* Fixed :meth:`~isaaclab.utils.wrench_composer.WrenchComposer.reset` not clearing the ``_active`` flag when called + with ``slice(None)``. +* Fixed :class:`~isaaclab.utils.wrench_composer.WrenchComposer` producing spurious torque when global forces are + applied without explicit positions. +* Fixed ``set_external_force_and_torque`` wiping forces from non-resetting environments during partial + episode resets by using ``reset(env_ids)`` + ``add_forces_and_torques`` instead of ``set_forces_and_torques``. + + +4.6.9 (2026-04-22) +~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Converted all four ray caster sensor classes (:class:`~isaaclab.sensors.RayCaster`, + :class:`~isaaclab.sensors.RayCasterCamera`, :class:`~isaaclab.sensors.MultiMeshRayCaster`, + :class:`~isaaclab.sensors.MultiMeshRayCasterCamera`) to launch Warp kernels directly via + ``wp.launch`` instead of going through Python-level torch wrappers. A new + :mod:`~isaaclab.sensors.ray_caster.kernels` module contains all sensor-specific kernels. + All intermediate ray buffers are now Warp-owned with zero-copy torch views, eliminating + per-step allocations. The existing :func:`~isaaclab.utils.warp.kernels.raycast_dynamic_meshes_kernel` + gained an ``env_mask`` parameter to support partial environment updates natively. A new + :func:`~isaaclab.utils.warp.kernels.raycast_mesh_masked_kernel` was added to + :mod:`~isaaclab.utils.warp.kernels` as the general-purpose masked single-mesh variant, + with ``return_distance`` and ``return_normal`` flags matching the design of + :func:`~isaaclab.utils.warp.kernels.raycast_mesh_kernel`. + + **Breaking change** — :attr:`~isaaclab.sensors.RayCasterData.pos_w`, + :attr:`~isaaclab.sensors.RayCasterData.quat_w`, and + :attr:`~isaaclab.sensors.RayCasterData.ray_hits_w` now return :class:`wp.array` + instead of :class:`torch.Tensor`. Call-sites that previously accessed these as tensors + must wrap the result with :func:`wp.to_torch`: + + .. code-block:: python + + # Before + hits = sensor.data.ray_hits_w # torch.Tensor (old) + # After + hits = wp.to_torch(sensor.data.ray_hits_w) # torch.Tensor (zero-copy view) + +* Changed the :attr:`~isaaclab.sensors.RayCaster.meshes` class variable cache key from + ``prim_path`` to a ``(prim_path, device)`` tuple so that meshes built on one device + (e.g. CPU) are not reused by a sensor running on another device (e.g. CUDA). + + **Breaking change** — callers that read or write :attr:`~isaaclab.sensors.RayCaster.meshes` + directly must update the key: + + .. code-block:: python + + # Before + wp_mesh = RayCaster.meshes[prim_path] + # After + wp_mesh = RayCaster.meshes[(prim_path, device)] + +Fixed +^^^^^ + +* Fixed frame composition in :meth:`~isaaclab.sensors.MultiMeshRayCaster._update_mesh_transforms` + which used simple subtraction instead of proper frame decomposition when applying mesh offsets. + With non-identity orientation offsets, tracked mesh positions were incorrect, causing raycasts to + miss or hit wrong surfaces. The method now uses :func:`~isaaclab.utils.math.combine_frame_transforms`. + + +4.6.8 (2026-04-21) +~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Pinned ``mujoco`` and ``mujoco-warp`` to ``3.6.0`` to align with the Newton library. + + +4.6.7 (2026-04-20) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :func:`~isaaclab.sim.utils.newton_model_utils.replace_newton_shape_colors` + to align Newton ``shape_color`` with authored USD where OmniPBR inputs or + ``primvars:displayColor`` apply. Set ``ISAACLAB_REPLACE_NEWTON_SHAPE_COLORS`` + to ``0``, ``false``, ``off``, or ``no`` to disable the pass; the function emits + a ``FutureWarning`` because this path is temporary until neutral USD materials + replace OmniPBR in content. +* Added ``test_newton_model_utils`` tests for the Newton shape color pass. + +Fixed +^^^^^ + +* Fixed nondeterministic environment replication when cloning from a template by + sorting prototype roots before building the clone plan in + :func:`~isaaclab.cloner.cloner_utils.clone_from_template`, keeping downstream + order stable across simulation and visualization backends. + +4.6.6 (2026-04-17) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Changed the way the python interpreter is called from ``isaaclab.sh`` to allow + error codes to bubble up to the process level. + + +4.6.5 (2026-04-16) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed flaky ``test_first_frame_is_textured_camera`` by removing warmup-step + workaround and relying on the renderer's streaming wait instead. + + +4.6.4 (2026-04-16) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed Newton viewer compatibility by restricting ``pyglet`` to ``<3``. + + +4.6.3 (2026-04-16) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Changed :class:`~isaaclab.sensors.imu.Imu` and + :class:`~isaaclab.sensors.imu.ImuData` factory type annotations to include + the Newton IMU backend types. + + +4.6.2 (2026-04-14) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + + +* Added :class:`~isaaclab.sim.spawners.meshes.MeshSquareCfg` and + :func:`~isaaclab.sim.spawners.meshes.spawn_mesh_square` for spawning 2D triangle + mesh grids, used as surface deformable bodies (cloth). +* Added physics material support to + :func:`~isaaclab.sim.spawners.from_files.spawn_from_usd` for deformable bodies + loaded from USD files. +* Added wheel builder installation CI tests that verify the isaaclab wheel + builds, installs, and imports correctly in a clean uv environment. + +Changed +^^^^^^^ + +* Moved :class:`DeformableBodyPropertiesCfg`, :class:`DeformableBodyMaterialCfg`, + and :class:`DeformableObjectSpawnerCfg` from ``isaaclab`` to ``isaaclab_physx``. + These are PhysX-specific and are now imported from + ``isaaclab_physx.sim.schemas``, ``isaaclab_physx.sim.spawners.materials``, and + ``isaaclab_physx.sim.spawners.spawner_cfg`` respectively. +* Changed deformable body property and material application in mesh and USD spawners + to use ``isaaclab_physx.sim.schemas`` instead of ``isaaclab.sim.schemas``. +* Changed :func:`~isaaclab.sim.spawners.from_files.spawn_from_usd` to call + ``define_deformable_body_properties`` when the deformable body API is not yet + present on the prim, instead of always calling ``modify_deformable_body_properties``. + +Removed +^^^^^^^ + +* Removed :func:`define_deformable_body_properties` and + :func:`modify_deformable_body_properties` from ``isaaclab.sim.schemas``. Use + ``isaaclab_physx.sim.schemas`` instead. +* Removed :class:`DeformableBodyPropertiesCfg` from ``isaaclab.sim.schemas``. Use + :class:`isaaclab_physx.sim.schemas.DeformableBodyPropertiesCfg` instead. +* Removed :class:`DeformableBodyMaterialCfg` and + :func:`spawn_deformable_body_material` from ``isaaclab.sim.spawners.materials``. + Use ``isaaclab_physx.sim.spawners.materials`` instead. +* Removed :class:`DeformableObjectSpawnerCfg` from ``isaaclab.sim.spawners``. Use + ``isaaclab_physx.sim.spawners.spawner_cfg.DeformableObjectSpawnerCfg`` instead. + + +4.6.1 (2026-04-14) +~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :attr:`~isaaclab.sim.schemas.JointDrivePropertiesCfg.ensure_drives_exist` + flag to :class:`~isaaclab.sim.schemas.JointDrivePropertiesCfg`. When enabled, + joints with zero stiffness and damping receive a minimal stiffness so that + backends like Newton recognise the drive as active. + + +4.6.0 (2026-04-13) +~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Unified :class:`~isaaclab.sensors.camera.Camera` and :class:`~isaaclab.sensors.camera.TiledCamera` + into a single implementation. :class:`Camera` now delegates all rendering to the + :class:`~isaaclab.renderers.Renderer` abstraction (same approach :class:`TiledCamera` used). + The public API is unchanged for :class:`Camera` users. +* **Breaking:** :attr:`~isaaclab.sensors.camera.CameraData.info` is now a flat + ``dict[str, Any]`` keyed by data type (e.g. ``camera.data.info["semantic_segmentation"]``). + The metadata is shared across all cameras and identical to what the underlying renderer returns. + + - **Camera users (old):** replace ``camera.data.info[cam_idx][data_type]`` with + ``camera.data.info[data_type]``. + - **TiledCamera users (old):** access pattern ``camera.data.info[data_type]`` is unchanged. + +* **Breaking:** :meth:`~isaaclab.renderers.BaseRenderer.write_output` has been replaced by + :meth:`~isaaclab.renderers.BaseRenderer.read_output`. The new method receives the full + :class:`~isaaclab.sensors.camera.CameraData` instance and iterates output types internally. + Custom renderer implementations must replace ``write_output(render_data, output_name, output_data)`` + with ``read_output(render_data, camera_data)``. + +Deprecated +^^^^^^^^^^ + +* :class:`~isaaclab.sensors.camera.TiledCamera` is deprecated. Use + :class:`~isaaclab.sensors.camera.Camera` directly — it now supports all renderer backends. +* :class:`~isaaclab.sensors.camera.TiledCameraCfg` is deprecated. Use + :class:`~isaaclab.sensors.camera.CameraCfg` directly. + +Removed +^^^^^^^ + +* Removed :attr:`~isaaclab.sensors.camera.Camera.render_product_paths`. Render products are + now managed internally by the renderer backend and are not part of the public API. + + +4.5.33 (2026-04-13) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :class:`~isaaclab.sensors.Pva` (Pose Velocity Acceleration) sensor, + renamed from the former ``Imu`` to better reflect its full output: pose, + velocity, and acceleration. +* Added :class:`~isaaclab.sensors.Imu` sensor that models a real inertial + measurement unit, providing only angular velocity (gyroscope) and linear + acceleration (accelerometer) in the sensor's body frame. +* Added :func:`~isaaclab.envs.mdp.observations.pva_orientation` and + :func:`~isaaclab.envs.mdp.observations.pva_projected_gravity` observation + functions for the PVA sensor. + +Changed +^^^^^^^ + +* Changed ``isaaclab.sensors.Imu`` to refer to a new lightweight IMU sensor + that only provides angular velocity and linear acceleration. The old + ``Imu``, ``ImuCfg``, ``ImuData``, ``BaseImu``, and ``BaseImuData`` names + now refer to this new sensor. For the original full-featured sensor, use + :class:`~isaaclab.sensors.Pva`, :class:`~isaaclab.sensors.PvaCfg`, etc. + +Removed +^^^^^^^ + +* Removed ``gravity_bias`` configuration parameter from + :class:`~isaaclab.sensors.PvaCfg`. The PVA sensor now always reports raw + kinematic acceleration without gravity contribution. +* Removed ``gravity_bias`` and ``visualizer_cfg`` configuration parameters from + :class:`~isaaclab.sensors.ImuCfg`. The IMU sensor now unconditionally includes + gravity in its accelerometer readings, matching real hardware behavior. The + gravity vector is queried from the simulation automatically. +* Removed ``imu_orientation`` and ``imu_projected_gravity`` observation + functions. Use :func:`~isaaclab.envs.mdp.observations.pva_orientation` and + :func:`~isaaclab.envs.mdp.observations.pva_projected_gravity` instead. + + +4.5.32 (2026-04-13) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed :class:`~isaaclab.envs.mdp.events.randomize_actuator_gains` producing zero + stiffness and damping for explicit actuators. The default gains were read from + ``asset.data.joint_stiffness``, which is zeroed out at the sim level for explicit + actuator models. The defaults are now patched with the actual actuator PD gains. + + +4.5.31 (2026-04-13) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :class:`~isaaclab.envs.mdp.randomize_rigid_body_inertia` event term for + randomizing body inertia tensors independently of mass. Supports diagonal-only + (Ixx, Iyy, Izz) and full 3x3 modes. + +Changed +^^^^^^^ + +* Split :class:`~isaaclab.envs.mdp.randomize_rigid_body_material` into + backend-specific implementations. PhysX uses bucket-based 3-tuple materials via the + tensor API; Newton samples friction and restitution continuously per shape via + view-level attribute bindings. +* Converted ``randomize_rigid_body_com`` from a plain function to a + :class:`~isaaclab.managers.ManagerTermBase` class with repeatable randomization + from cached defaults. Newton passes position-only (vec3); PhysX passes full pose + (pos + quat). +* Converted ``randomize_rigid_body_collider_offsets`` from a plain function to a + :class:`~isaaclab.managers.ManagerTermBase` class with backend-specific + implementations. PhysX uses rest/contact offsets directly; Newton maps them to + ``shape_margin`` and ``shape_gap``. + + +4.5.30 (2026-04-13) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :func:`~isaaclab.utils.warp.math_ops.transform_to_vec_quat` utility for + zero-copy splitting of ``wp.transformf`` arrays into ``vec3f`` and ``quatf`` views. + + +4.5.29 (2026-04-10) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added flag to toggle dataset compression in RecorderManager and dataset file handler. + +Changed +^^^^^^^ + +* Changed RecorderManager to clone value tensors before adding to episode data, removing multiple clones in ``episodes.add()`` and replacing with a single clone. + + +4.5.28 (2026-04-10) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :meth:`~isaaclab.physics.PhysicsManager.wait_for_playing` hook and + integrated it into :meth:`~isaaclab.sim.SimulationContext.step` so the + training loop blocks while the Kit GUI timeline is paused. + + +4.5.27 (2026-04-08) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + + +* Added :class:`~isaaclab.sim.views.BaseXformPrimView` abstract base class that defines + the common interface for backend-specific ``XformPrimView`` implementations. +* Added :class:`~isaaclab.sim.views.XformPrimView` factory to instantiate the correct + backend-specific ``XformPrimView`` based on the active simulation backend. + +Changed +^^^^^^^ + +* Refactored :class:`~isaaclab.sim.views.XformPrimView` to delegate backend-specific + logic to :class:`~isaaclab_physx.sim.views.FabricXformPrimView` and + :class:`~isaaclab_newton.sim.views.NewtonSiteXformPrimView`. The public API is + unchanged; use :class:`~isaaclab.sim.views.XformPrimView` for backend-aware + instantiation. + +* Added release version to + :class:`~isaaclab.test.benchmark.recorders.VersionInfoRecorder` output. + + +4.5.26 (2026-04-08) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Changed ``SummaryMetrics`` backend to + dynamically render unknown benchmark phases. Previously only hard-coded phase + names (``startup``, ``runtime``, ``train``, ``frametime``) were printed in the + summary report; any other phases were silently dropped. Unknown phases now + render their ``SingleMeasurement`` and ``StatisticalMeasurement`` entries + automatically. + + 4.5.25 (2026-04-01) ~~~~~~~~~~~~~~~~~~~ diff --git a/source/isaaclab/isaaclab/__init__.py b/source/isaaclab/isaaclab/__init__.py index c3e1b9450b7a..d547b628372e 100644 --- a/source/isaaclab/isaaclab/__init__.py +++ b/source/isaaclab/isaaclab/__init__.py @@ -6,6 +6,79 @@ """Package containing the core framework.""" import os +import sys + + +def _deprioritize_prebundle_paths(): + """Move Isaac Sim ``pip_prebundle`` and known conflicting extension directories to the end of ``sys.path``. + + Isaac Sim's ``setup_python_env.sh`` injects ``pip_prebundle`` directories + onto ``PYTHONPATH``. These contain older copies of packages like torch, + warp, and nvidia-cudnn that shadow the versions installed by Isaac Lab, + causing CUDA runtime errors. + + Additionally, certain Isaac Sim kit extensions (such as ``omni.warp.core``) + bundle their own copies of Python packages that conflict with pip-installed + versions. When loaded by the extension system these paths can appear on + ``sys.path`` before ``site-packages``, leading to version mismatches. + + Rather than removing these paths entirely (which would break packages like + ``sympy`` that only exist in the prebundle), this function moves them to + the **end** of ``sys.path`` so that pip-installed packages in + ``site-packages`` take priority. + + The ``PYTHONPATH`` environment variable is also rewritten so that child + processes inherit the corrected ordering. + """ + + # Extension directory fragments that are known to ship Python packages + # which conflict with Isaac Lab's pip-installed versions. + _CONFLICTING_EXT_FRAGMENTS = ( + "omni.warp.core", + "omni.isaac.ml_archive", + "omni.isaac.core_archive", + "omni.kit.pip_archive", + "isaacsim.pip.newton", + ) + + def _should_demote(path: str) -> bool: + norm = path.replace("\\", "/").lower() + if "pip_prebundle" in norm: + return True + for frag in _CONFLICTING_EXT_FRAGMENTS: + if frag.lower() in norm: + return True + return False + + # Partition: keep non-conflicting in place, collect conflicting. + clean = [] + demoted = [] + for p in sys.path: + if _should_demote(p): + demoted.append(p) + else: + clean.append(p) + + if not demoted: + return + + # Rebuild sys.path: originals first, then demoted at the very end. + sys.path[:] = clean + demoted + + # Rewrite PYTHONPATH with the same ordering for subprocesses. + if "PYTHONPATH" in os.environ: + parts = os.environ["PYTHONPATH"].split(os.pathsep) + env_clean = [] + env_demoted = [] + for p in parts: + if _should_demote(p): + env_demoted.append(p) + else: + env_clean.append(p) + os.environ["PYTHONPATH"] = os.pathsep.join(env_clean + env_demoted) + + +_deprioritize_prebundle_paths() # Conveniences to other module directories via relative paths. ISAACLAB_EXT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), "../")) diff --git a/source/isaaclab/isaaclab/app/app_launcher.py b/source/isaaclab/isaaclab/app/app_launcher.py index df6f7cb79e18..513757e0808b 100644 --- a/source/isaaclab/isaaclab/app/app_launcher.py +++ b/source/isaaclab/isaaclab/app/app_launcher.py @@ -49,57 +49,6 @@ def __call__(self, parser, namespace, values, option_string=None): setattr(namespace, f"{self.dest}_explicit", True) -def _parse_visualizer_csv(value: str) -> list[str]: - """Parse visualizer list from a single comma-delimited CLI token.""" - valid = {"kit", "newton", "rerun", "viser", "none"} - token = (value or "").strip() - if not token: - raise argparse.ArgumentTypeError( - "Invalid --visualizer value: empty string. Use a comma-separated list, e.g. --viz kit,newton." - ) - if " " in token: - raise argparse.ArgumentTypeError( - "Invalid --visualizer value: spaces are not allowed. " - "Use a comma-separated list without spaces, e.g. --viz kit,newton,rerun,viser." - ) - - names = [item.strip().lower() for item in token.split(",")] - if any(not name for name in names): - raise argparse.ArgumentTypeError( - "Invalid --visualizer value: empty visualizer entry detected. " - "Use a comma-separated list without empty items." - ) - invalid = [name for name in names if name not in valid] - if invalid: - raise argparse.ArgumentTypeError( - f"Invalid --visualizer value(s): {', '.join(invalid)}. Valid options: {', '.join(sorted(valid))}." - ) - # De-duplicate while preserving order. - return list(dict.fromkeys(names)) - - -def _normalize_visualizer_intent(intent: Any) -> tuple[bool, bool]: - """Normalize and validate upstream config visualizer intent payload. - - The expected schema is: - ``{"has_any_visualizers": bool, "has_kit_visualizer": bool}``. - """ - if intent is None: - return False, False - if not isinstance(intent, dict): - raise ValueError("Invalid value for `visualizer_intent`: expected dict or None.") - - has_any = intent.get("has_any_visualizers", False) - has_kit = intent.get("has_kit_visualizer", False) - if not isinstance(has_any, bool) or not isinstance(has_kit, bool): - raise ValueError( - "Invalid `visualizer_intent` values: expected booleans for `has_any_visualizers` and `has_kit_visualizer`." - ) - if has_kit and not has_any: - raise ValueError("Invalid `visualizer_intent`: `has_kit_visualizer=True` requires `has_any_visualizers=True`.") - return has_any, has_kit - - class ExplicitTrueAction(argparse.Action): """Custom action to track explicit use of boolean flags.""" @@ -133,6 +82,96 @@ class AppLauncher: """ + @staticmethod + def sync_visualizer_cli_settings_to_carb(launcher_args: dict) -> None: + """Write visualizer CLI selection and ``--max_visible_envs`` to carb settings. + + Callers may set ``visualizer_explicit`` / ``visualizer_disable_all`` when those values + were resolved elsewhere (e.g. :class:`AppLauncher` strips flags from *launcher_args*). + Otherwise ``disable_all`` is inferred from ``"none"`` in ``visualizer``. + + Also used when Kit is skipped (see :mod:`isaaclab_tasks.utils.sim_launcher`). + """ + visualizers = launcher_args.get("visualizer") + + if "max_visible_envs" in launcher_args: + v = launcher_args["max_visible_envs"] + if v is not None and int(v) < 0: + raise ValueError(f"Invalid value for --max_visible_envs: {v}. Expected non-negative int.") + + cli_explicit = bool(launcher_args.get("visualizer_explicit", False)) + if "visualizer_disable_all" in launcher_args: + cli_disable_all = bool(launcher_args["visualizer_disable_all"]) + else: + cli_disable_all = bool(cli_explicit) and visualizers is not None and "none" in visualizers + + with contextlib.suppress(Exception): + visualizer_str = " ".join(visualizers) if visualizers else "" + settings = get_settings_manager() + settings.set_string("/isaaclab/visualizer/types", visualizer_str) + settings.set_bool("/isaaclab/visualizer/explicit", cli_explicit) + settings.set_bool("/isaaclab/visualizer/disable_all", cli_disable_all) + + # Sentinel: ``-1`` means ``--max_visible_envs`` was not passed (see ``SimulationContext``). + if "max_visible_envs" in launcher_args: + settings.set_int("/isaaclab/visualizer/max_visible_envs", int(launcher_args["max_visible_envs"])) + else: + settings.set_int("/isaaclab/visualizer/max_visible_envs", -1) + + @staticmethod + def _parse_visualizer_csv(value: str) -> list[str]: + """Parse visualizer list from a single comma-delimited CLI token.""" + valid = {"kit", "newton", "rerun", "viser", "none"} + token = (value or "").strip() + if not token: + raise argparse.ArgumentTypeError( + "Invalid --visualizer value: empty string. Use a comma-separated list, e.g. --viz kit,newton." + ) + if " " in token: + raise argparse.ArgumentTypeError( + "Invalid --visualizer value: spaces are not allowed. " + "Use a comma-separated list without spaces, e.g. --viz kit,newton,rerun,viser." + ) + + names = [item.strip().lower() for item in token.split(",")] + if any(not name for name in names): + raise argparse.ArgumentTypeError( + "Invalid --visualizer value: empty visualizer entry detected. " + "Use a comma-separated list without empty items." + ) + invalid = [name for name in names if name not in valid] + if invalid: + raise argparse.ArgumentTypeError( + f"Invalid --visualizer value(s): {', '.join(invalid)}. Valid options: {', '.join(sorted(valid))}." + ) + # De-duplicate while preserving order. + return list(dict.fromkeys(names)) + + @staticmethod + def _normalize_visualizer_intent(intent: Any) -> tuple[bool, bool]: + """Normalize and validate upstream config visualizer intent payload. + + The expected schema is: + ``{"has_any_visualizers": bool, "has_kit_visualizer": bool}``. + """ + if intent is None: + return False, False + if not isinstance(intent, dict): + raise ValueError("Invalid value for `visualizer_intent`: expected dict or None.") + + has_any = intent.get("has_any_visualizers", False) + has_kit = intent.get("has_kit_visualizer", False) + if not isinstance(has_any, bool) or not isinstance(has_kit, bool): + raise ValueError( + "Invalid `visualizer_intent` values: expected booleans for `has_any_visualizers` and " + "`has_kit_visualizer`." + ) + if has_kit and not has_any: + raise ValueError( + "Invalid `visualizer_intent`: `has_kit_visualizer=True` requires `has_any_visualizers=True`." + ) + return has_any, has_kit + def __init__(self, launcher_args: argparse.Namespace | dict | None = None, **kwargs): """Create a `SimulationApp`_ instance based on the input settings. @@ -188,10 +227,11 @@ def __init__(self, launcher_args: argparse.Namespace | dict | None = None, **kwa self._livestream: Literal[0, 1, 2] # 0: Disabled, 1: WebRTC public, 2: WebRTC private self._offscreen_render: bool # 0: Disabled, 1: Enabled self._sim_experience_file: str # Experience file to load - self._visualizer_max_worlds: int | None # Optional max worlds override for Newton-based visualizers + self._video_enabled: bool # Whether --video recording is enabled # Exposed to train scripts self.device_id: int # device ID for GPU simulation (defaults to 0) + self.device: str # resolved device string (e.g. "cuda:0" or "cpu") self.local_rank: int # local rank of GPUs in the current node self.global_rank: int # global rank for multi-node training @@ -202,6 +242,15 @@ def __init__(self, launcher_args: argparse.Namespace | dict | None = None, **kwa self._create_app() # Load IsaacSim extensions self._load_extensions() + + # Re-run path sanitization. Kit and its extensions may have inserted + # additional ``pip_prebundle`` or conflicting extension directories onto + # ``sys.path`` during startup. A second pass ensures pip-installed + # packages still take priority over bundled copies. + from isaaclab import _deprioritize_prebundle_paths + + _deprioritize_prebundle_paths() + # Hide the stop button in the toolbar self._hide_stop_button() # Set settings from the given rendering mode @@ -329,10 +378,9 @@ def add_app_launcher_args(parser: argparse.ArgumentParser) -> None: - Multiple visualizers can be specified as a comma-delimited list: ``--viz rerun,newton,viser``. - * ``visualizer_max_worlds`` (int | None): Optional global override for the maximum number of worlds - rendered in Newton-based visualizers (newton, rerun, viser). If omitted, each visualizer uses its - config default. - + * ``max_visible_envs`` (int | None): Optional global override for partial visualization by capping + how many environments are shown in the visualizers. + More partial visualization configuration fields are available in the ``VisualizerCfg`` class. .. _`WebRTC`: https://docs.isaacsim.omniverse.nvidia.com/latest/installation/manual_livestream_clients.html#isaac-sim-short-webrtc-streaming-client @@ -413,7 +461,7 @@ def add_app_launcher_args(parser: argparse.ArgumentParser) -> None: arg_group.add_argument( "--visualizer", "--viz", - type=_parse_visualizer_csv, + type=AppLauncher._parse_visualizer_csv, action=ExplicitAction, default=None, help="Visualizer backends to enable as CSV (e.g., kit,newton,rerun,viser).", @@ -484,13 +532,10 @@ def add_app_launcher_args(parser: argparse.ArgumentParser) -> None: ), ) arg_group.add_argument( - "--visualizer_max_worlds", + "--max_visible_envs", type=int, - default=AppLauncher._APPLAUNCHER_CFG_INFO["visualizer_max_worlds"][1], - help=( - "Optional global max worlds override for Newton-based visualizers (newton/rerun/viser). " - "If omitted, visualizer config defaults are used." - ), + default=argparse.SUPPRESS, + help=("When set, caps the nums of envs shown in the launched visualizers."), ) # special flag for backwards compatibility @@ -512,7 +557,7 @@ def add_app_launcher_args(parser: argparse.ArgumentParser) -> None: "device": ([str], "cuda:0"), "experience": ([str], ""), "rendering_mode": ([str], "balanced"), - "visualizer_max_worlds": ([int, type(None)], None), + "max_visible_envs": ([int, type(None)], None), } """A dictionary of arguments added manually by the :meth:`AppLauncher.add_app_launcher_args` method. @@ -782,7 +827,9 @@ def _resolve_headless_settings(self, launcher_args: dict, livestream_arg: int, l def _resolve_visualizer_settings(self, launcher_args: dict) -> None: """Resolve visualizer CLI semantics and normalize selection.""" raw_visualizers = launcher_args.get("visualizer") - cfg_has_any, cfg_has_kit = _normalize_visualizer_intent(launcher_args.pop("visualizer_intent", None)) + cfg_has_any, cfg_has_kit = AppLauncher._normalize_visualizer_intent( + launcher_args.pop("visualizer_intent", None) + ) self._cfg_has_any_visualizers = cfg_has_any self._cfg_has_kit_visualizer = cfg_has_kit visualizer_explicit = bool(launcher_args.pop("visualizer_explicit", False)) @@ -792,7 +839,7 @@ def _resolve_visualizer_settings(self, launcher_args: dict) -> None: visualizer_types: list[str] = [] if raw_visualizers is not None: if isinstance(raw_visualizers, str): - visualizer_types = _parse_visualizer_csv(raw_visualizers) + visualizer_types = AppLauncher._parse_visualizer_csv(raw_visualizers) else: visualizer_types = [str(v).strip().lower() for v in raw_visualizers if str(v).strip()] @@ -858,12 +905,13 @@ def _resolve_xr_settings(self, launcher_args: dict): def _resolve_viewport_settings(self, launcher_args: dict): """Resolve viewport related settings.""" + self._video_enabled = bool(launcher_args.get("video", False)) # Check if we can disable the viewport to improve performance # This should only happen if we are running headless and do not require livestreaming or video recording # This is different from offscreen_render because this only affects the default viewport and # not other render-products in the scene self._render_viewport = True - if self._headless and not self._livestream and not launcher_args.get("video", False): + if self._headless and not self._livestream and not self._video_enabled: self._render_viewport = False # hide_ui flag @@ -906,7 +954,20 @@ def _resolve_device_settings(self, launcher_args: dict): # global rank (GPU id) in multi-gpu multi-node mode self.global_rank = int(os.getenv("RANK", "0")) + int(os.getenv("JAX_RANK", "0")) - self.device_id = self.local_rank + # When CUDA_VISIBLE_DEVICES restricts each process to a single GPU, + # local_rank may exceed the visible device count. Fall back to cuda:0 + # so the process uses the one GPU it can see. + # We compare local_rank against device_count (not WORLD_SIZE) so that + # multi-node setups work correctly: WORLD_SIZE is global across all + # nodes, but device_count is local. + import torch + + num_visible_gpus = torch.cuda.device_count() + if self.local_rank < num_visible_gpus: + self.device_id = self.local_rank + else: + self.device_id = 0 + device = "cuda:" + str(self.device_id) launcher_args["multi_gpu"] = False # limit CPU threads to minimize thread context switching @@ -924,6 +985,17 @@ def _resolve_device_settings(self, launcher_args: dict): launcher_args["physics_gpu"] = self.device_id launcher_args["active_gpu"] = self.device_id + # Set the current CUDA device early so that physics backends (e.g. Newton/Warp) + # that allocate on the "current" device during initialization get the correct GPU. + # Without this, all ranks may default to cuda:0 for early allocations. + if "cuda" in device: + import torch + + torch.cuda.set_device(self.device_id) + + # Store the resolved device string for downstream consumers (e.g. sim_launcher) + self.device = device + logger.info("Using device: %s", device) def _resolve_experience_file(self, launcher_args: dict): @@ -1085,6 +1157,8 @@ def _load_extensions(self): # (no Kit GUI) the AR profile must be enabled programmatically so that # the OpenXR session starts without user interaction settings.set_bool("/isaaclab/xr/auto_start", self._headless and self._xr) + # set setting to indicate video recording mode + settings.set_bool("/isaaclab/video/enabled", self._video_enabled) # set setting to indicate no RTX sensors are used (set to True when RTX sensor is created) settings.set_bool("/isaaclab/render/rtx_sensors", False) @@ -1148,28 +1222,14 @@ def _set_animation_recording_settings(self, launcher_args: dict) -> None: settings.set_float("/isaaclab/anim_recording/stop_time", stop_time) def _set_visualizer_settings(self, launcher_args: dict) -> None: - """Store visualizer selection and max-worlds override in settings.""" - visualizers = launcher_args.get("visualizer") - visualizer_max_worlds = launcher_args.get("visualizer_max_worlds") - - if visualizer_max_worlds is not None and visualizer_max_worlds < 0: - raise ValueError( - f"Invalid value for --visualizer_max_worlds: {visualizer_max_worlds}. Expected non-negative int." - ) - - with contextlib.suppress(Exception): - visualizer_str = " ".join(visualizers) if visualizers else "" - settings = get_settings_manager() - cli_visualizer_explicit = getattr(self, "_cli_visualizer_explicit", False) - cli_visualizer_disable_all = getattr(self, "_cli_visualizer_disable_all", False) - settings.set_string("/isaaclab/visualizer/types", visualizer_str) - settings.set_bool("/isaaclab/visualizer/explicit", cli_visualizer_explicit) - settings.set_bool("/isaaclab/visualizer/disable_all", cli_visualizer_disable_all) - # Store as int setting where -1 means "use per-visualizer defaults". - if visualizer_max_worlds is None: - settings.set_int("/isaaclab/visualizer/max_worlds", -1) - else: - settings.set_int("/isaaclab/visualizer/max_worlds", int(visualizer_max_worlds)) + """Persist visualizer CLI flags and ``max_visible_envs`` override for :class:`SimulationContext`.""" + AppLauncher.sync_visualizer_cli_settings_to_carb( + { + **launcher_args, + "visualizer_explicit": getattr(self, "_cli_visualizer_explicit", False), + "visualizer_disable_all": getattr(self, "_cli_visualizer_disable_all", False), + } + ) def _interrupt_signal_handle_callback(self, signal, frame): """Handle the interrupt signal from the keyboard.""" diff --git a/source/isaaclab/isaaclab/assets/articulation/base_articulation.py b/source/isaaclab/isaaclab/assets/articulation/base_articulation.py index 25ca2c4ceaf0..3cd9e33376db 100644 --- a/source/isaaclab/isaaclab/assets/articulation/base_articulation.py +++ b/source/isaaclab/isaaclab/assets/articulation/base_articulation.py @@ -16,6 +16,7 @@ import torch import warp as wp +from ...utils.leapp.leapp_semantics import OutputKindEnum, joint_names_resolver, leapp_tensor_semantics from ..asset_base import AssetBase if TYPE_CHECKING: @@ -1266,6 +1267,7 @@ def set_inertias_mask( raise NotImplementedError() @abstractmethod + @leapp_tensor_semantics(kind=OutputKindEnum.JOINT_POSITION, element_names_resolver=joint_names_resolver) def set_joint_position_target_index( self, *, @@ -1293,6 +1295,7 @@ def set_joint_position_target_index( raise NotImplementedError() @abstractmethod + @leapp_tensor_semantics(kind=OutputKindEnum.JOINT_POSITION, element_names_resolver=joint_names_resolver) def set_joint_position_target_mask( self, *, @@ -1320,6 +1323,7 @@ def set_joint_position_target_mask( raise NotImplementedError() @abstractmethod + @leapp_tensor_semantics(kind=OutputKindEnum.JOINT_VELOCITY, element_names_resolver=joint_names_resolver) def set_joint_velocity_target_index( self, *, @@ -1347,6 +1351,7 @@ def set_joint_velocity_target_index( raise NotImplementedError() @abstractmethod + @leapp_tensor_semantics(kind=OutputKindEnum.JOINT_VELOCITY, element_names_resolver=joint_names_resolver) def set_joint_velocity_target_mask( self, *, @@ -1374,6 +1379,7 @@ def set_joint_velocity_target_mask( raise NotImplementedError() @abstractmethod + @leapp_tensor_semantics(kind=OutputKindEnum.JOINT_EFFORT, element_names_resolver=joint_names_resolver) def set_joint_effort_target_index( self, *, @@ -1401,6 +1407,7 @@ def set_joint_effort_target_index( raise NotImplementedError() @abstractmethod + @leapp_tensor_semantics(kind=OutputKindEnum.JOINT_EFFORT, element_names_resolver=joint_names_resolver) def set_joint_effort_target_mask( self, *, @@ -2553,14 +2560,17 @@ def set_external_force_and_torque( env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, is_global: bool = False, ) -> None: - """Deprecated, same as :meth:`permanent_wrench_composer.set_forces_and_torques`.""" + """Deprecated. Resets target environments, then adds forces and torques via the permanent wrench composer.""" warnings.warn( - "The function 'set_external_force_and_torque' will be deprecated in a future release. Please" - " use 'permanent_wrench_composer.set_forces_and_torques' instead.", + "The function 'set_external_force_and_torque' is deprecated. Please use" + " 'permanent_wrench_composer.reset' followed by 'permanent_wrench_composer.add_forces_and_torques'" + " instead.", DeprecationWarning, stacklevel=2, ) - self.permanent_wrench_composer.set_forces_and_torques( + # Reset only target env_ids then add (not set which clears all envs globally) + self.permanent_wrench_composer.reset(env_ids=env_ids) + self.permanent_wrench_composer.add_forces_and_torques( forces, torques, positions=positions, body_ids=body_ids, env_ids=env_ids, is_global=is_global ) diff --git a/source/isaaclab/isaaclab/assets/articulation/base_articulation_data.py b/source/isaaclab/isaaclab/assets/articulation/base_articulation_data.py index 61ee8f28e7a9..1a2dc5f1b278 100644 --- a/source/isaaclab/isaaclab/assets/articulation/base_articulation_data.py +++ b/source/isaaclab/isaaclab/assets/articulation/base_articulation_data.py @@ -8,6 +8,21 @@ import warp as wp +from isaaclab.utils.leapp import ( + POSE6_ELEMENT_NAMES, + POSE7_ELEMENT_NAMES, + QUAT_XYZW_ELEMENT_NAMES, + XYZ_ELEMENT_NAMES, + InputKindEnum, + body_pose6_resolver, + body_pose_resolver, + body_quat_resolver, + body_xyz_resolver, + joint_names_resolver, + leapp_tensor_semantics, +) +from isaaclab.utils.warp import ProxyArray + class BaseArticulationData(ABC): """Data container for an articulation. @@ -45,16 +60,16 @@ def update(self, dt: float) -> None: # Names. ## - body_names: list[str] = None + body_names: list[str] | None = None """Body names in the order parsed by the simulation view.""" - joint_names: list[str] = None + joint_names: list[str] | None = None """Joint names in the order parsed by the simulation view.""" - fixed_tendon_names: list[str] = None + fixed_tendon_names: list[str] | None = None """Fixed tendon names in the order parsed by the simulation view.""" - spatial_tendon_names: list[str] = None + spatial_tendon_names: list[str] | None = None """Spatial tendon names in the order parsed by the simulation view.""" ## @@ -63,7 +78,8 @@ def update(self, dt: float) -> None: @property @abstractmethod - def default_root_pose(self) -> wp.array: + @leapp_tensor_semantics(const=True) + def default_root_pose(self) -> ProxyArray: """Default root pose ``[pos, quat]`` in the local environment frame. The position and quaternion are of the articulation root's actor frame. Shape is (num_instances), @@ -73,7 +89,8 @@ def default_root_pose(self) -> wp.array: @property @abstractmethod - def default_root_vel(self) -> wp.array: + @leapp_tensor_semantics(const=True) + def default_root_vel(self) -> ProxyArray: """Default root velocity ``[lin_vel, ang_vel]`` in the local environment frame. The linear and angular velocities are of the articulation root's center of mass frame. @@ -83,13 +100,15 @@ def default_root_vel(self) -> wp.array: @property @abstractmethod - def default_root_state(self) -> wp.array: + @leapp_tensor_semantics(const=True) + def default_root_state(self) -> ProxyArray: """Deprecated, same as :attr:`default_root_pose` and :attr:`default_root_vel`.""" raise NotImplementedError @property @abstractmethod - def default_joint_pos(self) -> wp.array: + @leapp_tensor_semantics(const=True) + def default_joint_pos(self) -> ProxyArray: """Default joint positions of all joints. Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to (num_instances, num_joints). @@ -100,7 +119,8 @@ def default_joint_pos(self) -> wp.array: @property @abstractmethod - def default_joint_vel(self) -> wp.array: + @leapp_tensor_semantics(const=True) + def default_joint_vel(self) -> ProxyArray: """Default joint velocities of all joints. Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to (num_instances, num_joints). @@ -115,7 +135,8 @@ def default_joint_vel(self) -> wp.array: @property @abstractmethod - def joint_pos_target(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.COMMAND_JOINT_POSITION) + def joint_pos_target(self) -> ProxyArray: """Joint position targets commanded by the user. Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to (num_instances, num_joints). @@ -128,7 +149,8 @@ def joint_pos_target(self) -> wp.array: @property @abstractmethod - def joint_vel_target(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.COMMAND_JOINT_VELOCITY) + def joint_vel_target(self) -> ProxyArray: """Joint velocity targets commanded by the user. Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to (num_instances, num_joints). @@ -141,7 +163,8 @@ def joint_vel_target(self) -> wp.array: @property @abstractmethod - def joint_effort_target(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.COMMAND_JOINT_TORQUES) + def joint_effort_target(self) -> ProxyArray: """Joint effort targets commanded by the user. Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to (num_instances, num_joints). @@ -158,7 +181,8 @@ def joint_effort_target(self) -> wp.array: @property @abstractmethod - def computed_torque(self) -> wp.array: + @leapp_tensor_semantics(kind="state/joint/computed_torque") + def computed_torque(self) -> ProxyArray: """Joint torques computed from the actuator model (before clipping). Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to (num_instances, num_joints). @@ -171,7 +195,8 @@ def computed_torque(self) -> wp.array: @property @abstractmethod - def applied_torque(self) -> wp.array: + @leapp_tensor_semantics(kind="state/joint/applied_torque") + def applied_torque(self) -> ProxyArray: """Joint torques applied from the actuator model (after clipping). Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to (num_instances, num_joints). @@ -187,7 +212,8 @@ def applied_torque(self) -> wp.array: @property @abstractmethod - def joint_stiffness(self) -> wp.array: + @leapp_tensor_semantics(const=True) + def joint_stiffness(self) -> ProxyArray: """Joint stiffness provided to the simulation. Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to (num_instances, num_joints). @@ -198,7 +224,8 @@ def joint_stiffness(self) -> wp.array: @property @abstractmethod - def joint_damping(self) -> wp.array: + @leapp_tensor_semantics(const=True) + def joint_damping(self) -> ProxyArray: """Joint damping provided to the simulation. Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to (num_instances, num_joints). @@ -209,7 +236,8 @@ def joint_damping(self) -> wp.array: @property @abstractmethod - def joint_armature(self) -> wp.array: + @leapp_tensor_semantics(const=True) + def joint_armature(self) -> ProxyArray: """Joint armature provided to the simulation. Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to (num_instances, num_joints). @@ -218,7 +246,8 @@ def joint_armature(self) -> wp.array: @property @abstractmethod - def joint_friction_coeff(self) -> wp.array: + @leapp_tensor_semantics(const=True) + def joint_friction_coeff(self) -> ProxyArray: """Joint static friction coefficient provided to the simulation. Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to (num_instances, num_joints). @@ -227,7 +256,8 @@ def joint_friction_coeff(self) -> wp.array: @property @abstractmethod - def joint_pos_limits(self) -> wp.array: + @leapp_tensor_semantics(const=True) + def joint_pos_limits(self) -> ProxyArray: """Joint position limits provided to the simulation. Shape is (num_instances, num_joints, 2), dtype = wp.vec2f. In torch this resolves to @@ -239,7 +269,8 @@ def joint_pos_limits(self) -> wp.array: @property @abstractmethod - def joint_vel_limits(self) -> wp.array: + @leapp_tensor_semantics(const=True) + def joint_vel_limits(self) -> ProxyArray: """Joint maximum velocity provided to the simulation. Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to (num_instances, num_joints). @@ -248,7 +279,8 @@ def joint_vel_limits(self) -> wp.array: @property @abstractmethod - def joint_effort_limits(self) -> wp.array: + @leapp_tensor_semantics(const=True) + def joint_effort_limits(self) -> ProxyArray: """Joint maximum effort provided to the simulation. Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to (num_instances, num_joints). @@ -261,7 +293,8 @@ def joint_effort_limits(self) -> wp.array: @property @abstractmethod - def soft_joint_pos_limits(self) -> wp.array: + @leapp_tensor_semantics(const=True) + def soft_joint_pos_limits(self) -> ProxyArray: r"""Soft joint positions limits for all joints. Shape is (num_instances, num_joints), dtype = wp.vec2f. In torch this resolves to @@ -286,7 +319,8 @@ def soft_joint_pos_limits(self) -> wp.array: @property @abstractmethod - def soft_joint_vel_limits(self) -> wp.array: + @leapp_tensor_semantics(const=True) + def soft_joint_vel_limits(self) -> ProxyArray: """Soft joint velocity limits for all joints. Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to (num_instances, num_joints). @@ -298,7 +332,8 @@ def soft_joint_vel_limits(self) -> wp.array: @property @abstractmethod - def gear_ratio(self) -> wp.array: + @leapp_tensor_semantics(const=True) + def gear_ratio(self) -> ProxyArray: """Gear ratio for relating motor torques to applied Joint torques. Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to (num_instances, num_joints). @@ -311,7 +346,8 @@ def gear_ratio(self) -> wp.array: @property @abstractmethod - def fixed_tendon_stiffness(self) -> wp.array: + @leapp_tensor_semantics(const=True) + def fixed_tendon_stiffness(self) -> ProxyArray: """Fixed tendon stiffness provided to the simulation. Shape is (num_instances, num_fixed_tendons), dtype = wp.float32. In torch this resolves to @@ -321,7 +357,8 @@ def fixed_tendon_stiffness(self) -> wp.array: @property @abstractmethod - def fixed_tendon_damping(self) -> wp.array: + @leapp_tensor_semantics(const=True) + def fixed_tendon_damping(self) -> ProxyArray: """Fixed tendon damping provided to the simulation. Shape is (num_instances, num_fixed_tendons), dtype = wp.float32. In torch this resolves to @@ -331,7 +368,8 @@ def fixed_tendon_damping(self) -> wp.array: @property @abstractmethod - def fixed_tendon_limit_stiffness(self) -> wp.array: + @leapp_tensor_semantics(const=True) + def fixed_tendon_limit_stiffness(self) -> ProxyArray: """Fixed tendon limit stiffness provided to the simulation. Shape is (num_instances, num_fixed_tendons), dtype = wp.float32. In torch this resolves to @@ -341,7 +379,8 @@ def fixed_tendon_limit_stiffness(self) -> wp.array: @property @abstractmethod - def fixed_tendon_rest_length(self) -> wp.array: + @leapp_tensor_semantics(const=True) + def fixed_tendon_rest_length(self) -> ProxyArray: """Fixed tendon rest length provided to the simulation. Shape is (num_instances, num_fixed_tendons), dtype = wp.float32. In torch this resolves to @@ -351,7 +390,8 @@ def fixed_tendon_rest_length(self) -> wp.array: @property @abstractmethod - def fixed_tendon_offset(self) -> wp.array: + @leapp_tensor_semantics(const=True) + def fixed_tendon_offset(self) -> ProxyArray: """Fixed tendon offset provided to the simulation. Shape is (num_instances, num_fixed_tendons), dtype = wp.float32. In torch this resolves to @@ -361,7 +401,8 @@ def fixed_tendon_offset(self) -> wp.array: @property @abstractmethod - def fixed_tendon_pos_limits(self) -> wp.array: + @leapp_tensor_semantics(const=True) + def fixed_tendon_pos_limits(self) -> ProxyArray: """Fixed tendon position limits provided to the simulation. Shape is (num_instances, num_fixed_tendons, 2), dtype = wp.vec2f. In torch this resolves to @@ -375,7 +416,8 @@ def fixed_tendon_pos_limits(self) -> wp.array: @property @abstractmethod - def spatial_tendon_stiffness(self) -> wp.array: + @leapp_tensor_semantics(const=True) + def spatial_tendon_stiffness(self) -> ProxyArray: """Spatial tendon stiffness provided to the simulation. Shape is (num_instances, num_spatial_tendons), dtype = wp.float32. In torch this resolves to @@ -385,7 +427,8 @@ def spatial_tendon_stiffness(self) -> wp.array: @property @abstractmethod - def spatial_tendon_damping(self) -> wp.array: + @leapp_tensor_semantics(const=True) + def spatial_tendon_damping(self) -> ProxyArray: """Spatial tendon damping provided to the simulation. Shape is (num_instances, num_spatial_tendons), dtype = wp.float32. In torch this resolves to @@ -395,7 +438,8 @@ def spatial_tendon_damping(self) -> wp.array: @property @abstractmethod - def spatial_tendon_limit_stiffness(self) -> wp.array: + @leapp_tensor_semantics(const=True) + def spatial_tendon_limit_stiffness(self) -> ProxyArray: """Spatial tendon limit stiffness provided to the simulation. Shape is (num_instances, num_spatial_tendons), dtype = wp.float32. In torch this resolves to @@ -405,7 +449,8 @@ def spatial_tendon_limit_stiffness(self) -> wp.array: @property @abstractmethod - def spatial_tendon_offset(self) -> wp.array: + @leapp_tensor_semantics(const=True) + def spatial_tendon_offset(self) -> ProxyArray: """Spatial tendon offset provided to the simulation. Shape is (num_instances, num_spatial_tendons), dtype = wp.float32. In torch this resolves to @@ -419,7 +464,8 @@ def spatial_tendon_offset(self) -> wp.array: @property @abstractmethod - def root_link_pose_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSE, element_names=POSE7_ELEMENT_NAMES) + def root_link_pose_w(self) -> ProxyArray: """Root link pose ``[pos, quat]`` in simulation world frame. Shape is (num_instances,), dtype = wp.transformf. In torch this resolves to (num_instances, 7). @@ -431,7 +477,8 @@ def root_link_pose_w(self) -> wp.array: @property @abstractmethod - def root_link_vel_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_VEL, element_names=POSE6_ELEMENT_NAMES) + def root_link_vel_w(self) -> ProxyArray: """Root link velocity ``[lin_vel, ang_vel]`` in simulation world frame. Shape is (num_instances,), dtype = wp.spatial_vectorf. In torch this resolves to (num_instances, 6). @@ -443,7 +490,8 @@ def root_link_vel_w(self) -> wp.array: @property @abstractmethod - def root_com_pose_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSE, element_names=POSE7_ELEMENT_NAMES) + def root_com_pose_w(self) -> ProxyArray: """Root center of mass pose ``[pos, quat]`` in simulation world frame. Shape is (num_instances,), dtype = wp.transformf. In torch this resolves to (num_instances, 7). @@ -455,7 +503,8 @@ def root_com_pose_w(self) -> wp.array: @property @abstractmethod - def root_com_vel_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_VEL, element_names=POSE6_ELEMENT_NAMES) + def root_com_vel_w(self) -> ProxyArray: """Root center of mass velocity ``[lin_vel, ang_vel]`` in simulation world frame. Shape is (num_instances,), dtype = wp.spatial_vectorf. In torch this resolves to (num_instances, 6). @@ -467,19 +516,22 @@ def root_com_vel_w(self) -> wp.array: @property @abstractmethod - def root_state_w(self) -> wp.array: + @leapp_tensor_semantics(kind="state/body/state") + def root_state_w(self) -> ProxyArray: """Deprecated, same as :attr:`root_link_pose_w` and :attr:`root_com_vel_w`.""" raise NotImplementedError @property @abstractmethod - def root_link_state_w(self) -> wp.array: + @leapp_tensor_semantics(kind="state/body/link_state") + def root_link_state_w(self) -> ProxyArray: """Deprecated, same as :attr:`root_link_pose_w` and :attr:`root_link_vel_w`.""" raise NotImplementedError @property @abstractmethod - def root_com_state_w(self) -> wp.array: + @leapp_tensor_semantics(kind="state/body/com_state") + def root_com_state_w(self) -> ProxyArray: """Deprecated, same as :attr:`root_com_pose_w` and :attr:`root_com_vel_w`.""" raise NotImplementedError @@ -489,7 +541,8 @@ def root_com_state_w(self) -> wp.array: @property @abstractmethod - def body_mass(self) -> wp.array: + @leapp_tensor_semantics(const=True) + def body_mass(self) -> ProxyArray: """Body mass ``wp.float32`` in the world frame. Shape is (num_instances, num_bodies), dtype = wp.float32. In torch this resolves to (num_instances, num_bodies). @@ -498,7 +551,8 @@ def body_mass(self) -> wp.array: @property @abstractmethod - def body_inertia(self) -> wp.array: + @leapp_tensor_semantics(const=True) + def body_inertia(self) -> ProxyArray: """Flattened body inertia in the world frame. Shape is (num_instances, num_bodies, 9), dtype = wp.float32. In torch this resolves to @@ -508,7 +562,8 @@ def body_inertia(self) -> wp.array: @property @abstractmethod - def body_link_pose_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSE, element_names_resolver=body_pose_resolver) + def body_link_pose_w(self) -> ProxyArray: """Body link pose ``[pos, quat]`` in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.transformf. In torch this resolves to @@ -521,7 +576,8 @@ def body_link_pose_w(self) -> wp.array: @property @abstractmethod - def body_link_vel_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_VEL, element_names_resolver=body_pose6_resolver) + def body_link_vel_w(self) -> ProxyArray: """Body link velocity ``[lin_vel, ang_vel]`` in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.spatial_vectorf. In torch this resolves to @@ -534,7 +590,8 @@ def body_link_vel_w(self) -> wp.array: @property @abstractmethod - def body_com_pose_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSE, element_names_resolver=body_pose_resolver) + def body_com_pose_w(self) -> ProxyArray: """Body center of mass pose ``[pos, quat]`` in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.transformf. In torch this resolves to @@ -547,7 +604,8 @@ def body_com_pose_w(self) -> wp.array: @property @abstractmethod - def body_com_vel_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_VEL, element_names_resolver=body_pose6_resolver) + def body_com_vel_w(self) -> ProxyArray: """Body center of mass velocity ``[lin_vel, ang_vel]`` in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.spatial_vectorf. In torch this resolves to @@ -560,25 +618,29 @@ def body_com_vel_w(self) -> wp.array: @property @abstractmethod - def body_state_w(self) -> wp.array: + @leapp_tensor_semantics(kind="state/body/state") + def body_state_w(self) -> ProxyArray: """Deprecated, same as :attr:`body_link_pose_w` and :attr:`body_com_vel_w`.""" raise NotImplementedError @property @abstractmethod - def body_link_state_w(self) -> wp.array: + @leapp_tensor_semantics(kind="state/body/link_state") + def body_link_state_w(self) -> ProxyArray: """Deprecated, same as :attr:`body_link_pose_w` and :attr:`body_link_vel_w`.""" raise NotImplementedError @property @abstractmethod - def body_com_state_w(self) -> wp.array: + @leapp_tensor_semantics(kind="state/body/com_state") + def body_com_state_w(self) -> ProxyArray: """Deprecated, same as :attr:`body_com_pose_w` and :attr:`body_com_vel_w`.""" raise NotImplementedError @property @abstractmethod - def body_com_acc_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ACC, element_names_resolver=body_pose6_resolver) + def body_com_acc_w(self) -> ProxyArray: """Acceleration of all bodies center of mass ``[lin_acc, ang_acc]``. Shape is (num_instances, num_bodies), dtype = wp.spatial_vectorf. In torch this resolves to @@ -590,7 +652,8 @@ def body_com_acc_w(self) -> wp.array: @property @abstractmethod - def body_com_pose_b(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSE, element_names_resolver=body_pose_resolver) + def body_com_pose_b(self) -> ProxyArray: """Center of mass pose ``[pos, quat]`` of all bodies in their respective body's link frames. Shape is (num_instances, num_bodies), dtype = wp.transformf. In torch this resolves to @@ -601,30 +664,14 @@ def body_com_pose_b(self) -> wp.array: """ raise NotImplementedError - @property - @abstractmethod - def body_incoming_joint_wrench_b(self) -> wp.array: - """Joint reaction wrench applied from body parent to child body in parent body frame. - - Shape is (num_instances, num_bodies), dtype = wp.spatial_vectorf. In torch this resolves to - (num_instances, num_bodies, 6). All body reaction wrenches are provided including the root body to the - world of an articulation. - - For more information on joint wrenches, please check the `PhysX documentation`_ and the - underlying `PhysX Tensor API`_. - - .. _PhysX documentation: https://nvidia-omniverse.github.io/PhysX/physx/5.5.1/docs/Articulations.html#link-incoming-joint-force - .. _PhysX Tensor API: https://docs.omniverse.nvidia.com/kit/docs/omni_physics/latest/extensions/runtime/source/omni.physics.tensors/docs/api/python.html#omni.physics.tensors.impl.api.ArticulationView.get_link_incoming_joint_force - """ - raise NotImplementedError - ## # Joint state properties. ## @property @abstractmethod - def joint_pos(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.JOINT_POSITION, element_names_resolver=joint_names_resolver) + def joint_pos(self) -> ProxyArray: """Joint positions of all joints. Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to @@ -634,7 +681,8 @@ def joint_pos(self) -> wp.array: @property @abstractmethod - def joint_vel(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.JOINT_VELOCITY, element_names_resolver=joint_names_resolver) + def joint_vel(self) -> ProxyArray: """Joint velocities of all joints. Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to @@ -644,7 +692,8 @@ def joint_vel(self) -> wp.array: @property @abstractmethod - def joint_acc(self) -> wp.array: + @leapp_tensor_semantics(kind="state/joint/acceleration", element_names_resolver=joint_names_resolver) + def joint_acc(self) -> ProxyArray: """Joint acceleration of all joints. Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to @@ -658,7 +707,8 @@ def joint_acc(self) -> wp.array: @property @abstractmethod - def projected_gravity_b(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.VECTOR3D, element_names=XYZ_ELEMENT_NAMES) + def projected_gravity_b(self) -> ProxyArray: """Projection of the gravity direction on base frame. Shape is (num_instances), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). @@ -667,7 +717,8 @@ def projected_gravity_b(self) -> wp.array: @property @abstractmethod - def heading_w(self) -> wp.array: + @leapp_tensor_semantics(kind="state/body/heading") + def heading_w(self) -> ProxyArray: """Yaw heading of the base frame (in radians). Shape is (num_instances), dtype = wp.float32. In torch this resolves to (num_instances,). @@ -680,7 +731,8 @@ def heading_w(self) -> wp.array: @property @abstractmethod - def root_link_lin_vel_b(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_LINEAR_VELOCITY, element_names=XYZ_ELEMENT_NAMES) + def root_link_lin_vel_b(self) -> ProxyArray: """Root link linear velocity in base frame. Shape is (num_instances), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). @@ -692,7 +744,8 @@ def root_link_lin_vel_b(self) -> wp.array: @property @abstractmethod - def root_link_ang_vel_b(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ANGULAR_VELOCITY, element_names=XYZ_ELEMENT_NAMES) + def root_link_ang_vel_b(self) -> ProxyArray: """Root link angular velocity in base frame. Shape is (num_instances), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). @@ -704,7 +757,8 @@ def root_link_ang_vel_b(self) -> wp.array: @property @abstractmethod - def root_com_lin_vel_b(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_LINEAR_VELOCITY, element_names=XYZ_ELEMENT_NAMES) + def root_com_lin_vel_b(self) -> ProxyArray: """Root center of mass linear velocity in base frame. Shape is (num_instances), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). @@ -716,7 +770,8 @@ def root_com_lin_vel_b(self) -> wp.array: @property @abstractmethod - def root_com_ang_vel_b(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ANGULAR_VELOCITY, element_names=XYZ_ELEMENT_NAMES) + def root_com_ang_vel_b(self) -> ProxyArray: """Root center of mass angular velocity in base frame. Shape is (num_instances), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). @@ -732,7 +787,8 @@ def root_com_ang_vel_b(self) -> wp.array: @property @abstractmethod - def root_link_pos_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSITION, element_names=XYZ_ELEMENT_NAMES) + def root_link_pos_w(self) -> ProxyArray: """Root link position in simulation world frame. Shape is (num_instances), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). @@ -743,7 +799,8 @@ def root_link_pos_w(self) -> wp.array: @property @abstractmethod - def root_link_quat_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ROTATION, element_names=QUAT_XYZW_ELEMENT_NAMES) + def root_link_quat_w(self) -> ProxyArray: """Root link orientation (x, y, z, w) in simulation world frame. Shape is (num_instances), dtype = wp.quatf. In torch this resolves to (num_instances, 4). @@ -754,7 +811,8 @@ def root_link_quat_w(self) -> wp.array: @property @abstractmethod - def root_link_lin_vel_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_LINEAR_VELOCITY, element_names=XYZ_ELEMENT_NAMES) + def root_link_lin_vel_w(self) -> ProxyArray: """Root linear velocity in simulation world frame. Shape is (num_instances), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). @@ -765,7 +823,8 @@ def root_link_lin_vel_w(self) -> wp.array: @property @abstractmethod - def root_link_ang_vel_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ANGULAR_VELOCITY, element_names=XYZ_ELEMENT_NAMES) + def root_link_ang_vel_w(self) -> ProxyArray: """Root link angular velocity in simulation world frame. Shape is (num_instances), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). @@ -776,7 +835,8 @@ def root_link_ang_vel_w(self) -> wp.array: @property @abstractmethod - def root_com_pos_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSITION, element_names=XYZ_ELEMENT_NAMES) + def root_com_pos_w(self) -> ProxyArray: """Root center of mass position in simulation world frame. Shape is (num_instances), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). @@ -787,7 +847,8 @@ def root_com_pos_w(self) -> wp.array: @property @abstractmethod - def root_com_quat_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ROTATION, element_names=QUAT_XYZW_ELEMENT_NAMES) + def root_com_quat_w(self) -> ProxyArray: """Root center of mass orientation (x, y, z, w) in simulation world frame. Shape is (num_instances), dtype = wp.quatf. In torch this resolves to (num_instances, 4). @@ -798,7 +859,8 @@ def root_com_quat_w(self) -> wp.array: @property @abstractmethod - def root_com_lin_vel_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_LINEAR_VELOCITY, element_names=XYZ_ELEMENT_NAMES) + def root_com_lin_vel_w(self) -> ProxyArray: """Root center of mass linear velocity in simulation world frame. Shape is (num_instances), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). @@ -809,7 +871,8 @@ def root_com_lin_vel_w(self) -> wp.array: @property @abstractmethod - def root_com_ang_vel_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ANGULAR_VELOCITY, element_names=XYZ_ELEMENT_NAMES) + def root_com_ang_vel_w(self) -> ProxyArray: """Root center of mass angular velocity in simulation world frame. Shape is (num_instances), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). @@ -820,7 +883,8 @@ def root_com_ang_vel_w(self) -> wp.array: @property @abstractmethod - def body_link_pos_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSITION, element_names_resolver=body_xyz_resolver) + def body_link_pos_w(self) -> ProxyArray: """Positions of all bodies in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to @@ -832,7 +896,8 @@ def body_link_pos_w(self) -> wp.array: @property @abstractmethod - def body_link_quat_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ROTATION, element_names_resolver=body_quat_resolver) + def body_link_quat_w(self) -> ProxyArray: """Orientation (x, y, z, w) of all bodies in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.quatf. In torch this resolves to @@ -844,7 +909,8 @@ def body_link_quat_w(self) -> wp.array: @property @abstractmethod - def body_link_lin_vel_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_LINEAR_VELOCITY, element_names_resolver=body_xyz_resolver) + def body_link_lin_vel_w(self) -> ProxyArray: """Linear velocity of all bodies in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to @@ -856,7 +922,8 @@ def body_link_lin_vel_w(self) -> wp.array: @property @abstractmethod - def body_link_ang_vel_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ANGULAR_VELOCITY, element_names_resolver=body_xyz_resolver) + def body_link_ang_vel_w(self) -> ProxyArray: """Angular velocity of all bodies in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to @@ -868,7 +935,8 @@ def body_link_ang_vel_w(self) -> wp.array: @property @abstractmethod - def body_com_pos_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSITION, element_names_resolver=body_xyz_resolver) + def body_com_pos_w(self) -> ProxyArray: """Positions of all bodies in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to @@ -880,7 +948,8 @@ def body_com_pos_w(self) -> wp.array: @property @abstractmethod - def body_com_quat_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ROTATION, element_names_resolver=body_quat_resolver) + def body_com_quat_w(self) -> ProxyArray: """Orientation (x, y, z, w) of the principal axes of inertia of all bodies in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.quatf. In torch this resolves to @@ -892,7 +961,8 @@ def body_com_quat_w(self) -> wp.array: @property @abstractmethod - def body_com_lin_vel_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_LINEAR_VELOCITY, element_names_resolver=body_xyz_resolver) + def body_com_lin_vel_w(self) -> ProxyArray: """Linear velocity of all bodies in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to @@ -904,7 +974,8 @@ def body_com_lin_vel_w(self) -> wp.array: @property @abstractmethod - def body_com_ang_vel_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ANGULAR_VELOCITY, element_names_resolver=body_xyz_resolver) + def body_com_ang_vel_w(self) -> ProxyArray: """Angular velocity of all bodies in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to @@ -916,7 +987,8 @@ def body_com_ang_vel_w(self) -> wp.array: @property @abstractmethod - def body_com_lin_acc_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_LINEAR_ACCELERATION, element_names_resolver=body_xyz_resolver) + def body_com_lin_acc_w(self) -> ProxyArray: """Linear acceleration of all bodies in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to @@ -928,7 +1000,8 @@ def body_com_lin_acc_w(self) -> wp.array: @property @abstractmethod - def body_com_ang_acc_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ANGULAR_ACCELERATION, element_names_resolver=body_xyz_resolver) + def body_com_ang_acc_w(self) -> ProxyArray: """Angular acceleration of all bodies in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to @@ -940,7 +1013,8 @@ def body_com_ang_acc_w(self) -> wp.array: @property @abstractmethod - def body_com_pos_b(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSITION, element_names_resolver=body_xyz_resolver) + def body_com_pos_b(self) -> ProxyArray: """Center of mass position of all of the bodies in their respective link frames. Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to @@ -952,7 +1026,8 @@ def body_com_pos_b(self) -> wp.array: @property @abstractmethod - def body_com_quat_b(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ROTATION, element_names_resolver=body_quat_resolver) + def body_com_quat_b(self) -> ProxyArray: """Orientation (x, y, z, w) of the principal axes of inertia of all of the bodies in their respective link frames. @@ -989,122 +1064,146 @@ def _create_buffers(self) -> None: """ @property - def root_pose_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSE, element_names=POSE7_ELEMENT_NAMES) + def root_pose_w(self) -> ProxyArray: """Shorthand for :attr:`root_link_pose_w`.""" return self.root_link_pose_w @property - def root_pos_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSITION, element_names=XYZ_ELEMENT_NAMES) + def root_pos_w(self) -> ProxyArray: """Shorthand for :attr:`root_link_pos_w`.""" return self.root_link_pos_w @property - def root_quat_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ROTATION, element_names=QUAT_XYZW_ELEMENT_NAMES) + def root_quat_w(self) -> ProxyArray: """Shorthand for :attr:`root_link_quat_w`.""" return self.root_link_quat_w @property - def root_vel_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_VEL, element_names=POSE6_ELEMENT_NAMES) + def root_vel_w(self) -> ProxyArray: """Shorthand for :attr:`root_com_vel_w`.""" return self.root_com_vel_w @property - def root_lin_vel_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_LINEAR_VELOCITY, element_names=XYZ_ELEMENT_NAMES) + def root_lin_vel_w(self) -> ProxyArray: """Shorthand for :attr:`root_com_lin_vel_w`.""" return self.root_com_lin_vel_w @property - def root_ang_vel_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ANGULAR_VELOCITY, element_names=XYZ_ELEMENT_NAMES) + def root_ang_vel_w(self) -> ProxyArray: """Shorthand for :attr:`root_com_ang_vel_w`.""" return self.root_com_ang_vel_w @property - def root_lin_vel_b(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_LINEAR_VELOCITY, element_names=XYZ_ELEMENT_NAMES) + def root_lin_vel_b(self) -> ProxyArray: """Shorthand for :attr:`root_com_lin_vel_b`.""" return self.root_com_lin_vel_b @property - def root_ang_vel_b(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ANGULAR_VELOCITY, element_names=XYZ_ELEMENT_NAMES) + def root_ang_vel_b(self) -> ProxyArray: """Shorthand for :attr:`root_com_ang_vel_b`.""" return self.root_com_ang_vel_b @property - def body_pose_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSE, element_names_resolver=body_pose_resolver) + def body_pose_w(self) -> ProxyArray: """Shorthand for :attr:`body_link_pose_w`.""" return self.body_link_pose_w @property - def body_pos_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSITION, element_names_resolver=body_xyz_resolver) + def body_pos_w(self) -> ProxyArray: """Shorthand for :attr:`body_link_pos_w`.""" return self.body_link_pos_w @property - def body_quat_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ROTATION, element_names_resolver=body_quat_resolver) + def body_quat_w(self) -> ProxyArray: """Shorthand for :attr:`body_link_quat_w`.""" return self.body_link_quat_w @property - def body_vel_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_VEL, element_names_resolver=body_pose6_resolver) + def body_vel_w(self) -> ProxyArray: """Shorthand for :attr:`body_com_vel_w`.""" return self.body_com_vel_w @property - def body_lin_vel_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_LINEAR_VELOCITY, element_names_resolver=body_xyz_resolver) + def body_lin_vel_w(self) -> ProxyArray: """Shorthand for :attr:`body_com_lin_vel_w`.""" return self.body_com_lin_vel_w @property - def body_ang_vel_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ANGULAR_VELOCITY, element_names_resolver=body_xyz_resolver) + def body_ang_vel_w(self) -> ProxyArray: """Shorthand for :attr:`body_com_ang_vel_w`.""" return self.body_com_ang_vel_w @property - def body_acc_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ACC, element_names_resolver=body_pose6_resolver) + def body_acc_w(self) -> ProxyArray: """Shorthand for :attr:`body_com_acc_w`.""" return self.body_com_acc_w @property - def body_lin_acc_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_LINEAR_ACCELERATION, element_names_resolver=body_xyz_resolver) + def body_lin_acc_w(self) -> ProxyArray: """Shorthand for :attr:`body_com_lin_acc_w`.""" return self.body_com_lin_acc_w @property - def body_ang_acc_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ANGULAR_ACCELERATION, element_names_resolver=body_xyz_resolver) + def body_ang_acc_w(self) -> ProxyArray: """Shorthand for :attr:`body_com_ang_acc_w`.""" return self.body_com_ang_acc_w @property - def com_pos_b(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSITION, element_names_resolver=body_xyz_resolver) + def com_pos_b(self) -> ProxyArray: """Shorthand for :attr:`body_com_pos_b`.""" return self.body_com_pos_b @property - def com_quat_b(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ROTATION, element_names_resolver=body_quat_resolver) + def com_quat_b(self) -> ProxyArray: """Shorthand for :attr:`body_com_quat_b`.""" return self.body_com_quat_b @property - def joint_limits(self) -> wp.array: + @leapp_tensor_semantics(const=True) + def joint_limits(self) -> ProxyArray: """Shorthand for :attr:`joint_pos_limits`.""" return self.joint_pos_limits @property - def default_joint_limits(self) -> wp.array: + @leapp_tensor_semantics(const=True) + def default_joint_limits(self) -> ProxyArray: """Shorthand for :attr:`default_joint_pos_limits`.""" return self.default_joint_pos_limits @property - def joint_velocity_limits(self) -> wp.array: + @leapp_tensor_semantics(const=True) + def joint_velocity_limits(self) -> ProxyArray: """Shorthand for :attr:`joint_vel_limits`.""" return self.joint_vel_limits @property - def joint_friction(self) -> wp.array: + @leapp_tensor_semantics(const=True) + def joint_friction(self) -> ProxyArray: """Shorthand for :attr:`joint_friction_coeff`.""" return self.joint_friction_coeff @property - def fixed_tendon_limit(self) -> wp.array: + @leapp_tensor_semantics(const=True) + def fixed_tendon_limit(self) -> ProxyArray: """Shorthand for :attr:`fixed_tendon_pos_limits`.""" return self.fixed_tendon_pos_limits @@ -1113,7 +1212,8 @@ def fixed_tendon_limit(self) -> wp.array: """ @property - def default_mass(self) -> wp.array: + @leapp_tensor_semantics(const=True) + def default_mass(self) -> ProxyArray: """Deprecated property. Please use :attr:`body_mass` instead and manage the default mass manually.""" warnings.warn( "The `default_mass` property will be deprecated in a IsaacLab 4.0. Please use `body_mass` instead. " @@ -1122,11 +1222,12 @@ def default_mass(self) -> wp.array: stacklevel=2, ) if self._default_mass is None: - self._default_mass = wp.clone(self.body_mass, self.device) - return self._default_mass + self._default_mass = wp.clone(self.body_mass.warp, self.device) + return ProxyArray(self._default_mass) @property - def default_inertia(self) -> wp.array: + @leapp_tensor_semantics(const=True) + def default_inertia(self) -> ProxyArray: """Deprecated property. Please use :attr:`body_inertia` instead and manage the default inertia manually.""" warnings.warn( "The `default_inertia` property will be deprecated in a IsaacLab 4.0. Please use `body_inertia` instead. " @@ -1135,11 +1236,12 @@ def default_inertia(self) -> wp.array: stacklevel=2, ) if self._default_inertia is None: - self._default_inertia = wp.clone(self.body_inertia, self.device) - return self._default_inertia + self._default_inertia = wp.clone(self.body_inertia.warp, self.device) + return ProxyArray(self._default_inertia) @property - def default_joint_stiffness(self) -> wp.array: + @leapp_tensor_semantics(const=True) + def default_joint_stiffness(self) -> ProxyArray: """Deprecated property. Please use :attr:`joint_stiffness` instead and manage the default joint stiffness manually.""" warnings.warn( @@ -1149,11 +1251,12 @@ def default_joint_stiffness(self) -> wp.array: stacklevel=2, ) if self._default_joint_stiffness is None: - self._default_joint_stiffness = wp.clone(self.joint_stiffness, self.device) - return self._default_joint_stiffness + self._default_joint_stiffness = wp.clone(self.joint_stiffness.warp, self.device) + return ProxyArray(self._default_joint_stiffness) @property - def default_joint_damping(self) -> wp.array: + @leapp_tensor_semantics(const=True) + def default_joint_damping(self) -> ProxyArray: """Deprecated property. Please use :attr:`joint_damping` instead and manage the default joint damping manually.""" warnings.warn( @@ -1163,11 +1266,12 @@ def default_joint_damping(self) -> wp.array: stacklevel=2, ) if self._default_joint_damping is None: - self._default_joint_damping = wp.clone(self.joint_damping, self.device) - return self._default_joint_damping + self._default_joint_damping = wp.clone(self.joint_damping.warp, self.device) + return ProxyArray(self._default_joint_damping) @property - def default_joint_armature(self) -> wp.array: + @leapp_tensor_semantics(const=True) + def default_joint_armature(self) -> ProxyArray: """Deprecated property. Please use :attr:`joint_armature` instead and manage the default joint armature manually.""" warnings.warn( @@ -1177,11 +1281,12 @@ def default_joint_armature(self) -> wp.array: stacklevel=2, ) if self._default_joint_armature is None: - self._default_joint_armature = wp.clone(self.joint_armature, self.device) - return self._default_joint_armature + self._default_joint_armature = wp.clone(self.joint_armature.warp, self.device) + return ProxyArray(self._default_joint_armature) @property - def default_joint_friction_coeff(self) -> wp.array: + @leapp_tensor_semantics(const=True) + def default_joint_friction_coeff(self) -> ProxyArray: """Deprecated property. Please use :attr:`joint_friction_coeff` instead and manage the default joint friction coefficient manually.""" warnings.warn( @@ -1191,11 +1296,12 @@ def default_joint_friction_coeff(self) -> wp.array: stacklevel=2, ) if self._default_joint_friction_coeff is None: - self._default_joint_friction_coeff = wp.clone(self.joint_friction_coeff, self.device) - return self._default_joint_friction_coeff + self._default_joint_friction_coeff = wp.clone(self.joint_friction_coeff.warp, self.device) + return ProxyArray(self._default_joint_friction_coeff) @property - def default_joint_viscous_friction_coeff(self) -> wp.array: + @leapp_tensor_semantics(const=True) + def default_joint_viscous_friction_coeff(self) -> ProxyArray: """Deprecated property. Please use :attr:`joint_viscous_friction_coeff` instead and manage the default joint viscous friction coefficient manually.""" warnings.warn( @@ -1205,11 +1311,14 @@ def default_joint_viscous_friction_coeff(self) -> wp.array: stacklevel=2, ) if self._default_joint_viscous_friction_coeff is None: - self._default_joint_viscous_friction_coeff = wp.clone(self.joint_viscous_friction_coeff, self.device) - return self._default_joint_viscous_friction_coeff + self._default_joint_viscous_friction_coeff = wp.clone( + getattr(self, "joint_viscous_friction_coeff").warp, self.device + ) + return ProxyArray(self._default_joint_viscous_friction_coeff) @property - def default_joint_pos_limits(self) -> wp.array: + @leapp_tensor_semantics(const=True) + def default_joint_pos_limits(self) -> ProxyArray: """Deprecated property. Please use :attr:`joint_pos_limits` instead and manage the default joint position limits manually.""" warnings.warn( @@ -1219,11 +1328,12 @@ def default_joint_pos_limits(self) -> wp.array: stacklevel=2, ) if self._default_joint_pos_limits is None: - self._default_joint_pos_limits = wp.clone(self.joint_pos_limits, self.device) - return self._default_joint_pos_limits + self._default_joint_pos_limits = wp.clone(self.joint_pos_limits.warp, self.device) + return ProxyArray(self._default_joint_pos_limits) @property - def default_fixed_tendon_stiffness(self) -> wp.array: + @leapp_tensor_semantics(const=True) + def default_fixed_tendon_stiffness(self) -> ProxyArray: """Deprecated property. Please use :attr:`fixed_tendon_stiffness` instead and manage the default fixed tendon stiffness manually.""" warnings.warn( @@ -1233,11 +1343,12 @@ def default_fixed_tendon_stiffness(self) -> wp.array: stacklevel=2, ) if self._default_fixed_tendon_stiffness is None: - self._default_fixed_tendon_stiffness = wp.clone(self.fixed_tendon_stiffness, self.device) - return self._default_fixed_tendon_stiffness + self._default_fixed_tendon_stiffness = wp.clone(self.fixed_tendon_stiffness.warp, self.device) + return ProxyArray(self._default_fixed_tendon_stiffness) @property - def default_fixed_tendon_damping(self) -> wp.array: + @leapp_tensor_semantics(const=True) + def default_fixed_tendon_damping(self) -> ProxyArray: """Deprecated property. Please use :attr:`fixed_tendon_damping` instead and manage the default fixed tendon damping manually.""" warnings.warn( @@ -1247,11 +1358,12 @@ def default_fixed_tendon_damping(self) -> wp.array: stacklevel=2, ) if self._default_fixed_tendon_damping is None: - self._default_fixed_tendon_damping = wp.clone(self.fixed_tendon_damping, self.device) - return self._default_fixed_tendon_damping + self._default_fixed_tendon_damping = wp.clone(self.fixed_tendon_damping.warp, self.device) + return ProxyArray(self._default_fixed_tendon_damping) @property - def default_fixed_tendon_limit_stiffness(self) -> wp.array: + @leapp_tensor_semantics(const=True) + def default_fixed_tendon_limit_stiffness(self) -> ProxyArray: """Deprecated property. Please use :attr:`fixed_tendon_limit_stiffness` instead and manage the default fixed tendon limit stiffness manually.""" warnings.warn( @@ -1261,11 +1373,12 @@ def default_fixed_tendon_limit_stiffness(self) -> wp.array: stacklevel=2, ) if self._default_fixed_tendon_limit_stiffness is None: - self._default_fixed_tendon_limit_stiffness = wp.clone(self.fixed_tendon_limit_stiffness, self.device) - return self._default_fixed_tendon_limit_stiffness + self._default_fixed_tendon_limit_stiffness = wp.clone(self.fixed_tendon_limit_stiffness.warp, self.device) + return ProxyArray(self._default_fixed_tendon_limit_stiffness) @property - def default_fixed_tendon_rest_length(self) -> wp.array: + @leapp_tensor_semantics(const=True) + def default_fixed_tendon_rest_length(self) -> ProxyArray: """Deprecated property. Please use :attr:`fixed_tendon_rest_length` instead and manage the default fixed tendon rest length manually.""" warnings.warn( @@ -1275,11 +1388,12 @@ def default_fixed_tendon_rest_length(self) -> wp.array: stacklevel=2, ) if self._default_fixed_tendon_rest_length is None: - self._default_fixed_tendon_rest_length = wp.clone(self.fixed_tendon_rest_length, self.device) - return self._default_fixed_tendon_rest_length + self._default_fixed_tendon_rest_length = wp.clone(self.fixed_tendon_rest_length.warp, self.device) + return ProxyArray(self._default_fixed_tendon_rest_length) @property - def default_fixed_tendon_offset(self) -> wp.array: + @leapp_tensor_semantics(const=True) + def default_fixed_tendon_offset(self) -> ProxyArray: """Deprecated property. Please use :attr:`fixed_tendon_offset` instead and manage the default fixed tendon offset manually.""" warnings.warn( @@ -1289,11 +1403,12 @@ def default_fixed_tendon_offset(self) -> wp.array: stacklevel=2, ) if self._default_fixed_tendon_offset is None: - self._default_fixed_tendon_offset = wp.clone(self.fixed_tendon_offset, self.device) - return self._default_fixed_tendon_offset + self._default_fixed_tendon_offset = wp.clone(self.fixed_tendon_offset.warp, self.device) + return ProxyArray(self._default_fixed_tendon_offset) @property - def default_fixed_tendon_pos_limits(self) -> wp.array: + @leapp_tensor_semantics(const=True) + def default_fixed_tendon_pos_limits(self) -> ProxyArray: """Deprecated property. Please use :attr:`fixed_tendon_pos_limits` instead and manage the default fixed tendon position limits manually.""" warnings.warn( @@ -1303,11 +1418,12 @@ def default_fixed_tendon_pos_limits(self) -> wp.array: stacklevel=2, ) if self._default_fixed_tendon_pos_limits is None: - self._default_fixed_tendon_pos_limits = wp.clone(self.fixed_tendon_pos_limits, self.device) - return self._default_fixed_tendon_pos_limits + self._default_fixed_tendon_pos_limits = wp.clone(self.fixed_tendon_pos_limits.warp, self.device) + return ProxyArray(self._default_fixed_tendon_pos_limits) @property - def default_spatial_tendon_stiffness(self) -> wp.array: + @leapp_tensor_semantics(const=True) + def default_spatial_tendon_stiffness(self) -> ProxyArray: """Deprecated property. Please use :attr:`spatial_tendon_stiffness` instead and manage the default spatial tendon stiffness manually.""" warnings.warn( @@ -1317,11 +1433,12 @@ def default_spatial_tendon_stiffness(self) -> wp.array: stacklevel=2, ) if self._default_spatial_tendon_stiffness is None: - self._default_spatial_tendon_stiffness = wp.clone(self.spatial_tendon_stiffness, self.device) - return self._default_spatial_tendon_stiffness + self._default_spatial_tendon_stiffness = wp.clone(self.spatial_tendon_stiffness.warp, self.device) + return ProxyArray(self._default_spatial_tendon_stiffness) @property - def default_spatial_tendon_damping(self) -> wp.array: + @leapp_tensor_semantics(const=True) + def default_spatial_tendon_damping(self) -> ProxyArray: """Deprecated property. Please use :attr:`spatial_tendon_damping` instead and manage the default spatial tendon damping manually.""" warnings.warn( @@ -1331,11 +1448,12 @@ def default_spatial_tendon_damping(self) -> wp.array: stacklevel=2, ) if self._default_spatial_tendon_damping is None: - self._default_spatial_tendon_damping = wp.clone(self.spatial_tendon_damping, self.device) - return self._default_spatial_tendon_damping + self._default_spatial_tendon_damping = wp.clone(self.spatial_tendon_damping.warp, self.device) + return ProxyArray(self._default_spatial_tendon_damping) @property - def default_spatial_tendon_limit_stiffness(self) -> wp.array: + @leapp_tensor_semantics(const=True) + def default_spatial_tendon_limit_stiffness(self) -> ProxyArray: """Deprecated property. Please use :attr:`spatial_tendon_limit_stiffness` instead and manage the default spatial tendon limit stiffness manually.""" warnings.warn( @@ -1345,11 +1463,14 @@ def default_spatial_tendon_limit_stiffness(self) -> wp.array: stacklevel=2, ) if self._default_spatial_tendon_limit_stiffness is None: - self._default_spatial_tendon_limit_stiffness = wp.clone(self.spatial_tendon_limit_stiffness, self.device) - return self._default_spatial_tendon_limit_stiffness + self._default_spatial_tendon_limit_stiffness = wp.clone( + self.spatial_tendon_limit_stiffness.warp, self.device + ) + return ProxyArray(self._default_spatial_tendon_limit_stiffness) @property - def default_spatial_tendon_offset(self) -> wp.array: + @leapp_tensor_semantics(const=True) + def default_spatial_tendon_offset(self) -> ProxyArray: """Deprecated property. Please use :attr:`spatial_tendon_offset` instead and manage the default spatial tendon offset manually.""" warnings.warn( @@ -1359,11 +1480,12 @@ def default_spatial_tendon_offset(self) -> wp.array: stacklevel=2, ) if self._default_spatial_tendon_offset is None: - self._default_spatial_tendon_offset = wp.clone(self.spatial_tendon_offset, self.device) - return self._default_spatial_tendon_offset + self._default_spatial_tendon_offset = wp.clone(self.spatial_tendon_offset.warp, self.device) + return ProxyArray(self._default_spatial_tendon_offset) @property - def default_fixed_tendon_limit(self) -> wp.array: + @leapp_tensor_semantics(const=True) + def default_fixed_tendon_limit(self) -> ProxyArray: """Deprecated property. Please use :attr:`default_fixed_tendon_pos_limits` instead.""" warnings.warn( "The `default_fixed_tendon_limit` property will be deprecated in a IsaacLab 4.0. Please use" @@ -1374,7 +1496,8 @@ def default_fixed_tendon_limit(self) -> wp.array: return self.default_fixed_tendon_pos_limits @property - def default_joint_friction(self) -> wp.array: + @leapp_tensor_semantics(const=True) + def default_joint_friction(self) -> ProxyArray: """Deprecated property. Please use :attr:`default_joint_friction_coeff` instead.""" warnings.warn( "The `default_joint_friction` property will be deprecated in a IsaacLab 4.0. Please use" diff --git a/source/isaaclab/isaaclab/assets/asset_base.py b/source/isaaclab/isaaclab/assets/asset_base.py index 654d199f0f99..a7da0d36fe12 100644 --- a/source/isaaclab/isaaclab/assets/asset_base.py +++ b/source/isaaclab/isaaclab/assets/asset_base.py @@ -53,6 +53,9 @@ class AssetBase(ABC): :meth:`_debug_vis_callback` methods. """ + _check_shapes: bool = __debug__ + """Class-level default for shape validation. Overridden per-instance in ``__init__``.""" + def __init__(self, cfg: AssetBaseCfg): """Initialize the asset base. @@ -66,6 +69,13 @@ def __init__(self, cfg: AssetBaseCfg): cfg.validate() # store inputs self.cfg = cfg.copy() + # Resolve shape-check flag once: True means checks are active. + # cfg.disable_shape_checks: None -> follow __debug__ + # True -> force disable checks; False -> force enable checks. + if self.cfg.disable_shape_checks is None: + self._check_shapes = __debug__ + else: + self._check_shapes = not self.cfg.disable_shape_checks # flag for whether the asset is initialized self._is_initialized = False # get stage handle @@ -257,13 +267,16 @@ def assert_shape_and_dtype( ) -> None: """Assert the shape and dtype of a tensor or warp array. + Controlled by :attr:`AssetBaseCfg.disable_shape_checks`. When checks are + disabled this method is a no-op. + Args: tensor: The tensor or warp array to assert the shape of. Floats are skipped. shape: The expected leading dimensions (e.g. ``(num_envs, num_joints)``). dtype: The expected warp dtype. name: Optional parameter name for error messages. """ - if __debug__: + if self._check_shapes: cls = type(self).__name__ prefix = f"{cls}: '{name}' " if name else f"{cls}: " if isinstance(tensor, (int, float)): @@ -294,6 +307,9 @@ def assert_shape_and_dtype_mask( ``(mask_0.shape[0], mask_1.shape[0], ...)`` (i.e. the *total* size of each dimension, not the number of selected entries). + Controlled by :attr:`AssetBaseCfg.disable_shape_checks`. When checks are + disabled this method is a no-op. + Args: tensor: The tensor or warp array to assert the shape of. Floats are skipped. masks: Tuple of mask arrays whose ``shape[0]`` dimensions form the expected leading shape. @@ -301,7 +317,7 @@ def assert_shape_and_dtype_mask( name: Optional parameter name for error messages. trailing_dims: Extra trailing dimensions to append (e.g. ``(9,)`` for inertias with ``wp.float32``). """ - if __debug__: + if self._check_shapes: shape = (*tuple(m.shape[0] for m in masks), *trailing_dims) self.assert_shape_and_dtype(tensor, shape, dtype, name) @@ -359,10 +375,10 @@ def _invoke(callback_name, event): PhysicsEvent.STOP, order=10, ) - # Optional: prim deletion (only supported by PhysX backend) + # Optional: prim deletion (only supported by Kit PhysX backend, not ovphysx) self._prim_deletion_handle = None physics_backend = physics_mgr_cls.__name__.lower() - if "physx" in physics_backend: + if physics_backend.startswith("physx"): from isaaclab_physx.physics import IsaacEvents self._prim_deletion_handle = physics_mgr_cls.register_callback( diff --git a/source/isaaclab/isaaclab/assets/asset_base_cfg.py b/source/isaaclab/isaaclab/assets/asset_base_cfg.py index 37d551ddec7d..4575acc08452 100644 --- a/source/isaaclab/isaaclab/assets/asset_base_cfg.py +++ b/source/isaaclab/isaaclab/assets/asset_base_cfg.py @@ -75,3 +75,16 @@ class InitialStateCfg: debug_vis: bool = False """Whether to enable debug visualization for the asset. Defaults to ``False``.""" + + disable_shape_checks: bool | None = None + """Disable shape/dtype validation in setter and writer methods. + + When ``True``, :meth:`~AssetBase.assert_shape_and_dtype` and + :meth:`~AssetBase.assert_shape_and_dtype_mask` become no-ops, + eliminating per-call assertion overhead. + + When ``False``, shape checks are always enabled, even under ``python -O``. + + When ``None`` (the default), shape checks follow Python's ``__debug__`` + flag — enabled in normal mode, disabled with ``python -O``. + """ diff --git a/source/isaaclab/isaaclab/assets/rigid_object/base_rigid_object.py b/source/isaaclab/isaaclab/assets/rigid_object/base_rigid_object.py index a2e57aed5419..d7bc6ea4c85d 100644 --- a/source/isaaclab/isaaclab/assets/rigid_object/base_rigid_object.py +++ b/source/isaaclab/isaaclab/assets/rigid_object/base_rigid_object.py @@ -845,13 +845,16 @@ def set_external_force_and_torque( env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, is_global: bool = False, ) -> None: - """Deprecated, same as :meth:`permanent_wrench_composer.set_forces_and_torques`.""" + """Deprecated. Resets target environments, then adds forces and torques via the permanent wrench composer.""" warnings.warn( - "The function 'set_external_force_and_torque' will be deprecated in a future release. Please" - " use 'permanent_wrench_composer.set_forces_and_torques' instead.", + "The function 'set_external_force_and_torque' is deprecated. Please use" + " 'permanent_wrench_composer.reset' followed by 'permanent_wrench_composer.add_forces_and_torques'" + " instead.", DeprecationWarning, stacklevel=2, ) - self.permanent_wrench_composer.set_forces_and_torques( + # Reset only target env_ids then add (not set which clears all envs globally) + self.permanent_wrench_composer.reset(env_ids=env_ids) + self.permanent_wrench_composer.add_forces_and_torques( forces, torques, positions=positions, body_ids=body_ids, env_ids=env_ids, is_global=is_global ) diff --git a/source/isaaclab/isaaclab/assets/rigid_object/base_rigid_object_data.py b/source/isaaclab/isaaclab/assets/rigid_object/base_rigid_object_data.py index e04a1ffa8bc1..b9134cf9ec93 100644 --- a/source/isaaclab/isaaclab/assets/rigid_object/base_rigid_object_data.py +++ b/source/isaaclab/isaaclab/assets/rigid_object/base_rigid_object_data.py @@ -8,6 +8,20 @@ import warp as wp +from isaaclab.utils.leapp import ( + POSE6_ELEMENT_NAMES, + POSE7_ELEMENT_NAMES, + QUAT_XYZW_ELEMENT_NAMES, + XYZ_ELEMENT_NAMES, + InputKindEnum, + body_pose6_resolver, + body_pose_resolver, + body_quat_resolver, + body_xyz_resolver, + leapp_tensor_semantics, +) +from isaaclab.utils.warp import ProxyArray + class BaseRigidObjectData(ABC): """Data container for a rigid object. @@ -52,7 +66,7 @@ def update(self, dt: float) -> None: # Names. ## - body_names: list[str] = None + body_names: list[str] | None = None """Body names in the order parsed by the simulation view.""" ## @@ -61,7 +75,8 @@ def update(self, dt: float) -> None: @property @abstractmethod - def default_root_pose(self) -> wp.array: + @leapp_tensor_semantics(const=True) + def default_root_pose(self) -> ProxyArray: """Default root pose ``[pos, quat]`` in local environment frame. The position and quaternion are of the rigid body's actor frame. @@ -71,7 +86,8 @@ def default_root_pose(self) -> wp.array: @property @abstractmethod - def default_root_vel(self) -> wp.array: + @leapp_tensor_semantics(const=True) + def default_root_vel(self) -> ProxyArray: """Default root velocity ``[lin_vel, ang_vel]`` in local environment frame. The linear and angular velocities are of the rigid body's center of mass frame. @@ -81,7 +97,7 @@ def default_root_vel(self) -> wp.array: @property @abstractmethod - def default_root_state(self) -> wp.array: + def default_root_state(self) -> ProxyArray: """Deprecated, same as :attr:`default_root_pose` and :attr:`default_root_vel`.""" raise NotImplementedError() @@ -91,7 +107,8 @@ def default_root_state(self) -> wp.array: @property @abstractmethod - def root_link_pose_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSE, element_names=POSE7_ELEMENT_NAMES) + def root_link_pose_w(self) -> ProxyArray: """Root link pose ``[pos, quat]`` in simulation world frame. Shape is (num_instances,), dtype = wp.transformf. In torch this resolves to (num_instances, 7). @@ -103,7 +120,8 @@ def root_link_pose_w(self) -> wp.array: @property @abstractmethod - def root_link_vel_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_VEL, element_names=POSE6_ELEMENT_NAMES) + def root_link_vel_w(self) -> ProxyArray: """Root link velocity ``[lin_vel, ang_vel]`` in simulation world frame. Shape is (num_instances,), dtype = wp.spatial_vectorf. In torch this resolves to (num_instances, 6). @@ -115,7 +133,8 @@ def root_link_vel_w(self) -> wp.array: @property @abstractmethod - def root_com_pose_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSE, element_names=POSE7_ELEMENT_NAMES) + def root_com_pose_w(self) -> ProxyArray: """Root center of mass pose ``[pos, quat]`` in simulation world frame. Shape is (num_instances,), dtype = wp.transformf. In torch this resolves to (num_instances, 7). @@ -127,7 +146,8 @@ def root_com_pose_w(self) -> wp.array: @property @abstractmethod - def root_com_vel_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_VEL, element_names=POSE6_ELEMENT_NAMES) + def root_com_vel_w(self) -> ProxyArray: """Root center of mass velocity ``[lin_vel, ang_vel]`` in simulation world frame. Shape is (num_instances,), dtype = wp.spatial_vectorf. In torch this resolves to (num_instances, 6). @@ -139,19 +159,22 @@ def root_com_vel_w(self) -> wp.array: @property @abstractmethod - def root_state_w(self) -> wp.array: + @leapp_tensor_semantics(kind="state/body/state") + def root_state_w(self) -> ProxyArray: """Deprecated, same as :attr:`root_link_pose_w` and :attr:`root_com_vel_w`.""" raise NotImplementedError() @property @abstractmethod - def root_link_state_w(self) -> wp.array: + @leapp_tensor_semantics(kind="state/body/link_state") + def root_link_state_w(self) -> ProxyArray: """Deprecated, same as :attr:`root_link_pose_w` and :attr:`root_link_vel_w`.""" raise NotImplementedError() @property @abstractmethod - def root_com_state_w(self) -> wp.array: + @leapp_tensor_semantics(kind="state/body/com_state") + def root_com_state_w(self) -> ProxyArray: """Deprecated, same as :attr:`root_com_pose_w` and :attr:`root_com_vel_w`.""" raise NotImplementedError() @@ -161,7 +184,8 @@ def root_com_state_w(self) -> wp.array: @property @abstractmethod - def body_link_pose_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSE, element_names_resolver=body_pose_resolver) + def body_link_pose_w(self) -> ProxyArray: """Body link pose ``[pos, quat]`` in simulation world frame. Shape is (num_instances, 1), dtype = wp.transformf. @@ -174,7 +198,8 @@ def body_link_pose_w(self) -> wp.array: @property @abstractmethod - def body_link_vel_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_VEL, element_names_resolver=body_pose6_resolver) + def body_link_vel_w(self) -> ProxyArray: """Body link velocity ``[lin_vel, ang_vel]`` in simulation world frame. Shape is (num_instances, 1), dtype = wp.spatial_vectorf. @@ -187,7 +212,8 @@ def body_link_vel_w(self) -> wp.array: @property @abstractmethod - def body_com_pose_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSE, element_names_resolver=body_pose_resolver) + def body_com_pose_w(self) -> ProxyArray: """Body center of mass pose ``[pos, quat]`` in simulation world frame. Shape is (num_instances, 1), dtype = wp.transformf. @@ -200,7 +226,8 @@ def body_com_pose_w(self) -> wp.array: @property @abstractmethod - def body_com_vel_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_VEL, element_names_resolver=body_pose6_resolver) + def body_com_vel_w(self) -> ProxyArray: """Body center of mass velocity ``[lin_vel, ang_vel]`` in simulation world frame. Shape is (num_instances, 1), dtype = wp.spatial_vectorf. @@ -213,25 +240,29 @@ def body_com_vel_w(self) -> wp.array: @property @abstractmethod - def body_state_w(self) -> wp.array: + @leapp_tensor_semantics(kind="state/body/state") + def body_state_w(self) -> ProxyArray: """Deprecated, same as :attr:`body_link_pose_w` and :attr:`body_com_vel_w`.""" raise NotImplementedError() @property @abstractmethod - def body_link_state_w(self) -> wp.array: + @leapp_tensor_semantics(kind="state/body/link_state") + def body_link_state_w(self) -> ProxyArray: """Deprecated, same as :attr:`body_link_pose_w` and :attr:`body_link_vel_w`.""" raise NotImplementedError() @property @abstractmethod - def body_com_state_w(self) -> wp.array: + @leapp_tensor_semantics(kind="state/body/com_state") + def body_com_state_w(self) -> ProxyArray: """Deprecated, same as :attr:`body_com_pose_w` and :attr:`body_com_vel_w`.""" raise NotImplementedError() @property @abstractmethod - def body_com_acc_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ACC, element_names_resolver=body_pose6_resolver) + def body_com_acc_w(self) -> ProxyArray: """Acceleration of all bodies ``[lin_acc, ang_acc]`` in the simulation world frame. Shape is (num_instances, 1), dtype = wp.spatial_vectorf. @@ -243,7 +274,8 @@ def body_com_acc_w(self) -> wp.array: @property @abstractmethod - def body_com_pose_b(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSE, element_names_resolver=body_pose_resolver) + def body_com_pose_b(self) -> ProxyArray: """Center of mass pose ``[pos, quat]`` of all bodies in their respective body's link frames. Shape is (num_instances, 1), dtype = wp.transformf. @@ -256,7 +288,8 @@ def body_com_pose_b(self) -> wp.array: @property @abstractmethod - def body_mass(self) -> wp.array: + @leapp_tensor_semantics(const=True) + def body_mass(self) -> ProxyArray: """Mass of all bodies in the simulation world frame. Shape is (num_instances, 1), dtype = wp.float32. @@ -266,7 +299,8 @@ def body_mass(self) -> wp.array: @property @abstractmethod - def body_inertia(self) -> wp.array: + @leapp_tensor_semantics(const=True) + def body_inertia(self) -> ProxyArray: """Inertia of all bodies in the simulation world frame. Shape is (num_instances, 1, 9), dtype = wp.float32. @@ -280,7 +314,8 @@ def body_inertia(self) -> wp.array: @property @abstractmethod - def projected_gravity_b(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.VECTOR3D, element_names=XYZ_ELEMENT_NAMES) + def projected_gravity_b(self) -> ProxyArray: """Projection of the gravity direction on base frame. Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). @@ -289,7 +324,8 @@ def projected_gravity_b(self) -> wp.array: @property @abstractmethod - def heading_w(self) -> wp.array: + @leapp_tensor_semantics(kind="state/body/heading") + def heading_w(self) -> ProxyArray: """Yaw heading of the base frame (in radians). Shape is (num_instances,), dtype = wp.float32. In torch this resolves to (num_instances,). @@ -302,7 +338,8 @@ def heading_w(self) -> wp.array: @property @abstractmethod - def root_link_lin_vel_b(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_LINEAR_VELOCITY, element_names=XYZ_ELEMENT_NAMES) + def root_link_lin_vel_b(self) -> ProxyArray: """Root link linear velocity in base frame. Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). @@ -314,7 +351,8 @@ def root_link_lin_vel_b(self) -> wp.array: @property @abstractmethod - def root_link_ang_vel_b(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ANGULAR_VELOCITY, element_names=XYZ_ELEMENT_NAMES) + def root_link_ang_vel_b(self) -> ProxyArray: """Root link angular velocity in base frame. Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). @@ -326,7 +364,8 @@ def root_link_ang_vel_b(self) -> wp.array: @property @abstractmethod - def root_com_lin_vel_b(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_LINEAR_VELOCITY, element_names=XYZ_ELEMENT_NAMES) + def root_com_lin_vel_b(self) -> ProxyArray: """Root center of mass linear velocity in base frame. Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). @@ -338,7 +377,8 @@ def root_com_lin_vel_b(self) -> wp.array: @property @abstractmethod - def root_com_ang_vel_b(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ANGULAR_VELOCITY, element_names=XYZ_ELEMENT_NAMES) + def root_com_ang_vel_b(self) -> ProxyArray: """Root center of mass angular velocity in base frame. Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). @@ -354,7 +394,8 @@ def root_com_ang_vel_b(self) -> wp.array: @property @abstractmethod - def root_link_pos_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSITION, element_names=XYZ_ELEMENT_NAMES) + def root_link_pos_w(self) -> ProxyArray: """Root link position in simulation world frame. Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). @@ -365,7 +406,8 @@ def root_link_pos_w(self) -> wp.array: @property @abstractmethod - def root_link_quat_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ROTATION, element_names=QUAT_XYZW_ELEMENT_NAMES) + def root_link_quat_w(self) -> ProxyArray: """Root link orientation (x, y, z, w) in simulation world frame. Shape is (num_instances,), dtype = wp.quatf. In torch this resolves to (num_instances, 4). @@ -376,7 +418,8 @@ def root_link_quat_w(self) -> wp.array: @property @abstractmethod - def root_link_lin_vel_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_LINEAR_VELOCITY, element_names=XYZ_ELEMENT_NAMES) + def root_link_lin_vel_w(self) -> ProxyArray: """Root linear velocity in simulation world frame. Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). @@ -387,7 +430,8 @@ def root_link_lin_vel_w(self) -> wp.array: @property @abstractmethod - def root_link_ang_vel_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ANGULAR_VELOCITY, element_names=XYZ_ELEMENT_NAMES) + def root_link_ang_vel_w(self) -> ProxyArray: """Root link angular velocity in simulation world frame. Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). @@ -398,7 +442,8 @@ def root_link_ang_vel_w(self) -> wp.array: @property @abstractmethod - def root_com_pos_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSITION, element_names=XYZ_ELEMENT_NAMES) + def root_com_pos_w(self) -> ProxyArray: """Root center of mass position in simulation world frame. Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). @@ -409,7 +454,8 @@ def root_com_pos_w(self) -> wp.array: @property @abstractmethod - def root_com_quat_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ROTATION, element_names=QUAT_XYZW_ELEMENT_NAMES) + def root_com_quat_w(self) -> ProxyArray: """Root center of mass orientation (x, y, z, w) in simulation world frame. Shape is (num_instances,), dtype = wp.quatf. In torch this resolves to (num_instances, 4). @@ -420,7 +466,8 @@ def root_com_quat_w(self) -> wp.array: @property @abstractmethod - def root_com_lin_vel_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_LINEAR_VELOCITY, element_names=XYZ_ELEMENT_NAMES) + def root_com_lin_vel_w(self) -> ProxyArray: """Root center of mass linear velocity in simulation world frame. Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). @@ -431,7 +478,8 @@ def root_com_lin_vel_w(self) -> wp.array: @property @abstractmethod - def root_com_ang_vel_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ANGULAR_VELOCITY, element_names=XYZ_ELEMENT_NAMES) + def root_com_ang_vel_w(self) -> ProxyArray: """Root center of mass angular velocity in simulation world frame. Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). @@ -442,7 +490,8 @@ def root_com_ang_vel_w(self) -> wp.array: @property @abstractmethod - def body_link_pos_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSITION, element_names_resolver=body_xyz_resolver) + def body_link_pos_w(self) -> ProxyArray: """Positions of all bodies in simulation world frame. Shape is (num_instances, 1), dtype = wp.vec3f. In torch this resolves to (num_instances, 1, 3). @@ -453,7 +502,8 @@ def body_link_pos_w(self) -> wp.array: @property @abstractmethod - def body_link_quat_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ROTATION, element_names_resolver=body_quat_resolver) + def body_link_quat_w(self) -> ProxyArray: """Orientation (x, y, z, w) of all bodies in simulation world frame. Shape is (num_instances, 1), dtype = wp.quatf. In torch this resolves to (num_instances, 1, 4). @@ -464,7 +514,8 @@ def body_link_quat_w(self) -> wp.array: @property @abstractmethod - def body_link_lin_vel_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_LINEAR_VELOCITY, element_names_resolver=body_xyz_resolver) + def body_link_lin_vel_w(self) -> ProxyArray: """Linear velocity of all bodies in simulation world frame. Shape is (num_instances, 1), dtype = wp.vec3f. In torch this resolves to (num_instances, 1, 3). @@ -475,7 +526,8 @@ def body_link_lin_vel_w(self) -> wp.array: @property @abstractmethod - def body_link_ang_vel_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ANGULAR_VELOCITY, element_names_resolver=body_xyz_resolver) + def body_link_ang_vel_w(self) -> ProxyArray: """Angular velocity of all bodies in simulation world frame. Shape is (num_instances, 1), dtype = wp.vec3f. In torch this resolves to (num_instances, 1, 3). @@ -486,7 +538,8 @@ def body_link_ang_vel_w(self) -> wp.array: @property @abstractmethod - def body_com_pos_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSITION, element_names_resolver=body_xyz_resolver) + def body_com_pos_w(self) -> ProxyArray: """Positions of all bodies' center of mass in simulation world frame. Shape is (num_instances, 1), dtype = wp.vec3f. In torch this resolves to (num_instances, 1, 3). @@ -497,7 +550,8 @@ def body_com_pos_w(self) -> wp.array: @property @abstractmethod - def body_com_quat_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ROTATION, element_names_resolver=body_quat_resolver) + def body_com_quat_w(self) -> ProxyArray: """Orientation (x, y, z, w) of the principal axes of inertia of all bodies in simulation world frame. Shape is (num_instances, 1), dtype = wp.quatf. In torch this resolves to (num_instances, 1, 4). @@ -508,7 +562,8 @@ def body_com_quat_w(self) -> wp.array: @property @abstractmethod - def body_com_lin_vel_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_LINEAR_VELOCITY, element_names_resolver=body_xyz_resolver) + def body_com_lin_vel_w(self) -> ProxyArray: """Linear velocity of all bodies in simulation world frame. Shape is (num_instances, 1), dtype = wp.vec3f. In torch this resolves to (num_instances, 1, 3). @@ -519,7 +574,8 @@ def body_com_lin_vel_w(self) -> wp.array: @property @abstractmethod - def body_com_ang_vel_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ANGULAR_VELOCITY, element_names_resolver=body_xyz_resolver) + def body_com_ang_vel_w(self) -> ProxyArray: """Angular velocity of all bodies in simulation world frame. Shape is (num_instances, 1), dtype = wp.vec3f. In torch this resolves to (num_instances, 1, 3). @@ -530,7 +586,8 @@ def body_com_ang_vel_w(self) -> wp.array: @property @abstractmethod - def body_com_lin_acc_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_LINEAR_ACCELERATION, element_names_resolver=body_xyz_resolver) + def body_com_lin_acc_w(self) -> ProxyArray: """Linear acceleration of all bodies in simulation world frame. Shape is (num_instances, 1), dtype = wp.vec3f. In torch this resolves to (num_instances, 1, 3). @@ -541,7 +598,8 @@ def body_com_lin_acc_w(self) -> wp.array: @property @abstractmethod - def body_com_ang_acc_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ANGULAR_ACCELERATION, element_names_resolver=body_xyz_resolver) + def body_com_ang_acc_w(self) -> ProxyArray: """Angular acceleration of all bodies in simulation world frame. Shape is (num_instances, 1), dtype = wp.vec3f. In torch this resolves to (num_instances, 1, 3). @@ -552,7 +610,8 @@ def body_com_ang_acc_w(self) -> wp.array: @property @abstractmethod - def body_com_pos_b(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSITION, element_names_resolver=body_xyz_resolver) + def body_com_pos_b(self) -> ProxyArray: """Center of mass position of all of the bodies in their respective link frames. Shape is (num_instances, 1), dtype = wp.vec3f. In torch this resolves to (num_instances, 1, 3). @@ -563,7 +622,8 @@ def body_com_pos_b(self) -> wp.array: @property @abstractmethod - def body_com_quat_b(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ROTATION, element_names_resolver=body_quat_resolver) + def body_com_quat_b(self) -> ProxyArray: """Orientation (x, y, z, w) of the principal axes of inertia of all of the bodies in their respective link frames. @@ -583,97 +643,116 @@ def _create_buffers(self) -> None: """ @property - def root_pose_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSE, element_names=POSE7_ELEMENT_NAMES) + def root_pose_w(self) -> ProxyArray: """Shorthand for :attr:`root_link_pose_w`.""" return self.root_link_pose_w @property - def root_pos_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSITION, element_names=XYZ_ELEMENT_NAMES) + def root_pos_w(self) -> ProxyArray: """Shorthand for :attr:`root_link_pos_w`.""" return self.root_link_pos_w @property - def root_quat_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ROTATION, element_names=QUAT_XYZW_ELEMENT_NAMES) + def root_quat_w(self) -> ProxyArray: """Shorthand for :attr:`root_link_quat_w`.""" return self.root_link_quat_w @property - def root_vel_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_VEL, element_names=POSE6_ELEMENT_NAMES) + def root_vel_w(self) -> ProxyArray: """Shorthand for :attr:`root_com_vel_w`.""" return self.root_com_vel_w @property - def root_lin_vel_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_LINEAR_VELOCITY, element_names=XYZ_ELEMENT_NAMES) + def root_lin_vel_w(self) -> ProxyArray: """Shorthand for :attr:`root_com_lin_vel_w`.""" return self.root_com_lin_vel_w @property - def root_ang_vel_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ANGULAR_VELOCITY, element_names=XYZ_ELEMENT_NAMES) + def root_ang_vel_w(self) -> ProxyArray: """Shorthand for :attr:`root_com_ang_vel_w`.""" return self.root_com_ang_vel_w @property - def root_lin_vel_b(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_LINEAR_VELOCITY, element_names=XYZ_ELEMENT_NAMES) + def root_lin_vel_b(self) -> ProxyArray: """Shorthand for :attr:`root_com_lin_vel_b`.""" return self.root_com_lin_vel_b @property - def root_ang_vel_b(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ANGULAR_VELOCITY, element_names=XYZ_ELEMENT_NAMES) + def root_ang_vel_b(self) -> ProxyArray: """Shorthand for :attr:`root_com_ang_vel_b`.""" return self.root_com_ang_vel_b @property - def body_pose_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSE, element_names_resolver=body_pose_resolver) + def body_pose_w(self) -> ProxyArray: """Shorthand for :attr:`body_link_pose_w`.""" return self.body_link_pose_w @property - def body_pos_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSITION, element_names_resolver=body_xyz_resolver) + def body_pos_w(self) -> ProxyArray: """Shorthand for :attr:`body_link_pos_w`.""" return self.body_link_pos_w @property - def body_quat_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ROTATION, element_names_resolver=body_quat_resolver) + def body_quat_w(self) -> ProxyArray: """Shorthand for :attr:`body_link_quat_w`.""" return self.body_link_quat_w @property - def body_vel_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_VEL, element_names_resolver=body_pose6_resolver) + def body_vel_w(self) -> ProxyArray: """Shorthand for :attr:`body_com_vel_w`.""" return self.body_com_vel_w @property - def body_lin_vel_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_LINEAR_VELOCITY, element_names_resolver=body_xyz_resolver) + def body_lin_vel_w(self) -> ProxyArray: """Shorthand for :attr:`body_com_lin_vel_w`.""" return self.body_com_lin_vel_w @property - def body_ang_vel_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ANGULAR_VELOCITY, element_names_resolver=body_xyz_resolver) + def body_ang_vel_w(self) -> ProxyArray: """Shorthand for :attr:`body_com_ang_vel_w`.""" return self.body_com_ang_vel_w @property - def body_acc_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ACC, element_names_resolver=body_pose6_resolver) + def body_acc_w(self) -> ProxyArray: """Shorthand for :attr:`body_com_acc_w`.""" return self.body_com_acc_w @property - def body_lin_acc_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_LINEAR_ACCELERATION, element_names_resolver=body_xyz_resolver) + def body_lin_acc_w(self) -> ProxyArray: """Shorthand for :attr:`body_com_lin_acc_w`.""" return self.body_com_lin_acc_w @property - def body_ang_acc_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ANGULAR_ACCELERATION, element_names_resolver=body_xyz_resolver) + def body_ang_acc_w(self) -> ProxyArray: """Shorthand for :attr:`body_com_ang_acc_w`.""" return self.body_com_ang_acc_w @property - def com_pos_b(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSITION, element_names_resolver=body_xyz_resolver) + def com_pos_b(self) -> ProxyArray: """Shorthand for :attr:`body_com_pos_b`.""" return self.body_com_pos_b @property - def com_quat_b(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ROTATION, element_names_resolver=body_quat_resolver) + def com_quat_b(self) -> ProxyArray: """Shorthand for :attr:`body_com_quat_b`.""" return self.body_com_quat_b @@ -682,7 +761,8 @@ def com_quat_b(self) -> wp.array: """ @property - def default_mass(self) -> wp.array: + @leapp_tensor_semantics(const=True) + def default_mass(self) -> ProxyArray: """Deprecated property. Please use :attr:`body_mass` instead and manage the default mass manually.""" warnings.warn( "The `default_mass` property will be deprecated in a IsaacLab 4.0. Please use `body_mass` instead. " @@ -691,11 +771,12 @@ def default_mass(self) -> wp.array: stacklevel=2, ) if self._default_mass is None: - self._default_mass = wp.clone(self.body_mass, self.device) - return self._default_mass + self._default_mass = wp.clone(self.body_mass.warp, self.device) + return ProxyArray(self._default_mass) @property - def default_inertia(self) -> wp.array: + @leapp_tensor_semantics(const=True) + def default_inertia(self) -> ProxyArray: """Deprecated property. Please use :attr:`body_inertia` instead and manage the default inertia manually.""" warnings.warn( "The `default_inertia` property will be deprecated in a IsaacLab 4.0. Please use `body_inertia` instead. " @@ -704,5 +785,5 @@ def default_inertia(self) -> wp.array: stacklevel=2, ) if self._default_inertia is None: - self._default_inertia = wp.clone(self.body_inertia, self.device) - return self._default_inertia + self._default_inertia = wp.clone(self.body_inertia.warp, self.device) + return ProxyArray(self._default_inertia) diff --git a/source/isaaclab/isaaclab/assets/rigid_object_collection/base_rigid_object_collection.py b/source/isaaclab/isaaclab/assets/rigid_object_collection/base_rigid_object_collection.py index 0384bc67da58..4be586145b0e 100644 --- a/source/isaaclab/isaaclab/assets/rigid_object_collection/base_rigid_object_collection.py +++ b/source/isaaclab/isaaclab/assets/rigid_object_collection/base_rigid_object_collection.py @@ -904,20 +904,18 @@ def set_external_force_and_torque( env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, is_global: bool = False, ) -> None: - """Deprecated, same as :meth:`permanent_wrench_composer.set_forces_and_torques`.""" + """Deprecated. Resets target environments, then adds forces and torques via the permanent wrench composer.""" warnings.warn( - "The function 'set_external_force_and_torque' will be deprecated in a future release. Please" - " use 'permanent_wrench_composer.set_forces_and_torques' instead.", + "The function 'set_external_force_and_torque' is deprecated. Please use" + " 'permanent_wrench_composer.reset' followed by 'permanent_wrench_composer.add_forces_and_torques'" + " instead.", DeprecationWarning, stacklevel=2, ) - self.permanent_wrench_composer.set_forces_and_torques( - forces=forces, - torques=torques, - positions=positions, - body_ids=body_ids, - env_ids=env_ids, - is_global=is_global, + # Reset only target env_ids then add (not set which clears all envs globally) + self.permanent_wrench_composer.reset(env_ids=env_ids) + self.permanent_wrench_composer.add_forces_and_torques( + forces, torques, positions=positions, body_ids=body_ids, env_ids=env_ids, is_global=is_global ) def write_object_state_to_sim( diff --git a/source/isaaclab/isaaclab/assets/rigid_object_collection/base_rigid_object_collection_data.py b/source/isaaclab/isaaclab/assets/rigid_object_collection/base_rigid_object_collection_data.py index 1913bb4bef9b..37842c23264a 100644 --- a/source/isaaclab/isaaclab/assets/rigid_object_collection/base_rigid_object_collection_data.py +++ b/source/isaaclab/isaaclab/assets/rigid_object_collection/base_rigid_object_collection_data.py @@ -8,6 +8,16 @@ import warp as wp +from isaaclab.utils.leapp import ( + InputKindEnum, + body_pose6_resolver, + body_pose_resolver, + body_quat_resolver, + body_xyz_resolver, + leapp_tensor_semantics, +) +from isaaclab.utils.warp import ProxyArray + class BaseRigidObjectCollectionData(ABC): """Data container for a rigid object collection. @@ -54,7 +64,7 @@ def update(self, dt: float) -> None: # Names. ## - body_names: list[str] = None + body_names: list[str] | None = None """Body names in the order parsed by the simulation view.""" ## @@ -63,7 +73,8 @@ def update(self, dt: float) -> None: @property @abstractmethod - def default_body_pose(self) -> wp.array: + @leapp_tensor_semantics(const=True) + def default_body_pose(self) -> ProxyArray: """Default body pose ``[pos, quat]`` in local environment frame. The position and quaternion are of the rigid body's actor frame. @@ -74,7 +85,8 @@ def default_body_pose(self) -> wp.array: @property @abstractmethod - def default_body_vel(self) -> wp.array: + @leapp_tensor_semantics(const=True) + def default_body_vel(self) -> ProxyArray: """Default body velocity ``[lin_vel, ang_vel]`` in local environment frame. The linear and angular velocities are of the rigid body's center of mass frame. @@ -85,7 +97,8 @@ def default_body_vel(self) -> wp.array: @property @abstractmethod - def default_body_state(self) -> wp.array: + @leapp_tensor_semantics(const=True) + def default_body_state(self) -> ProxyArray: """Deprecated, same as :attr:`default_body_pose` and :attr:`default_body_vel`.""" raise NotImplementedError() @@ -95,7 +108,8 @@ def default_body_state(self) -> wp.array: @property @abstractmethod - def body_link_pose_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSE, element_names_resolver=body_pose_resolver) + def body_link_pose_w(self) -> ProxyArray: """Body link pose ``[pos, quat]`` in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.transformf. In torch this resolves to @@ -108,7 +122,8 @@ def body_link_pose_w(self) -> wp.array: @property @abstractmethod - def body_link_vel_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_VEL, element_names_resolver=body_pose6_resolver) + def body_link_vel_w(self) -> ProxyArray: """Body link velocity ``[lin_vel, ang_vel]`` in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.spatial_vectorf. In torch this resolves to @@ -121,7 +136,8 @@ def body_link_vel_w(self) -> wp.array: @property @abstractmethod - def body_com_pose_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSE, element_names_resolver=body_pose_resolver) + def body_com_pose_w(self) -> ProxyArray: """Body center of mass pose ``[pos, quat]`` in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.transformf. In torch this resolves to @@ -134,7 +150,8 @@ def body_com_pose_w(self) -> wp.array: @property @abstractmethod - def body_com_vel_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_VEL, element_names_resolver=body_pose6_resolver) + def body_com_vel_w(self) -> ProxyArray: """Body center of mass velocity ``[lin_vel, ang_vel]`` in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.spatial_vectorf. In torch this resolves to @@ -147,25 +164,29 @@ def body_com_vel_w(self) -> wp.array: @property @abstractmethod - def body_state_w(self) -> wp.array: + @leapp_tensor_semantics(kind="state/body/state") + def body_state_w(self) -> ProxyArray: """Deprecated, same as :attr:`body_link_pose_w` and :attr:`body_com_vel_w`.""" raise NotImplementedError() @property @abstractmethod - def body_link_state_w(self) -> wp.array: + @leapp_tensor_semantics(kind="state/body/link_state") + def body_link_state_w(self) -> ProxyArray: """Deprecated, same as :attr:`body_link_pose_w` and :attr:`body_link_vel_w`.""" raise NotImplementedError() @property @abstractmethod - def body_com_state_w(self) -> wp.array: + @leapp_tensor_semantics(kind="state/body/com_state") + def body_com_state_w(self) -> ProxyArray: """Deprecated, same as :attr:`body_com_pose_w` and :attr:`body_com_vel_w`.""" raise NotImplementedError() @property @abstractmethod - def body_com_acc_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ACC, element_names_resolver=body_pose6_resolver) + def body_com_acc_w(self) -> ProxyArray: """Acceleration of all bodies ``[lin_acc, ang_acc]`` in the simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.spatial_vectorf. In torch this resolves to @@ -177,7 +198,8 @@ def body_com_acc_w(self) -> wp.array: @property @abstractmethod - def body_com_pose_b(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSE, element_names_resolver=body_pose_resolver) + def body_com_pose_b(self) -> ProxyArray: """Center of mass pose ``[pos, quat]`` of all bodies in their respective body's link frames. Shape is (num_instances, num_bodies), dtype = wp.transformf. In torch this resolves to @@ -190,7 +212,8 @@ def body_com_pose_b(self) -> wp.array: @property @abstractmethod - def body_mass(self) -> wp.array: + @leapp_tensor_semantics(const=True) + def body_mass(self) -> ProxyArray: """Mass of all bodies in the simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.float32. In torch this resolves to (num_instances, num_bodies). @@ -199,7 +222,8 @@ def body_mass(self) -> wp.array: @property @abstractmethod - def body_inertia(self) -> wp.array: + @leapp_tensor_semantics(const=True) + def body_inertia(self) -> ProxyArray: """Inertia of all bodies in the simulation world frame. Shape is (num_instances, num_bodies, 9), dtype = wp.float32. In torch this resolves to @@ -213,7 +237,8 @@ def body_inertia(self) -> wp.array: @property @abstractmethod - def projected_gravity_b(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.VECTOR3D, element_names_resolver=body_xyz_resolver) + def projected_gravity_b(self) -> ProxyArray: """Projection of the gravity direction on base frame. Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to @@ -223,7 +248,8 @@ def projected_gravity_b(self) -> wp.array: @property @abstractmethod - def heading_w(self) -> wp.array: + @leapp_tensor_semantics(kind="state/body/heading") + def heading_w(self) -> ProxyArray: """Yaw heading of the base frame (in radians). Shape is (num_instances, num_bodies), dtype = wp.float32. @@ -237,7 +263,8 @@ def heading_w(self) -> wp.array: @property @abstractmethod - def body_link_lin_vel_b(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_LINEAR_VELOCITY, element_names_resolver=body_xyz_resolver) + def body_link_lin_vel_b(self) -> ProxyArray: """Root link linear velocity in base frame. Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to @@ -250,7 +277,8 @@ def body_link_lin_vel_b(self) -> wp.array: @property @abstractmethod - def body_link_ang_vel_b(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ANGULAR_VELOCITY, element_names_resolver=body_xyz_resolver) + def body_link_ang_vel_b(self) -> ProxyArray: """Root link angular velocity in base frame. Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to @@ -263,7 +291,8 @@ def body_link_ang_vel_b(self) -> wp.array: @property @abstractmethod - def body_com_lin_vel_b(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_LINEAR_VELOCITY, element_names_resolver=body_xyz_resolver) + def body_com_lin_vel_b(self) -> ProxyArray: """Root center of mass linear velocity in base frame. Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to @@ -276,7 +305,8 @@ def body_com_lin_vel_b(self) -> wp.array: @property @abstractmethod - def body_com_ang_vel_b(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ANGULAR_VELOCITY, element_names_resolver=body_xyz_resolver) + def body_com_ang_vel_b(self) -> ProxyArray: """Root center of mass angular velocity in base frame. Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to @@ -293,7 +323,8 @@ def body_com_ang_vel_b(self) -> wp.array: @property @abstractmethod - def body_link_pos_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSITION, element_names_resolver=body_xyz_resolver) + def body_link_pos_w(self) -> ProxyArray: """Positions of all bodies in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to @@ -305,7 +336,8 @@ def body_link_pos_w(self) -> wp.array: @property @abstractmethod - def body_link_quat_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ROTATION, element_names_resolver=body_quat_resolver) + def body_link_quat_w(self) -> ProxyArray: """Orientation (x, y, z, w) of all bodies in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.quatf. In torch this resolves to @@ -317,7 +349,8 @@ def body_link_quat_w(self) -> wp.array: @property @abstractmethod - def body_link_lin_vel_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_LINEAR_VELOCITY, element_names_resolver=body_xyz_resolver) + def body_link_lin_vel_w(self) -> ProxyArray: """Linear velocity of all bodies in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to @@ -329,7 +362,8 @@ def body_link_lin_vel_w(self) -> wp.array: @property @abstractmethod - def body_link_ang_vel_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ANGULAR_VELOCITY, element_names_resolver=body_xyz_resolver) + def body_link_ang_vel_w(self) -> ProxyArray: """Angular velocity of all bodies in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to @@ -341,7 +375,8 @@ def body_link_ang_vel_w(self) -> wp.array: @property @abstractmethod - def body_com_pos_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSITION, element_names_resolver=body_xyz_resolver) + def body_com_pos_w(self) -> ProxyArray: """Positions of all bodies' center of mass in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to @@ -353,7 +388,8 @@ def body_com_pos_w(self) -> wp.array: @property @abstractmethod - def body_com_quat_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ROTATION, element_names_resolver=body_quat_resolver) + def body_com_quat_w(self) -> ProxyArray: """Orientation (x, y, z, w) of the principal axes of inertia of all bodies in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.quatf. In torch this resolves to @@ -365,7 +401,8 @@ def body_com_quat_w(self) -> wp.array: @property @abstractmethod - def body_com_lin_vel_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_LINEAR_VELOCITY, element_names_resolver=body_xyz_resolver) + def body_com_lin_vel_w(self) -> ProxyArray: """Linear velocity of all bodies in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to @@ -377,7 +414,8 @@ def body_com_lin_vel_w(self) -> wp.array: @property @abstractmethod - def body_com_ang_vel_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ANGULAR_VELOCITY, element_names_resolver=body_xyz_resolver) + def body_com_ang_vel_w(self) -> ProxyArray: """Angular velocity of all bodies in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to @@ -389,7 +427,8 @@ def body_com_ang_vel_w(self) -> wp.array: @property @abstractmethod - def body_com_lin_acc_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_LINEAR_ACCELERATION, element_names_resolver=body_xyz_resolver) + def body_com_lin_acc_w(self) -> ProxyArray: """Linear acceleration of all bodies in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to @@ -401,7 +440,8 @@ def body_com_lin_acc_w(self) -> wp.array: @property @abstractmethod - def body_com_ang_acc_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ANGULAR_ACCELERATION, element_names_resolver=body_xyz_resolver) + def body_com_ang_acc_w(self) -> ProxyArray: """Angular acceleration of all bodies in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to @@ -413,7 +453,8 @@ def body_com_ang_acc_w(self) -> wp.array: @property @abstractmethod - def body_com_pos_b(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSITION, element_names_resolver=body_xyz_resolver) + def body_com_pos_b(self) -> ProxyArray: """Center of mass position of all of the bodies in their respective link frames. Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to @@ -425,7 +466,8 @@ def body_com_pos_b(self) -> wp.array: @property @abstractmethod - def body_com_quat_b(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ROTATION, element_names_resolver=body_quat_resolver) + def body_com_quat_b(self) -> ProxyArray: """Orientation (x, y, z, w) of the principal axes of inertia of all of the bodies in their respective link frames. @@ -441,57 +483,68 @@ def body_com_quat_b(self) -> wp.array: """ @property - def body_pose_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSE, element_names_resolver=body_pose_resolver) + def body_pose_w(self) -> ProxyArray: """Shorthand for :attr:`body_link_pose_w`.""" return self.body_link_pose_w @property - def body_pos_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSITION, element_names_resolver=body_xyz_resolver) + def body_pos_w(self) -> ProxyArray: """Shorthand for :attr:`body_link_pos_w`.""" return self.body_link_pos_w @property - def body_quat_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ROTATION, element_names_resolver=body_quat_resolver) + def body_quat_w(self) -> ProxyArray: """Shorthand for :attr:`body_link_quat_w`.""" return self.body_link_quat_w @property - def body_vel_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_VEL, element_names_resolver=body_pose6_resolver) + def body_vel_w(self) -> ProxyArray: """Shorthand for :attr:`body_com_vel_w`.""" return self.body_com_vel_w @property - def body_lin_vel_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_LINEAR_VELOCITY, element_names_resolver=body_xyz_resolver) + def body_lin_vel_w(self) -> ProxyArray: """Shorthand for :attr:`body_com_lin_vel_w`.""" return self.body_com_lin_vel_w @property - def body_ang_vel_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ANGULAR_VELOCITY, element_names_resolver=body_xyz_resolver) + def body_ang_vel_w(self) -> ProxyArray: """Shorthand for :attr:`body_com_ang_vel_w`.""" return self.body_com_ang_vel_w @property - def body_acc_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ACC, element_names_resolver=body_pose6_resolver) + def body_acc_w(self) -> ProxyArray: """Shorthand for :attr:`body_com_acc_w`.""" return self.body_com_acc_w @property - def body_lin_acc_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_LINEAR_ACCELERATION, element_names_resolver=body_xyz_resolver) + def body_lin_acc_w(self) -> ProxyArray: """Shorthand for :attr:`body_com_lin_acc_w`.""" return self.body_com_lin_acc_w @property - def body_ang_acc_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ANGULAR_ACCELERATION, element_names_resolver=body_xyz_resolver) + def body_ang_acc_w(self) -> ProxyArray: """Shorthand for :attr:`body_com_ang_acc_w`.""" return self.body_com_ang_acc_w @property - def com_pos_b(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSITION, element_names_resolver=body_xyz_resolver) + def com_pos_b(self) -> ProxyArray: """Shorthand for :attr:`body_com_pos_b`.""" return self.body_com_pos_b @property - def com_quat_b(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ROTATION, element_names_resolver=body_quat_resolver) + def com_quat_b(self) -> ProxyArray: """Shorthand for :attr:`body_com_quat_b`.""" return self.body_com_quat_b @@ -505,7 +558,8 @@ def _create_buffers(self): """ @property - def default_object_pose(self) -> wp.array: + @leapp_tensor_semantics(const=True) + def default_object_pose(self) -> ProxyArray: """Deprecated property. Please use :attr:`default_body_pose` instead.""" warnings.warn( "The `default_object_pose` property will be deprecated in a IsaacLab 4.0. Please use" @@ -516,7 +570,8 @@ def default_object_pose(self) -> wp.array: return self.default_body_pose @property - def default_object_vel(self) -> wp.array: + @leapp_tensor_semantics(const=True) + def default_object_vel(self) -> ProxyArray: """Deprecated property. Please use :attr:`default_body_vel` instead.""" warnings.warn( "The `default_object_vel` property will be deprecated in a IsaacLab 4.0. Please use" @@ -527,7 +582,8 @@ def default_object_vel(self) -> wp.array: return self.default_body_vel @property - def default_object_state(self) -> wp.array: + @leapp_tensor_semantics(const=True) + def default_object_state(self) -> ProxyArray: """Deprecated property. Please use :attr:`default_body_state` instead.""" warnings.warn( "The `default_object_state` property will be deprecated in a IsaacLab 4.0. Please use" @@ -538,6 +594,7 @@ def default_object_state(self) -> wp.array: return self.default_body_state @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSE, element_names_resolver=body_pose_resolver) def object_link_pose_w(self): """Deprecated property. Please use :attr:`body_link_pose_w` instead.""" warnings.warn( @@ -549,6 +606,7 @@ def object_link_pose_w(self): return self.body_link_pose_w @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_VEL, element_names_resolver=body_pose6_resolver) def object_link_vel_w(self): """Deprecated property. Please use :attr:`body_link_vel_w` instead.""" warnings.warn( @@ -560,6 +618,7 @@ def object_link_vel_w(self): return self.body_link_vel_w @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSE, element_names_resolver=body_pose_resolver) def object_com_pose_w(self): """Deprecated property. Please use :attr:`body_com_pose_w` instead.""" warnings.warn( @@ -571,6 +630,7 @@ def object_com_pose_w(self): return self.body_com_pose_w @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_VEL, element_names_resolver=body_pose6_resolver) def object_com_vel_w(self): """Deprecated property. Please use :attr:`body_com_vel_w` instead.""" warnings.warn( @@ -582,6 +642,7 @@ def object_com_vel_w(self): return self.body_com_vel_w @property + @leapp_tensor_semantics(kind="state/body/state") def object_state_w(self): """Deprecated property. Please use :attr:`body_state_w` instead.""" warnings.warn( @@ -592,6 +653,7 @@ def object_state_w(self): return self.body_state_w @property + @leapp_tensor_semantics(kind="state/body/link_state") def object_link_state_w(self): """Deprecated property. Please use :attr:`body_link_state_w` instead.""" warnings.warn( @@ -603,6 +665,7 @@ def object_link_state_w(self): return self.body_link_state_w @property + @leapp_tensor_semantics(kind="state/body/com_state") def object_com_state_w(self): """Deprecated property. Please use :attr:`body_com_state_w` instead.""" warnings.warn( @@ -614,6 +677,7 @@ def object_com_state_w(self): return self.body_com_state_w @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ACC, element_names_resolver=body_pose6_resolver) def object_com_acc_w(self): """Deprecated property. Please use :attr:`body_com_acc_w` instead.""" warnings.warn( @@ -625,6 +689,7 @@ def object_com_acc_w(self): return self.body_com_acc_w @property + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSE, element_names_resolver=body_pose_resolver) def object_com_pose_b(self): """Deprecated property. Please use :attr:`body_com_pose_b` instead.""" warnings.warn( @@ -636,7 +701,8 @@ def object_com_pose_b(self): return self.body_com_pose_b @property - def object_link_pos_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSITION, element_names_resolver=body_xyz_resolver) + def object_link_pos_w(self) -> ProxyArray: """Deprecated property. Please use :attr:`body_link_pos_w` instead.""" warnings.warn( "The `object_link_pos_w` property will be deprecated in a IsaacLab 4.0. Please use" @@ -647,7 +713,8 @@ def object_link_pos_w(self) -> wp.array: return self.body_link_pos_w @property - def object_link_quat_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ROTATION, element_names_resolver=body_quat_resolver) + def object_link_quat_w(self) -> ProxyArray: """Deprecated property. Please use :attr:`body_link_quat_w` instead.""" warnings.warn( "The `object_link_quat_w` property will be deprecated in a IsaacLab 4.0. Please use" @@ -658,7 +725,8 @@ def object_link_quat_w(self) -> wp.array: return self.body_link_quat_w @property - def object_link_lin_vel_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_LINEAR_VELOCITY, element_names_resolver=body_xyz_resolver) + def object_link_lin_vel_w(self) -> ProxyArray: """Deprecated property. Please use :attr:`body_link_lin_vel_w` instead.""" warnings.warn( "The `object_link_lin_vel_w` property will be deprecated in a IsaacLab 4.0. Please use" @@ -669,7 +737,8 @@ def object_link_lin_vel_w(self) -> wp.array: return self.body_link_lin_vel_w @property - def object_link_ang_vel_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ANGULAR_VELOCITY, element_names_resolver=body_xyz_resolver) + def object_link_ang_vel_w(self) -> ProxyArray: """Deprecated property. Please use :attr:`body_link_ang_vel_w` instead.""" warnings.warn( "The `object_link_ang_vel_w` property will be deprecated in a IsaacLab 4.0. Please use" @@ -680,7 +749,8 @@ def object_link_ang_vel_w(self) -> wp.array: return self.body_link_ang_vel_w @property - def object_com_pos_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSITION, element_names_resolver=body_xyz_resolver) + def object_com_pos_w(self) -> ProxyArray: """Deprecated property. Please use :attr:`body_com_pos_w` instead.""" warnings.warn( "The `object_com_pos_w` property will be deprecated in a IsaacLab 4.0. Please use" @@ -691,7 +761,8 @@ def object_com_pos_w(self) -> wp.array: return self.body_com_pos_w @property - def object_com_quat_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ROTATION, element_names_resolver=body_quat_resolver) + def object_com_quat_w(self) -> ProxyArray: """Deprecated property. Please use :attr:`body_com_quat_w` instead.""" warnings.warn( "The `object_com_quat_w` property will be deprecated in a IsaacLab 4.0. Please use" @@ -702,7 +773,8 @@ def object_com_quat_w(self) -> wp.array: return self.body_com_quat_w @property - def object_com_lin_vel_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_LINEAR_VELOCITY, element_names_resolver=body_xyz_resolver) + def object_com_lin_vel_w(self) -> ProxyArray: """Deprecated property. Please use :attr:`body_com_lin_vel_w` instead.""" warnings.warn( "The `object_com_lin_vel_w` property will be deprecated in a IsaacLab 4.0. Please use" @@ -713,7 +785,8 @@ def object_com_lin_vel_w(self) -> wp.array: return self.body_com_lin_vel_w @property - def object_com_ang_vel_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ANGULAR_VELOCITY, element_names_resolver=body_xyz_resolver) + def object_com_ang_vel_w(self) -> ProxyArray: """Deprecated property. Please use :attr:`body_com_ang_vel_w` instead.""" warnings.warn( "The `object_com_ang_vel_w` property will be deprecated in a IsaacLab 4.0. Please use" @@ -724,7 +797,8 @@ def object_com_ang_vel_w(self) -> wp.array: return self.body_com_ang_vel_w @property - def object_com_lin_acc_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_LINEAR_ACCELERATION, element_names_resolver=body_xyz_resolver) + def object_com_lin_acc_w(self) -> ProxyArray: """Deprecated property. Please use :attr:`body_com_lin_acc_w` instead.""" warnings.warn( "The `object_com_lin_acc_w` property will be deprecated in a IsaacLab 4.0. Please use" @@ -735,7 +809,8 @@ def object_com_lin_acc_w(self) -> wp.array: return self.body_com_lin_acc_w @property - def object_com_ang_acc_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ANGULAR_ACCELERATION, element_names_resolver=body_xyz_resolver) + def object_com_ang_acc_w(self) -> ProxyArray: """Deprecated property. Please use :attr:`body_com_ang_acc_w` instead.""" warnings.warn( "The `object_com_ang_acc_w` property will be deprecated in a IsaacLab 4.0. Please use" @@ -746,7 +821,8 @@ def object_com_ang_acc_w(self) -> wp.array: return self.body_com_ang_acc_w @property - def object_com_pos_b(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSITION, element_names_resolver=body_xyz_resolver) + def object_com_pos_b(self) -> ProxyArray: """Deprecated property. Please use :attr:`body_com_pos_b` instead.""" warnings.warn( "The `object_com_pos_b` property will be deprecated in a IsaacLab 4.0. Please use" @@ -757,7 +833,8 @@ def object_com_pos_b(self) -> wp.array: return self.body_com_pos_b @property - def object_com_quat_b(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ROTATION, element_names_resolver=body_quat_resolver) + def object_com_quat_b(self) -> ProxyArray: """Deprecated property. Please use :attr:`body_com_quat_b` instead.""" warnings.warn( "The `object_com_quat_b` property will be deprecated in a IsaacLab 4.0. Please use" @@ -768,7 +845,8 @@ def object_com_quat_b(self) -> wp.array: return self.body_com_quat_b @property - def object_link_lin_vel_b(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_LINEAR_VELOCITY, element_names_resolver=body_xyz_resolver) + def object_link_lin_vel_b(self) -> ProxyArray: """Deprecated property. Please use :attr:`body_link_lin_vel_b` instead.""" warnings.warn( "The `object_link_lin_vel_b` property will be deprecated in a IsaacLab 4.0. Please use" @@ -779,7 +857,8 @@ def object_link_lin_vel_b(self) -> wp.array: return self.body_link_lin_vel_b @property - def object_link_ang_vel_b(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ANGULAR_VELOCITY, element_names_resolver=body_xyz_resolver) + def object_link_ang_vel_b(self) -> ProxyArray: """Deprecated property. Please use :attr:`body_link_ang_vel_b` instead.""" warnings.warn( "The `object_link_ang_vel_b` property will be deprecated in a IsaacLab 4.0. Please use" @@ -790,7 +869,8 @@ def object_link_ang_vel_b(self) -> wp.array: return self.body_link_ang_vel_b @property - def object_com_lin_vel_b(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_LINEAR_VELOCITY, element_names_resolver=body_xyz_resolver) + def object_com_lin_vel_b(self) -> ProxyArray: """Deprecated property. Please use :attr:`body_com_lin_vel_b` instead.""" warnings.warn( "The `object_com_lin_vel_b` property will be deprecated in a IsaacLab 4.0. Please use" @@ -801,7 +881,8 @@ def object_com_lin_vel_b(self) -> wp.array: return self.body_com_lin_vel_b @property - def object_com_ang_vel_b(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ANGULAR_VELOCITY, element_names_resolver=body_xyz_resolver) + def object_com_ang_vel_b(self) -> ProxyArray: """Deprecated property. Please use :attr:`body_com_ang_vel_b` instead.""" warnings.warn( "The `object_com_ang_vel_b` property will be deprecated in a IsaacLab 4.0. Please use" @@ -812,7 +893,8 @@ def object_com_ang_vel_b(self) -> wp.array: return self.body_com_ang_vel_b @property - def object_pose_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSE, element_names_resolver=body_pose_resolver) + def object_pose_w(self) -> ProxyArray: """Deprecated property. Please use :attr:`body_link_pose_w` instead.""" warnings.warn( "The `object_pose_w` property will be deprecated in a IsaacLab 4.0. Please use `body_link_pose_w` instead.", @@ -822,7 +904,8 @@ def object_pose_w(self) -> wp.array: return self.body_link_pose_w @property - def object_pos_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSITION, element_names_resolver=body_xyz_resolver) + def object_pos_w(self) -> ProxyArray: """Deprecated property. Please use :attr:`body_link_pos_w` instead.""" warnings.warn( "The `object_pos_w` property will be deprecated in a IsaacLab 4.0. Please use `body_link_pos_w` instead.", @@ -832,7 +915,8 @@ def object_pos_w(self) -> wp.array: return self.body_link_pos_w @property - def object_quat_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ROTATION, element_names_resolver=body_quat_resolver) + def object_quat_w(self) -> ProxyArray: """Deprecated property. Please use :attr:`body_link_quat_w` instead.""" warnings.warn( "The `object_quat_w` property will be deprecated in a IsaacLab 4.0. Please use `body_link_quat_w` instead.", @@ -842,7 +926,8 @@ def object_quat_w(self) -> wp.array: return self.body_link_quat_w @property - def object_vel_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_VEL, element_names_resolver=body_pose6_resolver) + def object_vel_w(self) -> ProxyArray: """Deprecated property. Please use :attr:`body_com_vel_w` instead.""" warnings.warn( "The `object_vel_w` property will be deprecated in a IsaacLab 4.0. Please use `body_com_vel_w` instead.", @@ -852,7 +937,8 @@ def object_vel_w(self) -> wp.array: return self.body_com_vel_w @property - def object_lin_vel_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_LINEAR_VELOCITY, element_names_resolver=body_xyz_resolver) + def object_lin_vel_w(self) -> ProxyArray: """Deprecated property. Please use :attr:`body_com_lin_vel_w` instead.""" warnings.warn( "The `object_lin_vel_w` property will be deprecated in a IsaacLab 4.0. Please use" @@ -863,7 +949,8 @@ def object_lin_vel_w(self) -> wp.array: return self.body_com_lin_vel_w @property - def object_ang_vel_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ANGULAR_VELOCITY, element_names_resolver=body_xyz_resolver) + def object_ang_vel_w(self) -> ProxyArray: """Deprecated property. Please use :attr:`body_com_ang_vel_w` instead.""" warnings.warn( "The `object_ang_vel_w` property will be deprecated in a IsaacLab 4.0. Please use" @@ -874,7 +961,8 @@ def object_ang_vel_w(self) -> wp.array: return self.body_com_ang_vel_w @property - def object_lin_vel_b(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_LINEAR_VELOCITY, element_names_resolver=body_xyz_resolver) + def object_lin_vel_b(self) -> ProxyArray: """Deprecated property. Please use :attr:`body_com_lin_vel_b` instead.""" warnings.warn( "The `object_lin_vel_b` property will be deprecated in a IsaacLab 4.0. Please use" @@ -885,7 +973,8 @@ def object_lin_vel_b(self) -> wp.array: return self.body_com_lin_vel_b @property - def object_ang_vel_b(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ANGULAR_VELOCITY, element_names_resolver=body_xyz_resolver) + def object_ang_vel_b(self) -> ProxyArray: """Deprecated property. Please use :attr:`body_com_ang_vel_b` instead.""" warnings.warn( "The `object_ang_vel_b` property will be deprecated in a IsaacLab 4.0. Please use" @@ -896,7 +985,8 @@ def object_ang_vel_b(self) -> wp.array: return self.body_com_ang_vel_b @property - def object_acc_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ACC, element_names_resolver=body_pose6_resolver) + def object_acc_w(self) -> ProxyArray: """Deprecated property. Please use :attr:`body_com_acc_w` instead.""" warnings.warn( "The `object_acc_w` property will be deprecated in a IsaacLab 4.0. Please use `body_com_acc_w` instead.", @@ -906,7 +996,8 @@ def object_acc_w(self) -> wp.array: return self.body_com_acc_w @property - def object_lin_acc_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_LINEAR_ACCELERATION, element_names_resolver=body_xyz_resolver) + def object_lin_acc_w(self) -> ProxyArray: """Deprecated property. Please use :attr:`body_com_lin_acc_w` instead.""" warnings.warn( "The `object_lin_acc_w` property will be deprecated in a IsaacLab 4.0. Please use" @@ -917,7 +1008,8 @@ def object_lin_acc_w(self) -> wp.array: return self.body_com_lin_acc_w @property - def object_ang_acc_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ANGULAR_ACCELERATION, element_names_resolver=body_xyz_resolver) + def object_ang_acc_w(self) -> ProxyArray: """Deprecated property. Please use :attr:`body_com_ang_acc_w` instead.""" warnings.warn( "The `object_ang_acc_w` property will be deprecated in a IsaacLab 4.0. Please use" @@ -932,7 +1024,8 @@ def object_ang_acc_w(self) -> wp.array: """ @property - def default_mass(self) -> wp.array: + @leapp_tensor_semantics(const=True) + def default_mass(self) -> ProxyArray: """Deprecated property. Please use :attr:`body_mass` instead and manage the default mass manually.""" warnings.warn( "The `default_mass` property will be deprecated in a IsaacLab 4.0. Please use `body_mass` instead. " @@ -941,11 +1034,12 @@ def default_mass(self) -> wp.array: stacklevel=2, ) if self._default_mass is None: - self._default_mass = wp.clone(self.body_mass, self.device) - return self._default_mass + self._default_mass = wp.clone(self.body_mass.warp, self.device) + return ProxyArray(self._default_mass) @property - def default_inertia(self) -> wp.array: + @leapp_tensor_semantics(const=True) + def default_inertia(self) -> ProxyArray: """Deprecated property. Please use :attr:`body_inertia` instead and manage the default inertia manually.""" warnings.warn( "The `default_inertia` property will be deprecated in a IsaacLab 4.0. Please use `body_inertia` instead. " @@ -954,5 +1048,5 @@ def default_inertia(self) -> wp.array: stacklevel=2, ) if self._default_inertia is None: - self._default_inertia = wp.clone(self.body_inertia, self.device) - return self._default_inertia + self._default_inertia = wp.clone(self.body_inertia.warp, self.device) + return ProxyArray(self._default_inertia) diff --git a/source/isaaclab/isaaclab/cli/__init__.py b/source/isaaclab/isaaclab/cli/__init__.py index 833bc6945cf7..22cfa1e51725 100644 --- a/source/isaaclab/isaaclab/cli/__init__.py +++ b/source/isaaclab/isaaclab/cli/__init__.py @@ -143,9 +143,9 @@ def cli() -> None: elif args.python is not None: if args.python: - run_python_command(args.python[0], args.python[1:]) + run_python_command(args.python[0], args.python[1:], check=True) else: - run_python_command("-i", []) + run_python_command("-i", [], check=True) elif args.sim is not None: command_run_isaacsim(args.sim) diff --git a/source/isaaclab/isaaclab/cli/commands/envs.py b/source/isaaclab/isaaclab/cli/commands/envs.py index 3499664b7e2d..1436b9e6ee23 100644 --- a/source/isaaclab/isaaclab/cli/commands/envs.py +++ b/source/isaaclab/isaaclab/cli/commands/envs.py @@ -702,7 +702,8 @@ def command_setup_uv(env_name: str) -> None: print_info("Added environment hooks to uv activation scripts.") - print_info(f"Created uv environment named '{env_name}'.\n") + print_info(f"Created uv environment named '{env_name}'.") + print() if is_windows(): print(f"\t\t1. To activate the environment, run: {env_name}\\Scripts\\activate") print("\t\t2. To install Isaac Lab extensions, run: isaaclab.bat -i") @@ -713,4 +714,3 @@ def command_setup_uv(env_name: str) -> None: print("\t\t2. To install Isaac Lab extensions, run: ./isaaclab.sh -i") print("\t\t3. To perform formatting, run: ./isaaclab.sh -f") print("\t\t4. To deactivate the environment, run: deactivate") - print("\n") diff --git a/source/isaaclab/isaaclab/cli/commands/install.py b/source/isaaclab/isaaclab/cli/commands/install.py index c442cfd89fe6..ba9735b92a6d 100644 --- a/source/isaaclab/isaaclab/cli/commands/install.py +++ b/source/isaaclab/isaaclab/cli/commands/install.py @@ -76,6 +76,148 @@ def _install_system_deps() -> None: ] run_command(["sudo"] + cmd if os.geteuid() != 0 else cmd) + # nlopt has no aarch64 manylinux wheel for the version pinned by + # isaacteleop[retargeters], so pip falls back to a CMake source build + # that needs SWIG. Mirrors the apt step in docker/Dockerfile.base. + if not shutil.which("swig"): + print_info("Installing swig (required for building nlopt on ARM)...") + cmd = ["apt-get", "update"] + run_command(["sudo"] + cmd if os.geteuid() != 0 else cmd) + cmd = ["apt-get", "install", "-y", "--no-install-recommends", "swig"] + run_command(["sudo"] + cmd if os.geteuid() != 0 else cmd) + + +def _torch_first_on_sys_path_is_prebundle(python_exe: str, *, env: dict[str, str]) -> bool: + """Return True when the first ``torch`` on ``sys.path`` comes from a prebundle directory. + + Checks whether the first directory on ``sys.path`` that contains a + ``torch`` package lives under a ``pip_prebundle`` path (e.g. + ``omni.isaac.ml_archive/pip_prebundle``). This catches the prebundle + regardless of whether the extension lives under ``exts/``, + ``extsDeprecated/``, or any other search path. + + Does not import ``torch`` (that can fail on missing ``libcudnn`` while the + prebundle still appears earlier on ``sys.path`` than ``site-packages``). + """ + probe = """import os, sys +for p in sys.path: + if not p: + continue + if os.path.isfile(os.path.join(p, "torch", "__init__.py")): + norm = os.path.normpath(p) + sys.exit(1 if "pip_prebundle" in norm else 0) +sys.exit(0) +""" + result = run_command( + [python_exe, "-c", probe], + env=env, + check=False, + capture_output=True, + text=True, + ) + return result.returncode == 1 + + +def _maybe_preinstall_arm_nlopt(pip_cmd: list[str]) -> None: + """Pre-install ``nlopt==2.6.2`` on ARM Linux to skip the source-build fallback. + + There is no aarch64 manylinux wheel for the ``nlopt 2.6.2`` version pinned + by ``isaacteleop[retargeters]``, so pip falls back to a CMake source build + that hides the host-Python ``numpy`` from its isolated build env. Mirror + the docker/Dockerfile.base arm64 step: install ``setuptools wheel numpy`` + in the host Python first, then ``--no-build-isolation`` install nlopt so + later submodule installs see it as already satisfied. + """ + if is_windows() or not is_arm(): + return + print_info("Pre-installing nlopt==2.6.2 on ARM (no-build-isolation)...") + print_info(" step 1/2: ensure setuptools/wheel/numpy are importable for the no-build-isolation backend") + run_command(pip_cmd + ["install", "setuptools", "wheel", "numpy"]) + print_info(" step 2/2: install nlopt==2.6.2 with --no-build-isolation") + run_command(pip_cmd + ["install", "--no-build-isolation", "nlopt==2.6.2"]) + + +def _maybe_uninstall_prebundled_torch( + python_exe: str, + pip_cmd: list[str], + using_uv: bool, + *, + probe_env: dict[str, str], +) -> None: + """Uninstall pip torch stack when ``sys.path`` would load ``torch`` from a prebundle first.""" + if not _torch_first_on_sys_path_is_prebundle(python_exe, env=probe_env): + return + print_info( + "The first ``torch`` on ``sys.path`` is under a prebundle directory (e.g. " + "``omni.isaac.ml_archive/pip_prebundle``). Uninstalling pip " + "``torch``/``torchvision``/``torchaudio`` before continuing." + ) + uninstall_flags = ["-y"] if not using_uv else [] + run_command( + pip_cmd + ["uninstall"] + uninstall_flags + ["torch", "torchvision", "torchaudio"], + check=False, + ) + + +# Pinocchio stack required by isaaclab.controllers.pink_ik. Installed via the cmeel +# ``pin`` wheel, which provides the ``pinocchio`` Python module under +# ``cmeel.prefix/lib/python3.12/site-packages/`` and registers it on sys.path via a +# ``cmeel.pth`` hook. +_PINOCCHIO_STACK = ("pin", "pin-pink==3.1.0", "daqp==0.7.2") + + +def _ensure_pinocchio_installed(python_exe: str, pip_cmd: list[str], *, probe_env: dict[str, str]) -> None: + """Ensure ``pinocchio`` is importable, force-installing the cmeel pin stack if not. + + Recent Isaac Sim base images preinstall ``pin-pink`` into the kit's bundled + ``site-packages`` without its ``pin`` (cmeel pinocchio) dependency. Pip then + treats the ``pin-pink`` requirement as satisfied and never resolves the + transitive ``pin`` dep, leaving ``import pinocchio`` broken. This probes + for ``pinocchio`` at runtime and force-installs the cmeel stack when needed + so the pink IK controller and its tests work out of the box. + + Only runs on Linux x86_64 / aarch64 — the same platforms that have + pinocchio listed in :mod:`isaaclab`'s ``setup.py`` install requirements. + Skipped on Windows and macOS (no cmeel wheels) and on unsupported + architectures so the rest of ``--install`` behaves unchanged there. + + A force-reinstall failure (e.g. transient PyPI / NVIDIA Artifactory issue) + is logged as a warning rather than aborting ``--install``: pinocchio is only + needed by the optional pink IK controller, so the rest of Isaac Lab should + still install cleanly. + """ + import platform + + if platform.system() != "Linux": + return + if platform.machine() not in {"x86_64", "AMD64", "aarch64", "arm64"}: + return + + probe_result = run_command( + [python_exe, "-c", "import pinocchio"], + env=probe_env, + check=False, + capture_output=True, + text=True, + ) + if probe_result.returncode == 0: + return + + print_info( + "``import pinocchio`` failed — the kit-bundled ``pin-pink`` likely shipped without its" + " ``pin`` dep. Force-installing the cmeel pinocchio stack." + ) + install_result = run_command( + pip_cmd + ["install", "--upgrade", "--force-reinstall", *_PINOCCHIO_STACK], + check=False, + ) + if install_result.returncode != 0: + print_warning( + "Force-installing the cmeel pinocchio stack failed (returncode " + f"{install_result.returncode}). The pink IK controller and its tests will not be" + " usable until ``pin pin-pink==3.1.0 daqp==0.7.2`` is installed manually." + ) + def _ensure_cuda_torch() -> None: """Ensure correct PyTorch and CUDA versions are installed.""" @@ -305,6 +447,9 @@ def _install_extra_frameworks(framework_name: str = "all") -> None: "newton_actuators", "warp", "mujoco_warp", + "websockets", + "viser", + "imgui_bundle", ] """Package directory names in Isaac Sim prebundle directories to repoint. @@ -352,7 +497,25 @@ def _repoint_prebundle_packages() -> None: print_warning(f"site-packages directory not found: {site_packages} — skipping prebundle repoint.") return - prebundle_dirs = list(isaacsim_path.rglob("pip_prebundle")) + # Discover pip_prebundle directories from both the Isaac Sim tree and + # Omniverse cache roots. Some Isaac Sim directories are symlinked into + # ~/.local/share/ov and may be missed by a plain rglob() on _isaac_sim. + candidate_roots: set[Path] = set() + for root in ( + isaacsim_path, + isaacsim_path.resolve(), + isaacsim_path / "extscache", + Path.home() / ".local" / "share" / "ov" / "data" / "exts", + Path.home() / ".local" / "share" / "ov" / "data" / "exts" / "v2", + ): + if root.exists(): + candidate_roots.add(root) + candidate_roots.add(root.resolve()) + + prebundle_dirs: set[Path] = set() + for root in candidate_roots: + prebundle_dirs.update(root.rglob("pip_prebundle")) + if not prebundle_dirs: print_debug("No pip_prebundle directories found under Isaac Sim.") return @@ -368,6 +531,17 @@ def _repoint_prebundle_packages() -> None: if not prebundled.exists() and not prebundled.is_symlink(): continue + # The 'nvidia' directory is a Python namespace package shared across many + # distributions (nvidia-cudnn-cu12, nvidia-cublas-cu12, nvidia-srl, …). + # When using Isaac Sim's built-in Python, site-packages/nvidia only contains + # 'srl'; replacing the whole prebundle nvidia/ with that symlink strips away + # the CUDA shared libraries (libcudnn.so.9, etc.) that torch needs. + # Only repoint the nvidia namespace when the target actually provides the + # CUDA subpackages (cudnn is the minimal required indicator). + if pkg_name == "nvidia" and not (venv_pkg / "cudnn").exists(): + print_debug(f"Skipping repoint of {prebundled}: {venv_pkg} lacks CUDA subpackages (cudnn missing).") + continue + try: if prebundled.is_symlink(): if prebundled.resolve() == venv_pkg.resolve(): @@ -482,12 +656,6 @@ def command_install(install_type: str = "all") -> None: if name == "newton" and "isaaclab_visualizers" not in isaaclab_submodules: isaaclab_submodules.append("isaaclab_visualizers") submodule_extras["isaaclab_visualizers"] = "[newton]" - # newton and physx are tightly coupled; always install both together. - # todo: remove once we move to UV and pyproject.toml-based packaging - if name == "newton" and "isaaclab_physx" not in isaaclab_submodules: - isaaclab_submodules.append("isaaclab_physx") - if name == "physx" and "isaaclab_newton" not in isaaclab_submodules: - isaaclab_submodules.append("isaaclab_newton") else: valid = sorted(VALID_ISAACLAB_SUBMODULES) + sorted(VALID_RL_FRAMEWORKS) + ["isaacsim"] print_warning(f"Unknown Isaac Lab submodule '{name}'. Valid values: {', '.join(valid)}. Skipping.") @@ -528,6 +696,12 @@ def command_install(install_type: str = "all") -> None: pip_cmd = get_pip_command(python_exe) using_uv = pip_cmd[0] == "uv" + # Probe with the user's original PYTHONPATH (before pip-time filtering) so we detect + # Isaac Sim's setup_python_env.sh ordering that prefers extsDeprecated/ml_archive. + probe_env = {**os.environ} + if saved_pythonpath is not None: + probe_env["PYTHONPATH"] = saved_pythonpath + try: # Upgrade pip first to avoid compatibility issues (skip when using uv). if not using_uv: @@ -537,6 +711,12 @@ def command_install(install_type: str = "all") -> None: # Pin setuptools to avoid issues with pkg_resources removal in 82.0.0. run_command(pip_cmd + ["install", "setuptools<82.0.0"]) + # On ARM Linux pre-install nlopt to dodge its from-source build fallback. + _maybe_preinstall_arm_nlopt(pip_cmd) + + # Drop pip-installed torch if Isaac Sim's deprecated ML prebundle would shadow it. + _maybe_uninstall_prebundled_torch(python_exe, pip_cmd, using_uv, probe_env=probe_env) + # Install Isaac Sim if requested. if install_isaacsim: _install_isaacsim() @@ -555,6 +735,11 @@ def command_install(install_type: str = "all") -> None: # Can prevent that from happening. _ensure_cuda_torch() + # Ensure ``pinocchio`` is actually importable. The kit-bundled ``pin-pink`` in recent + # Isaac Sim images ships without its cmeel ``pin`` dependency, so the transitive + # requirement from ``pip install -e source/isaaclab`` can be silently skipped. + _ensure_pinocchio_installed(python_exe, pip_cmd, probe_env=probe_env) + # Repoint prebundled packages in Isaac Sim to the environment's copies so # the active venv/conda versions are always loaded regardless of PYTHONPATH # ordering (e.g. torch+cu130 in venv vs torch+cu128 in prebundle on aarch64). diff --git a/source/isaaclab/isaaclab/cli/utils.py b/source/isaaclab/isaaclab/cli/utils.py index a1870b9c2225..611a1c6e8101 100644 --- a/source/isaaclab/isaaclab/cli/utils.py +++ b/source/isaaclab/isaaclab/cli/utils.py @@ -146,29 +146,39 @@ def _print_debug_env(prefix: str, env: dict[str, str] | None) -> None: _CMD_METACHARACTERS = frozenset("<>|&^") -def _escape_for_cmd_exe(cmd: list[str] | tuple[str, ...]) -> str | list[str]: +def _escape_for_cmd_exe(cmd: list[str] | tuple[str, ...]) -> list[str]: + """Wrap .bat/.cmd calls in cmd.exe /c so args with < > | & ^ stay literal. + + Uses cmd.exe caret-escaping (``^<``) for metacharacters in args without + whitespace; double-quotes args that contain whitespace. Avoids wrapping a + metacharacter-bearing arg in double quotes -- ``cmd.exe /c "...\"X, |, &, ^). - """ - # Only .bat/.cmd files are executed via cmd.exe. + # only .bat/.cmd needs wrapping exe = str(cmd[0]).lower() if not (exe.endswith(".bat") or exe.endswith(".cmd")): return list(cmd) - # Wrap args that contain metacharacters or whitespace in double quotes. parts: list[str] = [] for arg in cmd: s = str(arg) - if any(c in s for c in _CMD_METACHARACTERS) or " " in s or "\t" in s: + has_meta = any(c in s for c in _CMD_METACHARACTERS) + has_space = " " in s or "\t" in s + # Args with spaces fall back to double-quoting: cmd.exe does not + # interpret metacharacters inside "..." but the literal quotes can + # leak through the python.bat hop. Bypass python.bat entirely (see + # extract_python_exe) for the common case; pip args with spaces and + # metacharacters in the same token are not currently used. + if has_space: parts.append(f'"{s}"') + elif has_meta: + parts.append("".join(f"^{c}" if c in _CMD_METACHARACTERS else c for c in s)) else: parts.append(s) - # Return a string so subprocess skips list2cmdline. - return " ".join(parts) + return ["cmd.exe", "/c", " ".join(parts)] def run_command( @@ -310,7 +320,16 @@ def extract_python_exe() -> str: if isaacsim_path is not None: if is_windows(): - python_exe = isaacsim_path / "python.bat" + # Prefer the underlying python.exe over python.bat so we avoid + # cmd.exe metacharacter-quoting hazards on pip args like + # ``setuptools<82.0.0``. isaaclab.bat already sources + # setup_conda_env.bat before reaching the CLI, so children + # inherit the right env without going back through python.bat. + kit_python_exe = isaacsim_path / "kit" / "python" / "python.exe" + if kit_python_exe.exists(): + python_exe = kit_python_exe + else: + python_exe = isaacsim_path / "python.bat" else: python_exe = isaacsim_path / "python.sh" diff --git a/source/isaaclab/isaaclab/cloner/__init__.pyi b/source/isaaclab/isaaclab/cloner/__init__.pyi index 69adc7cd7378..8319388a8108 100644 --- a/source/isaaclab/isaaclab/cloner/__init__.pyi +++ b/source/isaaclab/isaaclab/cloner/__init__.pyi @@ -4,24 +4,26 @@ # SPDX-License-Identifier: BSD-3-Clause __all__ = [ + "ClonePlan", "TemplateCloneCfg", "random", "sequential", "clone_from_template", + "disabled_fabric_change_notifies", "filter_collisions", "grid_transforms", "make_clone_plan", - "resolve_visualizer_clone_fn", "usd_replicate", ] +from .clone_plan import ClonePlan from .cloner_cfg import TemplateCloneCfg from .cloner_strategies import random, sequential from .cloner_utils import ( clone_from_template, + disabled_fabric_change_notifies, filter_collisions, grid_transforms, make_clone_plan, - resolve_visualizer_clone_fn, usd_replicate, ) diff --git a/source/isaaclab/isaaclab/cloner/_fabric_notices.py b/source/isaaclab/isaaclab/cloner/_fabric_notices.py new file mode 100644 index 000000000000..0feb8eef014a --- /dev/null +++ b/source/isaaclab/isaaclab/cloner/_fabric_notices.py @@ -0,0 +1,152 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Pure-Python ctypes binding for ``omni::fabric::IFabricUsd::setEnableChangeNotifies``. + +Acquires the ``omni::fabric::IFabricUsd`` carb interface directly from the Carbonite +framework so cloning can suspend Fabric's USD notice listener without depending on +``isaacsim.core.simulation_manager``. + +Mirrors the in-tree pattern in :mod:`isaaclab_newton.physics._cubric` for +``omni::cubric::IAdapter`` — same problem (base-Kit Carbonite interface with no +Python binding), same solution. When Kit exposes this from Python, replace this +module with a one-line import. +""" + +from __future__ import annotations + +import ctypes +import logging +import threading + +logger = logging.getLogger(__name__) + +# carb::Framework vtable (carb/Framework.h) +# 0: loadPluginsEx, 8: unloadAllPlugins, 16: acquireInterfaceWithClient, +# 24: tryAcquireInterfaceWithClient ← used here +_FW_OFF_TRY_ACQUIRE = 24 + +# omni::fabric::IFabricUsd vtable (omni/fabric/usd/interface/IFabricUsd.h) +# 0..88: prefetch / export / type-conversion entry points +# 96: setEnableChangeNotifies(FabricId, bool) +# 104: getEnableChangeNotifies(FabricId) -> bool +_IFU_OFF_SET_ENABLE = 96 +_IFU_OFF_GET_ENABLE = 104 + + +class _Version(ctypes.Structure): + _fields_ = [("major", ctypes.c_uint32), ("minor", ctypes.c_uint32)] + + +class _InterfaceDesc(ctypes.Structure): + _fields_ = [("name", ctypes.c_char_p), ("version", _Version)] + + +def _read_u64(addr: int) -> int: + return ctypes.c_uint64.from_address(addr).value + + +class FabricNoticeBindings: + """Typed wrappers around ``omni::fabric::IFabricUsd``'s notice toggle.""" + + def __init__(self) -> None: + self._iface_ptr: int = 0 + self._set_fn = None + self._get_fn = None + self._validated: bool = False + + def initialize(self) -> bool: + """Acquire the ``IFabricUsd`` interface. Returns False if unavailable.""" + try: + libcarb = ctypes.CDLL("libcarb.so") + except OSError: + logger.info("libcarb.so unavailable — Fabric notice suspension disabled (Linux x86_64 only)") + return False + + libcarb.acquireFramework.restype = ctypes.c_void_p + libcarb.acquireFramework.argtypes = [ctypes.c_char_p, _Version] + fw_ptr = libcarb.acquireFramework(b"isaaclab.cloner", _Version(0, 0)) + if not fw_ptr: + return False + + try_acquire_addr = _read_u64(fw_ptr + _FW_OFF_TRY_ACQUIRE) + if not try_acquire_addr: + return False + + try_acquire = ctypes.CFUNCTYPE( + ctypes.c_void_p, # IFabricUsd* + ctypes.c_char_p, # clientName + _InterfaceDesc, # desc (by value) + ctypes.c_char_p, # pluginName + )(try_acquire_addr) + + desc = _InterfaceDesc(name=b"omni::fabric::IFabricUsd", version=_Version(1, 0)) + + # clientName varies across Kit configurations — same fallback chain as _cubric.py + ptr = try_acquire(b"carb.scripting-python.plugin", desc, None) or try_acquire(None, desc, None) + if not ptr: + return False + self._iface_ptr = ptr + + set_addr = _read_u64(ptr + _IFU_OFF_SET_ENABLE) + get_addr = _read_u64(ptr + _IFU_OFF_GET_ENABLE) + if not (set_addr and get_addr): + return False + + # FabricId is uint64; CARB_ABI uses the platform's standard C calling convention + self._set_fn = ctypes.CFUNCTYPE(None, ctypes.c_uint64, ctypes.c_bool)(set_addr) + self._get_fn = ctypes.CFUNCTYPE(ctypes.c_bool, ctypes.c_uint64)(get_addr) + return True + + @property + def available(self) -> bool: + return self._iface_ptr != 0 + + def set_enable(self, fabric_id: int, enable: bool) -> None: + if self._set_fn is not None: + self._set_fn(ctypes.c_uint64(fabric_id), ctypes.c_bool(enable)) + + def is_enabled(self, fabric_id: int) -> bool: + if self._get_fn is None: + return False + return bool(self._get_fn(ctypes.c_uint64(fabric_id))) + + def validate_with(self, fabric_id: int) -> bool: + """One-time toggle round-trip — guards against ABI offset drift. + + If Kit's ``IFabricUsd`` vtable layout changes, our hardcoded offsets call the + wrong functions and ``set_enable`` no longer flips the flag ``is_enabled`` reads + from. This catches that case the first time we have a real fabric_id to work + with, and lets the caller fall back to a no-op. + """ + if self._validated: + return True + original = self.is_enabled(fabric_id) + self.set_enable(fabric_id, not original) + ok = self.is_enabled(fabric_id) != original + self.set_enable(fabric_id, original) + self._validated = ok + return ok + + +_BINDINGS: FabricNoticeBindings | None = None +_INIT_TRIED: bool = False +_LOCK = threading.Lock() + + +def get_bindings() -> FabricNoticeBindings | None: + """Return the lazily-initialised bindings, or ``None`` if Kit/Carbonite is unavailable.""" + global _BINDINGS, _INIT_TRIED + with _LOCK: + if _BINDINGS is not None: + return _BINDINGS + if _INIT_TRIED: + return None + _INIT_TRIED = True + b = FabricNoticeBindings() + if not b.initialize(): + return None + _BINDINGS = b + return _BINDINGS diff --git a/source/isaaclab/isaaclab/cloner/clone_plan.py b/source/isaaclab/isaaclab/cloner/clone_plan.py new file mode 100644 index 000000000000..4a765463b32d --- /dev/null +++ b/source/isaaclab/isaaclab/cloner/clone_plan.py @@ -0,0 +1,39 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from __future__ import annotations + +from dataclasses import dataclass, field + +import torch + + +@dataclass(frozen=True) +class ClonePlan: + """Per-group mapping from prototype prims to per-environment clones. + + Produced by :func:`~isaaclab.cloner.clone_from_template` for each prototype group it + discovers under the template root. Lets downstream consumers (e.g. mesh samplers, + ray-cast sensors) read prototype geometry once and scatter to environments via + :attr:`clone_mask` instead of walking per-env USD paths. + + Attributes are population-time invariants and the dataclass is frozen. Hash and + equality operate on :attr:`dest_template` only (the natural identity — it is the key + in :attr:`SimulationContext.get_clone_plans`); the mutable list/tensor fields are + excluded since ``torch.Tensor`` is not hashable and structural equality is rarely the + semantics consumers want. + """ + + dest_template: str + """Destination path template for this group, e.g. ``"/World/envs/env_{}/Object"``.""" + + prototype_paths: list[str] = field(hash=False, compare=False) + """Prototype prim paths in this group, e.g. + ``["/World/template/Object/proto_asset_0", "/World/template/Object/proto_asset_1"]``.""" + + clone_mask: torch.Tensor = field(hash=False, compare=False) + """Boolean tensor of shape ``[num_prototypes_in_group, num_envs]``; + ``clone_mask[i, j]`` is ``True`` iff env ``j`` was populated from + :attr:`prototype_paths` ``[i]``. Each column sums to exactly one.""" diff --git a/source/isaaclab/isaaclab/cloner/cloner_cfg.py b/source/isaaclab/isaaclab/cloner/cloner_cfg.py index 72887017cfe6..19decec0c011 100644 --- a/source/isaaclab/isaaclab/cloner/cloner_cfg.py +++ b/source/isaaclab/isaaclab/cloner/cloner_cfg.py @@ -34,7 +34,7 @@ class TemplateCloneCfg: .. code-block:: python from isaaclab.cloner import TemplateCloneCfg, clone_from_template - from isaacsim.core.utils.stage import get_current_stage + from isaaclab.sim.utils.stage import get_current_stage stage = get_current_stage() cfg = TemplateCloneCfg( @@ -73,9 +73,6 @@ class TemplateCloneCfg: physics_clone_fn: callable | None = None """Function used to perform physics replication.""" - visualizer_clone_fn: callable | None = None - """Optional function used to build precomputed visualizer artifacts from the clone plan.""" - clone_strategy: callable = random """Function used to build prototype-to-environment mapping. Default is :func:`random`.""" diff --git a/source/isaaclab/isaaclab/cloner/cloner_utils.py b/source/isaaclab/isaaclab/cloner/cloner_utils.py index 3413cf1ef8fa..717d020a90ce 100644 --- a/source/isaaclab/isaaclab/cloner/cloner_utils.py +++ b/source/isaaclab/isaaclab/cloner/cloner_utils.py @@ -5,26 +5,109 @@ from __future__ import annotations +import contextlib import itertools import logging import math -from collections.abc import Callable +from collections.abc import Iterator from typing import TYPE_CHECKING import torch -from pxr import Gf, Sdf, Usd, UsdGeom, Vt +from pxr import Gf, Sdf, Usd, UsdGeom, UsdUtils, Vt import isaaclab.sim as sim_utils -from isaaclab.physics.scene_data_requirements import SceneDataRequirement, VisualizerPrebuiltArtifacts + +from . import _fabric_notices if TYPE_CHECKING: from .cloner_cfg import TemplateCloneCfg +from .clone_plan import ClonePlan + logger = logging.getLogger(__name__) -def clone_from_template(stage: Usd.Stage, num_clones: int, template_clone_cfg: TemplateCloneCfg) -> None: +@contextlib.contextmanager +def disabled_fabric_change_notifies(stage: Usd.Stage, *, restore: bool = True) -> Iterator[None]: + """Suspend the ``IFabricUsd`` USD notice listener for the body of the ``with`` block. + + Targets the same handler that :meth:`isaacsim.core.cloner.Cloner.disable_change_listener` + toggles, but goes through ``omni::fabric::IFabricUsd`` directly so we don't take an + ``isaacsim.core.simulation_manager`` dependency. + + The listener is a global ``TfNotice`` registered when ``omni.fabric`` loads; it + short-circuits via a soft flag (``IFabricUsd.cpp:739``). Toggling that flag is what + skips the per-``Sdf.CopySpec`` Fabric sync that dominates cloning time on large scenes. + + When this provides a measurable speedup + ---------------------------------------- + Bisection on the regression test (see ``test_cloner.py``) shows the listener cost is + only on the critical path when **all** of these hold: + + 1. The clone happens through the ``InteractiveScene`` path with ``replicate_physics=True``. + Calling :func:`usd_replicate` directly on a stage produces no measurable gap; with + ``replicate_physics=False`` the gap drops to ~1.19x. The PhysX replication path is + what amplifies per-spec listener work. + 2. The cloned prims carry PhysX rigid-body schemas (e.g. ``UsdPhysics.RigidBodyAPI``, + authored via ``rigid_props`` on a spawn cfg). Plain Xforms or geometry without + physics schemas produce ~1.0x — the listener has no Fabric-tracked state to sync. + ``mass_props`` and ``collision_props`` add nothing beyond ``rigid_props``. + 3. Total per-``Sdf.CopySpec`` firings reach ~32K — i.e. ``num_bodies × num_envs`` is + large enough to dominate scene-init cost. Below this the speedup sinks into noise. + + Conditions outside this envelope (no PhysX schemas, single-env scenes, raw + ``usd_replicate`` calls, ``replicate_physics=False``) won't see a perf win — the + suspension is correct but its effect is lost in the rest of the work. + + Re-entrant: if the flag is already off on entry, ``__exit__`` leaves it off. Falls + through to a no-op if the Carbonite interface can't be acquired (e.g. outside a live + Kit application) — the caller never breaks, it just doesn't get the perf win. + + Args: + stage: USD stage whose Fabric notice handler should be suspended. + restore: When ``True`` (default), re-enable the handler on exit. Set to ``False`` + inside a known clone-then-``sim.reset`` window where the downstream Fabric + resync happens anyway and re-enabling here would trigger a redundant + ``forceMinimalPopulate`` batch — see ``PluginInterface.cpp:337``. + + Yields: + None. + """ + bindings = _fabric_notices.get_bindings() + if bindings is None: + yield + return + + # usdrt only works with a live Kit app — defer import so module load stays cheap. + import usdrt + + # Avoid leaking a strong reference into the global ``StageCache`` for stages we did not + # author into the cache: ``Insert`` keeps the stage alive for the rest of the process. + cache = UsdUtils.StageCache.Get() + cached_id = cache.GetId(stage) + stage_id = cached_id.ToLongInt() if cached_id.IsValid() else cache.Insert(stage).ToLongInt() + # ``FabricId`` wraps a uint64; the C ABI needs the raw integer. + fabric_id = usdrt.Usd.Stage.Attach(stage_id).GetFabricId().id + # First-call ABI sanity check — if the toggle doesn't actually round-trip the flag + # (e.g. Kit's vtable shifted), fall through to a no-op rather than corrupting state. + if not bindings.validate_with(fabric_id): + logger.warning("Fabric notice toggle failed round-trip check — suspension disabled") + yield + return + was_enabled = bindings.is_enabled(fabric_id) + if was_enabled: + bindings.set_enable(fabric_id, False) + try: + yield + finally: + if restore and was_enabled: + bindings.set_enable(fabric_id, True) + + +def clone_from_template( + stage: Usd.Stage, num_clones: int, template_clone_cfg: TemplateCloneCfg +) -> dict[str, ClonePlan]: """Clone assets from a template root into per-environment destinations. This utility discovers prototype prims under ``cfg.template_root`` whose names start with @@ -37,59 +120,94 @@ def clone_from_template(stage: Usd.Stage, num_clones: int, template_clone_cfg: T num_clones: Number of environments to clone to (typically equals ``cfg.num_clones``). template_clone_cfg: Configuration describing template location, destination pattern, and replication/mapping behavior. + + Returns: + Mapping from each group's destination template (e.g. ``"/World/envs/env_{}/Object"``) + to its :class:`ClonePlan`. Empty when no prototype groups are discovered. + + Note: + This function suspends the Fabric USD notice listener for the duration of the call + and **leaves it disabled on return**. It is intended to be invoked from a scene-init + path that is followed by :meth:`isaaclab.sim.SimulationContext.reset`, whose Fabric + resync naturally recovers the listener state. Callers that bypass that reset + contract (ad-hoc tooling, unit tests on a bare stage) should re-enable Fabric + notices themselves or wrap the call in + :func:`disabled_fabric_change_notifies` with ``restore=True``. """ cfg: TemplateCloneCfg = template_clone_cfg - world_indices = torch.arange(num_clones, device=cfg.device) - clone_path_fmt = cfg.clone_regex.replace(".*", "{}") - prototype_id = cfg.template_prototype_identifier - prototypes = sim_utils.get_all_matching_child_prims( - cfg.template_root, - predicate=lambda prim: str(prim.GetPath()).split("/")[-1].startswith(prototype_id), - ) - if len(prototypes) > 0: - prototype_root_set = {"/".join(str(prototype.GetPath()).split("/")[:-1]) for prototype in prototypes} - # discover prototypes per root then make a clone plan - src: list[list[str]] = [] - dest: list[str] = [] - - for prototype_root in prototype_root_set: - protos = sim_utils.find_matching_prim_paths(f"{prototype_root}/.*") - protos = [proto for proto in protos if proto.split("/")[-1].startswith(prototype_id)] - src.append(protos) - dest.append(prototype_root.replace(cfg.template_root, clone_path_fmt)) - - src_paths, dest_paths, clone_masking = make_clone_plan(src, dest, num_clones, cfg.clone_strategy, cfg.device) - - # Spawn the first instance of clones from prototypes, then deactivate the prototypes, those first instances - # will be served as sources for usd and physics replication. - proto_idx = clone_masking.to(torch.int32).argmax(dim=1) - proto_mask = torch.zeros_like(clone_masking) - proto_mask.scatter_(1, proto_idx.view(-1, 1).to(torch.long), clone_masking.any(dim=1, keepdim=True)) - usd_replicate(stage, src_paths, dest_paths, world_indices, proto_mask) - stage.GetPrimAtPath(cfg.template_root).SetActive(False) - get_pos = lambda path: stage.GetPrimAtPath(path).GetAttribute("xformOp:translate").Get() # noqa: E731 - positions = torch.tensor([get_pos(clone_path_fmt.format(i)) for i in world_indices]) - # If all prototypes map to env_0, clone whole env_0 to all envs; else clone per-object - if torch.all(proto_idx == 0): - mapping = clone_masking.new_ones(1, num_clones) - replicate_args = [clone_path_fmt.format(0)], [clone_path_fmt], world_indices, mapping - if cfg.clone_physics and cfg.physics_clone_fn is not None: - cfg.physics_clone_fn(stage, *replicate_args, positions=positions, device=cfg.device) - if cfg.visualizer_clone_fn is not None: - cfg.visualizer_clone_fn(stage, *replicate_args, positions=positions, device=cfg.device) - if cfg.clone_usd: - # parse env_origins directly from clone_path - usd_replicate(stage, *replicate_args, positions=positions) + plans: dict[str, ClonePlan] = {} + # Suspend Fabric's USD notice listener for the duration of bulk authoring. ``restore=False`` + # because clone_from_template is only called at scene-init time, which is followed by + # ``SimulationContext.reset`` — that reset path does the Fabric resync naturally, and + # re-enabling here would trigger a redundant ``forceMinimalPopulate`` batch. + with disabled_fabric_change_notifies(stage, restore=False): + world_indices = torch.arange(num_clones, device=cfg.device) + clone_path_fmt = cfg.clone_regex.replace(".*", "{}") + prototype_id = cfg.template_prototype_identifier + prototypes = sim_utils.get_all_matching_child_prims( + cfg.template_root, + predicate=lambda prim: str(prim.GetPath()).split("/")[-1].startswith(prototype_id), + ) + if len(prototypes) > 0: + # Canonicalize prototype-root order. Some simulation/visualization backends might apply order-dependent + # processing, so varying USD traversal or set iteration order can change outputs noticeably. Sorting here + # removes that nondeterminism at the source (group order feeds ``make_clone_plan`` and downstream + # replication), which matters for run-to-run reproducibility across IsaacLab's multi-backend stack. + prototype_roots = sorted({"/".join(str(prototype.GetPath()).split("/")[:-1]) for prototype in prototypes}) + + # discover prototypes per root then make a clone plan + src: list[list[str]] = [] + dest: list[str] = [] + + for prototype_root in prototype_roots: + protos = sim_utils.find_matching_prim_paths(f"{prototype_root}/.*") + protos = [proto for proto in protos if proto.split("/")[-1].startswith(prototype_id)] + src.append(protos) + dest.append(prototype_root.replace(cfg.template_root, clone_path_fmt)) + + src_paths, dest_paths, clone_masking = make_clone_plan( + src, dest, num_clones, cfg.clone_strategy, cfg.device + ) + + # Per-group plans: slice ``clone_masking`` along the prototype axis using cumulative + # group sizes — each group's mask rows are contiguous in the ``[total_protos, num_envs]`` + # tensor that ``make_clone_plan`` produced. + offsets = [0, *itertools.accumulate(len(g) for g in src)] + plans = { + d: ClonePlan(dest_template=d, prototype_paths=list(ps), clone_mask=clone_masking[lo:hi]) + for ps, d, lo, hi in zip(src, dest, offsets, offsets[1:]) + } + + # Spawn the first instance of clones from prototypes, then deactivate the prototypes, those first + # instances will be served as sources for usd and physics replication. + proto_idx = clone_masking.to(torch.int32).argmax(dim=1) + proto_mask = torch.zeros_like(clone_masking) + proto_mask.scatter_(1, proto_idx.view(-1, 1).to(torch.long), clone_masking.any(dim=1, keepdim=True)) + usd_replicate(stage, src_paths, dest_paths, world_indices, proto_mask) + stage.GetPrimAtPath(cfg.template_root).SetActive(False) + get_pos = lambda path: stage.GetPrimAtPath(path).GetAttribute("xformOp:translate").Get() # noqa: E731 + positions = torch.tensor([get_pos(clone_path_fmt.format(i)) for i in world_indices]) + # Heterogeneous default: emit per-prototype (sources, destinations, mask) and trust + # env_0..N's existing xforms (proto-spawn above already placed them, so don't + # re-author). When every env happens to pick prototype 0, collapse below to a + # single env_0 → all-envs copy and re-author positions (the destination subtree + # replaces env_1..N's prior xform). + sources = [tpl.format(int(idx)) for tpl, idx in zip(dest_paths, proto_idx.tolist())] + usd_positions: torch.Tensor | None = None + if torch.all(proto_idx == 0): + sources = [clone_path_fmt.format(0)] + dest_paths = [clone_path_fmt] + clone_masking = clone_masking.new_ones(1, num_clones) + usd_positions = positions - else: - selected_src = [tpl.format(int(idx)) for tpl, idx in zip(dest_paths, proto_idx.tolist())] - replicate_args = selected_src, dest_paths, world_indices, clone_masking if cfg.clone_physics and cfg.physics_clone_fn is not None: - cfg.physics_clone_fn(stage, *replicate_args, positions=positions, device=cfg.device) - if cfg.visualizer_clone_fn is not None: - cfg.visualizer_clone_fn(stage, *replicate_args, positions=positions, device=cfg.device) + cfg.physics_clone_fn( + stage, sources, dest_paths, world_indices, clone_masking, positions=positions, device=cfg.device + ) if cfg.clone_usd: - usd_replicate(stage, *replicate_args) + usd_replicate(stage, sources, dest_paths, world_indices, clone_masking, positions=usd_positions) + + return plans def make_clone_plan( @@ -381,37 +499,3 @@ def grid_transforms(N: int, spacing: float = 1.0, up_axis: str = "z", device="cp ori = torch.zeros((N, 4), device=device) ori[:, 3] = 1.0 # w=1 for identity quaternion return pos, ori - - -def resolve_visualizer_clone_fn( - physics_backend: str, - requirements: SceneDataRequirement, - stage, - set_visualizer_artifact: Callable[[VisualizerPrebuiltArtifacts | None], None], -): - """Return an optional visualizer prebuild hook for clone workflows. - - Args: - physics_backend: Active physics backend name. - requirements: Aggregated scene-data requirements. - stage: USD stage used by the clone callback. - set_visualizer_artifact: Callback for storing prebuilt visualizer artifacts. - - Returns: - Clone callback when the prebuild path is supported; otherwise ``None``. - """ - if "physx" not in physics_backend or not requirements.requires_newton_model: - return None - try: - from isaaclab_newton.cloner.newton_replicate import ( - create_newton_visualizer_prebuild_clone_fn, - ) - except (ImportError, ModuleNotFoundError) as exc: - logger.warning("Visualizer prebuild hook unavailable: failed to import backend helper.") - logger.debug("Visualizer prebuild import failure details: %s", exc) - return None - - return create_newton_visualizer_prebuild_clone_fn( - stage=stage, - set_visualizer_artifact=set_visualizer_artifact, - ) diff --git a/source/isaaclab/isaaclab/controllers/rmp_flow.py b/source/isaaclab/isaaclab/controllers/rmp_flow.py index e8f456eb10e1..f5be9b0bb274 100644 --- a/source/isaaclab/isaaclab/controllers/rmp_flow.py +++ b/source/isaaclab/isaaclab/controllers/rmp_flow.py @@ -11,7 +11,7 @@ import torch # enable motion generation extensions -from isaacsim.core.utils.extensions import enable_extension, get_extension_path_from_name +from isaacsim.core.experimental.utils.app import enable_extension, get_extension_path enable_extension("isaacsim.robot_motion.lula") enable_extension("isaacsim.robot_motion.motion_generation") @@ -37,7 +37,7 @@ def _resolve_rmpflow_path(path: str) -> str: """ if path.startswith(_RMPFLOW_EXT_PREFIX): rel = path[len(_RMPFLOW_EXT_PREFIX) :] - ext_dir = get_extension_path_from_name(_RMPFLOW_EXT_NAME) + ext_dir = get_extension_path(_RMPFLOW_EXT_NAME) return os.path.join(ext_dir, rel) return path diff --git a/source/isaaclab/isaaclab/controllers/utils.py b/source/isaaclab/isaaclab/controllers/utils.py index fc091d324af8..879e82fe69d3 100644 --- a/source/isaaclab/isaaclab/controllers/utils.py +++ b/source/isaaclab/isaaclab/controllers/utils.py @@ -26,7 +26,7 @@ def convert_usd_to_urdf(usd_path: str, output_path: str, force_conversion: bool Returns: A tuple containing the paths to the URDF file and the mesh directory. """ - from isaacsim.core.utils.extensions import enable_extension + from isaacsim.core.experimental.utils.app import enable_extension enable_extension("isaacsim.asset.exporter.urdf") diff --git a/source/isaaclab/isaaclab/envs/common.py b/source/isaaclab/isaaclab/envs/common.py index f913005d1dbb..5da6f871361e 100644 --- a/source/isaaclab/isaaclab/envs/common.py +++ b/source/isaaclab/isaaclab/envs/common.py @@ -5,6 +5,8 @@ from __future__ import annotations +import warnings +from dataclasses import MISSING, fields from typing import Dict, Literal, TypeVar # noqa: UP035 import gymnasium as gym @@ -17,9 +19,25 @@ ## +def _viewer_cfg_value_matches_default(current: object, default: object) -> bool: + """Return True if ``current`` matches the dataclass field default (including list/tuple equivalence).""" + if current == default: + return True + if isinstance(current, (list, tuple)) and isinstance(default, (list, tuple)): + if len(current) != len(default): + return False + return all(a == b for a, b in zip(current, default, strict=True)) + return False + + @configclass class ViewerCfg: - """Configuration of the scene viewport camera.""" + """Configuration of the scene viewport camera. + + Note: + ViewerCfg is deprecated. In a future release, this config will be streamlined with + the KitVisualizerCfg. + """ eye: tuple[float, float, float] = (7.5, 7.5, 7.5) """Initial camera position (in m). Default is (7.5, 7.5, 7.5).""" @@ -67,6 +85,31 @@ class ViewerCfg: This quantity is only effective if :attr:`origin` is set to "asset_body". """ + def __post_init__(self) -> None: + # Dataclasses do not record which arguments were passed explicitly vs defaulted, and + # warning only on ``**kwargs`` would miss positional arguments. Comparing each field to + # its declared default catches any non-default effective configuration (including + # ``replace()`` and ``from_dict``), while keeping ``ViewerCfg()`` silent. + differing: list[str] = [] + for f in fields(self): + if not f.init: + continue + if f.default is not MISSING: + default_val = f.default + elif f.default_factory is not MISSING: + default_val = f.default_factory() + else: + continue + if not _viewer_cfg_value_matches_default(getattr(self, f.name), default_val): + differing.append(f.name) + if differing: + warnings.warn( + "ViewerCfg is deprecated. In a future release, this config will be streamlined with " + "the KitVisualizerCfg.", + DeprecationWarning, + stacklevel=2, + ) + ## # Types. diff --git a/source/isaaclab/isaaclab/envs/direct_marl_env.py b/source/isaaclab/isaaclab/envs/direct_marl_env.py index eb0a359e4f5b..b8fda8cf0986 100644 --- a/source/isaaclab/isaaclab/envs/direct_marl_env.py +++ b/source/isaaclab/isaaclab/envs/direct_marl_env.py @@ -36,6 +36,7 @@ from .direct_marl_env_cfg import DirectMARLEnvCfg from .ui import ViewportCameraController from .utils.spaces import sample_space, spec_to_gym_space +from .utils.video_recorder import VideoRecorder # import logger logger = logging.getLogger(__name__) @@ -150,10 +151,10 @@ def _init_sim(self, render_mode: str | None = None, **kwargs): # viewport is not available in other rendering modes so the function will throw a warning # FIXME: This needs to be fixed in the future when we unify the UI functionalities even for # non-rendering modes. - # Initialize when GUI is available OR when visualizers are active (headless rendering) - # Visualizers support camera updates via sim.set_camera_view() which forwards to all active visualizers - has_visualizers = bool(self.sim.get_setting("/isaaclab/visualizer")) - if self.sim.has_gui or has_visualizers: + # Initialize when a Kit viewport exists. ViewportCameraController uses omni.kit (renderer camera); + # skip in kitless Newton-only runs (e.g. --viz rerun) where no Kit app is running. + has_visualizers = self.sim.has_active_visualizers() + if (self.sim.has_gui or has_visualizers) and has_kit(): self.viewport_camera_controller = ViewportCameraController(self, self.cfg.viewer) else: self.viewport_camera_controller = None @@ -168,6 +169,19 @@ def _init_sim(self, render_mode: str | None = None, **kwargs): if "prestartup" in self.event_manager.available_modes: self.event_manager.apply(mode="prestartup") + # Instantiate the video recorder before sim.reset() so that any fallback Camera + # (used for state-based envs without an observation camera) is spawned into the USD + # stage and registered for the PHYSICS_READY callback before physics initialises. + # Forward render_mode so VideoRecorder only spawns fallback cameras when --video is active. + if self.cfg.video_recorder is not None: + self.cfg.video_recorder.env_render_mode = render_mode + vr = self.cfg.video_recorder + vr.eye = tuple(float(x) for x in self.cfg.viewer.eye) + vr.lookat = tuple(float(x) for x in self.cfg.viewer.lookat) + self.video_recorder: VideoRecorder = self.cfg.video_recorder.class_type(self.cfg.video_recorder, self.scene) + else: + self.video_recorder = None + # play the simulator to activate physics handles # note: this activates the physics simulation view that exposes TensorAPIs # note: when started in extension mode, first call sim.reset_async() and then initialize the managers @@ -203,6 +217,13 @@ def _init_sim(self, render_mode: str | None = None, **kwargs): # initialize data and constants # -- counter for simulation steps self._sim_step_counter = 0 + # -- controls camera/Kit rendering in step(). + # When False, the Kit app loop (app.update()) and camera/RTX sensor updates are + # skipped, but standalone visualizers (Newton, Rerun, Viser) continue to update. + # This is because Kit bundles camera rendering with its app loop and the two + # cannot be separated. Non-Kit visualizers have independent step() methods + # that do not trigger camera or GUI updates, so they remain active. + self.render_enabled: bool = True # -- counter for curriculum self.common_step_counter = 0 # -- init buffers @@ -377,6 +398,17 @@ def step(self, actions: dict[AgentID, ActionType]) -> EnvStepReturn: 5. Apply interval events if they are enabled. 6. Compute observations. + Rendering can be controlled per-step via :attr:`render_enabled`. + + When ``render_enabled`` is False: + + - The Kit app loop (``app.update()``) is **skipped**, which also disables + camera/RTX sensor rendering and GUI viewport updates. Kit bundles these + operations together, so they cannot be separated. + - Standalone visualizers (Newton, Rerun, Viser) **continue to update** + normally because their ``step()`` methods are independent of the Kit + app loop. + Args: actions: The actions to apply on the environment (keyed by the agent ID). Shape of individual tensors is (num_envs, action_dim). @@ -408,11 +440,11 @@ def step(self, actions: dict[AgentID, ActionType]) -> EnvStepReturn: self.scene.write_data_to_sim() # simulate self.sim.step(render=False) - # render between steps only if the GUI or an RTX sensor needs it - # note: we assume the render interval to be the shortest accepted rendering interval. - # If a camera needs rendering at a faster frequency, this will lead to unexpected behavior. + # render between steps only if the GUI or an RTX sensor needs it. + # When render_enabled is False, Kit visualizer (camera/GUI) is skipped + # but standalone visualizers (Newton, Rerun, Viser) still update. if self._sim_step_counter % self.cfg.sim.render_interval == 0 and is_rendering: - self.sim.render() + self.sim.render(skip_app_pumping=not self.render_enabled) # update buffers at sim dt self.scene.update(dt=self.physics_dt) @@ -521,33 +553,9 @@ def render(self, recompute: bool = False) -> np.ndarray | None: if self.render_mode == "human" or self.render_mode is None: return None elif self.render_mode == "rgb_array": - # check that if any render could have happened - if not self.sim.has_gui and not self.sim.has_offscreen_render: - raise RuntimeError( - f"Cannot render '{self.render_mode}' - no GUI and offscreen rendering not enabled." - " If running headless, make sure --enable_cameras is set." - ) - # create the annotator if it does not exist - if not hasattr(self, "_rgb_annotator"): - import omni.replicator.core as rep - - # create render product - self._render_product = rep.create.render_product( - self.cfg.viewer.cam_prim_path, self.cfg.viewer.resolution - ) - # create rgb annotator -- used to read data from the render product - self._rgb_annotator = rep.AnnotatorRegistry.get_annotator("rgb", device="cpu") - self._rgb_annotator.attach([self._render_product]) - # obtain the rgb data - rgb_data = self._rgb_annotator.get_data() - # convert to numpy array - rgb_data = np.frombuffer(rgb_data, dtype=np.uint8).reshape(*rgb_data.shape) - # return the rgb data - # note: initially the renderer is warming up and returns empty data - if rgb_data.size == 0: - return np.zeros((self.cfg.viewer.resolution[1], self.cfg.viewer.resolution[0], 3), dtype=np.uint8) - else: - return rgb_data[:, :, :3] + if self.video_recorder is None: + return None + return self.video_recorder.render_rgb_array() else: raise NotImplementedError( f"Render mode '{self.render_mode}' is not supported. Please use: {self.metadata['render_modes']}." diff --git a/source/isaaclab/isaaclab/envs/direct_marl_env_cfg.py b/source/isaaclab/isaaclab/envs/direct_marl_env_cfg.py index b22a6169d7a0..9f3e6a627b07 100644 --- a/source/isaaclab/isaaclab/envs/direct_marl_env_cfg.py +++ b/source/isaaclab/isaaclab/envs/direct_marl_env_cfg.py @@ -17,6 +17,7 @@ from isaaclab.utils.noise import NoiseModelCfg from .common import AgentID, SpaceType, ViewerCfg +from .utils.video_recorder_cfg import VideoRecorderCfg @configclass @@ -234,3 +235,6 @@ class DirectMARLEnvCfg: log_dir: str | None = None """Directory for logging experiment artifacts. Defaults to None, in which case no specific log directory is set.""" + + video_recorder: VideoRecorderCfg = VideoRecorderCfg() + """Configuration for video recording when ``render_mode="rgb_array"`` (i.e. ``--video``).""" diff --git a/source/isaaclab/isaaclab/envs/direct_rl_env.py b/source/isaaclab/isaaclab/envs/direct_rl_env.py index b362ac72bc21..9251eb0fe817 100644 --- a/source/isaaclab/isaaclab/envs/direct_rl_env.py +++ b/source/isaaclab/isaaclab/envs/direct_rl_env.py @@ -33,6 +33,7 @@ from .direct_rl_env_cfg import DirectRLEnvCfg from .ui import ViewportCameraController from .utils.spaces import sample_space, spec_to_gym_space +from .utils.video_recorder import VideoRecorder if has_kit(): import omni.kit.app @@ -155,10 +156,10 @@ def _init_sim(self, render_mode: str | None = None, **kwargs): # viewport is not available in other rendering modes so the function will throw a warning # FIXME: This needs to be fixed in the future when we unify the UI functionalities even for # non-rendering modes. - # Initialize when GUI is available OR when visualizers are active (headless rendering) - # Visualizers support camera updates via sim.set_camera_view() which forwards to all active visualizers - has_visualizers = bool(self.sim.get_setting("/isaaclab/visualizer")) - if self.sim.has_gui or has_visualizers: + # Initialize when a Kit viewport exists. ViewportCameraController uses omni.kit (renderer camera); + # skip in kitless Newton-only runs (e.g. --viz rerun) where no Kit app is running. + has_visualizers = self.sim.has_active_visualizers() + if (self.sim.has_gui or has_visualizers) and has_kit(): self.viewport_camera_controller = ViewportCameraController(self, self.cfg.viewer) else: self.viewport_camera_controller = None @@ -173,6 +174,20 @@ def _init_sim(self, render_mode: str | None = None, **kwargs): if "prestartup" in self.event_manager.available_modes: self.event_manager.apply(mode="prestartup") + # Instantiate the video recorder before sim.reset() so that any fallback Camera + # (used for state-based envs without an observation camera) is spawned into the USD + # stage and registered for the PHYSICS_READY callback before physics initialises. + # Forward render_mode so VideoRecorder only spawns fallback cameras when --video is active. + if self.cfg.video_recorder is not None: + self.cfg.video_recorder.env_render_mode = render_mode + # Perspective --video uses same eye/lookat as task viewer (Kit persp + Newton GL). + vr = self.cfg.video_recorder + vr.eye = tuple(float(x) for x in self.cfg.viewer.eye) + vr.lookat = tuple(float(x) for x in self.cfg.viewer.lookat) + self.video_recorder: VideoRecorder = self.cfg.video_recorder.class_type(self.cfg.video_recorder, self.scene) + else: + self.video_recorder = None + # play the simulator to activate physics handles # note: this activates the physics simulation view that exposes TensorAPIs # note: when started in extension mode, first call sim.reset_async() and then initialize the managers @@ -208,6 +223,13 @@ def _init_sim(self, render_mode: str | None = None, **kwargs): # initialize data and constants # -- counter for simulation steps self._sim_step_counter = 0 + # -- controls camera/Kit rendering in step(). + # When False, the Kit app loop (app.update()) and camera/RTX sensor updates are + # skipped, but standalone visualizers (Newton, Rerun, Viser) continue to update. + # This is because Kit bundles camera rendering with its app loop and the two + # cannot be separated. Non-Kit visualizers have independent step() methods + # that do not trigger camera or GUI updates, so they remain active. + self.render_enabled: bool = True # -- counter for curriculum self.common_step_counter = 0 # -- init buffers @@ -370,6 +392,18 @@ def step(self, action: torch.Tensor) -> VecEnvStepReturn: 5. Apply interval events if they are enabled. 6. Compute observations. + Rendering can be controlled per-step via :attr:`render_enabled`. + + When ``render_enabled`` is False: + + - The Kit app loop (``app.update()``) is **skipped**, which also disables + camera/RTX sensor rendering and GUI viewport updates. Kit bundles these + operations together, so they cannot be separated. + - Standalone visualizers (Newton, Rerun, Viser) **continue to update** + normally because their ``step()`` methods are independent of the Kit + app loop. + - Post-reset re-renders for RTX sensors are also skipped. + Args: action: The actions to apply on the environment. Shape is (num_envs, action_dim). @@ -397,11 +431,11 @@ def step(self, action: torch.Tensor) -> VecEnvStepReturn: self.scene.write_data_to_sim() # simulate self.sim.step(render=False) - # render between steps only if the GUI or an RTX sensor needs it - # note: we assume the render interval to be the shortest accepted rendering interval. - # If a camera needs rendering at a faster frequency, this will lead to unexpected behavior. + # render between steps only if the GUI or an RTX sensor needs it. + # When render_enabled is False, Kit visualizer (camera/GUI) is skipped + # but standalone visualizers (Newton, Rerun, Viser) still update. if self._sim_step_counter % self.cfg.sim.render_interval == 0 and is_rendering: - self.sim.render() + self.sim.render(skip_app_pumping=not self.render_enabled) # update buffers at sim dt self.scene.update(dt=self.physics_dt) @@ -419,7 +453,7 @@ def step(self, action: torch.Tensor) -> VecEnvStepReturn: if len(reset_env_ids) > 0: self._reset_idx(reset_env_ids) # if sensors are added to the scene, make sure we render to reflect changes in reset - if self.has_rtx_sensors and self.cfg.num_rerenders_on_reset > 0: + if self.render_enabled and is_rendering and self.has_rtx_sensors and self.cfg.num_rerenders_on_reset > 0: for _ in range(self.cfg.num_rerenders_on_reset): self.sim.render() @@ -489,33 +523,9 @@ def render(self, recompute: bool = False) -> np.ndarray | None: if self.render_mode == "human" or self.render_mode is None: return None elif self.render_mode == "rgb_array": - # check that if any render could have happened - if not self.sim.has_gui and not self.sim.has_offscreen_render: - raise RuntimeError( - f"Cannot render '{self.render_mode}' - no GUI and offscreen rendering not enabled." - " If running headless, make sure --enable_cameras is set." - ) - # create the annotator if it does not exist - if not hasattr(self, "_rgb_annotator"): - import omni.replicator.core as rep - - # create render product - self._render_product = rep.create.render_product( - self.cfg.viewer.cam_prim_path, self.cfg.viewer.resolution - ) - # create rgb annotator -- used to read data from the render product - self._rgb_annotator = rep.AnnotatorRegistry.get_annotator("rgb", device="cpu") - self._rgb_annotator.attach([self._render_product]) - # obtain the rgb data - rgb_data = self._rgb_annotator.get_data() - # convert to numpy array - rgb_data = np.frombuffer(rgb_data, dtype=np.uint8).reshape(*rgb_data.shape) - # return the rgb data - # note: initially the renerer is warming up and returns empty data - if rgb_data.size == 0: - return np.zeros((self.cfg.viewer.resolution[1], self.cfg.viewer.resolution[0], 3), dtype=np.uint8) - else: - return rgb_data[:, :, :3] + if self.video_recorder is None: + return None + return self.video_recorder.render_rgb_array() else: raise NotImplementedError( f"Render mode '{self.render_mode}' is not supported. Please use: {self.metadata['render_modes']}." diff --git a/source/isaaclab/isaaclab/envs/direct_rl_env_cfg.py b/source/isaaclab/isaaclab/envs/direct_rl_env_cfg.py index fd40b3104c21..69b917e1d01f 100644 --- a/source/isaaclab/isaaclab/envs/direct_rl_env_cfg.py +++ b/source/isaaclab/isaaclab/envs/direct_rl_env_cfg.py @@ -16,6 +16,7 @@ from isaaclab.utils.noise import NoiseModelCfg from .common import SpaceType, ViewerCfg +from .utils.video_recorder_cfg import VideoRecorderCfg @configclass @@ -254,3 +255,6 @@ class DirectRLEnvCfg: log_dir: str | None = None """Directory for logging experiment artifacts. Defaults to None, in which case no specific log directory is set.""" + + video_recorder: VideoRecorderCfg = VideoRecorderCfg() + """Configuration for video recording when ``render_mode="rgb_array"`` (i.e. ``--video``).""" diff --git a/source/isaaclab/isaaclab/envs/leapp_deployment_env.py b/source/isaaclab/isaaclab/envs/leapp_deployment_env.py new file mode 100644 index 000000000000..fe81e8f82e5f --- /dev/null +++ b/source/isaaclab/isaaclab/envs/leapp_deployment_env.py @@ -0,0 +1,449 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Deployment environment that runs LEAPP-exported policies in simulation. + +This environment bypasses all Isaac Lab managers (observation, action, reward, etc.) +and instead wires scene entity data properties and ``CommandManager`` outputs directly +to a LEAPP ``InferenceManager``, then writes the model outputs back to the +corresponding scene entities. All I/O resolution is driven by the +``isaaclab_connection`` field in the LEAPP YAML. +""" + +from __future__ import annotations + +import inspect +import logging +from dataclasses import dataclass +from typing import Any, cast + +import torch +import yaml + +try: + from leapp import InferenceManager +except ImportError as e: + raise ImportError("LEAPP package is required for policy deployment testing. Install with: pip install leapp") from e + +from isaaclab.managers import CommandManager, EventManager +from isaaclab.scene import InteractiveScene +from isaaclab.sim import SimulationContext +from isaaclab.sim.utils.stage import use_stage +from isaaclab.utils.configclass import resolve_cfg_presets + +from .ui import ViewportCameraController + +logger = logging.getLogger(__name__) + + +# ══════════════════════════════════════════════════════════════════ +# I/O spec dataclasses +# ══════════════════════════════════════════════════════════════════ + + +@dataclass +class StateInputSpec: + """Read a property from a scene entity's data object.""" + + entity_name: str + property_name: str + joint_ids: list[int] | None = None + + +@dataclass +class CommandInputSpec: + """Read a command tensor from ``CommandManager``.""" + + command_term_name: str + + +@dataclass +class WriteOutputSpec: + """Write a tensor to a scene entity method, optionally indexed by joint.""" + + entity_name: str + method_name: str + value_param: str + joint_ids: list[int] | None = None + + +# ══════════════════════════════════════════════════════════════════ +# Connection-string helpers +# ══════════════════════════════════════════════════════════════════ + + +def _resolve_joint_ids(element_names: list | None, entity: Any) -> list[int] | None: + """Convert ``element_names[0]`` joint names to integer joint indices. + + Args: + element_names: LEAPP element-name metadata for the tensor, or ``None`` + when the tensor does not define named elements. + entity: Scene entity that may provide ``joint_names`` and + ``find_joints()`` for name-to-index resolution. + + Returns: + Joint indices matching ``element_names[0]``, or ``None`` when no + slicing is needed because all joints are selected, the tensor is not + joint-indexed, or the entity does not support joint lookup. + """ + if element_names is None or not hasattr(entity, "find_joints"): + return None + + # leapp tensor semantics will always store the array in a nested list of lists. + # NOTE: this is added in explicitly to handle partial joint application. currently + # this environment does not handle element reordering yet. Thus, this function + # is specialized to handle joints, hence reading index 0. + joint_names = element_names[0] + if not isinstance(joint_names, list) or not joint_names: + return None + entity_joint_names = list(entity.joint_names) + # Only resolve indices when the leading element-name axis actually refers + # to a subset of this articulation's joints. Other tensors can use axis + # labels like ["x", "y", "z"] or body names in the first axis. + matching_joint_names = [name for name in joint_names if name in entity_joint_names] + if not matching_joint_names: + return None + if len(matching_joint_names) != len(joint_names): + raise ValueError( + f"LEAPP element names mix joint and non-joint labels for an articulation-backed tensor: {joint_names}" + ) + if joint_names == entity_joint_names: + return None + joint_ids, _ = entity.find_joints(joint_names, preserve_order=True) + return joint_ids + + +def _first_param_name(method: Any) -> str: + """Return the name of the first non-self parameter of *method*. + + Expects a bound method — ``inspect.signature`` on a bound method + already excludes ``self``, so ``params[0]`` is the first real parameter. + + Args: + method: Bound method whose first callable parameter should be + inspected. + + Returns: + The name of the first non-``self`` parameter. + """ + params = list(inspect.signature(method).parameters.values()) + if not params: + raise TypeError(f"{method} has no parameters") + return params[0].name + + +# ══════════════════════════════════════════════════════════════════ +# LeappDeploymentEnv +# ══════════════════════════════════════════════════════════════════ + + +class LeappDeploymentEnv: + """Runs a LEAPP-exported policy in an Isaac Lab scene. + + The environment sets up the simulation scene and physics from a standard + Isaac Lab config, then wires raw sensor/command data to a LEAPP + ``InferenceManager`` and writes the model outputs back to the corresponding + scene entities. + + I/O wiring is driven entirely by the ``isaaclab_connection`` metadata field + in the LEAPP YAML. Each connection string encodes the type of access, the + scene entity name, and the property or method to call: + + - ``state:{entity}:{property}`` -- read ``scene[entity].data.{property}`` + - ``command:{name}`` -- read ``command_manager.get_command(name)`` + - ``write:{entity}:{method}`` -- call ``scene[entity].{method}(tensor, ...)`` + + No observation, action, reward, termination, or curriculum managers are used. + The LEAPP model already contains all pre/post-processing. + """ + + def __init__(self, cfg: Any, leapp_yaml_path: str): + """Initialize the deployment environment. + + Args: + cfg: A ``ManagerBasedRLEnvCfg`` (or compatible) task config. + leapp_yaml_path: Path to the LEAPP ``.yaml`` pipeline description. + """ + + cfg.scene.num_envs = 1 + cfg.validate() + resolve_cfg_presets(cfg) + self.cfg = cfg + self._is_closed = False + self._leapp_yaml_path = leapp_yaml_path + self._step_count = 0 + self._sim_step_counter = 0 + + # ── Simulation + scene ──────────────────────────────────── + self.sim = SimulationContext(cfg.sim) + if "cuda" in self.sim.device: + torch.cuda.set_device(self.sim.device) + + with use_stage(self.sim.stage): + self.scene = InteractiveScene(cfg.scene) + with use_stage(self.sim.stage): + self.sim.reset() + self.scene.update(dt=self.physics_dt) + self.has_rtx_sensors = bool(self.sim.get_setting("/isaaclab/render/rtx_sensors")) + + # Match the standard env initialization path for viewport camera setup. + has_visualizers = bool(self.sim.get_setting("/isaaclab/visualizer")) + if self.sim.has_gui or has_visualizers: + self.viewport_camera_controller = ViewportCameraController(cast(Any, self), self.cfg.viewer) + else: + self.viewport_camera_controller = None + + # ── EventManager (optional, for resets) ─────────────────── + self.event_manager: EventManager | None = None + if hasattr(cfg, "events") and cfg.events is not None: + self.event_manager = EventManager(cfg.events, cast(Any, self)) + + # ── CommandManager (optional, for command/* inputs) ─────── + self.command_manager: CommandManager | None = None + if hasattr(cfg, "commands") and cfg.commands is not None: + self.command_manager = CommandManager(cfg.commands, cast(Any, self)) + + # ── LEAPP InferenceManager ──────────────────────────────── + self.inference = InferenceManager(leapp_yaml_path) + + # ── Parse YAML and resolve I/O mappings ─────────────────── + with open(leapp_yaml_path) as f: + self._leapp_desc = yaml.safe_load(f) + self._input_mapping: dict[str, StateInputSpec | CommandInputSpec] = {} + self._output_mapping: dict[str, WriteOutputSpec] = {} + self._resolve_io() + + logger.info( + "LeappDeploymentEnv ready — %d inputs, %d outputs mapped", + len(self._input_mapping), + len(self._output_mapping), + ) + + if self.sim.has_gui and getattr(self.cfg, "ui_window_class_type", None) is not None: + self._window = self.cfg.ui_window_class_type(self, window_name="IsaacLab") + else: + self._window = None + + # ── Properties ──────────────────────────────────────────────── + + @property + def num_envs(self) -> int: + return 1 + + @property + def physics_dt(self) -> float: + return self.cfg.sim.dt + + @property + def step_dt(self) -> float: + return self.cfg.sim.dt * self.cfg.decimation + + @property + def device(self) -> str: + return self.sim.device + + # ── I/O Resolution ──────────────────────────────────────────── + + def _resolve_io(self): + """Build ``_input_mapping`` and ``_output_mapping`` from LEAPP metadata. + + Parses the ``isaaclab_connection`` field in the loaded LEAPP YAML and + resolves each declared input/output to the corresponding scene entity, + command term, and optional joint index selection. + """ + pipeline = self._leapp_desc["pipeline"] + + for node_name, input_names in pipeline["inputs"].items(): + node = self.inference.nodes[node_name] + desc_by_name = {d["name"]: d for d in node.input_descriptions} + for input_name in input_names: + desc = desc_by_name[input_name] + connection = desc.get("isaaclab_connection") + if connection is None: + continue + key = f"{node_name}/{input_name}" + parts = connection.split(":") + conn_type = parts[0] + + if conn_type == "state": + entity_name, prop_name = parts[1], parts[2] + entity = self.scene[entity_name] + jids = _resolve_joint_ids(desc.get("element_names"), entity) + self._input_mapping[key] = StateInputSpec( + entity_name=entity_name, + property_name=prop_name, + joint_ids=jids, + ) + elif conn_type == "command": + command_name = parts[1] + if self.command_manager is None: + raise RuntimeError( + f"LEAPP input '{key}' requires command '{command_name}' but no " + "CommandManager is available (cfg.commands is None)." + ) + self._input_mapping[key] = CommandInputSpec(command_term_name=command_name) + else: + logger.warning("Unknown connection type '%s' for input '%s'", conn_type, key) + + for node_name, output_names in pipeline["outputs"].items(): + node = self.inference.nodes[node_name] + desc_by_name = {d["name"]: d for d in node.output_descriptions} + for output_name in output_names: + desc = desc_by_name[output_name] + connection = desc.get("isaaclab_connection") + if connection is None: + continue + key = f"{node_name}/{output_name}" + parts = connection.split(":") + conn_type = parts[0] + + if conn_type == "write": + entity_name, method_name = parts[1], parts[2] + entity = self.scene[entity_name] + jids = _resolve_joint_ids(desc.get("element_names"), entity) + value_param = _first_param_name(getattr(entity, method_name)) + self._output_mapping[key] = WriteOutputSpec( + entity_name=entity_name, + method_name=method_name, + value_param=value_param, + joint_ids=jids, + ) + else: + logger.warning("Unknown connection type '%s' for output '%s'", conn_type, key) + + # ── Read / Write ────────────────────────────────────────────── + + def _read_inputs(self) -> dict[str, torch.Tensor]: + """Read all mapped inputs from scene entities and command manager. + + Returns: + A mapping from ``"node_name/tensor_name"`` to the tensor value that + should be passed to the LEAPP inference pipeline. + """ + inputs: dict[str, torch.Tensor] = {} + for key, spec in self._input_mapping.items(): + if isinstance(spec, StateInputSpec): + entity = self.scene[spec.entity_name] + value = getattr(entity.data, spec.property_name).torch + if spec.joint_ids is not None: + value = value[:, spec.joint_ids] + inputs[key] = value + elif isinstance(spec, CommandInputSpec): + command_manager = self.command_manager + assert command_manager is not None + inputs[key] = command_manager.get_command(spec.command_term_name) + return inputs + + def _write_outputs(self, outputs: dict[str, torch.Tensor]): + """Write model outputs to scene entities. + + Args: + outputs: Model outputs keyed by ``"node_name/tensor_name"`` as + returned by :meth:`step` and ``InferenceManager.run_policy()``. + """ + for key, tensor in outputs.items(): + spec = self._output_mapping.get(key) + if spec is None: + continue + entity = self.scene[spec.entity_name] + method = getattr(entity, spec.method_name) + if spec.joint_ids is not None: + method(**{spec.value_param: tensor, "joint_ids": spec.joint_ids}) + else: + method(**{spec.value_param: tensor}) + + # ── Public API ──────────────────────────────────────────────── + + def reset(self) -> dict[str, torch.Tensor]: + """Reset the scene and inference state. + + Returns: + The initial input tensors (for logging / debugging). + """ + env_ids = [0] + + self.scene.reset(env_ids) + + if self.event_manager is not None and "reset" in self.event_manager.available_modes: + self.event_manager.apply(mode="reset", env_ids=env_ids, global_env_step_count=self._step_count) + if self.command_manager is not None: + self.command_manager.reset(env_ids) + + self.scene.write_data_to_sim() + self.sim.forward() + self.scene.update(dt=self.physics_dt) + + # If RTX sensors are present, rerender after reset to refresh their outputs. + if self.has_rtx_sensors and getattr(self.cfg, "num_rerenders_on_reset", 0) > 0: + for _ in range(self.cfg.num_rerenders_on_reset): + self.sim.render() + + if getattr(self.cfg, "wait_for_textures", False) and self.has_rtx_sensors: + assets_loading = getattr(self.sim.physics_manager, "assets_loading", None) + if callable(assets_loading): + while assets_loading(): + self.sim.render() + + self.inference.reset() + + return self._read_inputs() + + def step(self, external_inputs: dict[str, torch.Tensor] | None = None) -> dict[str, torch.Tensor]: + """Run one environment step: read -> infer -> write -> physics. + + Args: + external_inputs: Optional overrides keyed by ``"ModelName/input_name"``. + Takes precedence over auto-resolved state/command values. + + Returns: + The dict of pipeline outputs from ``InferenceManager.run_policy()``. + """ + self._step_count += 1 + + # 1. Update commands + if self.command_manager is not None: + self.command_manager.compute(dt=self.step_dt) + + # 2. Read inputs + inputs = self._read_inputs() + + # 3. Merge external overrides + if external_inputs is not None: + inputs.update(external_inputs) + + # 4. Infer + with torch.inference_mode(): + outputs = self.inference.run_policy(inputs) + + # 5. Write outputs to scene entities + self._write_outputs(outputs) + + # 6. Decimation loop + is_rendering = self.sim.is_rendering + for _ in range(self.cfg.decimation): + self._sim_step_counter += 1 + self.scene.write_data_to_sim() + self.sim.step(render=False) + if self._sim_step_counter % self.cfg.sim.render_interval == 0 and is_rendering: + self.sim.render() + self.scene.update(dt=self.physics_dt) + + return outputs + + def close(self): + """Clean up the environment and release simulator-owned resources.""" + if not self._is_closed: + self.sim.stop() + if self.command_manager is not None: + del self.command_manager + if self.event_manager is not None: + del self.event_manager + del self.scene + if self.viewport_camera_controller is not None: + del self.viewport_camera_controller + self.sim.clear_instance() + if self._window is not None: + self._window = None + self._is_closed = True diff --git a/source/isaaclab/isaaclab/envs/manager_based_env.py b/source/isaaclab/isaaclab/envs/manager_based_env.py index 996e88216e17..92db9ad117b5 100644 --- a/source/isaaclab/isaaclab/envs/manager_based_env.py +++ b/source/isaaclab/isaaclab/envs/manager_based_env.py @@ -21,11 +21,13 @@ from isaaclab.utils.configclass import resolve_cfg_presets from isaaclab.utils.seed import configure_seed from isaaclab.utils.timer import Timer +from isaaclab.utils.version import has_kit from .common import VecEnvObs from .manager_based_env_cfg import ManagerBasedEnvCfg from .ui import ViewportCameraController from .utils.io_descriptors import export_articulations_data, export_scene_data +from .utils.video_recorder import VideoRecorder # import logger logger = logging.getLogger(__name__) @@ -151,6 +153,14 @@ def _init_sim(self): # counter for simulation steps self._sim_step_counter = 0 + # -- controls camera/Kit rendering in step(). + # When False, the Kit app loop (app.update()) and camera/RTX sensor updates are + # skipped, but standalone visualizers (Newton, Rerun, Viser) continue to update. + # This is because Kit bundles camera rendering with its app loop and the two + # cannot be separated. Non-Kit visualizers have independent step() methods + # that do not trigger camera or GUI updates, so they remain active. + self.render_enabled: bool = True + # allocate dictionary to store metrics self.extras = {} @@ -165,10 +175,10 @@ def _init_sim(self): # viewport is not available in other rendering modes so the function will throw a warning # FIXME: This needs to be fixed in the future when we unify the UI functionalities even for # non-rendering modes. - # Initialize when GUI is available OR when visualizers are active (headless rendering) - # Visualizers support camera updates via sim.set_camera_view() which forwards to all active visualizers - has_visualizers = bool(self.sim.get_setting("/isaaclab/visualizer")) - if self.sim.has_gui or has_visualizers: + # Initialize when a Kit viewport exists. ViewportCameraController uses omni.kit (renderer camera); + # skip in kitless Newton-only runs (e.g. --viz rerun) where no Kit app is running. + has_visualizers = self.sim.has_active_visualizers() + if (self.sim.has_gui or has_visualizers) and has_kit(): self.viewport_camera_controller = ViewportCameraController(self, self.cfg.viewer) else: self.viewport_camera_controller = None @@ -182,6 +192,16 @@ def _init_sim(self): if "prestartup" in self.event_manager.available_modes: self.event_manager.apply(mode="prestartup") + # Instantiate the video recorder before sim.reset() so that any fallback Camera + # (used for state-based envs without an observation camera) is spawned into the USD + # stage and registered for the PHYSICS_READY callback before physics initialises. + # env_render_mode and eye/lookat are forwarded by subclasses (e.g. ManagerBasedRLEnv) + # into cfg.video_recorder before calling super().__init__(). + if self.cfg.video_recorder is not None: + self.video_recorder: VideoRecorder = self.cfg.video_recorder.class_type(self.cfg.video_recorder, self.scene) + else: + self.video_recorder = None + # play the simulator to activate physics handles # note: this activates the physics simulation view that exposes TensorAPIs # note: when started in extension mode, first call sim.reset_async() and then initialize the managers @@ -482,6 +502,17 @@ def step(self, action: torch.Tensor) -> tuple[VecEnvObs, dict]: simulation steps per environment step) and the :attr:`ManagerBasedEnvCfg.sim.dt` (physics time-step). Based on these parameters, the environment time-step is computed as the product of the two. + Rendering can be controlled per-step via :attr:`render_enabled`. + + When ``render_enabled`` is False: + + - The Kit app loop (``app.update()``) is **skipped**, which also disables + camera/RTX sensor rendering and GUI viewport updates. Kit bundles these + operations together, so they cannot be separated. + - Standalone visualizers (Newton, Rerun, Viser) **continue to update** + normally because their ``step()`` methods are independent of the Kit + app loop. + Args: action: The actions to apply on the environment. Shape is (num_envs, action_dim). @@ -506,11 +537,11 @@ def step(self, action: torch.Tensor) -> tuple[VecEnvObs, dict]: self.scene.write_data_to_sim() # simulate self.sim.step(render=False) - # render between steps only if the GUI or an RTX sensor needs it - # note: we assume the render interval to be the shortest accepted rendering interval. - # If a camera needs rendering at a faster frequency, this will lead to unexpected behavior. + # render between steps only if the GUI or an RTX sensor needs it. + # When render_enabled is False, Kit visualizer (camera/GUI) is skipped + # but standalone visualizers (Newton, Rerun, Viser) still update. if self._sim_step_counter % self.cfg.sim.render_interval == 0 and is_rendering: - self.sim.render() + self.sim.render(skip_app_pumping=not self.render_enabled) # update buffers at sim dt self.scene.update(dt=self.physics_dt) diff --git a/source/isaaclab/isaaclab/envs/manager_based_env_cfg.py b/source/isaaclab/isaaclab/envs/manager_based_env_cfg.py index 24a88d5e72c0..843701b03fd1 100644 --- a/source/isaaclab/isaaclab/envs/manager_based_env_cfg.py +++ b/source/isaaclab/isaaclab/envs/manager_based_env_cfg.py @@ -26,6 +26,7 @@ from isaaclab.utils import configclass from .common import ViewerCfg +from .utils.video_recorder_cfg import VideoRecorderCfg @configclass @@ -163,3 +164,6 @@ class ManagerBasedEnvCfg: log_dir: str | None = None """Directory for logging experiment artifacts. Defaults to None, in which case no specific log directory is set.""" + + video_recorder: VideoRecorderCfg = VideoRecorderCfg() + """Configuration for video recording when ``render_mode="rgb_array"`` (i.e. ``--video``).""" diff --git a/source/isaaclab/isaaclab/envs/manager_based_rl_env.py b/source/isaaclab/isaaclab/envs/manager_based_rl_env.py index d08b7e3be3a7..3e48dcd19f88 100644 --- a/source/isaaclab/isaaclab/envs/manager_based_rl_env.py +++ b/source/isaaclab/isaaclab/envs/manager_based_rl_env.py @@ -76,6 +76,14 @@ def __init__(self, cfg: ManagerBasedRLEnvCfg, render_mode: str | None = None, ** # initialize the episode length buffer BEFORE loading the managers to use it in mdp functions. self.episode_length_buf = torch.zeros(cfg.scene.num_envs, device=cfg.sim.device, dtype=torch.long) + # Forward render_mode and viewer camera to VideoRecorderCfg before super().__init__() + # creates the VideoRecorder, so fallback cameras are only spawned when --video is active + # (env_render_mode="rgb_array") and the perspective view matches the task viewport. + if cfg.video_recorder is not None: + cfg.video_recorder.env_render_mode = render_mode + cfg.video_recorder.eye = tuple(float(x) for x in cfg.viewer.eye) + cfg.video_recorder.lookat = tuple(float(x) for x in cfg.viewer.lookat) + # initialize the base class to setup the scene. super().__init__(cfg=cfg) # store the render mode @@ -163,6 +171,18 @@ def step(self, action: torch.Tensor) -> VecEnvStepReturn: 6. Compute the observations. 7. Return the observations, rewards, resets and extras. + Rendering can be controlled per-step via :attr:`render_enabled`. + + When ``render_enabled`` is False: + + - The Kit app loop (``app.update()``) is **skipped**, which also disables + camera/RTX sensor rendering and GUI viewport updates. Kit bundles these + operations together, so they cannot be separated. + - Standalone visualizers (Newton, Rerun, Viser) **continue to update** + normally because their ``step()`` methods are independent of the Kit + app loop. + - Post-reset re-renders for RTX sensors are also skipped. + Args: action: The actions to apply on the environment. Shape is (num_envs, action_dim). @@ -188,11 +208,11 @@ def step(self, action: torch.Tensor) -> VecEnvStepReturn: # simulate self.sim.step(render=False) self.recorder_manager.record_post_physics_decimation_step() - # render between steps only if the GUI or an RTX sensor needs it - # note: we assume the render interval to be the shortest accepted rendering interval. - # If a camera needs rendering at a faster frequency, this will lead to unexpected behavior. + # render between steps only if the GUI or an RTX sensor needs it. + # When render_enabled is False, Kit visualizer (camera/GUI) is skipped + # but standalone visualizers (Newton, Rerun, Viser) still update. if self._sim_step_counter % self.cfg.sim.render_interval == 0 and is_rendering: - self.sim.render() + self.sim.render(skip_app_pumping=not self.render_enabled) # update buffers at sim dt self.scene.update(dt=self.physics_dt) @@ -221,7 +241,7 @@ def step(self, action: torch.Tensor) -> VecEnvStepReturn: self._reset_idx(reset_env_ids) # if sensors are added to the scene, make sure we render to reflect changes in reset - if self.has_rtx_sensors and self.cfg.num_rerenders_on_reset > 0: + if self.render_enabled and is_rendering and self.has_rtx_sensors and self.cfg.num_rerenders_on_reset > 0: for _ in range(self.cfg.num_rerenders_on_reset): self.sim.render() @@ -270,35 +290,9 @@ def render(self, recompute: bool = False) -> np.ndarray | None: if self.render_mode == "human" or self.render_mode is None: return None elif self.render_mode == "rgb_array": - # check that if any render could have happened - # Check for GUI, offscreen rendering, or visualizers - has_visualizers = bool(self.sim.get_setting("/isaaclab/visualizer")) - if not (self.sim.has_gui or self.sim.has_offscreen_render or has_visualizers): - raise RuntimeError( - f"Cannot render '{self.render_mode}' - no GUI and offscreen rendering not enabled." - " If running headless, make sure --enable_cameras is set." - ) - # create the annotator if it does not exist - if not hasattr(self, "_rgb_annotator"): - import omni.replicator.core as rep - - # create render product - self._render_product = rep.create.render_product( - self.cfg.viewer.cam_prim_path, self.cfg.viewer.resolution - ) - # create rgb annotator -- used to read data from the render product - self._rgb_annotator = rep.AnnotatorRegistry.get_annotator("rgb", device="cpu") - self._rgb_annotator.attach([self._render_product]) - # obtain the rgb data - rgb_data = self._rgb_annotator.get_data() - # convert to numpy array - rgb_data = np.frombuffer(rgb_data, dtype=np.uint8).reshape(*rgb_data.shape) - # return the rgb data - # note: initially the renerer is warming up and returns empty data - if rgb_data.size == 0: - return np.zeros((self.cfg.viewer.resolution[1], self.cfg.viewer.resolution[0], 3), dtype=np.uint8) - else: - return rgb_data[:, :, :3] + if self.video_recorder is None: + return None + return self.video_recorder.render_rgb_array() else: raise NotImplementedError( f"Render mode '{self.render_mode}' is not supported. Please use: {self.metadata['render_modes']}." diff --git a/source/isaaclab/isaaclab/envs/manager_based_rl_mimic_env.py b/source/isaaclab/isaaclab/envs/manager_based_rl_mimic_env.py index 8518d716332e..d32284d029de 100644 --- a/source/isaaclab/isaaclab/envs/manager_based_rl_mimic_env.py +++ b/source/isaaclab/isaaclab/envs/manager_based_rl_mimic_env.py @@ -124,6 +124,7 @@ def get_object_poses(self, env_ids: Sequence[int] | None = None): ) return object_pose_matrix + @optional_method def get_subtask_start_signals(self, env_ids: Sequence[int] | None = None) -> dict[str, torch.Tensor]: """ Gets a dictionary of start signal flags for each subtask in a task. The flag is 1 @@ -140,6 +141,7 @@ def get_subtask_start_signals(self, env_ids: Sequence[int] | None = None) -> dic """ raise NotImplementedError + @optional_method def get_subtask_term_signals(self, env_ids: Sequence[int] | None = None) -> dict[str, torch.Tensor]: """ Gets a dictionary of termination signal flags for each subtask in a task. The flag is 1 diff --git a/source/isaaclab/isaaclab/envs/mdp/__init__.pyi b/source/isaaclab/isaaclab/envs/mdp/__init__.pyi index 399035f2c09c..5b7e28e29e4a 100644 --- a/source/isaaclab/isaaclab/envs/mdp/__init__.pyi +++ b/source/isaaclab/isaaclab/envs/mdp/__init__.pyi @@ -55,6 +55,7 @@ __all__ = [ "randomize_physics_scene_gravity", "randomize_rigid_body_collider_offsets", "randomize_rigid_body_com", + "randomize_rigid_body_inertia", "randomize_rigid_body_mass", "randomize_rigid_body_material", "randomize_rigid_body_scale", @@ -80,8 +81,8 @@ __all__ = [ "image_features", "imu_ang_vel", "imu_lin_acc", - "imu_orientation", - "imu_projected_gravity", + "pva_orientation", + "pva_projected_gravity", "joint_effort", "joint_pos", "joint_pos_limit_normalized", @@ -195,6 +196,7 @@ from .events import ( randomize_physics_scene_gravity, randomize_rigid_body_collider_offsets, randomize_rigid_body_com, + randomize_rigid_body_inertia, randomize_rigid_body_mass, randomize_rigid_body_material, randomize_rigid_body_scale, @@ -222,8 +224,8 @@ from .observations import ( image_features, imu_ang_vel, imu_lin_acc, - imu_orientation, - imu_projected_gravity, + pva_orientation, + pva_projected_gravity, joint_effort, joint_pos, joint_pos_limit_normalized, diff --git a/source/isaaclab/isaaclab/envs/mdp/actions/joint_actions.py b/source/isaaclab/isaaclab/envs/mdp/actions/joint_actions.py index 8fbeb996bfa5..ca0041213c78 100644 --- a/source/isaaclab/isaaclab/envs/mdp/actions/joint_actions.py +++ b/source/isaaclab/isaaclab/envs/mdp/actions/joint_actions.py @@ -10,7 +10,6 @@ from typing import TYPE_CHECKING import torch -import warp as wp import isaaclab.utils.string as string_utils from isaaclab.assets.articulation import Articulation @@ -193,7 +192,7 @@ def __init__(self, cfg: actions_cfg.JointPositionActionCfg, env: ManagerBasedEnv super().__init__(cfg, env) # use default joint positions as offset if cfg.use_default_offset: - self._offset = wp.to_torch(self._asset.data.default_joint_pos)[:, self._joint_ids].clone() + self._offset = self._asset.data.default_joint_pos.torch[:, self._joint_ids].clone() def apply_actions(self): # set position targets @@ -228,7 +227,7 @@ def __init__(self, cfg: actions_cfg.RelativeJointPositionActionCfg, env: Manager def apply_actions(self): # add current joint positions to the processed actions - current_actions = self.processed_actions + wp.to_torch(self._asset.data.joint_pos)[:, self._joint_ids] + current_actions = self.processed_actions + self._asset.data.joint_pos.torch[:, self._joint_ids] # set position targets self._asset.set_joint_position_target_index(target=current_actions, joint_ids=self._joint_ids) @@ -244,7 +243,7 @@ def __init__(self, cfg: actions_cfg.JointVelocityActionCfg, env: ManagerBasedEnv super().__init__(cfg, env) # use default joint velocity as offset if cfg.use_default_offset: - self._offset = wp.to_torch(self._asset.data.default_joint_vel)[:, self._joint_ids].clone() + self._offset = self._asset.data.default_joint_vel.torch[:, self._joint_ids].clone() def apply_actions(self): # set joint velocity targets diff --git a/source/isaaclab/isaaclab/envs/mdp/actions/joint_actions_to_limits.py b/source/isaaclab/isaaclab/envs/mdp/actions/joint_actions_to_limits.py index 488975e08187..7b77700cc6e3 100644 --- a/source/isaaclab/isaaclab/envs/mdp/actions/joint_actions_to_limits.py +++ b/source/isaaclab/isaaclab/envs/mdp/actions/joint_actions_to_limits.py @@ -10,7 +10,6 @@ from typing import TYPE_CHECKING import torch -import warp as wp import isaaclab.utils.math as math_utils import isaaclab.utils.string as string_utils @@ -169,8 +168,8 @@ def process_actions(self, actions: torch.Tensor): # rescale within the joint limits actions = math_utils.unscale_transform( actions, - wp.to_torch(self._asset.data.soft_joint_pos_limits)[:, self._joint_ids, 0], - wp.to_torch(self._asset.data.soft_joint_pos_limits)[:, self._joint_ids, 1], + self._asset.data.soft_joint_pos_limits.torch[:, self._joint_ids, 0], + self._asset.data.soft_joint_pos_limits.torch[:, self._joint_ids, 1], ) self._processed_actions[:] = actions[:] @@ -271,10 +270,10 @@ def reset(self, env_ids: Sequence[int] | None = None) -> None: # check if specific environment ids are provided if env_ids is None: super().reset(slice(None)) - self._prev_applied_actions[:] = wp.to_torch(self._asset.data.joint_pos)[:, self._joint_ids] + self._prev_applied_actions[:] = self._asset.data.joint_pos.torch[:, self._joint_ids] else: super().reset(env_ids) - curr_applied_actions = wp.to_torch(self._asset.data.joint_pos)[env_ids[:, None], self._joint_ids].view( + curr_applied_actions = self._asset.data.joint_pos.torch[env_ids[:, None], self._joint_ids].view( len(env_ids), -1 ) self._prev_applied_actions[env_ids, :] = curr_applied_actions @@ -288,8 +287,8 @@ def process_actions(self, actions: torch.Tensor): # clamp the targets self._processed_actions[:] = torch.clamp( ema_actions, - wp.to_torch(self._asset.data.soft_joint_pos_limits)[:, self._joint_ids, 0], - wp.to_torch(self._asset.data.soft_joint_pos_limits)[:, self._joint_ids, 1], + self._asset.data.soft_joint_pos_limits.torch[:, self._joint_ids, 0], + self._asset.data.soft_joint_pos_limits.torch[:, self._joint_ids, 1], ) # update previous targets self._prev_applied_actions[:] = self._processed_actions[:] diff --git a/source/isaaclab/isaaclab/envs/mdp/actions/non_holonomic_actions.py b/source/isaaclab/isaaclab/envs/mdp/actions/non_holonomic_actions.py index b4c88e3c171b..08d5e9be1c85 100644 --- a/source/isaaclab/isaaclab/envs/mdp/actions/non_holonomic_actions.py +++ b/source/isaaclab/isaaclab/envs/mdp/actions/non_holonomic_actions.py @@ -184,7 +184,7 @@ def process_actions(self, actions): def apply_actions(self): # obtain current heading - quat_w = self._asset.data.body_quat_w[:, self._body_idx].view(self.num_envs, 4) + quat_w = self._asset.data.body_quat_w.torch[:, self._body_idx].view(self.num_envs, 4) yaw_w = euler_xyz_from_quat(quat_w)[2] # compute joint velocities targets self._joint_vel_command[:, 0] = torch.cos(yaw_w) * self.processed_actions[:, 0] # x diff --git a/source/isaaclab/isaaclab/envs/mdp/actions/pink_task_space_actions.py b/source/isaaclab/isaaclab/envs/mdp/actions/pink_task_space_actions.py index 5d7e59418eea..3cb4450805b2 100644 --- a/source/isaaclab/isaaclab/envs/mdp/actions/pink_task_space_actions.py +++ b/source/isaaclab/isaaclab/envs/mdp/actions/pink_task_space_actions.py @@ -218,7 +218,7 @@ def _get_base_link_frame_transform(self) -> torch.Tensor: """ # Get base link frame pose in world origin using cached index articulation_data = self._env.scene[self.cfg.controller.articulation_name].data - base_link_frame_in_world_origin = wp.to_torch(articulation_data.body_link_state_w)[:, self._base_link_idx, :7] + base_link_frame_in_world_origin = articulation_data.body_link_state_w.torch[:, self._base_link_idx, :7] # Transform to environment origin frame (reuse buffer to avoid allocation) torch.sub( @@ -352,7 +352,7 @@ def _compute_ik_solutions(self) -> torch.Tensor: for env_index, ik_controller in enumerate(self._ik_controllers): # Get current joint positions for this environment - current_joint_pos = wp.to_torch(self._asset.data.joint_pos).cpu().numpy()[env_index] + current_joint_pos = self._asset.data.joint_pos.torch.cpu().numpy()[env_index] # Compute IK solution joint_pos_des = ik_controller.compute(current_joint_pos, self._sim_dt) diff --git a/source/isaaclab/isaaclab/envs/mdp/actions/rmpflow_task_space_actions.py b/source/isaaclab/isaaclab/envs/mdp/actions/rmpflow_task_space_actions.py index 741de96808c9..922db073a300 100644 --- a/source/isaaclab/isaaclab/envs/mdp/actions/rmpflow_task_space_actions.py +++ b/source/isaaclab/isaaclab/envs/mdp/actions/rmpflow_task_space_actions.py @@ -133,7 +133,7 @@ def jacobian_w(self) -> torch.Tensor: @property def jacobian_b(self) -> torch.Tensor: jacobian = self.jacobian_w - base_rot = wp.to_torch(self._asset.data.root_quat_w) + base_rot = self._asset.data.root_quat_w.torch base_rot_matrix = math_utils.matrix_from_quat(math_utils.quat_inv(base_rot)) jacobian[:, :3, :] = torch.bmm(base_rot_matrix, jacobian[:, :3, :]) jacobian[:, 3:, :] = torch.bmm(base_rot_matrix, jacobian[:, 3:, :]) @@ -178,11 +178,11 @@ def process_actions(self, actions: torch.Tensor): def apply_actions(self): # obtain quantities from simulation ee_pos_curr, ee_quat_curr = self._compute_frame_pose() - joint_pos = wp.to_torch(self._asset.data.joint_pos)[:, self._joint_ids] + joint_pos = self._asset.data.joint_pos.torch[:, self._joint_ids] # compute the delta in joint-space if ee_quat_curr.norm() != 0: joint_pos_des, joint_vel_des = self._rmpflow_controller.compute( - wp.to_torch(self._asset.data.joint_pos), wp.to_torch(self._asset.data.joint_vel) + self._asset.data.joint_pos.torch, self._asset.data.joint_vel.torch ) else: joint_pos_des = joint_pos.clone() @@ -206,10 +206,10 @@ def _compute_frame_pose(self) -> tuple[torch.Tensor, torch.Tensor]: A tuple of the body's position and orientation in the root frame. """ # obtain quantities from simulation - ee_pos_w = wp.to_torch(self._asset.data.body_pos_w)[:, self._body_idx] - ee_quat_w = wp.to_torch(self._asset.data.body_quat_w)[:, self._body_idx] - root_pos_w = wp.to_torch(self._asset.data.root_pos_w) - root_quat_w = wp.to_torch(self._asset.data.root_quat_w) + ee_pos_w = self._asset.data.body_pos_w.torch[:, self._body_idx] + ee_quat_w = self._asset.data.body_quat_w.torch[:, self._body_idx] + root_pos_w = self._asset.data.root_pos_w.torch + root_quat_w = self._asset.data.root_quat_w.torch # compute the pose of the body in the root frame ee_pose_b, ee_quat_b = math_utils.subtract_frame_transforms(root_pos_w, root_quat_w, ee_pos_w, ee_quat_w) # account for the offset diff --git a/source/isaaclab/isaaclab/envs/mdp/actions/task_space_actions.py b/source/isaaclab/isaaclab/envs/mdp/actions/task_space_actions.py index 99ee2e5cfb55..4aa66367d2c2 100644 --- a/source/isaaclab/isaaclab/envs/mdp/actions/task_space_actions.py +++ b/source/isaaclab/isaaclab/envs/mdp/actions/task_space_actions.py @@ -148,7 +148,7 @@ def jacobian_w(self) -> torch.Tensor: @property def jacobian_b(self) -> torch.Tensor: jacobian = self.jacobian_w - base_rot = wp.to_torch(self._asset.data.root_quat_w) + base_rot = self._asset.data.root_quat_w.torch base_rot_matrix = math_utils.matrix_from_quat(math_utils.quat_inv(base_rot)) jacobian[:, :3, :] = torch.bmm(base_rot_matrix, jacobian[:, :3, :]) jacobian[:, 3:, :] = torch.bmm(base_rot_matrix, jacobian[:, 3:, :]) @@ -205,7 +205,7 @@ def process_actions(self, actions: torch.Tensor): def apply_actions(self): # obtain quantities from simulation ee_pos_curr, ee_quat_curr = self._compute_frame_pose() - joint_pos = wp.to_torch(self._asset.data.joint_pos)[:, self._joint_ids] + joint_pos = self._asset.data.joint_pos.torch[:, self._joint_ids] # compute the delta in joint-space if ee_quat_curr.norm() != 0: jacobian = self._compute_frame_jacobian() @@ -229,10 +229,10 @@ def _compute_frame_pose(self) -> tuple[torch.Tensor, torch.Tensor]: A tuple of the body's position and orientation in the root frame. """ # obtain quantities from simulation - ee_pos_w = wp.to_torch(self._asset.data.body_pos_w)[:, self._body_idx] - ee_quat_w = wp.to_torch(self._asset.data.body_quat_w)[:, self._body_idx] - root_pos_w = wp.to_torch(self._asset.data.root_pos_w) - root_quat_w = wp.to_torch(self._asset.data.root_quat_w) + ee_pos_w = self._asset.data.body_pos_w.torch[:, self._body_idx] + ee_quat_w = self._asset.data.body_quat_w.torch[:, self._body_idx] + root_pos_w = self._asset.data.root_pos_w.torch + root_quat_w = self._asset.data.root_quat_w.torch # compute the pose of the body in the root frame ee_pose_b, ee_quat_b = math_utils.subtract_frame_transforms(root_pos_w, root_quat_w, ee_pos_w, ee_quat_w) # account for the offset @@ -442,7 +442,7 @@ def jacobian_w(self) -> torch.Tensor: @property def jacobian_b(self) -> torch.Tensor: jacobian = self.jacobian_w - base_rot = wp.to_torch(self._asset.data.root_quat_w) + base_rot = self._asset.data.root_quat_w.torch base_rot_matrix = math_utils.matrix_from_quat(math_utils.quat_inv(base_rot)) jacobian[:, :3, :] = torch.bmm(base_rot_matrix, jacobian[:, :3, :]) jacobian[:, 3:, :] = torch.bmm(base_rot_matrix, jacobian[:, 3:, :]) @@ -637,11 +637,11 @@ def _resolve_nullspace_joint_pos_targets(self): elif self.cfg.nullspace_joint_pos_target == "center": # Get the center of the robot soft joint limits self._nullspace_joint_pos_target = torch.mean( - wp.to_torch(self._asset.data.soft_joint_pos_limits)[:, self._joint_ids, :], dim=-1 + self._asset.data.soft_joint_pos_limits.torch[:, self._joint_ids, :], dim=-1 ) elif self.cfg.nullspace_joint_pos_target == "default": # Get the default joint positions - self._nullspace_joint_pos_target = wp.to_torch(self._asset.data.default_joint_pos)[:, self._joint_ids] + self._nullspace_joint_pos_target = self._asset.data.default_joint_pos.torch[:, self._joint_ids] else: raise ValueError("Invalid value for nullspace joint pos targets.") @@ -689,12 +689,12 @@ def _compute_ee_jacobian(self): def _compute_ee_pose(self): """Computes the pose of the ee frame in root frame.""" # Obtain quantities from simulation - self._ee_pose_w[:, 0:3] = wp.to_torch(self._asset.data.body_pos_w)[:, self._ee_body_idx] - self._ee_pose_w[:, 3:7] = wp.to_torch(self._asset.data.body_quat_w)[:, self._ee_body_idx] + self._ee_pose_w[:, 0:3] = self._asset.data.body_pos_w.torch[:, self._ee_body_idx] + self._ee_pose_w[:, 3:7] = self._asset.data.body_quat_w.torch[:, self._ee_body_idx] # Compute the pose of the ee body in the root frame self._ee_pose_b_no_offset[:, 0:3], self._ee_pose_b_no_offset[:, 3:7] = math_utils.subtract_frame_transforms( - wp.to_torch(self._asset.data.root_pos_w), - wp.to_torch(self._asset.data.root_quat_w), + self._asset.data.root_pos_w.torch, + self._asset.data.root_quat_w.torch, self._ee_pose_w[:, 0:3], self._ee_pose_w[:, 3:7], ) @@ -709,12 +709,12 @@ def _compute_ee_pose(self): def _compute_ee_velocity(self): """Computes the velocity of the ee frame in root frame.""" # Extract end-effector velocity in the world frame - self._ee_vel_w[:] = wp.to_torch(self._asset.data.body_vel_w)[:, self._ee_body_idx, :] + self._ee_vel_w[:] = self._asset.data.body_vel_w.torch[:, self._ee_body_idx, :] # Compute the relative velocity in the world frame - relative_vel_w = self._ee_vel_w - wp.to_torch(self._asset.data.root_vel_w) + relative_vel_w = self._ee_vel_w - self._asset.data.root_vel_w.torch # Convert ee velocities from world to root frame - root_quat_w = wp.to_torch(self._asset.data.root_quat_w) + root_quat_w = self._asset.data.root_quat_w.torch self._ee_vel_b[:, 0:3] = math_utils.quat_apply_inverse(root_quat_w, relative_vel_w[:, 0:3]) self._ee_vel_b[:, 3:6] = math_utils.quat_apply_inverse(root_quat_w, relative_vel_w[:, 3:6]) @@ -731,17 +731,15 @@ def _compute_ee_force(self): # Obtain contact forces only if the contact sensor is available if self._contact_sensor is not None: self._contact_sensor.update(self._sim_dt) - self._ee_force_w[:] = wp.to_torch(self._contact_sensor.data.net_forces_w)[:, 0, :] # type: ignore + self._ee_force_w[:] = self._contact_sensor.data.net_forces_w.torch[:, 0, :] # type: ignore # Rotate forces and torques into root frame - self._ee_force_b[:] = math_utils.quat_apply_inverse( - wp.to_torch(self._asset.data.root_quat_w), self._ee_force_w - ) + self._ee_force_b[:] = math_utils.quat_apply_inverse(self._asset.data.root_quat_w.torch, self._ee_force_w) def _compute_joint_states(self): """Computes the joint states for operational space control.""" # Extract joint positions and velocities - self._joint_pos[:] = wp.to_torch(self._asset.data.joint_pos)[:, self._joint_ids] - self._joint_vel[:] = wp.to_torch(self._asset.data.joint_vel)[:, self._joint_ids] + self._joint_pos[:] = self._asset.data.joint_pos.torch[:, self._joint_ids] + self._joint_vel[:] = self._asset.data.joint_vel.torch[:, self._joint_ids] def _compute_task_frame_pose(self): """Computes the pose of the task frame in root frame.""" @@ -750,10 +748,10 @@ def _compute_task_frame_pose(self): self._task_frame_transformer.update(self._sim_dt) # Calculate the pose of the task frame in the root frame self._task_frame_pose_b[:, :3], self._task_frame_pose_b[:, 3:] = math_utils.subtract_frame_transforms( - wp.to_torch(self._asset.data.root_pos_w), - wp.to_torch(self._asset.data.root_quat_w), - wp.to_torch(self._task_frame_transformer.data.target_pos_w)[:, 0, :], - wp.to_torch(self._task_frame_transformer.data.target_quat_w)[:, 0, :], + self._asset.data.root_pos_w.torch, + self._asset.data.root_quat_w.torch, + self._task_frame_transformer.data.target_pos_w.torch[:, 0, :], + self._task_frame_transformer.data.target_quat_w.torch[:, 0, :], ) def _preprocess_actions(self, actions: torch.Tensor): diff --git a/source/isaaclab/isaaclab/envs/mdp/commands/commands_cfg.py b/source/isaaclab/isaaclab/envs/mdp/commands/commands_cfg.py index 3af6b3e32ebe..34a7a6f994f2 100644 --- a/source/isaaclab/isaaclab/envs/mdp/commands/commands_cfg.py +++ b/source/isaaclab/isaaclab/envs/mdp/commands/commands_cfg.py @@ -83,6 +83,12 @@ class Ranges: ranges: Ranges = MISSING """Distribution ranges for the velocity commands.""" + vel_xy_success_threshold: float = 0.5 + """Threshold on the per-episode mean XY velocity error norm [m/s].""" + + vel_yaw_success_threshold: float = 0.4 + """Threshold on the per-episode mean yaw velocity error [rad/s].""" + goal_vel_visualizer_cfg: VisualizationMarkersCfg = GREEN_ARROW_X_MARKER_CFG.replace( prim_path="/Visuals/Command/velocity_goal" ) @@ -174,6 +180,12 @@ class Ranges: ranges: Ranges = MISSING """Ranges for the commands.""" + position_success_threshold: float | None = None + """If set, position-error norm below this value (per step) flags the episode as successful. + + The episode-level binary "ever within threshold" is mean-reduced across environments and + logged under ``Metrics/success_rate``. Defaults to ``None`` (success tracking disabled).""" + goal_pose_visualizer_cfg: VisualizationMarkersCfg = FRAME_MARKER_CFG.replace(prim_path="/Visuals/Command/goal_pose") """The configuration for the goal pose visualization marker. Defaults to FRAME_MARKER_CFG.""" @@ -221,6 +233,12 @@ class Ranges: ranges: Ranges = MISSING """Distribution ranges for the position commands.""" + position_success_threshold: float | None = None + """If set, XY position-error norm below this value (per step) flags the episode as successful. + + The episode-level binary "ever within threshold" is mean-reduced across environments and + logged under ``Metrics/success_rate``. Defaults to ``None`` (success tracking disabled).""" + goal_pose_visualizer_cfg: VisualizationMarkersCfg = GREEN_ARROW_X_MARKER_CFG.replace( prim_path="/Visuals/Command/pose_goal" ) diff --git a/source/isaaclab/isaaclab/envs/mdp/commands/pose_2d_command.py b/source/isaaclab/isaaclab/envs/mdp/commands/pose_2d_command.py index 1c181b3e32d7..ffd7bdad5e49 100644 --- a/source/isaaclab/isaaclab/envs/mdp/commands/pose_2d_command.py +++ b/source/isaaclab/isaaclab/envs/mdp/commands/pose_2d_command.py @@ -11,7 +11,6 @@ from typing import TYPE_CHECKING import torch -import warp as wp from isaaclab.assets import Articulation from isaaclab.managers import CommandTerm @@ -61,6 +60,15 @@ def __init__(self, cfg: UniformPose2dCommandCfg, env: ManagerBasedEnv): # -- metrics self.metrics["error_pos"] = torch.zeros(self.num_envs, device=self.device) self.metrics["error_heading"] = torch.zeros(self.num_envs, device=self.device) + # -- per-episode sticky success bit (only used when cfg.position_success_threshold is set) + self._track_success = cfg.position_success_threshold is not None + if self._track_success: + self._succeeded = torch.zeros(self.num_envs, dtype=torch.bool, device=self.device) + + # adds (optional) cmd kind and element names for leapp export + # during export, semantic data about this command will be used to annotate the command input + self.cfg.cmd_kind = self.cfg.cmd_kind or "command/body/pose" + self.cfg.element_names = self.cfg.element_names or ["x", "y", "z", "heading"] def __str__(self) -> str: msg = "PositionCommand:\n" @@ -83,12 +91,25 @@ def command(self) -> torch.Tensor: def _update_metrics(self): # logs data - self.metrics["error_pos_2d"] = torch.linalg.norm( - self.pos_command_w[:, :2] - wp.to_torch(self.robot.data.root_pos_w)[:, :2], dim=1 - ) - self.metrics["error_heading"] = torch.abs( - wrap_to_pi(self.heading_command_w - wp.to_torch(self.robot.data.heading_w)) + self.metrics["error_pos"] = torch.linalg.norm( + self.pos_command_w[:, :2] - self.robot.data.root_pos_w.torch[:, :2], dim=1 ) + self.metrics["error_heading"] = torch.abs(wrap_to_pi(self.heading_command_w - self.robot.data.heading_w.torch)) + if self._track_success: + self._succeeded |= self.metrics["error_pos"] < self.cfg.position_success_threshold + + def reset(self, env_ids: Sequence[int] | None = None) -> dict[str, float]: + extras = super().reset(env_ids) + if self._track_success: + if env_ids is None: + env_ids = slice(None) + # Write the unified ``Metrics/success_rate`` directly to env extras so it shares + # a TensorBoard card with the same metric from other tasks. + self._env.extras.setdefault("log", {})["Metrics/success_rate"] = ( + self._succeeded[env_ids].float().mean().item() + ) + self._succeeded[env_ids] = False + return extras def _resample_command(self, env_ids: Sequence[int]): # obtain env origins for the environments @@ -97,19 +118,19 @@ def _resample_command(self, env_ids: Sequence[int]): r = torch.empty(len(env_ids), device=self.device) self.pos_command_w[env_ids, 0] += r.uniform_(*self.cfg.ranges.pos_x) self.pos_command_w[env_ids, 1] += r.uniform_(*self.cfg.ranges.pos_y) - self.pos_command_w[env_ids, 2] += wp.to_torch(self.robot.data.default_root_pose)[env_ids, 2] + self.pos_command_w[env_ids, 2] += self.robot.data.default_root_pose.torch[env_ids, 2] if self.cfg.simple_heading: # set heading command to point towards target - target_vec = self.pos_command_w[env_ids] - wp.to_torch(self.robot.data.root_pos_w)[env_ids] + target_vec = self.pos_command_w[env_ids] - self.robot.data.root_pos_w.torch[env_ids] target_direction = torch.atan2(target_vec[:, 1], target_vec[:, 0]) flipped_target_direction = wrap_to_pi(target_direction + torch.pi) # compute errors to find the closest direction to the current heading # this is done to avoid the discontinuity at the -pi/pi boundary - curr_to_target = wrap_to_pi(target_direction - wp.to_torch(self.robot.data.heading_w)[env_ids]).abs() + curr_to_target = wrap_to_pi(target_direction - self.robot.data.heading_w.torch[env_ids]).abs() curr_to_flipped_target = wrap_to_pi( - flipped_target_direction - wp.to_torch(self.robot.data.heading_w)[env_ids] + flipped_target_direction - self.robot.data.heading_w.torch[env_ids] ).abs() # set the heading command to the closest direction @@ -124,9 +145,9 @@ def _resample_command(self, env_ids: Sequence[int]): def _update_command(self): """Re-target the position command to the current root state.""" - target_vec = self.pos_command_w - wp.to_torch(self.robot.data.root_pos_w)[:, :3] - self.pos_command_b[:] = quat_apply_inverse(yaw_quat(wp.to_torch(self.robot.data.root_quat_w)), target_vec) - self.heading_command_b[:] = wrap_to_pi(self.heading_command_w - wp.to_torch(self.robot.data.heading_w)) + target_vec = self.pos_command_w - self.robot.data.root_pos_w.torch[:, :3] + self.pos_command_b[:] = quat_apply_inverse(yaw_quat(self.robot.data.root_quat_w.torch), target_vec) + self.heading_command_b[:] = wrap_to_pi(self.heading_command_w - self.robot.data.heading_w.torch) def _set_debug_vis_impl(self, debug_vis: bool): # create markers if necessary for the first time @@ -186,19 +207,19 @@ def _resample_command(self, env_ids: Sequence[int]): self.terrain.terrain_levels[env_ids], self.terrain.terrain_types[env_ids], ids ] # offset the position command by the current root height - self.pos_command_w[env_ids, 2] += wp.to_torch(self.robot.data.default_root_pose)[env_ids, 2] + self.pos_command_w[env_ids, 2] += self.robot.data.default_root_pose.torch[env_ids, 2] if self.cfg.simple_heading: # set heading command to point towards target - target_vec = self.pos_command_w[env_ids] - wp.to_torch(self.robot.data.root_pos_w)[env_ids] + target_vec = self.pos_command_w[env_ids] - self.robot.data.root_pos_w.torch[env_ids] target_direction = torch.atan2(target_vec[:, 1], target_vec[:, 0]) flipped_target_direction = wrap_to_pi(target_direction + torch.pi) # compute errors to find the closest direction to the current heading # this is done to avoid the discontinuity at the -pi/pi boundary - curr_to_target = wrap_to_pi(target_direction - wp.to_torch(self.robot.data.heading_w)[env_ids]).abs() + curr_to_target = wrap_to_pi(target_direction - self.robot.data.heading_w.torch[env_ids]).abs() curr_to_flipped_target = wrap_to_pi( - flipped_target_direction - wp.to_torch(self.robot.data.heading_w)[env_ids] + flipped_target_direction - self.robot.data.heading_w.torch[env_ids] ).abs() # set the heading command to the closest direction diff --git a/source/isaaclab/isaaclab/envs/mdp/commands/pose_command.py b/source/isaaclab/isaaclab/envs/mdp/commands/pose_command.py index 33c58fd45f95..d98a6b5e7f81 100644 --- a/source/isaaclab/isaaclab/envs/mdp/commands/pose_command.py +++ b/source/isaaclab/isaaclab/envs/mdp/commands/pose_command.py @@ -11,11 +11,11 @@ from typing import TYPE_CHECKING import torch -import warp as wp from isaaclab.assets import Articulation from isaaclab.managers import CommandTerm from isaaclab.markers import VisualizationMarkers +from isaaclab.utils.leapp import POSE7_ELEMENT_NAMES from isaaclab.utils.math import combine_frame_transforms, compute_pose_error, quat_from_euler_xyz, quat_unique if TYPE_CHECKING: @@ -61,13 +61,22 @@ def __init__(self, cfg: UniformPoseCommandCfg, env: ManagerBasedEnv): self.body_idx = self.robot.find_bodies(cfg.body_name)[0][0] # create buffers - # -- commands: (x, y, z, qw, qx, qy, qz) in root frame + # -- commands: (x, y, z, qx, qy, qz, qw) in root frame self.pose_command_b = torch.zeros(self.num_envs, 7, device=self.device) self.pose_command_b[:, 3] = 1.0 self.pose_command_w = torch.zeros_like(self.pose_command_b) # -- metrics self.metrics["position_error"] = torch.zeros(self.num_envs, device=self.device) self.metrics["orientation_error"] = torch.zeros(self.num_envs, device=self.device) + # -- per-episode sticky success bit (only used when cfg.position_success_threshold is set) + self._track_success = cfg.position_success_threshold is not None + if self._track_success: + self._succeeded = torch.zeros(self.num_envs, dtype=torch.bool, device=self.device) + + # adds (optional) cmd kind and element names for leapp export + # during export, semantic data about this command will be used to annotate the command input + self.cfg.cmd_kind = self.cfg.cmd_kind or "command/body/pose" + self.cfg.element_names = self.cfg.element_names or POSE7_ELEMENT_NAMES def __str__(self) -> str: msg = "UniformPoseCommand:\n" @@ -94,8 +103,8 @@ def command(self) -> torch.Tensor: def _update_metrics(self): # transform command from base frame to simulation world frame self.pose_command_w[:, :3], self.pose_command_w[:, 3:] = combine_frame_transforms( - wp.to_torch(self.robot.data.root_pos_w), - wp.to_torch(self.robot.data.root_quat_w), + self.robot.data.root_pos_w.torch, + self.robot.data.root_quat_w.torch, self.pose_command_b[:, :3], self.pose_command_b[:, 3:], ) @@ -103,11 +112,26 @@ def _update_metrics(self): pos_error, rot_error = compute_pose_error( self.pose_command_w[:, :3], self.pose_command_w[:, 3:], - wp.to_torch(self.robot.data.body_pos_w)[:, self.body_idx], - wp.to_torch(self.robot.data.body_quat_w)[:, self.body_idx], + self.robot.data.body_pos_w.torch[:, self.body_idx], + self.robot.data.body_quat_w.torch[:, self.body_idx], ) self.metrics["position_error"] = torch.linalg.norm(pos_error, dim=-1) self.metrics["orientation_error"] = torch.linalg.norm(rot_error, dim=-1) + if self._track_success: + self._succeeded |= self.metrics["position_error"] < self.cfg.position_success_threshold + + def reset(self, env_ids: Sequence[int] | None = None) -> dict[str, float]: + extras = super().reset(env_ids) + if self._track_success: + if env_ids is None: + env_ids = slice(None) + # Write the unified ``Metrics/success_rate`` directly to env extras so it shares + # a TensorBoard card with the same metric from other tasks. + self._env.extras.setdefault("log", {})["Metrics/success_rate"] = ( + self._succeeded[env_ids].float().mean().item() + ) + self._succeeded[env_ids] = False + return extras def _resample_command(self, env_ids: Sequence[int]): # sample new pose targets @@ -153,5 +177,5 @@ def _debug_vis_callback(self, event): # -- goal pose self.goal_pose_visualizer.visualize(self.pose_command_w[:, :3], self.pose_command_w[:, 3:]) # -- current body pose - body_link_pose_w = wp.to_torch(self.robot.data.body_link_pose_w)[:, self.body_idx] + body_link_pose_w = self.robot.data.body_link_pose_w.torch[:, self.body_idx] self.current_pose_visualizer.visualize(body_link_pose_w[:, :3], body_link_pose_w[:, 3:7]) diff --git a/source/isaaclab/isaaclab/envs/mdp/commands/velocity_command.py b/source/isaaclab/isaaclab/envs/mdp/commands/velocity_command.py index eadc89af3af9..930f663f65d3 100644 --- a/source/isaaclab/isaaclab/envs/mdp/commands/velocity_command.py +++ b/source/isaaclab/isaaclab/envs/mdp/commands/velocity_command.py @@ -12,7 +12,6 @@ from typing import TYPE_CHECKING import torch -import warp as wp import isaaclab.utils.math as math_utils from isaaclab.assets import Articulation @@ -84,9 +83,19 @@ def __init__(self, cfg: UniformVelocityCommandCfg, env: ManagerBasedEnv): self.heading_target = torch.zeros(self.num_envs, device=self.device) self.is_heading_env = torch.zeros(self.num_envs, dtype=torch.bool, device=self.device) self.is_standing_env = torch.zeros_like(self.is_heading_env) - # -- metrics + # -- metrics: finalized per-episode means/rates, written at reset() and read by the base class self.metrics["error_vel_xy"] = torch.zeros(self.num_envs, device=self.device) self.metrics["error_vel_yaw"] = torch.zeros(self.num_envs, device=self.device) + self.metrics["success_rate"] = torch.zeros(self.num_envs, device=self.device) + # -- per-episode running sums (cleared at episode reset) + self._error_xy_sum = torch.zeros(self.num_envs, device=self.device) + self._error_yaw_sum = torch.zeros(self.num_envs, device=self.device) + self._step_count = torch.zeros(self.num_envs, device=self.device) + + # adds (optional) cmd kind and element names for leapp export + # during export, semantic data about this command will be used to annotate the command input + self.cfg.cmd_kind = self.cfg.cmd_kind or "command/body/velocity" + self.cfg.element_names = self.cfg.element_names or ["lin_vel_x", "lin_vel_y", "ang_vel_z"] def __str__(self) -> str: """Return a string representation of the command generator.""" @@ -113,17 +122,39 @@ def command(self) -> torch.Tensor: """ def _update_metrics(self): - # time for which the command was executed - max_command_time = self.cfg.resampling_time_range[1] - max_command_step = max_command_time / self._env.step_dt - # logs data - self.metrics["error_vel_xy"] += ( - torch.linalg.norm(self.vel_command_b[:, :2] - wp.to_torch(self.robot.data.root_lin_vel_b)[:, :2], dim=-1) - / max_command_step - ) - self.metrics["error_vel_yaw"] += ( - torch.abs(self.vel_command_b[:, 2] - wp.to_torch(self.robot.data.root_ang_vel_b)[:, 2]) / max_command_step - ) + # accumulate per-step tracking error sums; the per-episode mean is finalized in + # :meth:`reset` so the value is independent of episode length and + # ``resampling_time_range`` (no magic ``max_command_step`` divisor). + error_xy = torch.linalg.norm(self.vel_command_b[:, :2] - self.robot.data.root_lin_vel_b.torch[:, :2], dim=-1) + error_yaw = torch.abs(self.vel_command_b[:, 2] - self.robot.data.root_ang_vel_b.torch[:, 2]) + self._error_xy_sum += error_xy + self._error_yaw_sum += error_yaw + self._step_count += 1.0 + + def reset(self, env_ids: Sequence[int] | None = None) -> dict[str, float]: + # Finalize the just-ended episode's metrics into ``self.metrics`` BEFORE the base + # class reads them. ``success_rate`` is per-env binary: the *episode-mean* error + # is below both thresholds. Then super().reset() logs and zeros ``self.metrics``; + # we zero the running sums for ``env_ids`` afterwards so the next episode starts clean. + if env_ids is None: + env_ids = slice(None) + denom = self._step_count[env_ids].clamp_min(1.0) + mean_error_xy = self._error_xy_sum[env_ids] / denom + mean_error_yaw = self._error_yaw_sum[env_ids] / denom + self.metrics["error_vel_xy"][env_ids] = mean_error_xy + self.metrics["error_vel_yaw"][env_ids] = mean_error_yaw + self.metrics["success_rate"][env_ids] = ( + (mean_error_xy < self.cfg.vel_xy_success_threshold) & (mean_error_yaw < self.cfg.vel_yaw_success_threshold) + ).float() + extras = super().reset(env_ids) + # Route success_rate to the unified ``Metrics/success_rate`` path (shared TensorBoard + # / wandb card across tasks); pop it from the returned dict so CommandManager does + # not additionally log it under ``Metrics//success_rate``. + self._env.extras.setdefault("log", {})["Metrics/success_rate"] = extras.pop("success_rate") + self._error_xy_sum[env_ids] = 0.0 + self._error_yaw_sum[env_ids] = 0.0 + self._step_count[env_ids] = 0.0 + return extras def _resample_command(self, env_ids: Sequence[int]): # sample velocity commands @@ -154,7 +185,7 @@ def _update_command(self): env_ids = self.is_heading_env.nonzero(as_tuple=False).flatten() # compute angular velocity heading_error = math_utils.wrap_to_pi( - self.heading_target[env_ids] - wp.to_torch(self.robot.data.heading_w)[env_ids] + self.heading_target[env_ids] - self.robot.data.heading_w.torch[env_ids] ) self.vel_command_b[env_ids, 2] = torch.clip( self.cfg.heading_control_stiffness * heading_error, @@ -191,12 +222,12 @@ def _debug_vis_callback(self, event): return # get marker location # -- base state - base_pos_w = wp.to_torch(self.robot.data.root_pos_w).clone() + base_pos_w = self.robot.data.root_pos_w.torch.clone() base_pos_w[:, 2] += 0.5 # -- resolve the scales and quaternions vel_des_arrow_scale, vel_des_arrow_quat = self._resolve_xy_velocity_to_arrow(self.command[:, :2]) vel_arrow_scale, vel_arrow_quat = self._resolve_xy_velocity_to_arrow( - wp.to_torch(self.robot.data.root_lin_vel_b)[:, :2] + self.robot.data.root_lin_vel_b.torch[:, :2] ) # display markers self.goal_vel_visualizer.visualize(base_pos_w, vel_des_arrow_quat, vel_des_arrow_scale) @@ -218,7 +249,7 @@ def _resolve_xy_velocity_to_arrow(self, xy_velocity: torch.Tensor) -> tuple[torc zeros = torch.zeros_like(heading_angle) arrow_quat = math_utils.quat_from_euler_xyz(zeros, zeros, heading_angle) # convert everything back from base to world frame - base_quat_w = wp.to_torch(self.robot.data.root_quat_w) + base_quat_w = self.robot.data.root_quat_w.torch arrow_quat = math_utils.quat_mul(base_quat_w, arrow_quat) return arrow_scale, arrow_quat diff --git a/source/isaaclab/isaaclab/envs/mdp/events.py b/source/isaaclab/isaaclab/envs/mdp/events.py index 18c9b5eff63a..9483d2d2d0cd 100644 --- a/source/isaaclab/isaaclab/envs/mdp/events.py +++ b/source/isaaclab/isaaclab/envs/mdp/events.py @@ -26,7 +26,7 @@ import isaaclab.utils.math as math_utils from isaaclab.actuators import ImplicitActuator from isaaclab.managers import EventTermCfg, ManagerTermBase, SceneEntityCfg -from isaaclab.utils.version import compare_versions, get_isaac_sim_version +from isaaclab.utils.version import compare_versions if TYPE_CHECKING: from isaaclab_physx.assets import DeformableObject @@ -151,69 +151,50 @@ def randomize_rigid_body_scale( op_order_spec.default = Vt.TokenArray(["xformOp:translate", "xformOp:orient", "xformOp:scale"]) -class randomize_rigid_body_material(ManagerTermBase): - """Randomize the physics materials on all geometries of the asset. - - This function creates a set of physics materials with random static friction, dynamic friction, and restitution - values. The number of materials is specified by ``num_buckets``. The materials are generated by sampling - uniform random values from the given ranges. - - The material properties are then assigned to the geometries of the asset. The assignment is done by - creating a random integer tensor of shape (num_instances, max_num_shapes) where ``num_instances`` - is the number of assets spawned and ``max_num_shapes`` is the maximum number of shapes in the asset (over - all bodies). The integer values are used as indices to select the material properties from the - material buckets. - - If the flag ``make_consistent`` is set to ``True``, the dynamic friction is set to be less than or equal to - the static friction. This obeys the physics constraint on friction values. However, it may not always be - essential for the application. Thus, the flag is set to ``False`` by default. +class _RandomizeRigidBodyMaterialPhysx: + """PhysX backend implementation for material randomization. - .. attention:: - This function uses CPU tensors to assign the material properties. It is recommended to use this function - only during the initialization of the environment. Otherwise, it may lead to a significant performance - overhead. - - .. note:: - PhysX only allows 64000 unique physics materials in the scene. If the number of materials exceeds this - limit, the simulation will crash. Due to this reason, we sample the materials only once during initialization. - Afterwards, these materials are randomly assigned to the geometries of the asset. + Uses the bucket-based approach required by PhysX's 64000 unique material limit. + Materials are pre-sampled into buckets and randomly assigned to shapes. """ - def __init__(self, cfg: EventTermCfg, env: ManagerBasedEnv): - """Initialize the term. - - Args: - cfg: The configuration of the event term. - env: The environment instance. + def __init__( + self, cfg: EventTermCfg, env: ManagerBasedEnv, asset: RigidObject | Articulation, asset_cfg: SceneEntityCfg + ): + from isaaclab.assets import BaseArticulation - Raises: - ValueError: If the asset is not a RigidObject or an Articulation. - """ - from isaaclab.assets import BaseArticulation, BaseRigidObject + # obtain parameters for sampling friction and restitution values + static_friction_range = cfg.params.get("static_friction_range", (1.0, 1.0)) + dynamic_friction_range = cfg.params.get("dynamic_friction_range", (1.0, 1.0)) + restitution_range = cfg.params.get("restitution_range", (0.0, 0.0)) + num_buckets = int(cfg.params.get("num_buckets", 1)) - super().__init__(cfg, env) + # sample material properties from the given ranges + # note: we only sample the materials once during initialization + # afterwards these are randomly assigned to the geometries of the asset + range_list = [static_friction_range, dynamic_friction_range, restitution_range] + ranges = torch.tensor(range_list, device="cpu") + self.material_buckets = math_utils.sample_uniform(ranges[:, 0], ranges[:, 1], (num_buckets, 3), device="cpu") - # extract the used quantities (to enable type-hinting) - self.asset_cfg: SceneEntityCfg = cfg.params["asset_cfg"] - self.asset: RigidObject | Articulation = env.scene[self.asset_cfg.name] + # ensure dynamic friction is always less than static friction + make_consistent = cfg.params.get("make_consistent", False) + if make_consistent: + self.material_buckets[:, 1] = torch.min(self.material_buckets[:, 0], self.material_buckets[:, 1]) - if not isinstance(self.asset, (BaseRigidObject, BaseArticulation)): - raise ValueError( - f"Randomization term 'randomize_rigid_body_material' not supported for asset: '{self.asset_cfg.name}'" - f" with type: '{type(self.asset)}'." - ) + self.asset = asset + self.asset_cfg = asset_cfg # obtain number of shapes per body (needed for indexing the material properties correctly) # note: this is a workaround since the Articulation does not provide a direct way to obtain the number of shapes # per body. We use the physics simulation view to obtain the number of shapes per body. - if isinstance(self.asset, BaseArticulation) and self.asset_cfg.body_ids != slice(None): + if isinstance(asset, BaseArticulation) and asset_cfg.body_ids != slice(None): self.num_shapes_per_body = [] - for link_path in self.asset.root_view.link_paths[0]: - link_physx_view = self.asset._physics_sim_view.create_rigid_body_view(link_path) # type: ignore + for link_path in asset.root_view.link_paths[0]: + link_physx_view = asset._physics_sim_view.create_rigid_body_view(link_path) # type: ignore self.num_shapes_per_body.append(link_physx_view.max_shapes) # ensure the parsing is correct num_shapes = sum(self.num_shapes_per_body) - expected_shapes = self.asset.root_view.max_shapes + expected_shapes = asset.root_view.max_shapes if num_shapes != expected_shapes: raise ValueError( "Randomization term 'randomize_rigid_body_material' failed to parse the number of shapes per body." @@ -223,24 +204,6 @@ def __init__(self, cfg: EventTermCfg, env: ManagerBasedEnv): # in this case, we don't need to do special indexing self.num_shapes_per_body = None - # obtain parameters for sampling friction and restitution values - static_friction_range = cfg.params.get("static_friction_range", (1.0, 1.0)) - dynamic_friction_range = cfg.params.get("dynamic_friction_range", (1.0, 1.0)) - restitution_range = cfg.params.get("restitution_range", (0.0, 0.0)) - num_buckets = int(cfg.params.get("num_buckets", 1)) - - # sample material properties from the given ranges - # note: we only sample the materials once during initialization - # afterwards these are randomly assigned to the geometries of the asset - range_list = [static_friction_range, dynamic_friction_range, restitution_range] - ranges = torch.tensor(range_list, device="cpu") - self.material_buckets = math_utils.sample_uniform(ranges[:, 0], ranges[:, 1], (num_buckets, 3), device="cpu") - - # ensure dynamic friction is always less than static friction - make_consistent = cfg.params.get("make_consistent", False) - if make_consistent: - self.material_buckets[:, 1] = torch.min(self.material_buckets[:, 0], self.material_buckets[:, 1]) - def __call__( self, env: ManagerBasedEnv, @@ -286,6 +249,172 @@ def __call__( ) +class _RandomizeRigidBodyMaterialNewton: + """Newton backend implementation for material randomization. + + Newton can assign arbitrary friction/restitution per shape (no bucket limitation). + Samples friction (mu) and restitution continuously from the given ranges. + Newton uses a single friction coefficient (mu), so ``dynamic_friction_range`` + and ``num_buckets`` are ignored. + """ + + def __init__( + self, cfg: EventTermCfg, env: ManagerBasedEnv, asset: RigidObject | Articulation, asset_cfg: SceneEntityCfg + ): + import isaaclab_newton.physics.newton_manager as newton_manager_module # noqa: PLC0415 + from isaaclab_newton.assets import Articulation as NewtonArticulation # noqa: PLC0415 + from newton.solvers import SolverNotifyFlags # noqa: PLC0415 + + self.asset = asset + self.asset_cfg = asset_cfg + self._newton_manager = newton_manager_module.NewtonManager + self._notify_shape_properties = SolverNotifyFlags.SHAPE_PROPERTIES + + # cache friction/restitution ranges for continuous per-shape sampling + self._static_friction_range = cfg.params.get("static_friction_range", (1.0, 1.0)) + self._restitution_range = cfg.params.get("restitution_range", (0.0, 0.0)) + + # get friction/restitution view-level bindings + model = self._newton_manager.get_model() + self._friction_binding = asset._root_view.get_attribute("shape_material_mu", model)[:, 0] # type: ignore + self._restitution_binding = asset._root_view.get_attribute("shape_material_restitution", model)[:, 0] # type: ignore + + # compute shape indices for body-specific randomization + if isinstance(asset, NewtonArticulation) and asset_cfg.body_ids != slice(None): + num_shapes_per_body = asset.num_shapes_per_body + shape_indices_list = [] + for body_id in asset_cfg.body_ids: + start_idx = sum(num_shapes_per_body[:body_id]) + end_idx = start_idx + num_shapes_per_body[body_id] + shape_indices_list.extend(range(start_idx, end_idx)) + self._shape_indices = torch.tensor(shape_indices_list, dtype=torch.long) + else: + self._shape_indices = torch.arange(self._friction_binding.shape[1], dtype=torch.long) + + def __call__( + self, + env: ManagerBasedEnv, + env_ids: torch.Tensor | None, + static_friction_range: tuple[float, float], + dynamic_friction_range: tuple[float, float], + restitution_range: tuple[float, float], + num_buckets: int, + asset_cfg: SceneEntityCfg, + make_consistent: bool = False, + ): + device = env.device + # resolve environment ids + if env_ids is None: + env_ids = torch.arange(env.scene.num_envs, device=device, dtype=torch.int32) + else: + env_ids = env_ids.to(device) + + num_shapes = len(self._shape_indices) + shape_idx = self._shape_indices.to(device) + + # sample friction (mu) and restitution continuously per shape + friction_range = torch.tensor(self._static_friction_range, device=device) + restitution_range_t = torch.tensor(self._restitution_range, device=device) + friction_samples = math_utils.sample_uniform( + friction_range[0], friction_range[1], (len(env_ids), num_shapes), device=device + ) + restitution_samples = math_utils.sample_uniform( + restitution_range_t[0], restitution_range_t[1], (len(env_ids), num_shapes), device=device + ) + + # write only the affected env_ids to the warp binding + friction_view = wp.to_torch(self._friction_binding) + restitution_view = wp.to_torch(self._restitution_binding) + friction_view[env_ids[:, None], shape_idx] = friction_samples + restitution_view[env_ids[:, None], shape_idx] = restitution_samples + + # notify the physics engine + self._newton_manager.add_model_change(self._notify_shape_properties) + + +class randomize_rigid_body_material(ManagerTermBase): + """Randomize the physics materials on all geometries of the asset. + + This function creates a set of physics materials with random static friction, dynamic friction, and restitution + values and assigns them to the geometries of the asset. + + Automatically detects the active physics backend (PhysX or Newton) and delegates to + the appropriate backend-specific implementation: + + - **PhysX**: Uses the 3-tuple material format (static_friction, dynamic_friction, restitution) + with bucket-based assignment (limited to 64000 unique materials). Applied via the PhysX + tensor API (``root_view.set_material_properties``). + - **Newton**: Samples friction (mu) and restitution continuously per shape (no bucket + limitation). Newton uses a single friction coefficient, so ``dynamic_friction_range`` + and ``num_buckets`` are ignored. Applied directly to Newton's view-level bindings. + + If the flag ``make_consistent`` is set to ``True``, the dynamic friction is set to be less than or equal to + the static friction (PhysX only). This obeys the physics constraint on friction values. + + .. attention:: + On PhysX, this function uses CPU tensors to assign the material properties. It is recommended to + use this function only during the initialization of the environment. + + .. note:: + PhysX only allows 64000 unique physics materials in the scene. If the number of materials exceeds this + limit, the simulation will crash. Due to this reason, we sample the materials only once during initialization. + Afterwards, these materials are randomly assigned to the geometries of the asset. + """ + + def __init__(self, cfg: EventTermCfg, env: ManagerBasedEnv): + """Initialize the term. + + Args: + cfg: The configuration of the event term. + env: The environment instance. + + Raises: + ValueError: If the asset is not a RigidObject or an Articulation. + """ + from isaaclab.assets import BaseArticulation, BaseRigidObject + + super().__init__(cfg, env) + + # extract the used quantities (to enable type-hinting) + self.asset_cfg: SceneEntityCfg = cfg.params["asset_cfg"] + self.asset: RigidObject | Articulation = env.scene[self.asset_cfg.name] + + if not isinstance(self.asset, (BaseRigidObject, BaseArticulation)): + raise ValueError( + f"Randomization term 'randomize_rigid_body_material' not supported for asset: '{self.asset_cfg.name}'" + f" with type: '{type(self.asset)}'." + ) + + # detect physics backend and instantiate the appropriate implementation + manager_name = env.sim.physics_manager.__name__.lower() + if "newton" in manager_name: + self._impl = _RandomizeRigidBodyMaterialNewton(cfg, env, self.asset, self.asset_cfg) + else: + self._impl = _RandomizeRigidBodyMaterialPhysx(cfg, env, self.asset, self.asset_cfg) + + def __call__( + self, + env: ManagerBasedEnv, + env_ids: torch.Tensor | None, + static_friction_range: tuple[float, float], + dynamic_friction_range: tuple[float, float], + restitution_range: tuple[float, float], + num_buckets: int, + asset_cfg: SceneEntityCfg, + make_consistent: bool = False, + ): + self._impl( + env, + env_ids, + static_friction_range, + dynamic_friction_range, + restitution_range, + num_buckets, + asset_cfg, + make_consistent, + ) + + class randomize_rigid_body_mass(ManagerTermBase): """Randomize the mass of the bodies by adding, scaling, or setting random values. @@ -354,9 +483,9 @@ def __call__( min_mass: float = 1e-6, ): if self.default_mass is None: - self.default_mass = wp.to_torch(self.asset.data.body_mass).clone() + self.default_mass = self.asset.data.body_mass.torch.clone() if self.default_inertia is None: - self.default_inertia = wp.to_torch(self.asset.data.body_inertia).clone() + self.default_inertia = self.asset.data.body_inertia.torch.clone() # resolve environment ids if env_ids is None: env_ids = torch.arange(env.scene.num_envs, device=self.asset.device, dtype=torch.int32) @@ -370,7 +499,7 @@ def __call__( body_ids = torch.tensor(self.asset_cfg.body_ids, dtype=torch.int32, device=self.asset.device) # get the current masses of the bodies (num_assets, num_bodies) - masses = wp.to_torch(self.asset.data.body_mass).clone() + masses = self.asset.data.body_mass.torch.clone() # apply randomization on default values # this is to make sure when calling the function multiple times, the randomization is applied on the @@ -395,7 +524,7 @@ def __call__( ratios = masses[env_ids[:, None], body_ids] / self.default_mass[env_ids[:, None], body_ids] # scale the inertia tensors by the the ratios # since mass randomization is done on default values, we can use the default inertia tensors - inertias = wp.to_torch(self.asset.data.body_inertia).clone() + inertias = self.asset.data.body_inertia.torch.clone() # inertia has shape: (num_envs, num_bodies, 9) for all assets inertias[env_ids[:, None], body_ids] = self.default_inertia[env_ids[:, None], body_ids] * ratios[..., None] # set the inertia tensors into the physics simulation @@ -405,104 +534,420 @@ def __call__( ) -def randomize_rigid_body_com( - env: ManagerBasedEnv, - env_ids: torch.Tensor | None, - com_range: dict[str, tuple[float, float]], - asset_cfg: SceneEntityCfg, -): - """Randomize the center of mass (CoM) of rigid bodies by adding a random value sampled from the given ranges. +class randomize_rigid_body_inertia(ManagerTermBase): + """Randomize the inertia tensor of rigid bodies by adding, scaling, or setting values. + + This function modifies body inertia tensors independently of mass. The inertia tensor + is a 3x3 symmetric matrix stored as 9 elements: ``[Ixx, Ixy, Ixz, Iyx, Iyy, Iyz, Izx, Izy, Izz]``. + + Two modes are supported via the :attr:`diagonal_only` parameter: + + - **diagonal_only=True** (default): Only modifies diagonal elements (Ixx, Iyy, Izz at + indices 0, 4, 8). This is useful for adding numerical stability (armature/regularization) + without changing rotational coupling between axes. The diagonal elements represent + resistance to rotation about each principal axis. + + - **diagonal_only=False**: Modifies all 9 elements of the inertia tensor. This can + simulate manufacturing variations or asymmetric mass distributions. Off-diagonal + elements represent coupling between rotations about different axes. .. note:: - This function does not properly track the original CoM values. It is recommended to use this function - only once, during the initialization of the environment. + Unlike :class:`randomize_rigid_body_mass` which recomputes inertia based on mass + ratios, this function modifies inertia directly without affecting mass. """ - # extract the used quantities (to enable type-hinting) - asset: Articulation = env.scene[asset_cfg.name] - # resolve environment ids - if env_ids is None: - env_ids = torch.arange(env.scene.num_envs, device=asset.device) - else: - env_ids = env_ids.to(asset.device) - # resolve body indices - if asset_cfg.body_ids == slice(None): - body_ids = torch.arange(asset.num_bodies, dtype=torch.int, device=asset.device) - else: - body_ids = torch.tensor(asset_cfg.body_ids, dtype=torch.int, device=asset.device) + def __init__(self, cfg: EventTermCfg, env: ManagerBasedEnv): + """Initialize the term. - # sample random CoM values - range_list = [com_range.get(key, (0.0, 0.0)) for key in ["x", "y", "z"]] - ranges = torch.tensor(range_list, device=asset.device) - rand_samples = math_utils.sample_uniform( - ranges[:, 0], ranges[:, 1], (len(env_ids), 3), device=asset.device - ).unsqueeze(1) + Args: + cfg: The configuration of the event term. + env: The environment instance. - # get the current com of the bodies (num_assets, num_bodies) - coms = wp.to_torch(asset.data.body_com_pose_b).clone() + Raises: + ValueError: If the operation is not supported. + ValueError: If the lower bound is negative or zero when not allowed for scale operation. + ValueError: If the upper bound is less than the lower bound. + """ + from isaaclab.assets import BaseArticulation, BaseRigidObject, BaseRigidObjectCollection - # Randomize the com in range - coms[env_ids[:, None], body_ids, :3] += rand_samples + super().__init__(cfg, env) - # Set the new coms - asset.set_coms_index(coms=coms, env_ids=env_ids) + # extract the used quantities (to enable type-hinting) + self.asset_cfg: SceneEntityCfg = cfg.params["asset_cfg"] + self.asset: RigidObject | Articulation = env.scene[self.asset_cfg.name] + if not isinstance(self.asset, (BaseRigidObject, BaseArticulation, BaseRigidObjectCollection)): + raise ValueError( + f"Randomization term 'randomize_rigid_body_inertia' not supported for asset: '{self.asset_cfg.name}'" + f" with type: '{type(self.asset)}'." + ) -def randomize_rigid_body_collider_offsets( - env: ManagerBasedEnv, - env_ids: torch.Tensor | None, - asset_cfg: SceneEntityCfg, - rest_offset_distribution_params: tuple[float, float] | None = None, - contact_offset_distribution_params: tuple[float, float] | None = None, - distribution: Literal["uniform", "log_uniform", "gaussian"] = "uniform", -): - """Randomize the collider parameters of rigid bodies in an asset by adding, scaling, or setting random values. + # check for valid operation + if cfg.params["operation"] == "scale": + if "inertia_distribution_params" in cfg.params: + _validate_scale_range( + cfg.params["inertia_distribution_params"], "inertia_distribution_params", allow_zero=False + ) + elif cfg.params["operation"] not in ("abs", "add"): + raise ValueError( + f"Randomization term 'randomize_rigid_body_inertia' does not support operation:" + f" '{cfg.params['operation']}'." + ) + + self.default_inertia = None + # cache inertia indices: diagonal (0, 4, 8) for regularization, or all elements + diagonal_only = cfg.params.get("diagonal_only", True) + self._inertia_idx = torch.tensor([0, 4, 8], device=self.asset.device) if diagonal_only else slice(None) + + def __call__( + self, + env: ManagerBasedEnv, + env_ids: torch.Tensor | None, + asset_cfg: SceneEntityCfg, + inertia_distribution_params: tuple[float, float], + operation: Literal["add", "scale", "abs"] = "add", + distribution: Literal["uniform", "log_uniform", "gaussian"] = "uniform", + diagonal_only: bool = True, + ): + """Randomize body inertia tensors. + + Args: + env: The environment instance. + env_ids: The environment indices to randomize. If None, all environments are randomized. + asset_cfg: The asset configuration specifying the asset and body names. + inertia_distribution_params: Distribution parameters as a tuple of two floats + ``(low, high)`` for sampling inertia modification values. + operation: The operation to apply. Options: ``"add"``, ``"scale"``, ``"abs"``. + Defaults to ``"add"`` which is typical for regularization/armature. + distribution: The distribution to sample from. Options: ``"uniform"``, + ``"log_uniform"``, ``"gaussian"``. Defaults to ``"uniform"``. + diagonal_only: If True, only modify diagonal elements (Ixx, Iyy, Izz) for + numerical stability. If False, modify all 9 elements. Defaults to True. + """ + # store default inertia on first call for repeatable randomization + if self.default_inertia is None: + self.default_inertia = self.asset.data.body_inertia.torch.clone() + + # resolve environment ids + if env_ids is None: + env_ids = torch.arange(env.scene.num_envs, device=self.asset.device, dtype=torch.int32) + else: + env_ids = env_ids.to(self.asset.device) + + # resolve body indices + if self.asset_cfg.body_ids == slice(None): + body_ids = torch.arange(self.asset.num_bodies, dtype=torch.int32, device=self.asset.device) + else: + body_ids = torch.tensor(self.asset_cfg.body_ids, dtype=torch.int32, device=self.asset.device) + + # get default inertias for affected envs/bodies (advanced indexing creates a copy) + # shape: (len(env_ids), len(body_ids), 9) + inertias = self.default_inertia[env_ids[:, None], body_ids] + + # resolve the distribution function + if distribution == "uniform": + dist_fn = math_utils.sample_uniform + elif distribution == "log_uniform": + dist_fn = math_utils.sample_log_uniform + elif distribution == "gaussian": + dist_fn = math_utils.sample_gaussian + else: + raise NotImplementedError( + f"Unknown distribution: '{distribution}' for inertia randomization." + " Please use 'uniform', 'log_uniform', or 'gaussian'." + ) + + # sample random values once per (env, body) - shape: (len(env_ids), len(body_ids)) + random_values = dist_fn(*inertia_distribution_params, (len(env_ids), len(body_ids)), device=self.asset.device) + + # apply the operation with the SAME random value per body + if operation == "add": + inertias[:, :, self._inertia_idx] += random_values[..., None] + elif operation == "scale": + inertias[:, :, self._inertia_idx] *= random_values[..., None] + elif operation == "abs": + inertias[:, :, self._inertia_idx] = random_values[..., None] + + # set the inertia tensors into the physics simulation + self.asset.set_inertias_index(inertias=inertias, body_ids=body_ids, env_ids=env_ids) + + +class randomize_rigid_body_com(ManagerTermBase): + """Randomize the center of mass (CoM) of rigid bodies by adding a random value sampled from the given ranges. + + This class tracks the original CoM values and randomizes from those defaults on each call, + ensuring repeatable randomization across resets. + + Automatically detects the active physics backend: + + - **PhysX**: Passes the full CoM pose (position + quaternion) to ``set_coms_index``. + - **Newton**: Passes position-only (vec3) to ``set_coms_index``. Note that on Newton + (MuJoCo Warp), runtime CoM changes may cause simulation instability because + ``notify_model_changed(BODY_INERTIAL_PROPERTIES)`` does not fully recompute the + mass matrix after ``body_ipos`` changes. Use with caution until this is fixed upstream. + """ + + def __init__(self, cfg: EventTermCfg, env: ManagerBasedEnv): + """Initialize the term. + + Args: + cfg: The configuration of the event term. + env: The environment instance. + """ + super().__init__(cfg, env) + + self.asset_cfg: SceneEntityCfg = cfg.params["asset_cfg"] + self.asset: RigidObject | Articulation = env.scene[self.asset_cfg.name] + + # detect physics backend + manager_name = env.sim.physics_manager.__name__.lower() + self._is_newton = "newton" in manager_name + + self.default_com = None + + def __call__( + self, + env: ManagerBasedEnv, + env_ids: torch.Tensor | None, + com_range: dict[str, tuple[float, float]], + asset_cfg: SceneEntityCfg, + ): + # store default CoM on first call for repeatable randomization + if self.default_com is None: + self.default_com = self.asset.data.body_com_pose_b.torch.clone() + + # resolve environment ids + if env_ids is None: + env_ids = torch.arange(env.scene.num_envs, device=self.asset.device) + else: + env_ids = env_ids.to(self.asset.device) + + # resolve body indices + if self.asset_cfg.body_ids == slice(None): + body_ids = torch.arange(self.asset.num_bodies, dtype=torch.int, device=self.asset.device) + else: + body_ids = torch.tensor(self.asset_cfg.body_ids, dtype=torch.int, device=self.asset.device) + + # sample random CoM values + range_list = [com_range.get(key, (0.0, 0.0)) for key in ["x", "y", "z"]] + ranges = torch.tensor(range_list, device=self.asset.device) + rand_samples = math_utils.sample_uniform( + ranges[:, 0], ranges[:, 1], (len(env_ids), 3), device=self.asset.device + ).unsqueeze(1) + + # start from defaults and add random offsets + coms = self.default_com.clone() + coms[env_ids[:, None], body_ids, :3] += rand_samples + + # Newton expects position-only (vec3f), PhysX expects the full pose (pos + quat) + # note: pass partial data of shape (len(env_ids), len(body_ids), ...) to match the API + if self._is_newton: + self.asset.set_coms_index(coms=coms[env_ids[:, None], body_ids, :3], body_ids=body_ids, env_ids=env_ids) + else: + self.asset.set_coms_index(coms=coms[env_ids[:, None], body_ids], body_ids=body_ids, env_ids=env_ids) + + +class _RandomizeRigidBodyColliderOffsetsPhysx: + """PhysX backend implementation for collider offset randomization. + + Uses rest offset and contact offset directly via the PhysX tensor API. + """ + + def __init__(self, asset: RigidObject | Articulation): + self.asset = asset + self.default_rest_offsets = wp.to_torch(asset.root_view.get_rest_offsets()).clone() + self.default_contact_offsets = wp.to_torch(asset.root_view.get_contact_offsets()).clone() + + def __call__( + self, + env: ManagerBasedEnv, + env_ids: torch.Tensor | None, + asset_cfg: SceneEntityCfg, + rest_offset_distribution_params: tuple[float, float] | None = None, + contact_offset_distribution_params: tuple[float, float] | None = None, + distribution: Literal["uniform", "log_uniform", "gaussian"] = "uniform", + ): + if env_ids is None: + env_ids = torch.arange(env.scene.num_envs, device="cpu", dtype=torch.int32) + else: + env_ids = env_ids.to(device="cpu", dtype=torch.int32) + wp_env_ids = wp.from_torch(env_ids, dtype=wp.int32) + + if rest_offset_distribution_params is not None: + rest_offset = self.default_rest_offsets.clone() + rest_offset = _randomize_prop_by_op( + rest_offset, + rest_offset_distribution_params, + None, + slice(None), + operation="abs", + distribution=distribution, + ) + self.asset.root_view.set_rest_offsets(wp.from_torch(rest_offset), wp_env_ids) + + if contact_offset_distribution_params is not None: + contact_offset = self.default_contact_offsets.clone() + contact_offset = _randomize_prop_by_op( + contact_offset, + contact_offset_distribution_params, + None, + slice(None), + operation="abs", + distribution=distribution, + ) + self.asset.root_view.set_contact_offsets(wp.from_torch(contact_offset), wp_env_ids) + + +class _RandomizeRigidBodyColliderOffsetsNewton: + """Newton backend implementation for collider offset randomization. + + Maps PhysX concepts to Newton's geometry properties: + + - ``rest_offset`` -> ``shape_margin`` (Newton margin) + - ``contact_offset`` -> ``shape_gap`` (Newton gap = contact_offset - margin) + + See the `Newton collision schema`_ for details. + + .. _Newton collision schema: https://newton-physics.github.io/newton/latest/concepts/collisions.html + """ + + def __init__(self, asset: RigidObject | Articulation): + import isaaclab_newton.physics.newton_manager as newton_manager_module # noqa: PLC0415 + from newton.solvers import SolverNotifyFlags # noqa: PLC0415 + + self.asset = asset + self._newton_manager = newton_manager_module.NewtonManager + self._notify_shape_properties = SolverNotifyFlags.SHAPE_PROPERTIES + + model = self._newton_manager.get_model() + self._sim_bind_shape_margin = asset._root_view.get_attribute("shape_margin", model)[:, 0] # type: ignore + self._sim_bind_shape_gap = asset._root_view.get_attribute("shape_gap", model)[:, 0] # type: ignore + + self.default_margin = wp.to_torch(self._sim_bind_shape_margin).clone() + self.default_gap = wp.to_torch(self._sim_bind_shape_gap).clone() + + def __call__( + self, + env: ManagerBasedEnv, + env_ids: torch.Tensor | None, + asset_cfg: SceneEntityCfg, + rest_offset_distribution_params: tuple[float, float] | None = None, + contact_offset_distribution_params: tuple[float, float] | None = None, + distribution: Literal["uniform", "log_uniform", "gaussian"] = "uniform", + ): + device = env.device + if env_ids is None: + env_ids = torch.arange(env.scene.num_envs, device=device, dtype=torch.int32) + else: + env_ids = env_ids.to(device) + + margin_view = wp.to_torch(self._sim_bind_shape_margin) + + if rest_offset_distribution_params is not None: + margin = self.default_margin.clone() + margin = _randomize_prop_by_op( + margin, + rest_offset_distribution_params, + None, + slice(None), + operation="abs", + distribution=distribution, + ) + self.default_margin[env_ids] = margin[env_ids] + margin_view[env_ids] = margin[env_ids] + + if contact_offset_distribution_params is not None: + current_margin = self.default_margin + contact_offset = torch.zeros_like(self.default_gap) + contact_offset = _randomize_prop_by_op( + contact_offset, + contact_offset_distribution_params, + None, + slice(None), + operation="abs", + distribution=distribution, + ) + gap = torch.clamp(contact_offset - current_margin, min=0.0) + self.default_gap[env_ids] = gap[env_ids] + gap_view = wp.to_torch(self._sim_bind_shape_gap) + gap_view[env_ids] = gap[env_ids] + + if rest_offset_distribution_params is not None or contact_offset_distribution_params is not None: + self._newton_manager.add_model_change(self._notify_shape_properties) + + +class randomize_rigid_body_collider_offsets(ManagerTermBase): + """Randomize the collider parameters of rigid bodies by setting random values. This function allows randomizing the collider parameters of the asset, such as rest and contact offsets. - These correspond to the physics engine collider properties that affect the collision checking. + These correspond to the physics engine collider properties that affect collision checking. - The function samples random values from the given distribution parameters and applies the operation to - the collider properties. It then sets the values into the physics simulation. If the distribution parameters - are not provided for a particular property, the function does not modify the property. + Automatically detects the active physics backend (PhysX or Newton) and delegates to + the appropriate backend-specific implementation: + + - **PhysX**: Uses rest offset and contact offset directly via the PhysX tensor API + (``root_view.set_rest_offsets`` / ``root_view.set_contact_offsets``). + - **Newton**: Maps PhysX concepts to Newton's geometry properties. PhysX ``rest_offset`` + maps to Newton ``shape_margin``, and PhysX ``contact_offset`` is converted to Newton + ``shape_gap`` via ``gap = contact_offset - margin``. - Currently, the distribution parameters are applied as absolute values. + The function samples random values from the given distribution parameters and applies them + as absolute values to the collider properties. If the distribution parameters are not + provided for a particular property, the function does not modify it. .. tip:: - This function uses CPU tensors to assign the collision properties. It is recommended to use this function - only during the initialization of the environment. + This function uses CPU tensors (PhysX) or GPU tensors (Newton) to assign the collision + properties. It is recommended to use this function only during the initialization of + the environment. """ - # extract the used quantities (to enable type-hinting) - asset: RigidObject | Articulation = env.scene[asset_cfg.name] - # resolve environment ids - if env_ids is None: - env_ids = torch.arange(env.scene.num_envs, device="cpu") + def __init__(self, cfg: EventTermCfg, env: ManagerBasedEnv): + """Initialize the term. - # sample collider properties from the given ranges and set into the physics simulation - # -- rest offsets - if rest_offset_distribution_params is not None: - rest_offset = wp.to_torch(asset.root_view.get_rest_offsets()).clone() - rest_offset = _randomize_prop_by_op( - rest_offset, + Args: + cfg: The configuration of the event term. + env: The environment instance. + + Raises: + ValueError: If the asset is not a RigidObject or an Articulation. + """ + from isaaclab.assets import BaseArticulation, BaseRigidObject + + super().__init__(cfg, env) + + self.asset_cfg: SceneEntityCfg = cfg.params["asset_cfg"] + self.asset: RigidObject | Articulation = env.scene[self.asset_cfg.name] + + if not isinstance(self.asset, (BaseRigidObject, BaseArticulation)): + raise ValueError( + f"Randomization term 'randomize_rigid_body_collider_offsets' not supported for asset:" + f" '{self.asset_cfg.name}' with type: '{type(self.asset)}'." + ) + + # detect physics backend and instantiate the appropriate implementation + manager_name = env.sim.physics_manager.__name__.lower() + if "newton" in manager_name: + self._impl = _RandomizeRigidBodyColliderOffsetsNewton(self.asset) + else: + self._impl = _RandomizeRigidBodyColliderOffsetsPhysx(self.asset) + + def __call__( + self, + env: ManagerBasedEnv, + env_ids: torch.Tensor | None, + asset_cfg: SceneEntityCfg, + rest_offset_distribution_params: tuple[float, float] | None = None, + contact_offset_distribution_params: tuple[float, float] | None = None, + distribution: Literal["uniform", "log_uniform", "gaussian"] = "uniform", + ): + self._impl( + env, + env_ids, + asset_cfg, rest_offset_distribution_params, - None, - slice(None), - operation="abs", - distribution=distribution, - ) - asset.root_view.set_rest_offsets(rest_offset, env_ids.cpu()) - # -- contact offsets - if contact_offset_distribution_params is not None: - contact_offset = wp.to_torch(asset.root_view.get_contact_offsets()).clone() - contact_offset = _randomize_prop_by_op( - contact_offset, contact_offset_distribution_params, - None, - slice(None), - operation="abs", - distribution=distribution, + distribution, ) - asset.root_view.set_contact_offsets(contact_offset, env_ids.cpu()) class randomize_physics_scene_gravity(ManagerTermBase): @@ -687,8 +1132,16 @@ def __init__(self, cfg: EventTermCfg, env: ManagerBasedEnv): self.asset_cfg: SceneEntityCfg = cfg.params["asset_cfg"] self.asset: RigidObject | Articulation = env.scene[self.asset_cfg.name] - self.default_joint_stiffness = wp.to_torch(self.asset.data.joint_stiffness).clone() - self.default_joint_damping = wp.to_torch(self.asset.data.joint_damping).clone() + self.default_joint_stiffness = self.asset.data.joint_stiffness.torch.clone() + self.default_joint_damping = self.asset.data.joint_damping.torch.clone() + + # For explicit actuators the sim-level stiffness/damping is zeroed out, so patch + # the defaults with the actual actuator PD gains. + for actuator in self.asset.actuators.values(): + if not isinstance(actuator, ImplicitActuator): + joint_ids = actuator.joint_indices + self.default_joint_stiffness[:, joint_ids] = actuator.stiffness + self.default_joint_damping[:, joint_ids] = actuator.damping # check for valid operation if cfg.params["operation"] == "scale": @@ -802,13 +1255,21 @@ def __init__(self, cfg: EventTermCfg, env: ManagerBasedEnv): # extract the used quantities (to enable type-hinting) self.asset_cfg: SceneEntityCfg = cfg.params["asset_cfg"] - self.asset: RigidObject | Articulation = env.scene[self.asset_cfg.name] + self.asset: Articulation = env.scene[self.asset_cfg.name] + + # detect physics backend + manager_name = env.sim.physics_manager.__name__.lower() + self._backend = "newton" if "newton" in manager_name else "physx" + + # cache default values (common to both backends) + self.default_joint_friction_coeff = self.asset.data.joint_friction_coeff.torch.clone() + self.default_joint_armature = self.asset.data.joint_armature.torch.clone() + self.default_joint_pos_limits = self.asset.data.joint_pos_limits.torch.clone() - self.default_joint_friction_coeff = wp.to_torch(self.asset.data.joint_friction_coeff).clone() - self.default_dynamic_joint_friction_coeff = wp.to_torch(self.asset.data.joint_dynamic_friction_coeff).clone() - self.default_viscous_joint_friction_coeff = wp.to_torch(self.asset.data.joint_viscous_friction_coeff).clone() - self.default_joint_armature = wp.to_torch(self.asset.data.joint_armature).clone() - self.default_joint_pos_limits = wp.to_torch(self.asset.data.joint_pos_limits).clone() + # cache dynamic/viscous friction (PhysX only - Newton only has static friction) + if self._backend == "physx": + self.default_dynamic_joint_friction_coeff = (self.asset.data.joint_dynamic_friction_coeff.torch).clone() + self.default_viscous_joint_friction_coeff = (self.asset.data.joint_viscous_friction_coeff.torch).clone() # check for valid operation if cfg.params["operation"] == "scale": @@ -867,8 +1328,14 @@ def __call__( # Always set static friction (indexed once) static_friction_coeff = friction_coeff[env_ids_for_slice, joint_ids] - # if isaacsim version is lower than 5.0.0 we can set only the static friction coefficient - if get_isaac_sim_version().major >= 5: + if self._backend == "newton": + # Newton only supports static friction coefficient + self.asset.write_joint_friction_coefficient_to_sim_index( + joint_friction_coeff=static_friction_coeff, + joint_ids=joint_ids, + env_ids=env_ids, + ) + else: # Randomize raw tensors dynamic_friction_coeff = _randomize_prop_by_op( self.default_dynamic_joint_friction_coeff.clone(), @@ -897,24 +1364,20 @@ def __call__( # Index once at the end dynamic_friction_coeff = dynamic_friction_coeff[env_ids_for_slice, joint_ids] viscous_friction_coeff = viscous_friction_coeff[env_ids_for_slice, joint_ids] - else: - # For versions < 5.0.0, we do not set these values - dynamic_friction_coeff = None - viscous_friction_coeff = None - - # Single write call for all versions - self.asset.write_joint_friction_coefficient_to_sim_index( - joint_friction_coeff=static_friction_coeff, - joint_dynamic_friction_coeff=dynamic_friction_coeff, - joint_viscous_friction_coeff=viscous_friction_coeff, - joint_ids=joint_ids, - env_ids=env_ids, - ) + + # Single write call for all versions + self.asset.write_joint_friction_coefficient_to_sim_index( + joint_friction_coeff=static_friction_coeff, + joint_dynamic_friction_coeff=dynamic_friction_coeff, + joint_viscous_friction_coeff=viscous_friction_coeff, + joint_ids=joint_ids, + env_ids=env_ids, + ) # joint armature if armature_distribution_params is not None: armature = _randomize_prop_by_op( - wp.to_torch(self.asset.data.default_joint_armature).clone(), + self.asset.data.default_joint_armature.torch.clone(), armature_distribution_params, env_ids, joint_ids, @@ -1038,7 +1501,7 @@ def __call__( # stiffness if stiffness_distribution_params is not None: stiffness = _randomize_prop_by_op( - wp.to_torch(self.asset.data.fixed_tendon_stiffness).clone(), + self.asset.data.fixed_tendon_stiffness.torch.clone(), stiffness_distribution_params, env_ids, tendon_ids, @@ -1052,7 +1515,7 @@ def __call__( # damping if damping_distribution_params is not None: damping = _randomize_prop_by_op( - wp.to_torch(self.asset.data.fixed_tendon_damping).clone(), + self.asset.data.fixed_tendon_damping.torch.clone(), damping_distribution_params, env_ids, tendon_ids, @@ -1066,7 +1529,7 @@ def __call__( # limit stiffness if limit_stiffness_distribution_params is not None: limit_stiffness = _randomize_prop_by_op( - wp.to_torch(self.asset.data.fixed_tendon_limit_stiffness).clone(), + self.asset.data.fixed_tendon_limit_stiffness.torch.clone(), limit_stiffness_distribution_params, env_ids, tendon_ids, @@ -1079,7 +1542,7 @@ def __call__( # position limits if lower_limit_distribution_params is not None or upper_limit_distribution_params is not None: - limit = wp.to_torch(self.asset.data.fixed_tendon_pos_limits).clone() + limit = self.asset.data.fixed_tendon_pos_limits.torch.clone() # -- lower limit if lower_limit_distribution_params is not None: limit[..., 0] = _randomize_prop_by_op( @@ -1115,7 +1578,7 @@ def __call__( # rest length if rest_length_distribution_params is not None: rest_length = _randomize_prop_by_op( - wp.to_torch(self.asset.data.fixed_tendon_rest_length).clone(), + self.asset.data.fixed_tendon_rest_length.torch.clone(), rest_length_distribution_params, env_ids, tendon_ids, @@ -1129,7 +1592,7 @@ def __call__( # offset if offset_distribution_params is not None: offset = _randomize_prop_by_op( - wp.to_torch(self.asset.data.fixed_tendon_offset).clone(), + self.asset.data.fixed_tendon_offset.torch.clone(), offset_distribution_params, env_ids, tendon_ids, @@ -1201,7 +1664,7 @@ def push_by_setting_velocity( asset: RigidObject | Articulation = env.scene[asset_cfg.name] # velocities - vel_w = wp.to_torch(asset.data.root_vel_w)[env_ids] + vel_w = asset.data.root_vel_w.torch[env_ids] # sample random velocities range_list = [velocity_range.get(key, (0.0, 0.0)) for key in ["x", "y", "z", "roll", "pitch", "yaw"]] ranges = torch.tensor(range_list, device=asset.device) @@ -1233,8 +1696,8 @@ def reset_root_state_uniform( # extract the used quantities (to enable type-hinting) asset: RigidObject | Articulation = env.scene[asset_cfg.name] # get default root state - default_root_pose = wp.to_torch(asset.data.default_root_pose)[env_ids].clone() - default_root_vel = wp.to_torch(asset.data.default_root_vel)[env_ids].clone() + default_root_pose = asset.data.default_root_pose.torch[env_ids].clone() + default_root_vel = asset.data.default_root_vel.torch[env_ids].clone() # poses range_list = [pose_range.get(key, (0.0, 0.0)) for key in ["x", "y", "z", "roll", "pitch", "yaw"]] @@ -1286,8 +1749,8 @@ def reset_root_state_with_random_orientation( # extract the used quantities (to enable type-hinting) asset: RigidObject | Articulation = env.scene[asset_cfg.name] # get default root state - default_root_pose = wp.to_torch(asset.data.default_root_pose)[env_ids].clone() - default_root_vel = wp.to_torch(asset.data.default_root_vel)[env_ids].clone() + default_root_pose = asset.data.default_root_pose.torch[env_ids].clone() + default_root_vel = asset.data.default_root_vel.torch[env_ids].clone() # poses range_list = [pose_range.get(key, (0.0, 0.0)) for key in ["x", "y", "z"]] @@ -1354,7 +1817,7 @@ def reset_root_state_from_terrain( # sample random valid poses ids = torch.randint(0, valid_positions.shape[2], size=(len(env_ids),), device=env.device) positions = valid_positions[terrain.terrain_levels[env_ids], terrain.terrain_types[env_ids], ids] - positions += wp.to_torch(asset.data.default_root_pose)[env_ids, :3] + positions += asset.data.default_root_pose.torch[env_ids, :3] # sample random orientations range_list = [pose_range.get(key, (0.0, 0.0)) for key in ["roll", "pitch", "yaw"]] @@ -1369,7 +1832,7 @@ def reset_root_state_from_terrain( ranges = torch.tensor(range_list, device=asset.device) rand_samples = math_utils.sample_uniform(ranges[:, 0], ranges[:, 1], (len(env_ids), 6), device=asset.device) - velocities = wp.to_torch(asset.data.default_root_vel)[env_ids] + rand_samples + velocities = asset.data.default_root_vel.torch[env_ids] + rand_samples # set into the physics simulation asset.write_root_pose_to_sim_index(root_pose=torch.cat([positions, orientations], dim=-1), env_ids=env_ids) @@ -1398,18 +1861,18 @@ def reset_joints_by_scale( iter_env_ids = env_ids # get default joint state - joint_pos = wp.to_torch(asset.data.default_joint_pos)[iter_env_ids, asset_cfg.joint_ids].clone() - joint_vel = wp.to_torch(asset.data.default_joint_vel)[iter_env_ids, asset_cfg.joint_ids].clone() + joint_pos = asset.data.default_joint_pos.torch[iter_env_ids, asset_cfg.joint_ids].clone() + joint_vel = asset.data.default_joint_vel.torch[iter_env_ids, asset_cfg.joint_ids].clone() # scale these values randomly joint_pos *= math_utils.sample_uniform(*position_range, joint_pos.shape, joint_pos.device) joint_vel *= math_utils.sample_uniform(*velocity_range, joint_vel.shape, joint_vel.device) # clamp joint pos to limits - joint_pos_limits = wp.to_torch(asset.data.soft_joint_pos_limits)[iter_env_ids, asset_cfg.joint_ids] + joint_pos_limits = asset.data.soft_joint_pos_limits.torch[iter_env_ids, asset_cfg.joint_ids] joint_pos = joint_pos.clamp_(joint_pos_limits[..., 0], joint_pos_limits[..., 1]) # clamp joint vel to limits - joint_vel_limits = wp.to_torch(asset.data.soft_joint_vel_limits)[iter_env_ids, asset_cfg.joint_ids] + joint_vel_limits = asset.data.soft_joint_vel_limits.torch[iter_env_ids, asset_cfg.joint_ids] joint_vel = joint_vel.clamp_(-joint_vel_limits, joint_vel_limits) # set into the physics simulation @@ -1439,18 +1902,18 @@ def reset_joints_by_offset( iter_env_ids = env_ids # get default joint state - joint_pos = wp.to_torch(asset.data.default_joint_pos)[iter_env_ids, asset_cfg.joint_ids].clone() - joint_vel = wp.to_torch(asset.data.default_joint_vel)[iter_env_ids, asset_cfg.joint_ids].clone() + joint_pos = asset.data.default_joint_pos.torch[iter_env_ids, asset_cfg.joint_ids].clone() + joint_vel = asset.data.default_joint_vel.torch[iter_env_ids, asset_cfg.joint_ids].clone() # bias these values randomly joint_pos += math_utils.sample_uniform(*position_range, joint_pos.shape, joint_pos.device) joint_vel += math_utils.sample_uniform(*velocity_range, joint_vel.shape, joint_vel.device) # clamp joint pos to limits - joint_pos_limits = wp.to_torch(asset.data.soft_joint_pos_limits)[iter_env_ids, asset_cfg.joint_ids] + joint_pos_limits = asset.data.soft_joint_pos_limits.torch[iter_env_ids, asset_cfg.joint_ids] joint_pos = joint_pos.clamp_(joint_pos_limits[..., 0], joint_pos_limits[..., 1]) # clamp joint vel to limits - joint_vel_limits = wp.to_torch(asset.data.soft_joint_vel_limits)[iter_env_ids, asset_cfg.joint_ids] + joint_vel_limits = asset.data.soft_joint_vel_limits.torch[iter_env_ids, asset_cfg.joint_ids] joint_vel = joint_vel.clamp_(-joint_vel_limits, joint_vel_limits) # set into the physics simulation @@ -1480,7 +1943,7 @@ def reset_nodal_state_uniform( # extract the used quantities (to enable type-hinting) asset: DeformableObject = env.scene[asset_cfg.name] # get default root state - nodal_state = wp.to_torch(asset.data.default_nodal_state_w)[env_ids].clone() + nodal_state = asset.data.default_nodal_state_w.torch[env_ids].clone() # position range_list = [position_range.get(key, (0.0, 0.0)) for key in ["x", "y", "z"]] @@ -1511,8 +1974,8 @@ def reset_scene_to_default(env: ManagerBasedEnv, env_ids: torch.Tensor, reset_jo # rigid bodies for rigid_object in env.scene.rigid_objects.values(): # obtain default and deal with the offset for env origins - default_root_pose = wp.to_torch(rigid_object.data.default_root_pose)[env_ids].clone() - default_root_vel = wp.to_torch(rigid_object.data.default_root_vel)[env_ids].clone() + default_root_pose = rigid_object.data.default_root_pose.torch[env_ids].clone() + default_root_vel = rigid_object.data.default_root_vel.torch[env_ids].clone() default_root_pose[:, :3] += env.scene.env_origins[env_ids] # set into the physics simulation rigid_object.write_root_pose_to_sim_index(root_pose=default_root_pose, env_ids=env_ids) @@ -1520,15 +1983,15 @@ def reset_scene_to_default(env: ManagerBasedEnv, env_ids: torch.Tensor, reset_jo # articulations for articulation_asset in env.scene.articulations.values(): # obtain default and deal with the offset for env origins - default_root_pose = wp.to_torch(articulation_asset.data.default_root_pose)[env_ids].clone() - default_root_vel = wp.to_torch(articulation_asset.data.default_root_vel)[env_ids].clone() + default_root_pose = articulation_asset.data.default_root_pose.torch[env_ids].clone() + default_root_vel = articulation_asset.data.default_root_vel.torch[env_ids].clone() default_root_pose[:, :3] += env.scene.env_origins[env_ids] # set into the physics simulation articulation_asset.write_root_pose_to_sim_index(root_pose=default_root_pose, env_ids=env_ids) articulation_asset.write_root_velocity_to_sim_index(root_velocity=default_root_vel, env_ids=env_ids) # obtain default joint positions - default_joint_pos = wp.to_torch(articulation_asset.data.default_joint_pos)[env_ids].clone() - default_joint_vel = wp.to_torch(articulation_asset.data.default_joint_vel)[env_ids].clone() + default_joint_pos = articulation_asset.data.default_joint_pos.torch[env_ids].clone() + default_joint_vel = articulation_asset.data.default_joint_vel.torch[env_ids].clone() # set into the physics simulation articulation_asset.write_joint_position_to_sim_index(position=default_joint_pos, env_ids=env_ids) articulation_asset.write_joint_velocity_to_sim_index(velocity=default_joint_vel, env_ids=env_ids) @@ -1539,7 +2002,7 @@ def reset_scene_to_default(env: ManagerBasedEnv, env_ids: torch.Tensor, reset_jo # deformable objects for deformable_object in env.scene.deformable_objects.values(): # obtain default and set into the physics simulation - nodal_state = wp.to_torch(deformable_object.data.default_nodal_state_w)[env_ids].clone() + nodal_state = deformable_object.data.default_nodal_state_w.torch[env_ids].clone() deformable_object.write_nodal_state_to_sim(nodal_state, env_ids=env_ids) @@ -1582,7 +2045,7 @@ def __init__(self, cfg: EventTermCfg, env: ManagerBasedEnv): ) # enable replicator extension if not already enabled (local: isaacsim only available with Kit) - from isaacsim.core.utils.extensions import enable_extension # noqa: PLC0415 + from isaacsim.core.experimental.utils.app import enable_extension # noqa: PLC0415 enable_extension("omni.replicator.core") # we import the module here since we may not always need the replicator @@ -1665,9 +2128,18 @@ def rep_texture_randomization(): if prim.IsInstanceable(): prim.SetInstanceable(False) + # Resolve OmniPBR.mdl to an absolute path so that pxr.Ar.GetResolver().Resolve() + # returns a valid path. Kit's omni_usd_resolver intentionally returns "" for builtin + # MDL short-names (OMNI_USD_RESOLVER_MDL_BUILTIN_BYPASS=1), which causes Replicator + # >= 1.13.0 to pass an empty resolved path into UsdMdl.RegistryUtils, raising a + # 'rtx::neuraylib::MdlModuleId' is Invalid error. + import carb.tokens # noqa: PLC0415 + + omni_pbr_mdl = carb.tokens.get_tokens_interface().resolve("${kit}/mdl/core/Base/OmniPBR.mdl") + # TODO: Should we specify the value when creating the material? self.material_prims = rep.functional.create_batch.material( - mdl="OmniPBR.mdl", bind_prims=prims_group, count=num_prims, project_uvw=True + mdl=omni_pbr_mdl, bind_prims=prims_group, count=num_prims, project_uvw=True ) def __call__( @@ -1744,7 +2216,7 @@ def __init__(self, cfg: EventTermCfg, env: ManagerBasedEnv): super().__init__(cfg, env) # enable replicator extension if not already enabled (local: isaacsim only available with Kit) - from isaacsim.core.utils.extensions import enable_extension # noqa: PLC0415 + from isaacsim.core.experimental.utils.app import enable_extension # noqa: PLC0415 enable_extension("omni.replicator.core") # we import the module here since we may not always need the replicator @@ -1814,9 +2286,18 @@ def rep_color_randomization(): if prim.IsInstanceable(): prim.SetInstanceable(False) + # Resolve OmniPBR.mdl to an absolute path so that pxr.Ar.GetResolver().Resolve() + # returns a valid path. Kit's omni_usd_resolver intentionally returns "" for builtin + # MDL short-names (OMNI_USD_RESOLVER_MDL_BUILTIN_BYPASS=1), which causes Replicator + # >= 1.13.0 to pass an empty resolved path into UsdMdl.RegistryUtils, raising a + # 'rtx::neuraylib::MdlModuleId' is Invalid error. + import carb.tokens # noqa: PLC0415 + + omni_pbr_mdl = carb.tokens.get_tokens_interface().resolve("${kit}/mdl/core/Base/OmniPBR.mdl") + # TODO: Should we specify the value when creating the material? self.material_prims = rep.functional.create_batch.material( - mdl="OmniPBR.mdl", bind_prims=prims_group, count=num_prims, project_uvw=True + mdl=omni_pbr_mdl, bind_prims=prims_group, count=num_prims, project_uvw=True ) def __call__( diff --git a/source/isaaclab/isaaclab/envs/mdp/observations.py b/source/isaaclab/isaaclab/envs/mdp/observations.py index 5bae5ec2d545..8f97da3595dd 100644 --- a/source/isaaclab/isaaclab/envs/mdp/observations.py +++ b/source/isaaclab/isaaclab/envs/mdp/observations.py @@ -14,7 +14,6 @@ from typing import TYPE_CHECKING import torch -import warp as wp import isaaclab.utils.math as math_utils from isaaclab.managers import SceneEntityCfg @@ -24,7 +23,7 @@ if TYPE_CHECKING: from isaaclab.assets import Articulation, RigidObject from isaaclab.envs import ManagerBasedEnv, ManagerBasedRLEnv - from isaaclab.sensors import Camera, Imu, RayCaster, RayCasterCamera, TiledCamera + from isaaclab.sensors import Camera, Imu, JointWrenchSensor, Pva, RayCaster, RayCasterCamera from isaaclab.envs.utils.io_descriptors import ( generic_io_descriptor, @@ -46,7 +45,7 @@ def base_pos_z(env: ManagerBasedEnv, asset_cfg: SceneEntityCfg = SceneEntityCfg( """Root height in the simulation world frame.""" # extract the used quantities (to enable type-hinting) asset: Articulation = env.scene[asset_cfg.name] - return wp.to_torch(asset.data.root_pos_w)[:, 2].unsqueeze(-1) + return asset.data.root_pos_w.torch[:, 2].unsqueeze(-1) @generic_io_descriptor( @@ -56,7 +55,7 @@ def base_lin_vel(env: ManagerBasedEnv, asset_cfg: SceneEntityCfg = SceneEntityCf """Root linear velocity in the asset's root frame.""" # extract the used quantities (to enable type-hinting) asset: RigidObject = env.scene[asset_cfg.name] - return wp.to_torch(asset.data.root_lin_vel_b) + return asset.data.root_lin_vel_b.torch @generic_io_descriptor( @@ -66,7 +65,7 @@ def base_ang_vel(env: ManagerBasedEnv, asset_cfg: SceneEntityCfg = SceneEntityCf """Root angular velocity in the asset's root frame.""" # extract the used quantities (to enable type-hinting) asset: RigidObject = env.scene[asset_cfg.name] - return wp.to_torch(asset.data.root_ang_vel_b) + return asset.data.root_ang_vel_b.torch @generic_io_descriptor( @@ -76,7 +75,7 @@ def projected_gravity(env: ManagerBasedEnv, asset_cfg: SceneEntityCfg = SceneEnt """Gravity projection on the asset's root frame.""" # extract the used quantities (to enable type-hinting) asset: RigidObject = env.scene[asset_cfg.name] - return wp.to_torch(asset.data.projected_gravity_b) + return asset.data.projected_gravity_b.torch @generic_io_descriptor( @@ -86,7 +85,7 @@ def root_pos_w(env: ManagerBasedEnv, asset_cfg: SceneEntityCfg = SceneEntityCfg( """Asset root position in the environment frame.""" # extract the used quantities (to enable type-hinting) asset: RigidObject = env.scene[asset_cfg.name] - return wp.to_torch(asset.data.root_pos_w) - env.scene.env_origins + return asset.data.root_pos_w.torch - env.scene.env_origins @generic_io_descriptor( @@ -104,7 +103,7 @@ def root_quat_w( # extract the used quantities (to enable type-hinting) asset: RigidObject = env.scene[asset_cfg.name] - quat = wp.to_torch(asset.data.root_quat_w) + quat = asset.data.root_quat_w.torch # make the quaternion real-part positive if configured return math_utils.quat_unique(quat) if make_quat_unique else quat @@ -116,7 +115,7 @@ def root_lin_vel_w(env: ManagerBasedEnv, asset_cfg: SceneEntityCfg = SceneEntity """Asset root linear velocity in the environment frame.""" # extract the used quantities (to enable type-hinting) asset: RigidObject = env.scene[asset_cfg.name] - return wp.to_torch(asset.data.root_lin_vel_w) + return asset.data.root_lin_vel_w.torch @generic_io_descriptor( @@ -126,7 +125,7 @@ def root_ang_vel_w(env: ManagerBasedEnv, asset_cfg: SceneEntityCfg = SceneEntity """Asset root angular velocity in the environment frame.""" # extract the used quantities (to enable type-hinting) asset: RigidObject = env.scene[asset_cfg.name] - return wp.to_torch(asset.data.root_ang_vel_w) + return asset.data.root_ang_vel_w.torch """ @@ -155,7 +154,7 @@ def body_pose_w( asset: Articulation = env.scene[asset_cfg.name] # access the body poses in world frame - pose = wp.to_torch(asset.data.body_pose_w)[:, asset_cfg.body_ids, :7] + pose = asset.data.body_pose_w.torch[:, asset_cfg.body_ids, :7] if isinstance(asset_cfg.body_ids, (slice, int)): pose = pose.clone() # if slice or int, make a copy to avoid modifying original data pose[..., :3] = pose[..., :3] - env.scene.env_origins.unsqueeze(1) @@ -182,8 +181,8 @@ def body_projected_gravity_b( # extract the used quantities (to enable type-hinting) asset: Articulation = env.scene[asset_cfg.name] - body_quat = wp.to_torch(asset.data.body_quat_w)[:, asset_cfg.body_ids] - gravity_dir = wp.to_torch(asset.data.GRAVITY_VEC_W).unsqueeze(1) + body_quat = asset.data.body_quat_w.torch[:, asset_cfg.body_ids] + gravity_dir = asset.data.GRAVITY_VEC_W.torch.unsqueeze(1) return math_utils.quat_apply_inverse(body_quat, gravity_dir).view(env.num_envs, -1) @@ -202,7 +201,7 @@ def joint_pos(env: ManagerBasedEnv, asset_cfg: SceneEntityCfg = SceneEntityCfg(" """ # extract the used quantities (to enable type-hinting) asset: Articulation = env.scene[asset_cfg.name] - return wp.to_torch(asset.data.joint_pos)[:, asset_cfg.joint_ids] + return asset.data.joint_pos.torch[:, asset_cfg.joint_ids] @generic_io_descriptor( @@ -218,8 +217,7 @@ def joint_pos_rel(env: ManagerBasedEnv, asset_cfg: SceneEntityCfg = SceneEntityC # extract the used quantities (to enable type-hinting) asset: Articulation = env.scene[asset_cfg.name] return ( - wp.to_torch(asset.data.joint_pos)[:, asset_cfg.joint_ids] - - wp.to_torch(asset.data.default_joint_pos)[:, asset_cfg.joint_ids] + asset.data.joint_pos.torch[:, asset_cfg.joint_ids] - asset.data.default_joint_pos.torch[:, asset_cfg.joint_ids] ) @@ -234,9 +232,9 @@ def joint_pos_limit_normalized( # extract the used quantities (to enable type-hinting) asset: Articulation = env.scene[asset_cfg.name] return math_utils.scale_transform( - wp.to_torch(asset.data.joint_pos)[:, asset_cfg.joint_ids], - wp.to_torch(asset.data.soft_joint_pos_limits)[:, asset_cfg.joint_ids, 0], - wp.to_torch(asset.data.soft_joint_pos_limits)[:, asset_cfg.joint_ids, 1], + asset.data.joint_pos.torch[:, asset_cfg.joint_ids], + asset.data.soft_joint_pos_limits.torch[:, asset_cfg.joint_ids, 0], + asset.data.soft_joint_pos_limits.torch[:, asset_cfg.joint_ids, 1], ) @@ -250,7 +248,7 @@ def joint_vel(env: ManagerBasedEnv, asset_cfg: SceneEntityCfg = SceneEntityCfg(" """ # extract the used quantities (to enable type-hinting) asset: Articulation = env.scene[asset_cfg.name] - return wp.to_torch(asset.data.joint_vel)[:, asset_cfg.joint_ids] + return asset.data.joint_vel.torch[:, asset_cfg.joint_ids] @generic_io_descriptor( @@ -266,8 +264,7 @@ def joint_vel_rel(env: ManagerBasedEnv, asset_cfg: SceneEntityCfg = SceneEntityC # extract the used quantities (to enable type-hinting) asset: Articulation = env.scene[asset_cfg.name] return ( - wp.to_torch(asset.data.joint_vel)[:, asset_cfg.joint_ids] - - wp.to_torch(asset.data.default_joint_vel)[:, asset_cfg.joint_ids] + asset.data.joint_vel.torch[:, asset_cfg.joint_ids] - asset.data.default_joint_vel.torch[:, asset_cfg.joint_ids] ) @@ -288,7 +285,7 @@ def joint_effort(env: ManagerBasedEnv, asset_cfg: SceneEntityCfg = SceneEntityCf """ # extract the used quantities (to enable type-hinting) asset: Articulation = env.scene[asset_cfg.name] - return wp.to_torch(asset.data.applied_torque)[:, asset_cfg.joint_ids] + return asset.data.applied_torque.torch[:, asset_cfg.joint_ids] """ @@ -304,80 +301,80 @@ def height_scan(env: ManagerBasedEnv, sensor_cfg: SceneEntityCfg, offset: float # extract the used quantities (to enable type-hinting) sensor: RayCaster = env.scene.sensors[sensor_cfg.name] # height scan: height = sensor_height - hit_point_z - offset - return sensor.data.pos_w[:, 2].unsqueeze(1) - sensor.data.ray_hits_w[..., 2] - offset + return sensor.data.pos_w.torch[:, 2].unsqueeze(1) - sensor.data.ray_hits_w.torch[..., 2] - offset -def body_incoming_wrench(env: ManagerBasedEnv, asset_cfg: SceneEntityCfg) -> torch.Tensor: - """Incoming spatial wrench on bodies of an articulation in the simulation world frame. +def body_incoming_wrench(env: ManagerBasedEnv, sensor_cfg: SceneEntityCfg) -> torch.Tensor: + """Incoming spatial wrench [N, N·m] on bodies of an articulation in the sensor convention. - This is the 6-D wrench (force and torque) applied to the body link by the incoming joint force. + This is the 6-D wrench (force followed by torque) applied to the body link by the incoming joint force. """ # extract the used quantities (to enable type-hinting) - asset: Articulation = env.scene[asset_cfg.name] - # obtain the link incoming forces in world frame - body_incoming_joint_wrench_b = wp.to_torch(asset.data.body_incoming_joint_wrench_b)[:, asset_cfg.body_ids] - return body_incoming_joint_wrench_b.view(env.num_envs, -1) + sensor: JointWrenchSensor = env.scene.sensors[sensor_cfg.name] + sensor_data = sensor.data + force_data = sensor_data.force + torque_data = sensor_data.torque + if force_data is None or torque_data is None: + raise RuntimeError("Joint wrench sensor data is not initialized. Call sim.reset() before reading observations.") + force = force_data.torch[:, sensor_cfg.body_ids] + torque = torque_data.torch[:, sensor_cfg.body_ids] + return torch.cat((force, torque), dim=-1).view(env.num_envs, -1) -def imu_orientation(env: ManagerBasedEnv, asset_cfg: SceneEntityCfg = SceneEntityCfg("imu")) -> torch.Tensor: - """Imu sensor orientation in the simulation world frame. +def pva_orientation(env: ManagerBasedEnv, asset_cfg: SceneEntityCfg = SceneEntityCfg("pva")) -> torch.Tensor: + """PVA sensor orientation in the simulation world frame. Args: env: The environment. - asset_cfg: The SceneEntity associated with an IMU sensor. Defaults to SceneEntityCfg("imu"). + asset_cfg: The SceneEntity associated with a PVA sensor. Defaults to SceneEntityCfg("pva"). Returns: Orientation in the world frame in (x, y, z, w) quaternion form. Shape is (num_envs, 4). """ - # extract the used quantities (to enable type-hinting) - asset: Imu = env.scene[asset_cfg.name] - # return the orientation quaternion - return wp.to_torch(asset.data.quat_w) + asset: Pva = env.scene[asset_cfg.name] + return asset.data.quat_w.torch -def imu_projected_gravity(env: ManagerBasedEnv, asset_cfg: SceneEntityCfg = SceneEntityCfg("imu")) -> torch.Tensor: - """Imu sensor orientation w.r.t the env.scene.origin. +def pva_projected_gravity(env: ManagerBasedEnv, asset_cfg: SceneEntityCfg = SceneEntityCfg("pva")) -> torch.Tensor: + """PVA sensor projected gravity in the sensor frame. Args: env: The environment. - asset_cfg: The SceneEntity associated with an Imu sensor. + asset_cfg: The SceneEntity associated with a PVA sensor. Defaults to SceneEntityCfg("pva"). Returns: - Gravity projected on imu_frame, shape of torch.tensor is (num_env,3). + Gravity projected on sensor frame, shape of torch.tensor is (num_env, 3). """ - - asset: Imu = env.scene[asset_cfg.name] - return wp.to_torch(asset.data.projected_gravity_b) + asset: Pva = env.scene[asset_cfg.name] + return asset.data.projected_gravity_b.torch def imu_ang_vel(env: ManagerBasedEnv, asset_cfg: SceneEntityCfg = SceneEntityCfg("imu")) -> torch.Tensor: - """Imu sensor angular velocity w.r.t. environment origin expressed in the sensor frame. + """IMU sensor angular velocity w.r.t. environment origin expressed in the sensor frame [rad/s]. Args: env: The environment. asset_cfg: The SceneEntity associated with an IMU sensor. Defaults to SceneEntityCfg("imu"). Returns: - The angular velocity (rad/s) in the sensor frame. Shape is (num_envs, 3). + The angular velocity [rad/s] in the sensor frame. Shape is (num_envs, 3). """ - # extract the used quantities (to enable type-hinting) asset: Imu = env.scene[asset_cfg.name] - # return the angular velocity - return wp.to_torch(asset.data.ang_vel_b) + return asset.data.ang_vel_b.torch def imu_lin_acc(env: ManagerBasedEnv, asset_cfg: SceneEntityCfg = SceneEntityCfg("imu")) -> torch.Tensor: - """Imu sensor linear acceleration w.r.t. the environment origin expressed in sensor frame. + """IMU sensor linear acceleration w.r.t. the environment origin expressed in sensor frame [m/s^2]. Args: env: The environment. asset_cfg: The SceneEntity associated with an IMU sensor. Defaults to SceneEntityCfg("imu"). Returns: - The linear acceleration (m/s^2) in the sensor frame. Shape is (num_envs, 3). + The linear acceleration [m/s^2] in the sensor frame. Shape is (num_envs, 3). """ asset: Imu = env.scene[asset_cfg.name] - return wp.to_torch(asset.data.lin_acc_b) + return asset.data.lin_acc_b.torch def image( @@ -408,7 +405,7 @@ def image( The images produced at the last time-step """ # extract the used quantities (to enable type-hinting) - sensor: TiledCamera | Camera | RayCasterCamera = env.scene.sensors[sensor_cfg.name] + sensor: Camera | RayCasterCamera = env.scene.sensors[sensor_cfg.name] # obtain the input image images = sensor.data.output[data_type] diff --git a/source/isaaclab/isaaclab/envs/mdp/rewards.py b/source/isaaclab/isaaclab/envs/mdp/rewards.py index 5a53583f5e4b..4645e4fd805e 100644 --- a/source/isaaclab/isaaclab/envs/mdp/rewards.py +++ b/source/isaaclab/isaaclab/envs/mdp/rewards.py @@ -14,7 +14,6 @@ from typing import TYPE_CHECKING import torch -import warp as wp from isaaclab.managers import SceneEntityCfg from isaaclab.managers.manager_base import ManagerTermBase @@ -79,14 +78,14 @@ def lin_vel_z_l2(env: ManagerBasedRLEnv, asset_cfg: SceneEntityCfg = SceneEntity """Penalize z-axis base linear velocity using L2 squared kernel.""" # extract the used quantities (to enable type-hinting) asset: RigidObject = env.scene[asset_cfg.name] - return torch.square(wp.to_torch(asset.data.root_lin_vel_b)[:, 2]) + return torch.square(asset.data.root_lin_vel_b.torch[:, 2]) def ang_vel_xy_l2(env: ManagerBasedRLEnv, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")) -> torch.Tensor: """Penalize xy-axis base angular velocity using L2 squared kernel.""" # extract the used quantities (to enable type-hinting) asset: RigidObject = env.scene[asset_cfg.name] - return torch.sum(torch.square(wp.to_torch(asset.data.root_ang_vel_b)[:, :2]), dim=1) + return torch.sum(torch.square(asset.data.root_ang_vel_b.torch[:, :2]), dim=1) def flat_orientation_l2(env: ManagerBasedRLEnv, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")) -> torch.Tensor: @@ -96,7 +95,7 @@ def flat_orientation_l2(env: ManagerBasedRLEnv, asset_cfg: SceneEntityCfg = Scen """ # extract the used quantities (to enable type-hinting) asset: RigidObject = env.scene[asset_cfg.name] - return torch.sum(torch.square(wp.to_torch(asset.data.projected_gravity_b)[:, :2]), dim=1) + return torch.sum(torch.square(asset.data.projected_gravity_b.torch[:, :2]), dim=1) def base_height_l2( @@ -116,18 +115,18 @@ def base_height_l2( if sensor_cfg is not None: sensor: RayCaster = env.scene[sensor_cfg.name] # Adjust the target height using the sensor data - adjusted_target_height = target_height + torch.mean(sensor.data.ray_hits_w[..., 2], dim=1) + adjusted_target_height = target_height + torch.mean(sensor.data.ray_hits_w.torch[..., 2], dim=1) else: # Use the provided target height directly for flat terrain adjusted_target_height = target_height # Compute the L2 squared penalty - return torch.square(wp.to_torch(asset.data.root_pos_w)[:, 2] - adjusted_target_height) + return torch.square(asset.data.root_pos_w.torch[:, 2] - adjusted_target_height) def body_lin_acc_l2(env: ManagerBasedRLEnv, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")) -> torch.Tensor: """Penalize the linear acceleration of bodies using L2-kernel.""" asset: Articulation = env.scene[asset_cfg.name] - return torch.sum(torch.linalg.norm(wp.to_torch(asset.data.body_lin_acc_w)[:, asset_cfg.body_ids, :], dim=-1), dim=1) + return torch.sum(torch.linalg.norm(asset.data.body_lin_acc_w.torch[:, asset_cfg.body_ids, :], dim=-1), dim=1) """ @@ -144,14 +143,14 @@ def joint_torques_l2(env: ManagerBasedRLEnv, asset_cfg: SceneEntityCfg = SceneEn """ # extract the used quantities (to enable type-hinting) asset: Articulation = env.scene[asset_cfg.name] - return torch.sum(torch.square(wp.to_torch(asset.data.applied_torque)[:, asset_cfg.joint_ids]), dim=1) + return torch.sum(torch.square(asset.data.applied_torque.torch[:, asset_cfg.joint_ids]), dim=1) def joint_vel_l1(env: ManagerBasedRLEnv, asset_cfg: SceneEntityCfg) -> torch.Tensor: """Penalize joint velocities on the articulation using an L1-kernel.""" # extract the used quantities (to enable type-hinting) asset: Articulation = env.scene[asset_cfg.name] - return torch.sum(torch.abs(wp.to_torch(asset.data.joint_vel)[:, asset_cfg.joint_ids]), dim=1) + return torch.sum(torch.abs(asset.data.joint_vel.torch[:, asset_cfg.joint_ids]), dim=1) def joint_vel_l2(env: ManagerBasedRLEnv, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")) -> torch.Tensor: @@ -163,7 +162,7 @@ def joint_vel_l2(env: ManagerBasedRLEnv, asset_cfg: SceneEntityCfg = SceneEntity """ # extract the used quantities (to enable type-hinting) asset: Articulation = env.scene[asset_cfg.name] - return torch.sum(torch.square(wp.to_torch(asset.data.joint_vel)[:, asset_cfg.joint_ids]), dim=1) + return torch.sum(torch.square(asset.data.joint_vel.torch[:, asset_cfg.joint_ids]), dim=1) def joint_acc_l2(env: ManagerBasedRLEnv, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")) -> torch.Tensor: @@ -175,7 +174,7 @@ def joint_acc_l2(env: ManagerBasedRLEnv, asset_cfg: SceneEntityCfg = SceneEntity """ # extract the used quantities (to enable type-hinting) asset: Articulation = env.scene[asset_cfg.name] - return torch.sum(torch.square(wp.to_torch(asset.data.joint_acc)[:, asset_cfg.joint_ids]), dim=1) + return torch.sum(torch.square(asset.data.joint_acc.torch[:, asset_cfg.joint_ids]), dim=1) def joint_deviation_l1(env: ManagerBasedRLEnv, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")) -> torch.Tensor: @@ -184,8 +183,7 @@ def joint_deviation_l1(env: ManagerBasedRLEnv, asset_cfg: SceneEntityCfg = Scene asset: Articulation = env.scene[asset_cfg.name] # compute out of limits constraints angle = ( - wp.to_torch(asset.data.joint_pos)[:, asset_cfg.joint_ids] - - wp.to_torch(asset.data.default_joint_pos)[:, asset_cfg.joint_ids] + asset.data.joint_pos.torch[:, asset_cfg.joint_ids] - asset.data.default_joint_pos.torch[:, asset_cfg.joint_ids] ) return torch.sum(torch.abs(angle), dim=1) @@ -199,12 +197,12 @@ def joint_pos_limits(env: ManagerBasedRLEnv, asset_cfg: SceneEntityCfg = SceneEn asset: Articulation = env.scene[asset_cfg.name] # compute out of limits constraints out_of_limits = -( - wp.to_torch(asset.data.joint_pos)[:, asset_cfg.joint_ids] - - wp.to_torch(asset.data.soft_joint_pos_limits)[:, asset_cfg.joint_ids, 0] + asset.data.joint_pos.torch[:, asset_cfg.joint_ids] + - asset.data.soft_joint_pos_limits.torch[:, asset_cfg.joint_ids, 0] ).clip(max=0.0) out_of_limits += ( - wp.to_torch(asset.data.joint_pos)[:, asset_cfg.joint_ids] - - wp.to_torch(asset.data.soft_joint_pos_limits)[:, asset_cfg.joint_ids, 1] + asset.data.joint_pos.torch[:, asset_cfg.joint_ids] + - asset.data.soft_joint_pos_limits.torch[:, asset_cfg.joint_ids, 1] ).clip(min=0.0) return torch.sum(out_of_limits, dim=1) @@ -223,8 +221,8 @@ def joint_vel_limits( asset: Articulation = env.scene[asset_cfg.name] # compute out of limits constraints out_of_limits = ( - torch.abs(wp.to_torch(asset.data.joint_vel)[:, asset_cfg.joint_ids]) - - wp.to_torch(asset.data.soft_joint_vel_limits)[:, asset_cfg.joint_ids] * soft_ratio + torch.abs(asset.data.joint_vel.torch[:, asset_cfg.joint_ids]) + - asset.data.soft_joint_vel_limits.torch[:, asset_cfg.joint_ids] * soft_ratio ) # clip to max error = 1 rad/s per joint to avoid huge penalties out_of_limits = out_of_limits.clip_(min=0.0, max=1.0) @@ -250,8 +248,8 @@ def applied_torque_limits(env: ManagerBasedRLEnv, asset_cfg: SceneEntityCfg = Sc # compute out of limits constraints # TODO: We need to fix this to support implicit joints. out_of_limits = torch.abs( - wp.to_torch(asset.data.applied_torque)[:, asset_cfg.joint_ids] - - wp.to_torch(asset.data.computed_torque)[:, asset_cfg.joint_ids] + asset.data.applied_torque.torch[:, asset_cfg.joint_ids] + - asset.data.computed_torque.torch[:, asset_cfg.joint_ids] ) return torch.sum(out_of_limits, dim=1) @@ -276,7 +274,7 @@ def undesired_contacts(env: ManagerBasedRLEnv, threshold: float, sensor_cfg: Sce # extract the used quantities (to enable type-hinting) contact_sensor: ContactSensor = env.scene.sensors[sensor_cfg.name] # check if contact force is above threshold - net_contact_forces = wp.to_torch(contact_sensor.data.net_forces_w_history) + net_contact_forces = contact_sensor.data.net_forces_w_history.torch is_contact = ( torch.max(torch.linalg.norm(net_contact_forces[:, :, sensor_cfg.body_ids], dim=-1), dim=1)[0] > threshold ) @@ -288,7 +286,7 @@ def desired_contacts(env, sensor_cfg: SceneEntityCfg, threshold: float = 1.0) -> """Penalize if none of the desired contacts are present.""" contact_sensor: ContactSensor = env.scene.sensors[sensor_cfg.name] contacts = ( - wp.to_torch(contact_sensor.data.net_forces_w_history)[:, :, sensor_cfg.body_ids, :].norm(dim=-1).max(dim=1)[0] + contact_sensor.data.net_forces_w_history.torch[:, :, sensor_cfg.body_ids, :].norm(dim=-1).max(dim=1)[0] > threshold ) zero_contact = (~contacts).all(dim=1) @@ -299,7 +297,7 @@ def contact_forces(env: ManagerBasedRLEnv, threshold: float, sensor_cfg: SceneEn """Penalize contact forces as the amount of violations of the net contact force.""" # extract the used quantities (to enable type-hinting) contact_sensor: ContactSensor = env.scene.sensors[sensor_cfg.name] - net_contact_forces = wp.to_torch(contact_sensor.data.net_forces_w_history) + net_contact_forces = contact_sensor.data.net_forces_w_history.torch # compute the violation violation = ( torch.max(torch.linalg.norm(net_contact_forces[:, :, sensor_cfg.body_ids], dim=-1), dim=1)[0] - threshold @@ -321,9 +319,7 @@ def track_lin_vel_xy_exp( asset: RigidObject = env.scene[asset_cfg.name] # compute the error lin_vel_error = torch.sum( - torch.square( - env.command_manager.get_command(command_name)[:, :2] - wp.to_torch(asset.data.root_lin_vel_b)[:, :2] - ), + torch.square(env.command_manager.get_command(command_name)[:, :2] - asset.data.root_lin_vel_b.torch[:, :2]), dim=1, ) return torch.exp(-lin_vel_error / std**2) @@ -337,6 +333,6 @@ def track_ang_vel_z_exp( asset: RigidObject = env.scene[asset_cfg.name] # compute the error ang_vel_error = torch.square( - env.command_manager.get_command(command_name)[:, 2] - wp.to_torch(asset.data.root_ang_vel_b)[:, 2] + env.command_manager.get_command(command_name)[:, 2] - asset.data.root_ang_vel_b.torch[:, 2] ) return torch.exp(-ang_vel_error / std**2) diff --git a/source/isaaclab/isaaclab/envs/mdp/terminations.py b/source/isaaclab/isaaclab/envs/mdp/terminations.py index 1936f5dd50b6..d717fb0dfcd0 100644 --- a/source/isaaclab/isaaclab/envs/mdp/terminations.py +++ b/source/isaaclab/isaaclab/envs/mdp/terminations.py @@ -14,7 +14,6 @@ from typing import TYPE_CHECKING import torch -import warp as wp from isaaclab.managers import SceneEntityCfg @@ -58,7 +57,7 @@ def bad_orientation( """ # extract the used quantities (to enable type-hinting) asset: RigidObject = env.scene[asset_cfg.name] - return torch.acos(-wp.to_torch(asset.data.projected_gravity_b)[:, 2]).abs() > limit_angle + return torch.acos(-asset.data.projected_gravity_b.torch[:, 2]).abs() > limit_angle def root_height_below_minimum( @@ -71,7 +70,7 @@ def root_height_below_minimum( """ # extract the used quantities (to enable type-hinting) asset: RigidObject = env.scene[asset_cfg.name] - return wp.to_torch(asset.data.root_pos_w)[:, 2] < minimum_height + return asset.data.root_pos_w.torch[:, 2] < minimum_height """ @@ -86,9 +85,9 @@ def joint_pos_out_of_limit(env: ManagerBasedRLEnv, asset_cfg: SceneEntityCfg = S if asset_cfg.joint_ids is None: asset_cfg.joint_ids = slice(None) - limits = wp.to_torch(asset.data.soft_joint_pos_limits)[:, asset_cfg.joint_ids] - out_of_upper_limits = torch.any(wp.to_torch(asset.data.joint_pos)[:, asset_cfg.joint_ids] > limits[..., 1], dim=1) - out_of_lower_limits = torch.any(wp.to_torch(asset.data.joint_pos)[:, asset_cfg.joint_ids] < limits[..., 0], dim=1) + limits = asset.data.soft_joint_pos_limits.torch[:, asset_cfg.joint_ids] + out_of_upper_limits = torch.any(asset.data.joint_pos.torch[:, asset_cfg.joint_ids] > limits[..., 1], dim=1) + out_of_lower_limits = torch.any(asset.data.joint_pos.torch[:, asset_cfg.joint_ids] < limits[..., 0], dim=1) return torch.logical_or(out_of_upper_limits, out_of_lower_limits) @@ -105,8 +104,8 @@ def joint_pos_out_of_manual_limit( if asset_cfg.joint_ids is None: asset_cfg.joint_ids = slice(None) # compute any violations - out_of_upper_limits = torch.any(wp.to_torch(asset.data.joint_pos)[:, asset_cfg.joint_ids] > bounds[1], dim=1) - out_of_lower_limits = torch.any(wp.to_torch(asset.data.joint_pos)[:, asset_cfg.joint_ids] < bounds[0], dim=1) + out_of_upper_limits = torch.any(asset.data.joint_pos.torch[:, asset_cfg.joint_ids] > bounds[1], dim=1) + out_of_lower_limits = torch.any(asset.data.joint_pos.torch[:, asset_cfg.joint_ids] < bounds[0], dim=1) return torch.logical_or(out_of_upper_limits, out_of_lower_limits) @@ -115,9 +114,9 @@ def joint_vel_out_of_limit(env: ManagerBasedRLEnv, asset_cfg: SceneEntityCfg = S # extract the used quantities (to enable type-hinting) asset: Articulation = env.scene[asset_cfg.name] # compute any violations - limits = wp.to_torch(asset.data.soft_joint_vel_limits) + limits = asset.data.soft_joint_vel_limits.torch return torch.any( - torch.abs(wp.to_torch(asset.data.joint_vel)[:, asset_cfg.joint_ids]) > limits[:, asset_cfg.joint_ids], dim=1 + torch.abs(asset.data.joint_vel.torch[:, asset_cfg.joint_ids]) > limits[:, asset_cfg.joint_ids], dim=1 ) @@ -128,7 +127,7 @@ def joint_vel_out_of_manual_limit( # extract the used quantities (to enable type-hinting) asset: Articulation = env.scene[asset_cfg.name] # compute any violations - return torch.any(torch.abs(wp.to_torch(asset.data.joint_vel)[:, asset_cfg.joint_ids]) > max_velocity, dim=1) + return torch.any(torch.abs(asset.data.joint_vel.torch[:, asset_cfg.joint_ids]) > max_velocity, dim=1) def joint_effort_out_of_limit( @@ -144,8 +143,8 @@ def joint_effort_out_of_limit( asset: Articulation = env.scene[asset_cfg.name] # check if any joint effort is out of limit out_of_limits = ~torch.isclose( - wp.to_torch(asset.data.computed_torque)[:, asset_cfg.joint_ids], - wp.to_torch(asset.data.applied_torque)[:, asset_cfg.joint_ids], + asset.data.computed_torque.torch[:, asset_cfg.joint_ids], + asset.data.applied_torque.torch[:, asset_cfg.joint_ids], ) return torch.any(out_of_limits, dim=1) @@ -159,7 +158,7 @@ def illegal_contact(env: ManagerBasedRLEnv, threshold: float, sensor_cfg: SceneE """Terminate when the contact force on the sensor exceeds the force threshold.""" # extract the used quantities (to enable type-hinting) contact_sensor: ContactSensor = env.scene.sensors[sensor_cfg.name] - net_contact_forces = wp.to_torch(contact_sensor.data.net_forces_w_history) + net_contact_forces = contact_sensor.data.net_forces_w_history.torch # check if any contact force exceeds the threshold return torch.any( torch.max(torch.linalg.norm(net_contact_forces[:, :, sensor_cfg.body_ids], dim=-1), dim=1)[0] > threshold, dim=1 diff --git a/source/isaaclab/isaaclab/envs/ui/viewport_camera_controller.py b/source/isaaclab/isaaclab/envs/ui/viewport_camera_controller.py index 4126d7b74735..509b17033397 100644 --- a/source/isaaclab/isaaclab/envs/ui/viewport_camera_controller.py +++ b/source/isaaclab/isaaclab/envs/ui/viewport_camera_controller.py @@ -12,7 +12,6 @@ import numpy as np import torch -import warp as wp from isaaclab.assets.articulation.articulation import Articulation @@ -162,7 +161,7 @@ def update_view_to_asset_root(self, asset_name: str): # set origin type to asset_root self.cfg.origin_type = "asset_root" # update the camera origins (convert Warp array to torch tensor first, then index) - root_pos = wp.to_torch(self._env.scene[self.cfg.asset_name].data.root_pos_w) + root_pos = self._env.scene[self.cfg.asset_name].data.root_pos_w.torch self.viewer_origin = root_pos[self.cfg.env_index] # update the camera view self.update_view_location() @@ -196,7 +195,7 @@ def update_view_to_asset_body(self, asset_name: str, body_name: str): # set origin type to asset_body self.cfg.origin_type = "asset_body" # update the camera origins (convert Warp array to torch tensor first, then index) - body_pos = wp.to_torch(self._env.scene[self.cfg.asset_name].data.body_pos_w) + body_pos = self._env.scene[self.cfg.asset_name].data.body_pos_w.torch self.viewer_origin = body_pos[self.cfg.env_index, body_id].squeeze(0) # update the camera view self.update_view_location() @@ -218,8 +217,17 @@ def update_view_location(self, eye: Sequence[float] | None = None, lookat: Seque cam_eye = viewer_origin + self.default_cam_eye cam_target = viewer_origin + self.default_cam_lookat - # set the camera view - self._env.sim.set_camera_view(eye=cam_eye, target=cam_target) + eye_t = (float(cam_eye[0]), float(cam_eye[1]), float(cam_eye[2])) + target_t = (float(cam_target[0]), float(cam_target[1]), float(cam_target[2])) + self._env.sim.set_camera_view(eye=eye_t, target=target_t) + + # Renderer viewport camera (Isaac RTX / Kit); optional — pure-Newton installs have no isaaclab_physx. + try: + from isaaclab_physx.renderers.kit_viewport_utils import set_kit_renderer_camera_view + + set_kit_renderer_camera_view(eye=cam_eye, target=cam_target, camera_prim_path=self.cfg.cam_prim_path) + except (ImportError, ModuleNotFoundError): + pass """ Private Functions diff --git a/source/isaaclab/isaaclab/envs/utils/io_descriptors.py b/source/isaaclab/isaaclab/envs/utils/io_descriptors.py index ccf1feb43ec3..3a9d54f12e5a 100644 --- a/source/isaaclab/isaaclab/envs/utils/io_descriptors.py +++ b/source/isaaclab/isaaclab/envs/utils/io_descriptors.py @@ -20,8 +20,6 @@ import functools import inspect -import warp as wp - @configclass class GenericActionIODescriptor: @@ -321,7 +319,7 @@ def record_joint_pos_offsets(output: torch.Tensor, descriptor: GenericObservatio ids = kwargs["asset_cfg"].joint_ids # Get the offsets of the joints for the first robot in the scene. # This assumes that all robots have the same joint offsets. - descriptor.joint_pos_offsets = wp.to_torch(asset.data.default_joint_pos)[:, ids][0] + descriptor.joint_pos_offsets = asset.data.default_joint_pos.torch[:, ids][0] def record_joint_vel_offsets(output: torch.Tensor, descriptor: GenericObservationIODescriptor, **kwargs): @@ -338,7 +336,7 @@ def record_joint_vel_offsets(output: torch.Tensor, descriptor: GenericObservatio ids = kwargs["asset_cfg"].joint_ids # Get the offsets of the joints for the first robot in the scene. # This assumes that all robots have the same joint offsets. - descriptor.joint_vel_offsets = wp.to_torch(asset.data.default_joint_vel)[:, ids][0] + descriptor.joint_vel_offsets = asset.data.default_joint_vel.torch[:, ids][0] def export_articulations_data(env: ManagerBasedEnv) -> dict[str, dict[str, list[float]]]: @@ -358,25 +356,25 @@ def export_articulations_data(env: ManagerBasedEnv) -> dict[str, dict[str, list[ articulation_joint_data[articulation_name] = {} articulation_joint_data[articulation_name]["joint_names"] = articulation.joint_names articulation_joint_data[articulation_name]["default_joint_pos"] = ( - articulation.data.default_joint_pos[0].detach().cpu().numpy().tolist() + articulation.data.default_joint_pos.torch[0].detach().cpu().numpy().tolist() ) articulation_joint_data[articulation_name]["default_joint_vel"] = ( - articulation.data.default_joint_vel[0].detach().cpu().numpy().tolist() + articulation.data.default_joint_vel.torch[0].detach().cpu().numpy().tolist() ) articulation_joint_data[articulation_name]["default_joint_pos_limits"] = ( - articulation.data.default_joint_pos_limits[0].detach().cpu().numpy().tolist() + articulation.data.default_joint_pos_limits.torch[0].detach().cpu().numpy().tolist() ) articulation_joint_data[articulation_name]["default_joint_damping"] = ( - articulation.data.joint_damping[0].detach().cpu().numpy().tolist() + articulation.data.joint_damping.torch[0].detach().cpu().numpy().tolist() ) articulation_joint_data[articulation_name]["default_joint_stiffness"] = ( - articulation.data.joint_stiffness[0].detach().cpu().numpy().tolist() + articulation.data.joint_stiffness.torch[0].detach().cpu().numpy().tolist() ) articulation_joint_data[articulation_name]["default_joint_friction"] = ( - articulation.data.joint_friction_coeff[0].detach().cpu().numpy().tolist() + articulation.data.joint_friction_coeff.torch[0].detach().cpu().numpy().tolist() ) articulation_joint_data[articulation_name]["default_joint_armature"] = ( - articulation.data.joint_armature[0].detach().cpu().numpy().tolist() + articulation.data.joint_armature.torch[0].detach().cpu().numpy().tolist() ) return articulation_joint_data diff --git a/source/isaaclab/isaaclab/envs/utils/recording_hooks.py b/source/isaaclab/isaaclab/envs/utils/recording_hooks.py new file mode 100644 index 000000000000..584b6d73adf5 --- /dev/null +++ b/source/isaaclab/isaaclab/envs/utils/recording_hooks.py @@ -0,0 +1,50 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Hooks that run after visualizers during :meth:`~isaaclab.sim.SimulationContext.render`. + +Lives alongside :mod:`video_recorder` / :mod:`video_recorder_cfg` because both tie into +``--video`` / ``rgb_array`` recording. Keeps :class:`~isaaclab.sim.SimulationContext` free +of imports from ``isaaclab_physx``, ``isaaclab_newton``, and other recording backends. +Each integration is loaded lazily so optional extensions are not required at import time. +""" + +from __future__ import annotations + +from typing import Any + + +def run_recording_hooks_after_visualizers(sim: Any) -> None: + """Run recording-related work after :meth:`~isaaclab.sim.SimulationContext.render` steps visualizers. + + Isaac Sim / RTX follow-up is loaded lazily so minimal installs still work. + Newton GL video is handled by :class:`~isaaclab.envs.utils.video_recorder.VideoRecorder` + (e.g. :class:`~isaaclab_newton.video_recording.newton_gl_perspective_video.NewtonGlPerspectiveVideo`), + not here. + + Args: + sim: Active :class:`~isaaclab.sim.SimulationContext` instance. + """ + _recording_followup_isaac_sim(sim) + + +def _recording_followup_isaac_sim(sim: Any) -> None: + """Isaac Sim: keep RTX / Replicator outputs fresh when recording video without a Kit visualizer. + + When ``--video`` uses ``rgb_array`` / :class:`~gymnasium.wrappers.RecordVideo`, Replicator + render products must see Kit's event loop pumped. :class:`~isaaclab_visualizers.kit.KitVisualizer` + already calls ``omni.kit.app.get_app().update()`` in its ``step()``; if no such visualizer + is active, we pump here (guarded by ``/isaaclab/video/enabled`` and ``is_rendering``). + + Implemented by ``pump_kit_app_for_headless_video_render_if_needed`` in + :mod:`isaaclab_physx.renderers.isaac_rtx_renderer_utils`. + """ + try: + from isaaclab_physx.renderers.isaac_rtx_renderer_utils import ( + pump_kit_app_for_headless_video_render_if_needed, + ) + except ImportError: + return + pump_kit_app_for_headless_video_render_if_needed(sim) diff --git a/source/isaaclab/isaaclab/envs/utils/video_recorder.py b/source/isaaclab/isaaclab/envs/utils/video_recorder.py new file mode 100644 index 000000000000..3ff6a7e1a0a4 --- /dev/null +++ b/source/isaaclab/isaaclab/envs/utils/video_recorder.py @@ -0,0 +1,247 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Video recorder implementation. + +Backend resolution (``--video`` + ``--visualizer``): + +1. **Active visualizer** - ``"kit"`` uses the Kit camera; ``"newton"`` uses the Newton GL viewer. + ``"viser"`` / ``"rerun"`` have no capture API and fall through to rule 2. +2. **Physics/renderer stack** - + - PhysX or Isaac RTX uses the Kit camera; + - Newton physics or Newton Warp uses the Newton GL viewer. + Kit wins when both signals present. Raises if nothing resolves. + +Set :attr:`~isaaclab.envs.utils.video_recorder_cfg.VideoRecorderCfg.backend_source` to ``"renderer"`` +to ignore active visualizers and record from the physics/renderer stack. + +Camera sync when a visualizer drives the backend: construction copies the visualizer config's +``eye`` / ``lookat`` into the recorder config; each :meth:`~VideoRecorder.render_rgb_array` +call then re-reads the Newton viewer's live ``camera.pos/pitch/yaw``. Kit video uses the +configured ``eye`` / ``lookat`` at construction time. + +See :mod:`video_recorder_cfg` for configuration. +""" + +from __future__ import annotations + +import logging +from typing import TYPE_CHECKING, Literal + +import numpy as np + +if TYPE_CHECKING: + from isaaclab.scene import InteractiveScene + + from .video_recorder_cfg import VideoRecorderCfg + +logger = logging.getLogger(__name__) + +_VideoBackend = Literal["kit", "newton_gl"] + +# visualizer types that map to a supported video backend. +# viser and rerun are intentionally absent - they have no video-capture API. +_VISUALIZER_TO_VIDEO_BACKEND: dict[str, _VideoBackend] = { + "kit": "kit", + "newton": "newton_gl", +} + + +def _resolve_video_backend( + scene: InteractiveScene, backend_source: str = "visualizer" +) -> tuple[_VideoBackend, str | None]: + """Return ``(backend, matched_visualizer_type)`` for the active scene. + + ``matched_visualizer_type`` is ``"kit"`` / ``"newton"`` when a visualizer drove the + selection, or ``None`` when the physics/renderer preset stack was used instead. + + Args: + scene: The interactive scene that owns the sim context. + backend_source: ``"visualizer"`` to let active visualizers choose the backend, or ``"renderer"`` + to ignore active visualizers and use the physics/renderer stack. + + Raises: + RuntimeError: If no supported backend is detected. + """ + if backend_source not in ("visualizer", "renderer"): + raise ValueError("VideoRecorderCfg.backend_source must be either 'visualizer' or 'renderer'.") + + # Prefer the visualizer backend when --visualizer is active alongside --video. + visualizer_types: list[str] = scene.sim.resolve_visualizer_types() if backend_source == "visualizer" else [] + if visualizer_types: + # kit takes priority when multiple visualizers are active + for preferred in ("kit", "newton"): + if preferred in visualizer_types: + backend = _VISUALIZER_TO_VIDEO_BACKEND[preferred] + logger.debug("[VideoRecorder] Using '%s' backend from active '%s' visualizer.", backend, preferred) + return backend, preferred + # only unsupported visualizer types (viser, rerun) are active. + logger.warning( + "[VideoRecorder] Active visualizer(s) %s do not support video capture; " + "falling back to physics/renderer stack detection.", + visualizer_types, + ) + + # fall back to physics/renderer preset stack detection. + sim = scene.sim + physics_name = sim.physics_manager.__name__.lower() + renderer_types: list[str] = scene._sensor_renderer_types() + + use_kit = "physx" in physics_name or "isaac_rtx" in renderer_types + use_newton_gl = "newton" in physics_name or "newton_warp" in renderer_types + + if use_kit: + return "kit", None + if use_newton_gl: + return "newton_gl", None + raise RuntimeError( + "Video recording (--video) requires a supported backend: " + "PhysX or Isaac RTX renderer (Kit camera), or Newton physics / Newton Warp renderer (GL viewer). " + "No supported backend detected; do not use --video for this setup." + ) + + +def _sync_camera_from_visualizer( + scene: InteractiveScene, + visualizer_type: str, + cfg: VideoRecorderCfg, +) -> None: + """Overwrite ``cfg.eye`` and ``cfg.lookat`` from the active visualizer. + + Args: + scene: The interactive scene that owns the sim context. + visualizer_type: The visualizer type string matched by ``_resolve_video_backend`` + (e.g. ``"kit"`` or ``"newton"``). + cfg: The recorder configuration to update in place. + """ + try: + resolved_cfgs = scene.sim._resolve_visualizer_cfgs() + except Exception as exc: + logger.debug("[VideoRecorder] Could not resolve visualizer cfgs for camera sync: %s", exc) + return + + for vcfg in resolved_cfgs: + if getattr(vcfg, "visualizer_type", None) != visualizer_type: + continue + pos = getattr(vcfg, "eye", None) + tgt = getattr(vcfg, "lookat", None) + if pos is None or tgt is None: + break + cfg.eye = tuple(float(x) for x in pos) + cfg.lookat = tuple(float(x) for x in tgt) + logger.debug( + "[VideoRecorder] Camera synced from '%s' visualizer: position=%s, target=%s.", + visualizer_type, + cfg.eye, + cfg.lookat, + ) + return + + logger.debug( + "[VideoRecorder] Could not find eye/lookat on '%s' visualizer cfg; keeping existing camera values.", + visualizer_type, + ) + + +class VideoRecorder: + """Records perspective video frames from the scene's active renderer. + + Args: + cfg: Recorder configuration. + scene: The interactive scene that owns the sensors. + """ + + def __init__(self, cfg: VideoRecorderCfg, scene: InteractiveScene): + self.cfg = cfg + self._scene = scene + self._backend: _VideoBackend | None = None + self._capture = None + # visualizer type that drove backend selection (or None when using physics/renderer stack). + self._matched_visualizer: str | None = None + # live visualizer instance - looked up lazily on first render_rgb_array() call because + # visualizers are initialised by sim.reset(), which runs after VideoRecorder.__init__. + self._live_visualizer = None + + if cfg.env_render_mode == "rgb_array": + backend_source = getattr(cfg, "backend_source", "visualizer") + self._backend, self._matched_visualizer = _resolve_video_backend(scene, backend_source) + if self._matched_visualizer is not None: + _sync_camera_from_visualizer(scene, self._matched_visualizer, cfg) + if self._backend == "newton_gl": + try: + import pyglet as _pyglet # noqa: F401 - verify pyglet is available + except ImportError as e: + raise ImportError( + "The Newton GL video backend requires 'pyglet'. Install IsaacLab with './isaaclab.sh -i'." + ) from e + from isaaclab_newton.video_recording.newton_gl_perspective_video import ( + create_newton_gl_perspective_video, + ) + from isaaclab_newton.video_recording.newton_gl_perspective_video_cfg import NewtonGlPerspectiveVideoCfg + + ncfg = NewtonGlPerspectiveVideoCfg( + window_width=cfg.window_width, + window_height=cfg.window_height, + eye=cfg.eye, + lookat=cfg.lookat, + ) + self._capture = create_newton_gl_perspective_video(ncfg) + else: + from isaaclab_physx.video_recording.isaacsim_kit_perspective_video import ( + create_isaacsim_kit_perspective_video, + ) + from isaaclab_physx.video_recording.isaacsim_kit_perspective_video_cfg import ( + IsaacsimKitPerspectiveVideoCfg, + ) + + kcfg = IsaacsimKitPerspectiveVideoCfg( + eye=cfg.eye, + lookat=cfg.lookat, + window_width=cfg.window_width, + window_height=cfg.window_height, + ) + self._capture = create_isaacsim_kit_perspective_video(kcfg) + + def _sync_newton_camera(self) -> None: + """Push the Newton visualizer's live camera pose into the capture object. + + Called once per :meth:`render_rgb_array` when a Newton visualizer is active. + The live visualizer instance is resolved lazily (visualizers are initialised by + ``sim.reset()``, which runs after ``VideoRecorder.__init__``). + """ + if self._live_visualizer is None: + for viz in self._scene.sim.visualizers: + if getattr(getattr(viz, "cfg", None), "visualizer_type", None) == "newton": + self._live_visualizer = viz + break + if self._live_visualizer is None: + return + + viewer = getattr(self._live_visualizer, "_viewer", None) + if viewer is None: + return + + import math + + cam = viewer.camera + pos = (float(cam.pos[0]), float(cam.pos[1]), float(cam.pos[2])) + yaw_rad = math.radians(float(cam.yaw)) + pitch_rad = math.radians(float(cam.pitch)) + dx = math.cos(pitch_rad) * math.cos(yaw_rad) + dy = math.cos(pitch_rad) * math.sin(yaw_rad) + dz = math.sin(pitch_rad) + target = (pos[0] + dx, pos[1] + dy, pos[2] + dz) + self._capture.update_camera(pos, target) + + def render_rgb_array(self) -> np.ndarray | None: + """Return an RGB frame for the resolved backend. Fails if backend is unavailable.""" + if self._backend is None or self._capture is None: + return None + if self._matched_visualizer == "newton": + # Newton GL camera state lives in the capture object and must be synced each frame + # to follow interactive viewer movement. + self._sync_newton_camera() + # Kit capture uses the configured eye/lookat applied to the recording camera at construction time. + return self._capture.render_rgb_array() diff --git a/source/isaaclab/isaaclab/envs/utils/video_recorder_cfg.py b/source/isaaclab/isaaclab/envs/utils/video_recorder_cfg.py new file mode 100644 index 000000000000..c0cbb1d9a11d --- /dev/null +++ b/source/isaaclab/isaaclab/envs/utils/video_recorder_cfg.py @@ -0,0 +1,58 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Configuration for :class:`~isaaclab.envs.utils.video_recorder.VideoRecorder`. + +Captures a single wide-angle perspective view of the scene. Newton backends use the +Newton GL viewer; Kit backends use the ``/OmniverseKit_Persp`` camera via +``omni.replicator.core``. +""" + +from __future__ import annotations + +from typing import Literal + +from isaaclab.utils import configclass + +from .video_recorder import VideoRecorder + + +@configclass +class VideoRecorderCfg: + """Configuration for :class:`~isaaclab.envs.utils.video_recorder.VideoRecorder`.""" + + class_type: type = VideoRecorder + """Recorder class to instantiate; must accept ``(cfg, scene)``.""" + + env_render_mode: str | None = None + """Gym render mode forwarded from the environment constructor (``"rgb_array"`` when ``--video`` is active). + + Set automatically by the environment base classes; do not set manually. + """ + + eye: tuple[float, float, float] = (7.5, 7.5, 7.5) + """Perspective camera position in world space (metres). + + Direct RL / MARL and manager-based RL environments overwrite this from + :attr:`~isaaclab.envs.common.ViewerCfg.eye` before recording so ``--video`` matches the + task viewport for both Kit (PhysX / Isaac RTX) and Newton GL (Newton / OVRTX / etc.). + """ + + lookat: tuple[float, float, float] = (0.0, 0.0, 0.0) + """Perspective camera look-at target in world space (metres). Set from ``ViewerCfg.lookat`` at env init.""" + + backend_source: Literal["visualizer", "renderer"] = "visualizer" + """Source used to resolve the video capture backend. + + ``"visualizer"`` records from the active Kit or Newton visualizer when one is enabled, and falls back to the + physics/renderer stack otherwise. ``"renderer"`` ignores active visualizers and records from the backend implied by + the physics/renderer stack. + """ + + window_width: int = 1280 + """Width in pixels of the recorded frame.""" + + window_height: int = 720 + """Height in pixels of the recorded frame.""" diff --git a/source/isaaclab/isaaclab/managers/manager_term_cfg.py b/source/isaaclab/isaaclab/managers/manager_term_cfg.py index de7c23aa220b..06f2516324b5 100644 --- a/source/isaaclab/isaaclab/managers/manager_term_cfg.py +++ b/source/isaaclab/isaaclab/managers/manager_term_cfg.py @@ -118,6 +118,11 @@ class CommandTermCfg: debug_vis: bool = False """Whether to visualize debug information. Defaults to False.""" + cmd_kind: str | None = None + """Type hint for the command for deployment.""" + element_names: list[str] | list[list[str]] | None = None + """Element names for the command for deployment.""" + ## # Curriculum manager. diff --git a/source/isaaclab/isaaclab/managers/observation_manager.py b/source/isaaclab/isaaclab/managers/observation_manager.py index ee017cd87de7..7299ff954467 100644 --- a/source/isaaclab/isaaclab/managers/observation_manager.py +++ b/source/isaaclab/isaaclab/managers/observation_manager.py @@ -512,6 +512,7 @@ def _prepare_terms(self): # read common config for the group self._group_obs_concatenate[group_name] = group_cfg.concatenate_terms + # to account for the batch dimension self._group_obs_concatenate_dim[group_name] = ( group_cfg.concatenate_dim + 1 if group_cfg.concatenate_dim >= 0 else group_cfg.concatenate_dim ) @@ -550,7 +551,7 @@ def _prepare_terms(self): if group_cfg.history_length is not None: term_cfg.history_length = group_cfg.history_length term_cfg.flatten_history_dim = group_cfg.flatten_history_dim - # add term config to list to list + # add term config to list self._group_obs_term_names[group_name].append(term_name) self._group_obs_term_cfgs[group_name].append(term_cfg) @@ -604,6 +605,9 @@ def _prepare_terms(self): f" Received: {mod_cfg.func}" ) + # TODO(jichuanh): improvement can be made in two ways: + # 1. modifier specific check can be done in the modifier class + # 2. general param vs function matching check can be a common utility # check if term's arguments are matched by params term_params = list(mod_cfg.params.keys()) args = inspect.signature(mod_cfg.func).parameters @@ -642,7 +646,9 @@ def _prepare_terms(self): old_dims.insert(1, term_cfg.history_length) obs_dims = tuple(old_dims) if term_cfg.flatten_history_dim: - obs_dims = (obs_dims[0], np.prod(obs_dims[1:])) + # Cast to ``int`` so the dim is a plain Python int rather than ``np.int64``; + # otherwise the tuple would render as ``(np.int64(N),)`` in __str__. + obs_dims = (obs_dims[0], int(np.prod(obs_dims[1:]))) self._group_obs_term_dim[group_name].append(obs_dims[1:]) diff --git a/source/isaaclab/isaaclab/managers/recorder_manager.py b/source/isaaclab/isaaclab/managers/recorder_manager.py index cc95d2381562..2e6ebf0b2446 100644 --- a/source/isaaclab/isaaclab/managers/recorder_manager.py +++ b/source/isaaclab/isaaclab/managers/recorder_manager.py @@ -55,6 +55,9 @@ class RecorderManagerBaseCfg: export_in_close: bool = False """Whether to export episodes in the close call.""" + dataset_compression: bool = True + """Enable dataset compression.""" + class RecorderTerm(ManagerTermBase): """Base class for recorder terms. @@ -335,13 +338,14 @@ def add_to_episodes(self, key: str, value: torch.Tensor | dict, env_ids: Sequenc self.add_to_episodes(f"{key}/{sub_key}", sub_value, env_ids) return + if isinstance(value, wp.array): + value = wp.to_torch(value) + value = value.clone() # Clone once for all envs for value_index, env_id in enumerate(env_ids): if env_id not in self._episodes: self._episodes[env_id] = EpisodeData() self._episodes[env_id].env_id = env_id - if isinstance(value, wp.array): - value = wp.to_torch(value) - self._episodes[env_id].add(key, value[value_index]) + self._episodes[env_id].add(key, value[value_index], clone=False) def set_success_to_episodes(self, env_ids: Sequence[int] | None, success_values: torch.Tensor): """Sets the task success values to the episodes for the given environment ids. @@ -513,7 +517,9 @@ def export_episodes(self, env_ids: Sequence[int] | None = None, demo_ids: Sequen if target_dataset_file_handler is not None: # Use corresponding demo_id if provided, otherwise None current_demo_id = demo_ids[i] if demo_ids is not None else None - target_dataset_file_handler.write_episode(self._episodes[env_id], current_demo_id) + target_dataset_file_handler.write_episode( + self._episodes[env_id], current_demo_id, self.cfg.dataset_compression + ) need_to_flush = True # Update episode count if episode_succeeded: @@ -567,6 +573,7 @@ def _prepare_terms(self): "dataset_export_mode", "export_in_record_pre_reset", "export_in_close", + "dataset_compression", ]: continue # check if term config is None diff --git a/source/isaaclab/isaaclab/physics/base_scene_data_provider.py b/source/isaaclab/isaaclab/physics/base_scene_data_provider.py index e5b709da0ce7..9760a71d25ba 100644 --- a/source/isaaclab/isaaclab/physics/base_scene_data_provider.py +++ b/source/isaaclab/isaaclab/physics/base_scene_data_provider.py @@ -15,8 +15,8 @@ class BaseSceneDataProvider(ABC): """Backend-agnostic scene data provider interface.""" @abstractmethod - def update(self, env_ids: list[int] | None = None) -> None: - """Refresh any cached scene data.""" + def update(self) -> None: + """Refresh any cached scene data (full model/state).""" raise NotImplementedError @abstractmethod @@ -25,8 +25,8 @@ def get_newton_model(self) -> Any | None: raise NotImplementedError @abstractmethod - def get_newton_state(self, env_ids: list[int] | None = None) -> Any | None: - """Return Newton state handle when available.""" + def get_newton_state(self) -> Any | None: + """Return Newton state handle when available (full state).""" raise NotImplementedError @abstractmethod diff --git a/source/isaaclab/isaaclab/physics/physics_manager.py b/source/isaaclab/isaaclab/physics/physics_manager.py index 5676fa8ef02b..7a4cdfe84403 100644 --- a/source/isaaclab/isaaclab/physics/physics_manager.py +++ b/source/isaaclab/isaaclab/physics/physics_manager.py @@ -276,6 +276,16 @@ def pre_render(cls) -> None: """ pass + @classmethod + def after_visualizers_render(cls) -> None: + """Hook after visualizers have stepped during :meth:`~isaaclab.sim.SimulationContext.render`. + + Use for physics-backend sync (e.g. fabric) if needed. Recording pipelines (Kit/RTX, + Newton GL video, etc.) run from :mod:`isaaclab.envs.utils.recording_hooks` so they are not + tied to a specific physics manager. Default is a no-op. + """ + pass + @classmethod def close(cls) -> None: """Clean up physics resources. @@ -324,6 +334,11 @@ def stop(cls) -> None: """Stop physics simulation. Default is no-op.""" pass + @classmethod + def wait_for_playing(cls) -> None: + """Block until the timeline is playing. Default is no-op.""" + pass + @classmethod def get_backend(cls) -> str: """Get the tensor backend being used ("numpy" or "torch").""" diff --git a/source/isaaclab/isaaclab/physics/scene_data_requirements.py b/source/isaaclab/isaaclab/physics/scene_data_requirements.py index 616592d9b1e0..f67aaa2bb6d9 100644 --- a/source/isaaclab/isaaclab/physics/scene_data_requirements.py +++ b/source/isaaclab/isaaclab/physics/scene_data_requirements.py @@ -13,7 +13,6 @@ from collections.abc import Iterable from dataclasses import dataclass -from typing import Any @dataclass(frozen=True) @@ -24,21 +23,6 @@ class SceneDataRequirement: requires_usd_stage: bool = False -@dataclass(frozen=True) -class VisualizerPrebuiltArtifacts: - """Prebuilt model/state payload shared from scene setup to providers. - - This gets produced during clone-time visualizer prebuild and then read by - scene data providers as a fast path (instead of rebuilding from USD). - """ - - model: Any - state: Any - rigid_body_paths: list[str] - articulation_paths: list[str] - num_envs: int - - _VISUALIZER_REQUIREMENTS: dict[str, SceneDataRequirement] = { "kit": SceneDataRequirement(requires_usd_stage=True), "newton": SceneDataRequirement(requires_newton_model=True), diff --git a/source/isaaclab/isaaclab/renderers/__init__.pyi b/source/isaaclab/isaaclab/renderers/__init__.pyi index e6785bd0e090..ae408c03ae7d 100644 --- a/source/isaaclab/isaaclab/renderers/__init__.pyi +++ b/source/isaaclab/isaaclab/renderers/__init__.pyi @@ -5,10 +5,17 @@ __all__ = [ "BaseRenderer", + "CameraRenderSpec", + "RenderBufferKind", + "RenderBufferSpec", "Renderer", "RendererCfg", + "RenderContext", ] from .base_renderer import BaseRenderer +from .camera_render_spec import CameraRenderSpec +from .output_contract import RenderBufferKind, RenderBufferSpec from .renderer import Renderer from .renderer_cfg import RendererCfg +from .render_context import RenderContext diff --git a/source/isaaclab/isaaclab/renderers/base_renderer.py b/source/isaaclab/isaaclab/renderers/base_renderer.py index 470150f9c98c..2fc498eae8e3 100644 --- a/source/isaaclab/isaaclab/renderers/base_renderer.py +++ b/source/isaaclab/isaaclab/renderers/base_renderer.py @@ -10,22 +10,36 @@ from abc import ABC, abstractmethod from typing import TYPE_CHECKING, Any +from .camera_render_spec import CameraRenderSpec +from .output_contract import RenderBufferKind, RenderBufferSpec + if TYPE_CHECKING: import torch - from isaaclab.sensors import SensorBase + from isaaclab.sensors.camera.camera_data import CameraData class BaseRenderer(ABC): """Abstract base class for renderer implementations.""" + @abstractmethod + def supported_output_types(self) -> dict[RenderBufferKind, RenderBufferSpec]: + """Per-output layout (channels + dtype) this renderer can produce. + + Outputs absent from the mapping are not produced by this backend. + + Returns: + Mapping from supported :class:`RenderBufferKind` to its :class:`RenderBufferSpec`. + """ + pass + @abstractmethod def prepare_stage(self, stage: Any, num_envs: int) -> None: - """Prepare the stage for rendering before create_render_data is called. + """Prepare the stage for rendering before :meth:`create_render_data` is called. Some renderers need to export or preprocess the USD stage before creating render data. This method is called after the renderer is - instantiated and before create_render_data. + instantiated and before :meth:`create_render_data`. Args: stage: USD stage to prepare, or None if not applicable. @@ -34,19 +48,14 @@ def prepare_stage(self, stage: Any, num_envs: int) -> None: pass @abstractmethod - def create_render_data(self, sensor: SensorBase) -> Any: - """Create render data for the given sensor. - - The returned object is opaque to the interface: callers pass it to other - renderer methods without inspecting its contents. Its structure is - implementation-specific (each renderer defines its own type). + def create_render_data(self, spec: CameraRenderSpec) -> Any: + """Create render data for the given camera :class:`CameraRenderSpec`. Args: - sensor: The camera sensor to create render data for. + spec: Immutable description of the tiled camera (paths, config, device). Returns: - Renderer-specific data object holding resources needed for rendering. - Passed to subsequent render calls. + Renderer-specific data for subsequent :meth:`render` / :meth:`read_output` calls. """ pass @@ -93,13 +102,13 @@ def render(self, render_data: Any) -> None: pass @abstractmethod - def write_output(self, render_data: Any, output_name: str, output_data: torch.Tensor) -> None: - """Write a specific output type to the given buffer. + def read_output(self, render_data: Any, camera_data: CameraData) -> None: + """Read rendered outputs from the renderer into the camera data container. Args: render_data: The render data object from :meth:`create_render_data`. - output_name: Name of the output (e.g. ``"rgba"``, ``"depth"``). - output_data: Pre-allocated tensor to write the output into. + camera_data: The :class:`~isaaclab.sensors.camera.camera_data.CameraData` + instance to populate. """ pass diff --git a/source/isaaclab/isaaclab/renderers/camera_render_spec.py b/source/isaaclab/isaaclab/renderers/camera_render_spec.py new file mode 100644 index 000000000000..526b90121713 --- /dev/null +++ b/source/isaaclab/isaaclab/renderers/camera_render_spec.py @@ -0,0 +1,37 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Immutable description of a tiled camera passed to render backends.""" + +from __future__ import annotations + +from dataclasses import dataclass + +from isaaclab.sensors.camera.camera_cfg import CameraCfg + + +@dataclass(frozen=True) +class CameraRenderSpec: + """Stable inputs for :meth:`~isaaclab.renderers.base_renderer.BaseRenderer.create_render_data`. + + Backends use this instead of holding a reference to the :class:`~isaaclab.sensors.camera.Camera` + sensor instance, avoiding circular dependencies between sensors and render data. + + Args: + cfg: Camera configuration (data types, resolution, filters, etc.). + device: Torch device string (e.g. ``"cuda:0"``) used by GPU annotators and Warp. + num_instances: Number of tiled camera instances (environments). + camera_prim_paths: Absolute USD paths for each environment's camera prim. + view_count: Number of camera prims (must match ``len(camera_prim_paths)``). + camera_path_relative_to_env_0: Camera prim path with ``/World/envs/env_0/`` prefix + stripped; required by OVRTX. Empty string if the first camera is not under env 0. + """ + + cfg: CameraCfg + device: str + num_instances: int + camera_prim_paths: tuple[str, ...] + view_count: int + camera_path_relative_to_env_0: str diff --git a/source/isaaclab/isaaclab/renderers/output_contract.py b/source/isaaclab/isaaclab/renderers/output_contract.py new file mode 100644 index 000000000000..bfa3fff41d8b --- /dev/null +++ b/source/isaaclab/isaaclab/renderers/output_contract.py @@ -0,0 +1,54 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Renderer→consumer output contract types. + +Leaf module shared by :class:`~isaaclab.renderers.BaseRenderer` and +:class:`~isaaclab.sensors.camera.CameraData` to avoid a direct dependency +between them. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from enum import StrEnum +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + import torch + + +class RenderBufferKind(StrEnum): + """Canonical names for the per-pixel render buffer kinds a renderer can publish. + + String values match the vocabulary used by + :attr:`isaaclab.sensors.camera.CameraCfg.data_types`. + """ + + RGB = "rgb" + RGBA = "rgba" + ALBEDO = "albedo" + DEPTH = "depth" + DISTANCE_TO_IMAGE_PLANE = "distance_to_image_plane" + DISTANCE_TO_CAMERA = "distance_to_camera" + NORMALS = "normals" + MOTION_VECTORS = "motion_vectors" + SEMANTIC_SEGMENTATION = "semantic_segmentation" + INSTANCE_SEGMENTATION_FAST = "instance_segmentation_fast" + INSTANCE_ID_SEGMENTATION_FAST = "instance_id_segmentation_fast" + SIMPLE_SHADING_CONSTANT_DIFFUSE = "simple_shading_constant_diffuse" + SIMPLE_SHADING_DIFFUSE_MDL = "simple_shading_diffuse_mdl" + SIMPLE_SHADING_FULL_MDL = "simple_shading_full_mdl" + + +@dataclass(frozen=True) +class RenderBufferSpec: + """Per-pixel layout (channels + dtype) for one render buffer kind.""" + + channels: int + """Number of per-pixel channels (last dimension of the allocated tensor).""" + + dtype: torch.dtype + """Torch dtype the renderer writes for this render buffer kind.""" diff --git a/source/isaaclab/isaaclab/renderers/render_context.py b/source/isaaclab/isaaclab/renderers/render_context.py new file mode 100644 index 000000000000..1c1a45a19454 --- /dev/null +++ b/source/isaaclab/isaaclab/renderers/render_context.py @@ -0,0 +1,129 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Simulation-scoped renderers for camera sensors.""" + +from __future__ import annotations + +import logging +from typing import Any, cast + +from isaaclab.sensors.camera.camera_data import CameraData + +from .base_renderer import BaseRenderer +from .renderer import Renderer +from .renderer_cfg import RendererCfg + +logger = logging.getLogger(__name__) + + +class RenderContext: + """Holds :class:`BaseRenderer` instances for all :class:`Camera` sensors in a simulation. + + A camera reuses a backend when a prior camera registered a config equal under ``==`` (value + equality) and the same concrete ``RendererCfg`` subclass. A distinct ``RendererCfg`` that + maps to a different implementation (e.g. Isaac RTX vs Newton) produces another backend; each + has :meth:`BaseRenderer.prepare_stage` run before use. + + :meth:`update_transforms` is invoked at most once per :meth:`get_physics_step_count` for the + context; + """ + + __slots__ = ( + "_renderer_entries", + "_prepared_renderer_ids", + "_prepared_num_envs", + "_last_transforms_step", + ) + + def __init__(self) -> None: + self._renderer_entries: list[tuple[RendererCfg, BaseRenderer]] = [] + self._prepared_renderer_ids: set[int] = set() + self._prepared_num_envs: int | None = None + self._last_transforms_step: int | None = None + + def get_renderer(self, cfg: RendererCfg) -> BaseRenderer: + """Return a backend for this configuration, reusing a matching instance if present. + + Lookups use ``==`` and concrete ``RendererCfg`` type, so :func:`hash` is not used (configs + are typically not hashable). + + Args: + cfg: Renderer configuration from the initializing camera. + + Returns: + A shared or newly created renderer backend. + """ + for stored_cfg, r in self._renderer_entries: + if type(stored_cfg) is type(cfg) and stored_cfg == cfg: + return r + new_renderer = cast(BaseRenderer, Renderer(cfg)) # type: ignore[misc] + self._renderer_entries.append((cfg, new_renderer)) + logger.info( + "Created new renderer for simulation: %s", + type(new_renderer).__name__, + ) + return new_renderer + + def ensure_prepare_stage(self, stage: Any, num_envs: int) -> None: + """Call :meth:`BaseRenderer.prepare_stage` for each registered backend (once per backend). + + If a new backend is added after the first :meth:`prepare_stage` call, this method ensures + that new backend is prepared for the same ``stage`` and ``num_envs`` when the camera + that owns it is initialized. + + Args: + stage: USD stage passed to each backend. + num_envs: Environment count. + + Raises: + RuntimeError: If :meth:`get_renderer` was never called, or ``num_envs`` disagrees with + a value already used for a prepared backend in this context. + """ + if not self._renderer_entries: + raise RuntimeError("get_renderer must be called at least once before ensure_prepare_stage.") + if self._prepared_num_envs is not None and self._prepared_num_envs != num_envs: + raise RuntimeError( + "RenderContext prepare_stage was used with a different num_envs " + f"({self._prepared_num_envs} vs {num_envs})." + ) + for _cfg, renderer in self._renderer_entries: + rid = id(renderer) + if rid not in self._prepared_renderer_ids: + renderer.prepare_stage(stage, num_envs) + self._prepared_renderer_ids.add(rid) + if self._prepared_num_envs is None: + self._prepared_num_envs = num_envs + + def update_transforms(self, physics_step_count: int) -> None: + """Call :meth:`BaseRenderer.update_transforms` on all backends (at most once per step).""" + if not self._renderer_entries: + return + if self._last_transforms_step == physics_step_count: + return + for _cfg, renderer in self._renderer_entries: + renderer.update_transforms() + self._last_transforms_step = physics_step_count + + def render_into_camera( + self, + renderer: BaseRenderer, + render_data: Any, + camera_data: CameraData, + physics_step_count: int, + ) -> None: + """Sync scene transforms, render, and read outputs into ``camera_data``.""" + self.update_transforms(physics_step_count) + renderer.render(render_data) + renderer.read_output(render_data, camera_data) + + def reset_stage_prepare_flag(self) -> None: + """Allow :meth:`ensure_prepare_stage` to run ``prepare_stage`` again (e.g. a new USD stage).""" + self._prepared_renderer_ids.clear() + self._prepared_num_envs = None + + def reset_transform_cadence(self) -> None: + """Clear per-step transform dedupe (e.g. a long pause with no physics).""" + self._last_transforms_step = None diff --git a/source/isaaclab/isaaclab/scene/interactive_scene.py b/source/isaaclab/isaaclab/scene/interactive_scene.py index 306c0dd390b2..ce744fe4bffe 100644 --- a/source/isaaclab/isaaclab/scene/interactive_scene.py +++ b/source/isaaclab/isaaclab/scene/interactive_scene.py @@ -28,11 +28,11 @@ RigidObjectCollection, RigidObjectCollectionCfg, ) -from isaaclab.physics.scene_data_requirements import resolve_scene_data_requirements +from isaaclab.physics.scene_data_requirements import aggregate_requirements, resolve_scene_data_requirements from isaaclab.sensors import ContactSensorCfg, FrameTransformerCfg, SensorBase, SensorBaseCfg from isaaclab.sim import SimulationContext from isaaclab.sim.utils.stage import get_current_stage, get_current_stage_id -from isaaclab.sim.views import XformPrimView +from isaaclab.sim.views import FrameView from isaaclab.terrains import TerrainImporter, TerrainImporterCfg # Note: This is a temporary import for the VisuoTactileSensorCfg class. @@ -138,15 +138,17 @@ def __init__(self, cfg: InteractiveSceneCfg): self.sim = SimulationContext.instance() self.stage = get_current_stage() self.stage_id = get_current_stage_id() - self.sim.clear_scene_data_visualizer_prebuilt_artifact() self.physics_backend = self.sim.physics_manager.__name__.lower() - visualizer_clone_fn = None requested_viz_types = set(self.sim.resolve_visualizer_types()) - if "physx" in self.physics_backend: + if self.physics_backend.startswith("ovphysx"): + from isaaclab_ovphysx.cloner import ovphysx_replicate + + physics_clone_fn = ovphysx_replicate + elif self.physics_backend.startswith("physx"): from isaaclab_physx.cloner import physx_replicate physics_clone_fn = physx_replicate - elif "newton" in self.physics_backend: + elif self.physics_backend.startswith("newton"): from isaaclab_newton.cloner import newton_physics_replicate physics_clone_fn = newton_physics_replicate @@ -162,7 +164,10 @@ def __init__(self, cfg: InteractiveSceneCfg): clone_in_fabric=self.cfg.clone_in_fabric, device=self.device, physics_clone_fn=physics_clone_fn, - visualizer_clone_fn=None, + # For ovphysx: env_1..N are created by physx.clone() in the physics + # runtime after add_usd(). USD replication of the asset hierarchy + # to env_1..N is skipped — only env_0 needs physics prims in the USD. + clone_usd=not self.physics_backend.startswith("ovphysx"), ) # create source prim @@ -173,39 +178,34 @@ def __init__(self, cfg: InteractiveSceneCfg): self._ALL_INDICES = torch.arange(self.cfg.num_envs, dtype=torch.long, device=self.device) self._default_env_origins, _ = cloner.grid_transforms(self.num_envs, self.cfg.env_spacing, device=self.device) # copy empty prim of env_0 to env_1, env_2, ..., env_{num_envs-1} with correct location. - cloner.usd_replicate( - self.stage, [self.env_fmt.format(0)], [self.env_fmt], self._ALL_INDICES, positions=self._default_env_origins - ) + # Suspend Fabric's USD notice listener: scene-init is followed by ``SimulationContext.reset``, + # which does the Fabric resync naturally — re-enabling here would just trigger a redundant batch. + # Note: ``restore=False`` means the listener stays disabled past this ``with`` block — through + # ``_add_entities_from_cfg`` and ``clone_environments`` below — until ``SimulationContext.reset`` + # re-enables it. The nested suspension inside ``clone_environments`` becomes a no-op as a result. + with cloner.disabled_fabric_change_notifies(self.stage, restore=False): + cloner.usd_replicate( + self.stage, + [self.env_fmt.format(0)], + [self.env_fmt], + self._ALL_INDICES, + positions=self._default_env_origins, + ) self._global_prim_paths = list() has_scene_cfg_entities = self._is_scene_setup_from_cfg() if has_scene_cfg_entities: self._add_entities_from_cfg() - requirements = resolve_scene_data_requirements( - visualizer_types=requested_viz_types, - renderer_types=self._sensor_renderer_types(), - ) - self.sim.update_scene_data_requirements(requirements) - visualizer_clone_fn = cloner.resolve_visualizer_clone_fn( - physics_backend=self.physics_backend, - requirements=requirements, - stage=self.stage, - set_visualizer_artifact=self.sim.set_scene_data_visualizer_prebuilt_artifact, - ) - if visualizer_clone_fn is not None: - logger.debug( - "Enabling visualizer artifact prebuild for clone path " - "(backend=%s, requires_newton_model=%s, requires_usd_stage=%s).", - self.physics_backend, - requirements.requires_newton_model, - requirements.requires_usd_stage, - ) - self.cloner_cfg.visualizer_clone_fn = visualizer_clone_fn + # Aggregate scene-data requirements from declared visualizers and constructed sensors, + # then publish to ``SimulationContext`` so downstream providers (constructed later by + # :meth:`SimulationContext.initialize_visualizers`) see the full picture in one read. + self._aggregate_scene_data_requirements(requested_viz_types) if has_scene_cfg_entities: self.clone_environments(copy_from_source=(not self.cfg.replicate_physics)) # Collision filtering is PhysX-specific (PhysxSchema.PhysxSceneAPI) + # Intentionally matches both physx and ovphysx (both are PhysX-based) if self.cfg.filter_collisions and "physx" in self.physics_backend: self.filter_collisions(self._global_prim_paths) @@ -218,41 +218,75 @@ def clone_environments(self, copy_from_source: bool = False): may increase). Defaults to False. """ # PhysX-only: set env id bit count for replicated physics. Newton handles env separation in its own API. + # Intentionally matches both physx and ovphysx (both are PhysX-based) if self.cfg.replicate_physics and "physx" in self.physics_backend: prim = self.stage.GetPrimAtPath("/physicsScene") prim.CreateAttribute("physxScene:envIdInBoundsBitCount", Sdf.ValueTypeNames.Int).Set(4) - if self._is_scene_setup_from_cfg(): - self.cloner_cfg.clone_physics = not copy_from_source - cloner.clone_from_template(self.stage, num_clones=self.num_envs, template_clone_cfg=self.cloner_cfg) - else: - mapping = torch.ones((1, self.num_envs), device=self.device, dtype=torch.bool) - replicate_args = ( - [self.env_fmt.format(0)], - [self.env_fmt], - self._ALL_INDICES, - mapping, - self._default_env_origins, - ) + # Suspend Fabric's USD notice listener around bulk authoring (re-entrant with the inner + # call inside :func:`clone_from_template`). ``restore=False`` because the downstream + # ``SimulationContext.reset`` does the Fabric resync — re-enabling here would batch-resync + # everything we just authored, which is slower than the unsuppressed baseline. + with cloner.disabled_fabric_change_notifies(self.stage, restore=False): + if self._is_scene_setup_from_cfg(): + self.cloner_cfg.clone_physics = not copy_from_source + plans = cloner.clone_from_template( + self.stage, num_clones=self.num_envs, template_clone_cfg=self.cloner_cfg + ) + else: + mapping = torch.ones((1, self.num_envs), device=self.device, dtype=torch.bool) + replicate_args = ( + [self.env_fmt.format(0)], + [self.env_fmt], + self._ALL_INDICES, + mapping, + ) + + if not copy_from_source and self.cloner_cfg.physics_clone_fn is not None: + self.cloner_cfg.physics_clone_fn( + self.stage, *replicate_args, positions=self._default_env_origins, device=self.cloner_cfg.device + ) + if self.cloner_cfg.clone_usd: + cloner.usd_replicate(self.stage, *replicate_args, positions=self._default_env_origins) + # Synthesize a single trivial ClonePlan so consumers (scene data providers, + # pointcloud samplers, etc.) get a uniform interface regardless of whether + # the scene was authored via prototypes or by hand under env_0. + plans = { + self.env_fmt: cloner.ClonePlan( + dest_template=self.env_fmt, + prototype_paths=[self.env_fmt.format(0)], + clone_mask=mapping, + ) + } + + # Publish to ``SimulationContext`` (the canonical owner). The :attr:`clone_plans` + # property below forwards reads back through ``sim.get_clone_plans()`` so consumers + # holding a scene reference still see the published plans without a duplicate cache. + self.sim.set_clone_plans(plans) - if not copy_from_source: - # skip physx cloning, this means physx will walk and parse the stage one by one faithfully - self.cloner_cfg.physics_clone_fn(self.stage, *replicate_args, device=self.cloner_cfg.device) - if self.cloner_cfg.visualizer_clone_fn is not None: - self.cloner_cfg.visualizer_clone_fn(self.stage, *replicate_args, device=self.cloner_cfg.device) - cloner.usd_replicate(self.stage, *replicate_args) + def _aggregate_scene_data_requirements(self, visualizer_types=()) -> None: + """Aggregate scene-data requirements from visualizers and sensor renderers. + + Runs once after :meth:`_add_entities_from_cfg` so all sensors are constructed and + their renderer types are visible. Pushes the merged :class:`SceneDataRequirement` to + :class:`SimulationContext` for later consumption by the scene data provider. + """ + discovered_req = resolve_scene_data_requirements( + visualizer_types=visualizer_types, + renderer_types=self._sensor_renderer_types(), + ) + current_req = self.sim.get_scene_data_requirements() + requirements = aggregate_requirements((current_req, discovered_req)) + if requirements != current_req: + self.sim.update_scene_data_requirements(requirements) def _sensor_renderer_types(self) -> list[str]: - """Return renderer type names used by scene sensors.""" - renderer_types: list[str] = [] - for sensor in self._sensors.values(): - sensor_cfg = getattr(sensor, "cfg", None) - renderer_cfg = getattr(sensor_cfg, "renderer_cfg", None) - if renderer_cfg is None: - continue - renderer_type = getattr(renderer_cfg, "renderer_type", "default") - renderer_types.append(renderer_type) - return renderer_types + """Return renderer type names used by scene sensors (skipping any without a renderer cfg).""" + return [ + getattr(rcfg, "renderer_type", "default") + for s in self._sensors.values() + if (rcfg := getattr(getattr(s, "cfg", None), "renderer_cfg", None)) is not None + ] def filter_collisions(self, global_prim_paths: list[str] | None = None): """Filter environments collisions. @@ -393,11 +427,23 @@ def surface_grippers(self) -> dict[str, SurfaceGripper]: return self._surface_grippers @property - def extras(self) -> dict[str, XformPrimView]: + def clone_plans(self) -> dict[str, cloner.ClonePlan]: + """Per-group clone plans produced by :meth:`clone_environments`. + + Forwards to :meth:`SimulationContext.get_clone_plans`, which is the canonical owner. + Keyed by each group's destination path template + (e.g. ``"/World/envs/env_{}/Object"``); the value records the prototype prim paths + and the per-env prototype assignment mask. Empty until :meth:`clone_environments` + runs, and (for the cfg path) empty when the scene cfg has no template prototypes. + """ + return self.sim.get_clone_plans() + + @property + def extras(self) -> dict[str, FrameView]: """A dictionary of miscellaneous simulation objects that neither inherit from assets nor sensors. The keys are the names of the miscellaneous objects, and the values are the - :class:`~isaaclab.sim.views.XformPrimView` instances of the corresponding prims. + :class:`~isaaclab.sim.views.FrameView` instances of the corresponding prims. As an example, lights or other props in the scene that do not have any attributes or properties that you want to alter at runtime can be added to this dictionary. @@ -463,6 +509,11 @@ def update(self, dt: float) -> None: Args: dt: The amount of time passed from last :meth:`update` call. """ + # Scene-wide renderer transform sync once per step when all sensors update, + # so per-camera fetches do not own this concern (deduped inside RenderContext). + if not self.cfg.lazy_sensor_update: + self.sim.render_context.update_transforms(self.sim.get_physics_step_count()) + # -- assets for articulation in self._articulations.values(): articulation.update(dt) @@ -602,30 +653,30 @@ def get_state(self, is_relative: bool = False) -> dict[str, dict[str, dict[str, state["articulation"] = dict() for asset_name, articulation in self._articulations.items(): asset_state = dict() - asset_state["root_pose"] = wp.to_torch(articulation.data.root_pose_w).clone() + asset_state["root_pose"] = articulation.data.root_pose_w.torch.clone() if is_relative: asset_state["root_pose"][:, :3] -= self.env_origins - asset_state["root_velocity"] = wp.to_torch(articulation.data.root_vel_w).clone() - asset_state["joint_position"] = wp.to_torch(articulation.data.joint_pos).clone() - asset_state["joint_velocity"] = wp.to_torch(articulation.data.joint_vel).clone() + asset_state["root_velocity"] = articulation.data.root_vel_w.torch.clone() + asset_state["joint_position"] = articulation.data.joint_pos.torch.clone() + asset_state["joint_velocity"] = articulation.data.joint_vel.torch.clone() state["articulation"][asset_name] = asset_state # deformable objects state["deformable_object"] = dict() for asset_name, deformable_object in self._deformable_objects.items(): asset_state = dict() - asset_state["nodal_position"] = wp.to_torch(deformable_object.data.nodal_pos_w).clone() + asset_state["nodal_position"] = deformable_object.data.nodal_pos_w.torch.clone() if is_relative: asset_state["nodal_position"][:, :3] -= self.env_origins - asset_state["nodal_velocity"] = wp.to_torch(deformable_object.data.nodal_vel_w).clone() + asset_state["nodal_velocity"] = deformable_object.data.nodal_vel_w.torch.clone() state["deformable_object"][asset_name] = asset_state # rigid objects state["rigid_object"] = dict() for asset_name, rigid_object in self._rigid_objects.items(): asset_state = dict() - asset_state["root_pose"] = wp.to_torch(rigid_object.data.root_pose_w).clone() + asset_state["root_pose"] = rigid_object.data.root_pose_w.torch.clone() if is_relative: asset_state["root_pose"][:, :3] -= self.env_origins - asset_state["root_velocity"] = wp.to_torch(rigid_object.data.root_vel_w).clone() + asset_state["root_velocity"] = rigid_object.data.root_vel_w.torch.clone() state["rigid_object"][asset_name] = asset_state # surface grippers state["gripper"] = dict() @@ -790,6 +841,14 @@ def _add_entities_from_cfg(self): # noqa: C901 asset_cfg.filter_prim_paths_expr = [ p.format(ENV_REGEX_NS=self.env_regex_ns) for p in asset_cfg.filter_prim_paths_expr ] + if hasattr(asset_cfg, "sensor_shape_prim_expr") and asset_cfg.sensor_shape_prim_expr: + asset_cfg.sensor_shape_prim_expr = [ + p.format(ENV_REGEX_NS=self.env_regex_ns) for p in asset_cfg.sensor_shape_prim_expr + ] + if hasattr(asset_cfg, "filter_shape_prim_expr") and asset_cfg.filter_shape_prim_expr: + asset_cfg.filter_shape_prim_expr = [ + p.format(ENV_REGEX_NS=self.env_regex_ns) for p in asset_cfg.filter_shape_prim_expr + ] elif isinstance(asset_cfg, VisuoTactileSensorCfg): if hasattr(asset_cfg, "camera_cfg") and asset_cfg.camera_cfg is not None: asset_cfg.camera_cfg.prim_path = asset_cfg.camera_cfg.prim_path.format( @@ -815,7 +874,7 @@ def _add_entities_from_cfg(self): # noqa: C901 ) # store xform prim view corresponding to this asset # all prims in the scene are Xform prims (i.e. have a transform component) - self._extras[asset_name] = XformPrimView(asset_cfg.prim_path, device=self.device, stage=self.stage) + self._extras[asset_name] = FrameView(asset_cfg.prim_path, device=self.device, stage=self.stage) else: raise ValueError(f"Unknown asset config type for {asset_name}: {asset_cfg}") diff --git a/source/isaaclab/isaaclab/sensors/__init__.py b/source/isaaclab/isaaclab/sensors/__init__.py index fe46ae576ca2..717fc4a7163c 100644 --- a/source/isaaclab/isaaclab/sensors/__init__.py +++ b/source/isaaclab/isaaclab/sensors/__init__.py @@ -26,12 +26,14 @@ +---------------------+---------------------------+---------------------------------------------------------------+ | Contact Sensor | /World/robot/feet_* | Leaf is available and checks if the schema exists | +---------------------+---------------------------+---------------------------------------------------------------+ -| Ray Caster | /World/robot/base | Leaf exists and is a physics body (Articulation / Rigid Body) | +| Ray Caster | /World/robot/base/raycast | ``spawn`` creates an Xform leaf; else the leaf must exist | +---------------------+---------------------------+---------------------------------------------------------------+ | Frame Transformer | /World/robot/base | Leaf exists and is a physics body (Articulation / Rigid Body) | +---------------------+---------------------------+---------------------------------------------------------------+ | Imu | /World/robot/base | Leaf exists and is a physics body (Rigid Body) | +---------------------+---------------------------+---------------------------------------------------------------+ +| Pva | /World/robot/base | Leaf exists and is a physics body (Rigid Body) | ++---------------------+---------------------------+---------------------------------------------------------------+ """ diff --git a/source/isaaclab/isaaclab/sensors/__init__.pyi b/source/isaaclab/isaaclab/sensors/__init__.pyi index 2d225a919989..1bd092de46e6 100644 --- a/source/isaaclab/isaaclab/sensors/__init__.pyi +++ b/source/isaaclab/isaaclab/sensors/__init__.pyi @@ -9,6 +9,8 @@ __all__ = [ "Camera", "CameraCfg", "CameraData", + "RenderBufferKind", + "RenderBufferSpec", "TiledCamera", "TiledCameraCfg", "transform_points", @@ -31,6 +33,16 @@ __all__ = [ "Imu", "ImuCfg", "ImuData", + "BaseJointWrenchSensor", + "BaseJointWrenchSensorData", + "JointWrenchSensor", + "JointWrenchSensorCfg", + "JointWrenchSensorData", + "BasePva", + "BasePvaData", + "Pva", + "PvaCfg", + "PvaData", "MultiMeshRayCaster", "MultiMeshRayCasterCamera", "MultiMeshRayCasterCameraCfg", @@ -51,6 +63,8 @@ from .camera import ( Camera, CameraCfg, CameraData, + RenderBufferKind, + RenderBufferSpec, TiledCamera, TiledCameraCfg, transform_points, @@ -74,6 +88,14 @@ from .frame_transformer import ( FrameTransformerData, ) from .imu import BaseImu, BaseImuData, Imu, ImuCfg, ImuData +from .joint_wrench import ( + BaseJointWrenchSensor, + BaseJointWrenchSensorData, + JointWrenchSensor, + JointWrenchSensorCfg, + JointWrenchSensorData, +) +from .pva import BasePva, BasePvaData, Pva, PvaCfg, PvaData from .ray_caster import ( MultiMeshRayCaster, MultiMeshRayCasterCamera, diff --git a/source/isaaclab/isaaclab/sensors/camera/__init__.pyi b/source/isaaclab/isaaclab/sensors/camera/__init__.pyi index 0bdc3fb85261..cac009dea0d4 100644 --- a/source/isaaclab/isaaclab/sensors/camera/__init__.pyi +++ b/source/isaaclab/isaaclab/sensors/camera/__init__.pyi @@ -7,6 +7,8 @@ __all__ = [ "Camera", "CameraCfg", "CameraData", + "RenderBufferKind", + "RenderBufferSpec", "TiledCamera", "TiledCameraCfg", "transform_points", @@ -17,7 +19,7 @@ __all__ = [ from .camera import Camera from .camera_cfg import CameraCfg -from .camera_data import CameraData +from .camera_data import CameraData, RenderBufferKind, RenderBufferSpec from .tiled_camera import TiledCamera from .tiled_camera_cfg import TiledCameraCfg from .utils import ( diff --git a/source/isaaclab/isaaclab/sensors/camera/camera.py b/source/isaaclab/isaaclab/sensors/camera/camera.py index 70ccc6c14dd8..be52668dbd6c 100644 --- a/source/isaaclab/isaaclab/sensors/camera/camera.py +++ b/source/isaaclab/isaaclab/sensors/camera/camera.py @@ -5,33 +5,31 @@ from __future__ import annotations -import json import logging from collections.abc import Sequence -from typing import TYPE_CHECKING, Any, Literal +from typing import TYPE_CHECKING, Literal import numpy as np import torch import warp as wp -from packaging import version -from pxr import Sdf, UsdGeom +from pxr import UsdGeom import isaaclab.sim as sim_utils import isaaclab.utils.sensors as sensor_utils from isaaclab.app.settings_manager import get_settings_manager -from isaaclab.sim.views import XformPrimView -from isaaclab.utils import has_kit, to_camel_case -from isaaclab.utils.array import convert_to_torch +from isaaclab.renderers import BaseRenderer +from isaaclab.renderers.camera_render_spec import CameraRenderSpec +from isaaclab.sim.views import FrameView +from isaaclab.utils import to_camel_case from isaaclab.utils.math import ( convert_camera_frame_orientation_convention, create_rotation_matrix_from_view, quat_from_matrix, ) -from isaaclab.utils.version import get_isaac_sim_version from ..sensor_base import SensorBase -from .camera_data import CameraData +from .camera_data import CameraData, RenderBufferKind if TYPE_CHECKING: from .camera_cfg import CameraCfg @@ -96,14 +94,6 @@ class Camera(SensorBase): } """The set of sensor types that are not supported by the camera class.""" - SIMPLE_SHADING_MODES: dict[str, int] = { - "simple_shading_constant_diffuse": 0, - "simple_shading_diffuse_mdl": 1, - "simple_shading_full_mdl": 2, - } - SIMPLE_SHADING_AOV: str = "SimpleShadingSD" - SIMPLE_SHADING_MODE_SETTING: str = "/rtx/sdg/simpleShading/mode" - def __init__(self, cfg: CameraCfg): """Initializes the camera sensor. @@ -119,100 +109,39 @@ def __init__(self, cfg: CameraCfg): # initialize base class super().__init__(cfg) - # toggle rendering of rtx sensors as True - # this flag is read by SimulationContext to determine if rtx sensors should be rendered - settings = get_settings_manager() - settings.set_bool("/isaaclab/render/rtx_sensors", True) - - # This is only introduced in isaac sim 6.0 - if has_kit(): - isaac_sim_version = get_isaac_sim_version() - if isaac_sim_version.major >= 6: - # Set RTX flag to enable fast path when no regular RGB/RGBA annotators are requested - needs_color_render = "rgb" in self.cfg.data_types or "rgba" in self.cfg.data_types - if not needs_color_render: - settings.set_bool("/rtx/sdg/force/disableColorRender", True) - - # If we have GUI / viewport enabled, we turn off fast path so that the viewport is not black - if settings.get("/isaaclab/has_gui"): - settings.set_bool("/rtx/sdg/force/disableColorRender", False) - else: - if "albedo" in self.cfg.data_types: - logger.warning( - "Albedo annotator is only supported in Isaac Sim 6.0+. The albedo data type will be ignored." - ) - if any(data_type in self.SIMPLE_SHADING_MODES for data_type in self.cfg.data_types): - logger.warning( - "Simple shading annotators are only supported in Isaac Sim 6.0+. The simple shading data types" - " will be ignored." - ) - - # Set simple shading mode (if requested) before rendering - simple_shading_mode = self._resolve_simple_shading_mode() - if simple_shading_mode is not None: - settings.set_int(self.SIMPLE_SHADING_MODE_SETTING, simple_shading_mode) - - # spawn the asset - if self.cfg.spawn is not None: - # Use spawn_path when set (points to template location for scene-cloned sensors). - # This allows the camera to be spawned inside the asset template (e.g. inside - # proto_asset_0) before clone_environments replicates it to all env paths. - spawn_target = ( - self.cfg.spawn.spawn_path - if getattr(self.cfg.spawn, "spawn_path", None) is not None - else self.cfg.prim_path - ) - # compute the rotation offset - rot = torch.tensor(self.cfg.offset.rot, dtype=torch.float32, device="cpu").unsqueeze(0) - rot_offset = convert_camera_frame_orientation_convention( - rot, origin=self.cfg.offset.convention, target="opengl" - ) - rot_offset = rot_offset.squeeze(0).cpu().numpy() - # ensure vertical aperture is set, otherwise replace with default for squared pixels - if self.cfg.spawn.vertical_aperture is None: - self.cfg.spawn.vertical_aperture = self.cfg.spawn.horizontal_aperture * self.cfg.height / self.cfg.width - self.cfg.spawn.func(spawn_target, self.cfg.spawn, translation=self.cfg.offset.pos, orientation=rot_offset) - # check that spawn was successful; use spawn_path if set (template location) since env - # paths are not yet populated at init time — they are filled in by clone_environments. - check_path = ( - self.cfg.spawn.spawn_path - if self.cfg.spawn is not None and getattr(self.cfg.spawn, "spawn_path", None) is not None - else self.cfg.prim_path + # TODO(follow-up PR): move this flag flip out of Camera. The cleanest path is + # an apply_pre_reset_settings() hook on RendererCfg (default no-op) that + # IsaacRtxRendererCfg overrides to flip /isaaclab/render/rtx_sensors. The + # flag must be set pre-sim.reset() because SimulationContext.is_rendering + # and several env classes read it before the renderer's __init__ runs. + if self.cfg.renderer_cfg.renderer_type == "isaac_rtx": + get_settings_manager().set_bool("/isaaclab/render/rtx_sensors", True) + + # Compute camera orientation (convention conversion) and spawn + rot = torch.tensor(self.cfg.offset.rot, dtype=torch.float32, device="cpu").unsqueeze(0) + rot_offset = convert_camera_frame_orientation_convention( + rot, origin=self.cfg.offset.convention, target="opengl" ) - matching_prims = sim_utils.find_matching_prims(check_path) - if len(matching_prims) == 0: - raise RuntimeError(f"Could not find prim with path {check_path}.") + rot_offset = rot_offset.squeeze(0).cpu().numpy() + if self.cfg.spawn is not None and self.cfg.spawn.vertical_aperture is None: + self.cfg.spawn.vertical_aperture = self.cfg.spawn.horizontal_aperture * self.cfg.height / self.cfg.width + self._resolve_and_spawn("camera", translation=self.cfg.offset.pos, orientation=rot_offset) # UsdGeom Camera prim for the sensor self._sensor_prims: list[UsdGeom.Camera] = list() - # Create empty variables for storing output data - self._data = CameraData() - - if not has_kit(): - return - # HACK: We need to disable instancing for semantic_segmentation and instance_segmentation_fast to work - # checks for Isaac Sim v4.5 as this issue exists there - if get_isaac_sim_version() == version.parse("4.5"): - if "semantic_segmentation" in self.cfg.data_types or "instance_segmentation_fast" in self.cfg.data_types: - logger.warning( - "Isaac Sim 4.5 introduced a bug in Camera and TiledCamera when outputting instance and semantic" - " segmentation outputs for instanceable assets. As a workaround, the instanceable flag on assets" - " will be disabled in the current workflow and may lead to longer load times and increased memory" - " usage." - ) - with Sdf.ChangeBlock(): - for prim in self.stage.Traverse(): - prim.SetInstanceable(False) + # Allocated in :meth:`_create_buffers` once the renderer's output contract is known. + self._data: CameraData | None = None + # Renderer and render data — assigned in _initialize_impl. + self._renderer: BaseRenderer | None = None + self._render_data = None def __del__(self): - """Unsubscribes from callbacks and detach from the replicator registry.""" + """Unsubscribes from callbacks and cleans up renderer resources.""" # unsubscribe callbacks super().__del__() - # delete from replicator registry - for _, annotators in self._rep_registry.items(): - for annotator, render_product_path in zip(annotators, self._render_product_paths): - annotator.detach([render_product_path]) - annotator = None + # cleanup render resources (renderer may be None if never initialized) + if self._renderer is not None: + self._renderer.cleanup(self._render_data) def __str__(self) -> str: """Returns: A string containing information about the instance.""" @@ -220,10 +149,6 @@ def __str__(self) -> str: return ( f"Camera @ '{self.cfg.prim_path}': \n" f"\tdata types : {list(self.data.output.keys())} \n" - f"\tsemantic filter : {self.cfg.semantic_filter}\n" - f"\tcolorize semantic segm. : {self.cfg.colorize_semantic_segmentation}\n" - f"\tcolorize instance segm. : {self.cfg.colorize_instance_segmentation}\n" - f"\tcolorize instance id segm.: {self.cfg.colorize_instance_id_segmentation}\n" f"\tupdate period (s): {self.cfg.update_period}\n" f"\tshape : {self.image_shape}\n" f"\tnumber of sensors : {self._view.count}" @@ -249,14 +174,6 @@ def frame(self) -> torch.tensor: """Frame number when the measurement took place.""" return self._frame - @property - def render_product_paths(self) -> list[str]: - """The path of the render products for the cameras. - - This can be used via replicator interfaces to attach to writes or external annotator registry. - """ - return self._render_product_paths - @property def image_shape(self) -> tuple[int, int]: """A tuple containing (height, width) of the camera sensor.""" @@ -373,8 +290,16 @@ def set_world_poses( elif not isinstance(orientations, torch.Tensor): orientations = torch.tensor(orientations, device=self._device) orientations = convert_camera_frame_orientation_convention(orientations, origin=convention, target="opengl") - # set the pose - self._view.set_world_poses(positions, orientations, env_ids) + # convert torch tensors to warp arrays for the view + pos_wp = wp.from_torch(positions.contiguous()) if positions is not None else None + ori_wp = wp.from_torch(orientations.contiguous()) if orientations is not None else None + if env_ids is not None: + if not isinstance(env_ids, torch.Tensor): + env_ids = torch.tensor(env_ids, dtype=torch.int32, device=self._device) + idx_wp = wp.from_torch(env_ids.to(dtype=torch.int32), dtype=wp.int32) + else: + idx_wp = None + self._view.set_world_poses(pos_wp, ori_wp, idx_wp) def set_world_poses_from_view( self, eyes: torch.Tensor, targets: torch.Tensor, env_ids: Sequence[int] | None = None @@ -397,7 +322,10 @@ def set_world_poses_from_view( up_axis = UsdGeom.GetStageUpAxis(self.stage) # set camera poses using the view orientations = quat_from_matrix(create_rotation_matrix_from_view(eyes, targets, up_axis, device=self._device)) - self._view.set_world_poses(eyes, orientations, env_ids) + if not isinstance(env_ids, torch.Tensor): + env_ids = torch.tensor(env_ids, dtype=torch.int32, device=self._device) + idx_wp = wp.from_torch(env_ids.to(dtype=torch.int32), dtype=wp.int32) + self._view.set_world_poses(wp.from_torch(eyes.contiguous()), wp.from_torch(orientations.contiguous()), idx_wp) """ Operations @@ -428,30 +356,33 @@ def reset(self, env_ids: Sequence[int] | None = None, env_mask: wp.array | None def _initialize_impl(self): """Initializes the sensor handles and internal buffers. - This function creates handles and registers the provided data types with the replicator registry to - be able to access the data from the sensor. It also initializes the internal buffers to store the data. + This function obtains the simulation-scoped :class:`~isaaclab.renderers.base_renderer.BaseRenderer` + from :attr:`~isaaclab.sim.simulation_context.SimulationContext.render_context` using the configured + :attr:`~isaaclab.sensors.camera.CameraCfg.renderer_cfg` and delegates all render-product + and annotator management to it. It also initializes the internal buffers to store the data. Raises: RuntimeError: If the number of camera prims in the view does not match the number of environments. - RuntimeError: If replicator was not found. + RuntimeError: Propagated from the renderer constructor when the active backend's + runtime requirements are not satisfied (e.g. the RTX backend requires the + simulation app to be launched with ``--enable_cameras``). """ - renderer_type = getattr(self.cfg.renderer_cfg, "renderer_type", "default") - needs_kit_cameras = renderer_type in ("default", "isaac_rtx") - if needs_kit_cameras and not get_settings_manager().get("/isaaclab/cameras_enabled"): - raise RuntimeError( - "A camera was spawned without the --enable_cameras flag. Please use --enable_cameras to enable" - " rendering." - ) - - import omni.replicator.core as rep - from omni.syntheticdata.scripts.SyntheticData import SyntheticData - # Initialize parent class super()._initialize_impl() - # Create a view for the sensor with Fabric enabled for fast pose queries, otherwise position will be stale. - self._view = XformPrimView( - self.cfg.prim_path, device=self._device, stage=self.stage, sync_usd_on_fabric_write=True - ) + + sim_ctx = sim_utils.SimulationContext.instance() + if sim_ctx is None: + raise RuntimeError("SimulationContext is not initialized.") + self._renderer = sim_ctx.render_context.get_renderer(self.cfg.renderer_cfg) + logger.info("Using renderer: %s", type(self._renderer).__name__) + + # Stage preprocessing must happen before creating the view because the view keeps + # references to prims located in the stage. + sim_ctx.render_context.ensure_prepare_stage(self.stage, self._num_envs) + + # Create a view for the sensor with Fabric enabled for fast pose queries. + # TODO: remove sync_usd_on_fabric_write=True once the GPU Fabric sync bug is fixed. + self._view = FrameView(self.cfg.prim_path, device=self._device, stage=self.stage, sync_usd_on_fabric_write=True) # Check that sizes are correct if self._view.count != self._num_envs: raise RuntimeError( @@ -464,10 +395,6 @@ def _initialize_impl(self): # Create frame count buffer self._frame = torch.zeros(self._view.count, device=self._device, dtype=torch.long) - # Attach the sensor data types to render node - self._render_product_paths: list[str] = list() - self._rep_registry: dict[str, list[rep.annotators.Annotator]] = {name: list() for name in self.cfg.data_types} - # Convert all encapsulated prims to Camera for cam_prim in self._view.prims: # Obtain the prim path @@ -476,84 +403,27 @@ def _initialize_impl(self): if not cam_prim.IsA(UsdGeom.Camera): raise RuntimeError(f"Prim at path '{cam_prim_path}' is not a Camera.") # Add to list - sensor_prim = UsdGeom.Camera(cam_prim) - self._sensor_prims.append(sensor_prim) - - # Get render product - # From Isaac Sim 2023.1 onwards, render product is a HydraTexture so we need to extract the path - render_prod_path = rep.create.render_product(cam_prim_path, resolution=(self.cfg.width, self.cfg.height)) - if not isinstance(render_prod_path, str): - render_prod_path = render_prod_path.path - self._render_product_paths.append(render_prod_path) - - # Check if semantic types or semantic filter predicate is provided - if isinstance(self.cfg.semantic_filter, list): - semantic_filter_predicate = ":*; ".join(self.cfg.semantic_filter) + ":*" - elif isinstance(self.cfg.semantic_filter, str): - semantic_filter_predicate = self.cfg.semantic_filter - else: - raise ValueError(f"Semantic types must be a list or a string. Received: {self.cfg.semantic_filter}.") - # set the semantic filter predicate - # copied from rep.scripts.writes_default.basic_writer.py - SyntheticData.Get().set_instance_mapping_semantic_filter(semantic_filter_predicate) - - # Iterate over each data type and create annotator - # TODO: This will move out of the loop once Replicator supports multiple render products within a single - # annotator, i.e.: rep_annotator.attach(self._render_product_paths) - for name in self.cfg.data_types: - # note: we are verbose here to make it easier to understand the code. - # if colorize is true, the data is mapped to colors and a uint8 4 channel image is returned. - # if colorize is false, the data is returned as a uint32 image with ids as values. - if name == "semantic_segmentation": - init_params = { - "colorize": self.cfg.colorize_semantic_segmentation, - "mapping": json.dumps(self.cfg.semantic_segmentation_mapping), - } - elif name == "instance_segmentation_fast": - init_params = {"colorize": self.cfg.colorize_instance_segmentation} - elif name == "instance_id_segmentation_fast": - init_params = {"colorize": self.cfg.colorize_instance_id_segmentation} - else: - init_params = None + self._sensor_prims.append(UsdGeom.Camera(cam_prim)) - # Resolve device name - if "cuda" in self._device: - device_name = self._device.split(":")[0] - else: - device_name = "cpu" - - # TODO: this is a temporary solution because replicator has not exposed the annotator yet - # once it's exposed, we can remove this - if name == "albedo": - rep.AnnotatorRegistry.register_annotator_from_aov( - aov="DiffuseAlbedoSD", output_data_type=np.uint8, output_channels=4 - ) - if name in self.SIMPLE_SHADING_MODES: - rep.AnnotatorRegistry.register_annotator_from_aov( - aov=self.SIMPLE_SHADING_AOV, output_data_type=np.uint8, output_channels=4 - ) - - # Map special cases to their corresponding annotator names - simple_shading_cases = {key: self.SIMPLE_SHADING_AOV for key in self.SIMPLE_SHADING_MODES} - special_cases = { - "rgba": "rgb", - "depth": "distance_to_image_plane", - "albedo": "DiffuseAlbedoSD", - **simple_shading_cases, - } - # Get the annotator name, falling back to the original name if not a special case - annotator_name = special_cases.get(name, name) - # Create the annotator node - rep_annotator = rep.AnnotatorRegistry.get_annotator(annotator_name, init_params, device=device_name) - - # attach annotator to render product - rep_annotator.attach(render_prod_path) - # add to registry - self._rep_registry[name].append(rep_annotator) - - # Create internal buffers + # View needs to exist before creating render data + cam_paths = tuple(cam_prim.GetPath().pathString for cam_prim in self._view.prims) + env_0_prefix = "/World/envs/env_0/" + rel_under_env0 = ( + cam_paths[0].removeprefix(env_0_prefix) if cam_paths and cam_paths[0].startswith(env_0_prefix) else "" + ) + device_str = self._device if isinstance(self._device, str) else str(self._device) + render_spec = CameraRenderSpec( + cfg=self.cfg, + device=device_str, + num_instances=self.num_instances, + camera_prim_paths=cam_paths, + view_count=self._view.count, + camera_path_relative_to_env_0=rel_under_env0, + ) + self._render_data = self._renderer.create_render_data(render_spec) + + # Create internal buffers (includes intrinsic matrix and pose init) self._create_buffers() - self._update_intrinsic_matrices(self._ALL_INDICES) def _update_buffers_impl(self, env_mask: wp.array): env_ids = wp.to_torch(env_mask).nonzero(as_tuple=False).squeeze(-1) @@ -561,50 +431,23 @@ def _update_buffers_impl(self, env_mask: wp.array): return # Increment frame count self._frame[env_ids] += 1 - # -- pose + # update latest camera pose if requested if self.cfg.update_latest_camera_pose: self._update_poses(env_ids) - # Ensure the RTX renderer has been pumped so annotator buffers are fresh. - # Lazy import Isaac RTX Renderer dependency. - # For now the Camera implementation works only with Isaac RTX Renderer. - # Future consideration should be to move Renderer from TiledCamera up the hierarchy to Camera - # to make the Camera backend-agnostic. - from isaaclab_physx.renderers.isaac_rtx_renderer_utils import ensure_isaac_rtx_render_update - - ensure_isaac_rtx_render_update() - - # -- read the data from annotator registry - # check if buffer is called for the first time. If so then, allocate the memory - if len(self._data.output) == 0: - # this is the first time buffer is called - # it allocates memory for all the sensors - self._create_annotator_data() + + sim_ctx = sim_utils.SimulationContext.instance() + renderer = self._renderer + assert renderer is not None + if sim_ctx is not None: + sim_ctx.render_context.render_into_camera( + renderer, + self._render_data, + self._data, + sim_ctx.get_physics_step_count(), + ) else: - # iterate over all the data types - for name, annotators in self._rep_registry.items(): - # iterate over all the annotators - for index in env_ids: - # get the output - output = annotators[index].get_data() - # process the output - data, info = self._process_annotator_output(name, output) - # add data to output - self._data.output[name][index] = data - # add info to output - self._data.info[index][name] = info - # NOTE: The `distance_to_camera` annotator returns the distance to the camera optical center. However, - # the replicator depth clipping is applied w.r.t. to the image plane which may result in values - # larger than the clipping range in the output. We apply an additional clipping to ensure values - # are within the clipping range for all the annotators. - if name == "distance_to_camera": - self._data.output[name][self._data.output[name] > self.cfg.spawn.clipping_range[1]] = torch.inf - # apply defined clipping behavior - if ( - name == "distance_to_camera" or name == "distance_to_image_plane" - ) and self.cfg.depth_clipping_behavior != "none": - self._data.output[name][torch.isinf(self._data.output[name])] = ( - 0.0 if self.cfg.depth_clipping_behavior == "zero" else self.cfg.spawn.clipping_range[1] - ) + renderer.render(self._render_data) + renderer.read_output(self._render_data, self._data) """ Private Helpers @@ -632,19 +475,40 @@ def _check_supported_data_types(self, cfg: CameraCfg): def _create_buffers(self): """Create buffers for storing data.""" - # create the data object - # -- pose of the cameras + specs = self._renderer.supported_output_types() + # Split requested names into known/unsupported; warn once for any the renderer can't produce. + known: list[str] = [] + unsupported: list[str] = [] + for name in self.cfg.data_types: + try: + if RenderBufferKind(name) in specs: + known.append(name) + else: + unsupported.append(name) + except ValueError: + unsupported.append(name) + if unsupported: + logger.warning( + "Renderer %s does not support the following requested data types and will not produce them: %s", + type(self._renderer).__name__, + unsupported, + ) + self._data = CameraData.allocate( + data_types=known, + height=self.cfg.height, + width=self.cfg.width, + num_views=self._view.count, + device=self._device, + supported_specs=specs, + ) + # Camera-frame state (pose / intrinsics) is owned by the camera, not + # the renderer: populate it on the freshly constructed ``CameraData``. + self._data.intrinsic_matrices = torch.zeros((self._view.count, 3, 3), device=self._device) + self._update_intrinsic_matrices(self._ALL_INDICES) self._data.pos_w = torch.zeros((self._view.count, 3), device=self._device) self._data.quat_w_world = torch.zeros((self._view.count, 4), device=self._device) - # -- intrinsic matrix - self._data.intrinsic_matrices = torch.zeros((self._view.count, 3, 3), device=self._device) - self._data.image_shape = self.image_shape - # -- output data - # lazy allocation of data dictionary - # since the size of the output data is not known in advance, we leave it as None - # the memory will be allocated when the buffer() function is called for the first time. - self._data.output = {} - self._data.info = [{name: None for name in self.cfg.data_types} for _ in range(self._view.count)] + self._update_poses(self._ALL_INDICES) + self._renderer.set_outputs(self._render_data, self._data.output) def _update_intrinsic_matrices(self, env_ids: Sequence[int]): """Compute camera's matrix of intrinsic parameters. @@ -691,113 +555,20 @@ def _update_poses(self, env_ids: Sequence[int]): if len(self._sensor_prims) == 0: raise RuntimeError("Camera prim is None. Please call 'sim.play()' first.") - # get the poses from the view - poses, quat = self._view.get_world_poses(env_ids) - self._data.pos_w[env_ids] = poses + # get the poses from the view (returns ProxyArray, use .torch for tensor access) + if env_ids is not None and not isinstance(env_ids, torch.Tensor): + env_ids = torch.tensor(env_ids, dtype=torch.int32, device=self._device) + indices = wp.from_torch(env_ids.to(dtype=torch.int32), dtype=wp.int32) if env_ids is not None else None + pos_w, quat_w = self._view.get_world_poses(indices) + self._data.pos_w[env_ids] = pos_w.torch self._data.quat_w_world[env_ids] = convert_camera_frame_orientation_convention( - quat, origin="opengl", target="world" + quat_w.torch, origin="opengl", target="world" ) - - def _create_annotator_data(self): - """Create the buffers to store the annotator data. - - We create a buffer for each annotator and store the data in a dictionary. Since the data - shape is not known beforehand, we create a list of buffers and concatenate them later. - - This is an expensive operation and should be called only once. - """ - # add data from the annotators - for name, annotators in self._rep_registry.items(): - # create a list to store the data for each annotator - data_all_cameras = list() - # iterate over all the annotators - for index in self._ALL_INDICES: - # get the output - output = annotators[index].get_data() - # process the output - data, info = self._process_annotator_output(name, output) - # append the data - data_all_cameras.append(data) - # store the info - self._data.info[index][name] = info - # concatenate the data along the batch dimension - self._data.output[name] = torch.stack(data_all_cameras, dim=0) - # NOTE: `distance_to_camera` and `distance_to_image_plane` are not both clipped to the maximum defined - # in the clipping range. The clipping is applied only to `distance_to_image_plane` and then both - # outputs are only clipped where the values in `distance_to_image_plane` exceed the threshold. To - # have a unified behavior between all cameras, we clip both outputs to the maximum value defined. - if name == "distance_to_camera": - self._data.output[name][self._data.output[name] > self.cfg.spawn.clipping_range[1]] = torch.inf - # clip the data if needed - if ( - name == "distance_to_camera" or name == "distance_to_image_plane" - ) and self.cfg.depth_clipping_behavior != "none": - self._data.output[name][torch.isinf(self._data.output[name])] = ( - 0.0 if self.cfg.depth_clipping_behavior == "zero" else self.cfg.spawn.clipping_range[1] - ) - - def _process_annotator_output(self, name: str, output: Any) -> tuple[torch.tensor, dict | None]: - """Process the annotator output. - - This function is called after the data has been collected from all the cameras. - """ - # extract info and data from the output - if isinstance(output, dict): - data = output["data"] - info = output["info"] - else: - data = output - info = None - # convert data into torch tensor - data = convert_to_torch(data, device=self.device) - - # process data for different segmentation types - # Note: Replicator returns raw buffers of dtype int32 for segmentation types - # so we need to convert them to uint8 4 channel images for colorized types - height, width = self.image_shape - if name == "semantic_segmentation": - if self.cfg.colorize_semantic_segmentation: - data = data.view(torch.uint8).reshape(height, width, -1) - else: - data = data.view(height, width, 1) - elif name == "instance_segmentation_fast": - if self.cfg.colorize_instance_segmentation: - data = data.view(torch.uint8).reshape(height, width, -1) - else: - data = data.view(height, width, 1) - elif name == "instance_id_segmentation_fast": - if self.cfg.colorize_instance_id_segmentation: - data = data.view(torch.uint8).reshape(height, width, -1) - else: - data = data.view(height, width, 1) - # make sure buffer dimensions are consistent as (H, W, C) - elif name == "distance_to_camera" or name == "distance_to_image_plane" or name == "depth": - data = data.view(height, width, 1) - # we only return the RGB channels from the RGBA output if rgb is required - # normals return (x, y, z) in first 3 channels, 4th channel is unused - elif name == "rgb" or name == "normals": - data = data[..., :3] - # motion vectors return (x, y) in first 2 channels, 3rd and 4th channels are unused - elif name == "motion_vectors": - data = data[..., :2] - elif name in self.SIMPLE_SHADING_MODES: - data = data[..., :3] - - # return the data and info - return data, info - - def _resolve_simple_shading_mode(self) -> int | None: - """Resolve the requested simple shading mode from data types.""" - requested = [data_type for data_type in self.cfg.data_types if data_type in self.SIMPLE_SHADING_MODES] - if not requested: - return None - if len(requested) > 1: - logger.warning( - "Multiple simple shading modes requested (%s). Using '%s' only.", - requested, - requested[0], + # notify renderer of updated poses (guarded in case called before initialization completes) + if self._render_data is not None: + self._renderer.update_camera( + self._render_data, self._data.pos_w, self._data.quat_w_world, self._data.intrinsic_matrices ) - return self.SIMPLE_SHADING_MODES[requested[0]] """ Internal simulation callbacks. @@ -805,6 +576,10 @@ def _resolve_simple_shading_mode(self) -> int | None: def _invalidate_initialize_callback(self, event): """Invalidates the scene elements.""" + if self._renderer is not None and self._render_data is not None: + self._renderer.cleanup(self._render_data) + self._render_data = None + self._renderer = None # call parent super()._invalidate_initialize_callback(event) # set all existing views to None to invalidate them diff --git a/source/isaaclab/isaaclab/sensors/camera/camera_cfg.py b/source/isaaclab/isaaclab/sensors/camera/camera_cfg.py index 1b5070cfd214..5ee6cf30b6f6 100644 --- a/source/isaaclab/isaaclab/sensors/camera/camera_cfg.py +++ b/source/isaaclab/isaaclab/sensors/camera/camera_cfg.py @@ -5,6 +5,7 @@ from __future__ import annotations +import warnings from dataclasses import MISSING, field from typing import TYPE_CHECKING, Literal @@ -19,6 +20,18 @@ if TYPE_CHECKING: from .camera import Camera +# Default values for the RTX-flavored fields kept on :class:`CameraCfg` for +# backward compatibility. These mirror the defaults on +# :class:`~isaaclab_physx.renderers.IsaacRtxRendererCfg`. +_DEPRECATED_RENDERER_FIELD_DEFAULTS: dict = { + "semantic_filter": "*:*", + "colorize_semantic_segmentation": True, + "colorize_instance_id_segmentation": True, + "colorize_instance_segmentation": True, + "semantic_segmentation_mapping": {}, + "depth_clipping_behavior": "none", +} + @configclass class CameraCfg(SensorBaseCfg): @@ -67,6 +80,11 @@ class OffsetCfg: - ``"max"``: Values are clipped to the maximum value. - ``"zero"``: Values are clipped to zero. - ``"none``: No clipping is applied. Values will be returned as ``inf``. + + .. deprecated:: 4.6.22 + This field is RTX-specific. Set + :attr:`~isaaclab_physx.renderers.IsaacRtxRendererCfg.depth_clipping_behavior` + on :attr:`renderer_cfg` instead. """ data_types: list[str] = ["rgb"] @@ -85,7 +103,7 @@ class OffsetCfg: """Whether to update the latest camera pose when fetching the camera's data. Defaults to False. If True, the latest camera pose is updated in the camera's data which will slow down performance - due to the use of :class:`XformPrimView`. + due to the use of :class:`FrameView`. If False, the pose of the camera during initialization is returned. """ @@ -108,6 +126,11 @@ class OffsetCfg: For more information on the semantics filter, see the documentation on `Replicator Semantics Schema Editor`_. .. _Replicator Semantics Schema Editor: https://docs.omniverse.nvidia.com/extensions/latest/ext_replicator/semantics_schema_editor.html#semantics-filtering + + .. deprecated:: 4.6.22 + This field is RTX-specific. Set + :attr:`~isaaclab_physx.renderers.IsaacRtxRendererCfg.semantic_filter` on + :attr:`renderer_cfg` instead. """ colorize_semantic_segmentation: bool = True @@ -115,6 +138,11 @@ class OffsetCfg: If True, semantic segmentation is converted to an image where semantic IDs are mapped to colors and returned as a ``uint8`` 4-channel array. If False, the output is returned as a ``int32`` array. + + .. deprecated:: 4.6.22 + This field is RTX-specific. Set + :attr:`~isaaclab_physx.renderers.IsaacRtxRendererCfg.colorize_semantic_segmentation` + on :attr:`renderer_cfg` instead. """ colorize_instance_id_segmentation: bool = True @@ -122,6 +150,11 @@ class OffsetCfg: If True, instance id segmentation is converted to an image where instance IDs are mapped to colors. and returned as a ``uint8`` 4-channel array. If False, the output is returned as a ``int32`` array. + + .. deprecated:: 4.6.22 + This field is RTX-specific. Set + :attr:`~isaaclab_physx.renderers.IsaacRtxRendererCfg.colorize_instance_id_segmentation` + on :attr:`renderer_cfg` instead. """ colorize_instance_segmentation: bool = True @@ -129,6 +162,11 @@ class OffsetCfg: If True, instance segmentation is converted to an image where instance IDs are mapped to colors. and returned as a ``uint8`` 4-channel array. If False, the output is returned as a ``int32`` array. + + .. deprecated:: 4.6.22 + This field is RTX-specific. Set + :attr:`~isaaclab_physx.renderers.IsaacRtxRendererCfg.colorize_instance_segmentation` + on :attr:`renderer_cfg` instead. """ semantic_segmentation_mapping: dict = {} @@ -147,7 +185,35 @@ class OffsetCfg: "class:robot": (61, 178, 255, 255), } + .. deprecated:: 4.6.22 + This field is RTX-specific. Set + :attr:`~isaaclab_physx.renderers.IsaacRtxRendererCfg.semantic_segmentation_mapping` + on :attr:`renderer_cfg` instead. """ renderer_cfg: RendererCfg = field(default_factory=IsaacRtxRendererCfg) """Renderer configuration for camera sensor.""" + + def __post_init__(self): + """Forward deprecated RTX-flavored fields onto :attr:`renderer_cfg`. + + Each deprecated field set to a non-default value emits a + :class:`DeprecationWarning` and is copied onto ``self.renderer_cfg`` + when that cfg defines the same-named field. + """ + # Forwarded by name: any same-named field on ``renderer_cfg`` will receive the value. + for field_name, default in _DEPRECATED_RENDERER_FIELD_DEFAULTS.items(): + value = getattr(self, field_name) + if value == default: + continue + warnings.warn( + f"CameraCfg.{field_name} is deprecated and will be removed in a future release." + f" Set this field on CameraCfg.renderer_cfg instead.", + DeprecationWarning, + stacklevel=2, + ) + if hasattr(self.renderer_cfg, field_name): + setattr(self.renderer_cfg, field_name, value) + # Reset to default so re-runs of ``__post_init__`` (via ``SensorBase.__init__``'s + # ``cfg.copy()``) don't re-forward and clobber a user-set ``renderer_cfg`` field. + setattr(self, field_name, default) diff --git a/source/isaaclab/isaaclab/sensors/camera/camera_data.py b/source/isaaclab/isaaclab/sensors/camera/camera_data.py index 2cbe5006fecd..6ec5484531b2 100644 --- a/source/isaaclab/isaaclab/sensors/camera/camera_data.py +++ b/source/isaaclab/isaaclab/sensors/camera/camera_data.py @@ -3,13 +3,19 @@ # # SPDX-License-Identifier: BSD-3-Clause +from __future__ import annotations + from dataclasses import dataclass from typing import Any import torch +# Re-exported as part of the public isaaclab.sensors.camera API +from isaaclab.renderers.output_contract import RenderBufferKind, RenderBufferSpec from isaaclab.utils.math import convert_camera_frame_orientation_convention +__all__ = ["CameraData", "RenderBufferKind", "RenderBufferSpec"] + @dataclass class CameraData: @@ -56,7 +62,7 @@ class CameraData: .. _Replicator Documentation: https://docs.omniverse.nvidia.com/prod_extensions/prod_extensions/ext_replicator/annotators_details.html#annotator-output """ - info: list[dict[str, Any]] = None + info: dict[str, Any] = None """The retrieved sensor info with sensor types as key. This contains extra information provided by the sensor such as semantic segmentation label mapping, prim paths. @@ -64,6 +70,80 @@ class CameraData: types, the info is empty. """ + @classmethod + def allocate( + cls, + data_types: list[str], + height: int, + width: int, + num_views: int, + device: torch.device | str, + supported_specs: dict[RenderBufferKind, RenderBufferSpec], + ) -> CameraData: + """Build a :class:`CameraData` with output buffers pre-allocated. + + Allocates one ``(num_views, height, width, channels)`` tensor per kind + in the intersection of ``data_types`` and ``supported_specs``, using + the channels and dtype from each :class:`RenderBufferSpec`. + + Args: + data_types: Requested output names (typically :attr:`CameraCfg.data_types`). + Every name must be a member of :class:`RenderBufferKind`. + height: Image height in pixels. + width: Image width in pixels. + num_views: Number of camera views (batch dimension). + device: Torch device on which to allocate the buffers. + supported_specs: Per-buffer layout the active renderer can produce, + keyed by :class:`RenderBufferKind`. Names absent from this mapping + are not allocated. + + Returns: + A new :class:`CameraData` with :attr:`image_shape`, :attr:`output`, + and :attr:`info` populated; all other fields at their defaults. + + Raises: + ValueError: If ``data_types`` contains names that are not members of + :class:`RenderBufferKind`. + """ + requested: set[RenderBufferKind] = set() + unknown: list[str] = [] + for name in data_types: + try: + requested.add(RenderBufferKind(name)) + except ValueError: + unknown.append(name) + if unknown: + raise ValueError(f"Unknown RenderBufferKind name(s): {unknown}. Expected members of RenderBufferKind.") + # rgb is exposed as a view into rgba when the renderer publishes both, + # so requesting either one allocates the shared rgba buffer. + rgb_alias = ( + RenderBufferKind.RGBA in supported_specs + and RenderBufferKind.RGB in supported_specs + and (RenderBufferKind.RGB in requested or RenderBufferKind.RGBA in requested) + ) + if rgb_alias: + requested.update({RenderBufferKind.RGB, RenderBufferKind.RGBA}) + + buffers: dict[str, torch.Tensor] = {} + for name, spec in supported_specs.items(): + if name not in requested: + continue + if rgb_alias and name == RenderBufferKind.RGB: + continue + buffers[str(name)] = torch.zeros( + (num_views, height, width, spec.channels), + dtype=spec.dtype, + device=device, + ).contiguous() + if rgb_alias: + buffers[str(RenderBufferKind.RGB)] = buffers[str(RenderBufferKind.RGBA)][..., :3] + + return cls( + image_shape=(height, width), + output=buffers, + info={name: None for name in buffers}, + ) + ## # Additional Frame orientation conventions ## diff --git a/source/isaaclab/isaaclab/sensors/camera/tiled_camera.py b/source/isaaclab/isaaclab/sensors/camera/tiled_camera.py index e6ae56adaa53..c34cb4088834 100644 --- a/source/isaaclab/isaaclab/sensors/camera/tiled_camera.py +++ b/source/isaaclab/isaaclab/sensors/camera/tiled_camera.py @@ -3,359 +3,38 @@ # # SPDX-License-Identifier: BSD-3-Clause -from __future__ import annotations - -import logging -import math -from collections.abc import Sequence -from typing import TYPE_CHECKING, Any +"""Deprecated module. Use :class:`~isaaclab.sensors.camera.Camera` instead. -import torch -import warp as wp +.. deprecated:: 4.6.0 + :class:`TiledCamera` is deprecated. :class:`~isaaclab.sensors.camera.Camera` now includes + TiledCamera's vectorized rendering optimizations via the same :class:`~isaaclab.renderers.Renderer` + abstraction. Use :class:`~isaaclab.sensors.camera.Camera` with + :class:`~isaaclab.sensors.camera.CameraCfg` (or :class:`~isaaclab.sensors.camera.TiledCameraCfg`) + directly. +""" -from pxr import UsdGeom +from __future__ import annotations -from isaaclab.app.settings_manager import get_settings_manager -from isaaclab.renderers import Renderer -from isaaclab.sim.views import XformPrimView +import warnings -from ..sensor_base import SensorBase from .camera import Camera - -logger = logging.getLogger(__name__) - -if TYPE_CHECKING: - from isaaclab.renderers import Renderer - - from .tiled_camera_cfg import TiledCameraCfg +from .tiled_camera_cfg import TiledCameraCfg class TiledCamera(Camera): - SIMPLE_SHADING_AOV: str = "SimpleShadingSD" - r"""The tiled rendering based camera sensor for acquiring the same data as the Camera class. - - This class inherits from the :class:`Camera` class but uses the tiled-rendering API to acquire - the visual data. Tiled-rendering concatenates the rendered images from multiple cameras into a single image. - This allows for rendering multiple cameras in parallel and is useful for rendering large scenes with multiple - cameras efficiently. - - The following sensor types are supported: - - - ``"rgb"``: A 3-channel rendered color image. - - ``"rgba"``: A 4-channel rendered color image with alpha channel. - - ``"albedo"``: A 4-channel fast diffuse-albedo only path for color image. - Note that this path will achieve the best performance when used alone or with depth only. - - ``"distance_to_camera"``: An image containing the distance to camera optical center. - - ``"distance_to_image_plane"``: An image containing distances of 3D points from camera plane along camera's z-axis. - - ``"depth"``: Alias for ``"distance_to_image_plane"``. - - ``"simple_shading_constant_diffuse"``: Simple shading (constant diffuse) RGB approximation. - - ``"simple_shading_diffuse_mdl"``: Simple shading (diffuse MDL) RGB approximation. - - ``"simple_shading_full_mdl"``: Simple shading (full MDL) RGB approximation. - - ``"normals"``: An image containing the local surface normal vectors at each pixel. - - ``"motion_vectors"``: An image containing the motion vector data at each pixel. - - ``"semantic_segmentation"``: The semantic segmentation data. - - ``"instance_segmentation_fast"``: The instance segmentation data. - - ``"instance_id_segmentation_fast"``: The instance id segmentation data. - - .. note:: - Currently the following sensor types are not supported in a "view" format: - - - ``"instance_segmentation"``: The instance segmentation data. Please use the fast counterparts instead. - - ``"instance_id_segmentation"``: The instance id segmentation data. Please use the fast counterparts instead. - - ``"bounding_box_2d_tight"``: The tight 2D bounding box data (only contains non-occluded regions). - - ``"bounding_box_2d_tight_fast"``: The tight 2D bounding box data (only contains non-occluded regions). - - ``"bounding_box_2d_loose"``: The loose 2D bounding box data (contains occluded regions). - - ``"bounding_box_2d_loose_fast"``: The loose 2D bounding box data (contains occluded regions). - - ``"bounding_box_3d"``: The 3D view space bounding box data. - - ``"bounding_box_3d_fast"``: The 3D view space bounding box data. - - .. _replicator extension: https://docs.omniverse.nvidia.com/extensions/latest/ext_replicator/annotators_details.html#annotator-output - .. _USDGeom Camera: https://graphics.pixar.com/usd/docs/api/class_usd_geom_camera.html - - .. versionadded:: v1.0.0 - - This feature is available starting from Isaac Sim 4.2. Before this version, the tiled rendering APIs - were not available. + """Deprecated alias for :class:`Camera`. + .. deprecated:: 4.6.0 + Use :class:`Camera` directly — it now includes TiledCamera's vectorized rendering + optimizations via the same Renderer abstraction. """ - cfg: TiledCameraCfg - """The configuration parameters.""" - def __init__(self, cfg: TiledCameraCfg): - """Initializes the tiled camera sensor. - - Args: - cfg: The configuration parameters. - - Raises: - RuntimeError: If no camera prim is found at the given path. - ValueError: If the provided data types are not supported by the camera. - """ - self.renderer: Renderer | None = None - self.render_data = None - super().__init__(cfg) - - def __del__(self): - """Unsubscribes from callbacks and detach from the replicator registry.""" - # unsubscribe from callbacks - SensorBase.__del__(self) - # cleanup render resources (renderer may be None if never initialized) - if hasattr(self, "renderer") and self.renderer is not None: - self.renderer.cleanup(getattr(self, "render_data", None)) - - def __str__(self) -> str: - """Returns: A string containing information about the instance.""" - # message for class - return ( - f"Tiled Camera @ '{self.cfg.prim_path}': \n" - f"\tdata types : {list(self.data.output.keys())} \n" - f"\tsemantic filter : {self.cfg.semantic_filter}\n" - f"\tcolorize semantic segm. : {self.cfg.colorize_semantic_segmentation}\n" - f"\tcolorize instance segm. : {self.cfg.colorize_instance_segmentation}\n" - f"\tcolorize instance id segm.: {self.cfg.colorize_instance_id_segmentation}\n" - f"\tupdate period (s): {self.cfg.update_period}\n" - f"\tshape : {self.image_shape}\n" - f"\tnumber of sensors : {self._view.count}" + warnings.warn( + "TiledCamera is deprecated and will be removed in a future release. " + "Use Camera directly — it now includes TiledCamera's vectorized rendering " + "optimizations via the same Renderer abstraction.", + DeprecationWarning, + stacklevel=2, ) - - """ - Operations - """ - - def reset(self, env_ids: Sequence[int] | None = None, env_mask: wp.array | None = None): - if not self._is_initialized: - raise RuntimeError( - "TiledCamera could not be initialized. Please ensure --enable_cameras is used to enable rendering." - ) - # reset the timestamps - SensorBase.reset(self, env_ids, env_mask) - # resolve to indices for torch indexing - if env_ids is None and env_mask is not None: - env_ids = wp.to_torch(env_mask).nonzero(as_tuple=False).squeeze(-1) - elif env_ids is None: - env_ids = slice(None) - # reset the frame count - self._frame[env_ids] = 0 - - """ - Implementation. - """ - - def _initialize_impl(self): - """Initializes the sensor handles and internal buffers. - - This function creates handles and registers the provided data types with the renderer to - be able to access the data from the sensor. It also initializes the internal buffers to store the data. - - Raises: - RuntimeError: If the number of camera prims in the view does not match the number of environments. - RuntimeError: If replicator was not found. - """ - renderer_type = getattr(self.cfg.renderer_cfg, "renderer_type", "default") - needs_kit_cameras = renderer_type in ("default", "isaac_rtx") - if needs_kit_cameras and not get_settings_manager().get("/isaaclab/cameras_enabled"): - raise RuntimeError( - "A camera was spawned without the --enable_cameras flag. Please use --enable_cameras to enable" - " rendering." - ) - - # Initialize parent class - SensorBase._initialize_impl(self) - - self.renderer = Renderer(self.cfg.renderer_cfg) - logger.info("Using renderer: %s", type(self.renderer).__name__) - - # Stage preprocessing needs to happen before creating the view because - # the view keeps references to the prims located in the stage - self.renderer.prepare_stage(self.stage, self._num_envs) - - # Create a view for the sensor - self._view = XformPrimView(self.cfg.prim_path, device=self._device, stage=self.stage) - # Check that sizes are correct - if self._view.count != self._num_envs: - raise RuntimeError( - f"Number of camera prims in the view ({self._view.count}) does not match" - f" the number of environments ({self._num_envs})." - ) - - # Create all env_ids buffer - self._ALL_INDICES = torch.arange(self._view.count, device=self._device, dtype=torch.long) - # Create frame count buffer - self._frame = torch.zeros(self._view.count, device=self._device, dtype=torch.long) - - # Convert all encapsulated prims to Camera - for cam_prim in self._view.prims: - # Get camera prim - cam_prim_path = cam_prim.GetPath().pathString - # Check if prim is a camera - if not cam_prim.IsA(UsdGeom.Camera): - raise RuntimeError(f"Prim at path '{cam_prim_path}' is not a Camera.") - # Add to list - self._sensor_prims.append(UsdGeom.Camera(cam_prim)) - - # View needs to exist before creating render data - self.render_data = self.renderer.create_render_data(self) - - # Create internal buffers - self._create_buffers() - - def _update_poses(self, env_ids: Sequence[int]): - super()._update_poses(env_ids) - self.renderer.update_camera( - self.render_data, self._data.pos_w, self._data.quat_w_world, self._data.intrinsic_matrices - ) - - def _update_buffers_impl(self, env_mask: wp.array): - env_ids = wp.to_torch(env_mask).nonzero(as_tuple=False).squeeze(-1) - if len(env_ids) == 0: - return - # Increment frame count - self._frame[env_ids] += 1 - - # update latest camera pose - if self.cfg.update_latest_camera_pose: - self._update_poses(env_ids) - - self.renderer.update_transforms() - self.renderer.render(self.render_data) - - for output_name, output_data in self._data.output.items(): - if output_name == "rgb": - continue - self.renderer.write_output(self.render_data, output_name, output_data) - - """ - Private Helpers - """ - - def _check_supported_data_types(self, cfg: TiledCameraCfg): - """Checks if the data types are supported by the ray-caster camera.""" - # check if there is any intersection in unsupported types - # reason: these use np structured data types which we can't yet convert to torch tensor - common_elements = set(cfg.data_types) & Camera.UNSUPPORTED_TYPES - if common_elements: - # provide alternative fast counterparts - fast_common_elements = [] - for item in common_elements: - if "instance_segmentation" in item or "instance_id_segmentation" in item: - fast_common_elements.append(item + "_fast") - # raise error - raise ValueError( - f"TiledCamera class does not support the following sensor types: {common_elements}." - "\n\tThis is because these sensor types output numpy structured data types which" - "can't be converted to torch tensors easily." - "\n\tHint: If you need to work with these sensor types, we recommend using their fast counterparts." - f"\n\t\tFast counterparts: {fast_common_elements}" - ) - - def _create_buffers(self): - """Create buffers for storing data.""" - # create the data object - # -- intrinsic matrix - self._data.intrinsic_matrices = torch.zeros((self._view.count, 3, 3), device=self._device) - self._update_intrinsic_matrices(self._ALL_INDICES) - # -- pose of the cameras - self._data.pos_w = torch.zeros((self._view.count, 3), device=self._device) - self._data.quat_w_world = torch.zeros((self._view.count, 4), device=self._device) - self._update_poses(self._ALL_INDICES) - self._data.image_shape = self.image_shape - # -- output data - data_dict = dict() - if "rgba" in self.cfg.data_types or "rgb" in self.cfg.data_types: - data_dict["rgba"] = torch.zeros( - (self._view.count, self.cfg.height, self.cfg.width, 4), device=self.device, dtype=torch.uint8 - ).contiguous() - if "rgb" in self.cfg.data_types: - # RGB is the first 3 channels of RGBA - data_dict["rgb"] = data_dict["rgba"][..., :3] - if "albedo" in self.cfg.data_types: - data_dict["albedo"] = torch.zeros( - (self._view.count, self.cfg.height, self.cfg.width, 4), device=self.device, dtype=torch.uint8 - ).contiguous() - for data_type in self.SIMPLE_SHADING_MODES: - if data_type in self.cfg.data_types: - data_dict[data_type] = torch.zeros( - (self._view.count, self.cfg.height, self.cfg.width, 3), device=self.device, dtype=torch.uint8 - ).contiguous() - if "distance_to_image_plane" in self.cfg.data_types: - data_dict["distance_to_image_plane"] = torch.zeros( - (self._view.count, self.cfg.height, self.cfg.width, 1), device=self.device, dtype=torch.float32 - ).contiguous() - if "depth" in self.cfg.data_types: - data_dict["depth"] = torch.zeros( - (self._view.count, self.cfg.height, self.cfg.width, 1), device=self.device, dtype=torch.float32 - ).contiguous() - if "distance_to_camera" in self.cfg.data_types: - data_dict["distance_to_camera"] = torch.zeros( - (self._view.count, self.cfg.height, self.cfg.width, 1), device=self.device, dtype=torch.float32 - ).contiguous() - if "normals" in self.cfg.data_types: - data_dict["normals"] = torch.zeros( - (self._view.count, self.cfg.height, self.cfg.width, 3), device=self.device, dtype=torch.float32 - ).contiguous() - if "motion_vectors" in self.cfg.data_types: - data_dict["motion_vectors"] = torch.zeros( - (self._view.count, self.cfg.height, self.cfg.width, 2), device=self.device, dtype=torch.float32 - ).contiguous() - if "semantic_segmentation" in self.cfg.data_types: - if self.cfg.colorize_semantic_segmentation: - data_dict["semantic_segmentation"] = torch.zeros( - (self._view.count, self.cfg.height, self.cfg.width, 4), device=self.device, dtype=torch.uint8 - ).contiguous() - else: - data_dict["semantic_segmentation"] = torch.zeros( - (self._view.count, self.cfg.height, self.cfg.width, 1), device=self.device, dtype=torch.int32 - ).contiguous() - if "instance_segmentation_fast" in self.cfg.data_types: - if self.cfg.colorize_instance_segmentation: - data_dict["instance_segmentation_fast"] = torch.zeros( - (self._view.count, self.cfg.height, self.cfg.width, 4), device=self.device, dtype=torch.uint8 - ).contiguous() - else: - data_dict["instance_segmentation_fast"] = torch.zeros( - (self._view.count, self.cfg.height, self.cfg.width, 1), device=self.device, dtype=torch.int32 - ).contiguous() - if "instance_id_segmentation_fast" in self.cfg.data_types: - if self.cfg.colorize_instance_id_segmentation: - data_dict["instance_id_segmentation_fast"] = torch.zeros( - (self._view.count, self.cfg.height, self.cfg.width, 4), device=self.device, dtype=torch.uint8 - ).contiguous() - else: - data_dict["instance_id_segmentation_fast"] = torch.zeros( - (self._view.count, self.cfg.height, self.cfg.width, 1), device=self.device, dtype=torch.int32 - ).contiguous() - - self._data.output = data_dict - self._data.info = dict() - self.renderer.set_outputs(self.render_data, self._data.output) - - def _tiled_image_shape(self) -> tuple[int, int]: - """Returns a tuple containing the dimension of the tiled image.""" - cols, rows = self._tiling_grid_shape() - return (self.cfg.width * cols, self.cfg.height * rows) - - def _tiling_grid_shape(self) -> tuple[int, int]: - """Returns a tuple containing the tiling grid dimension.""" - cols = math.ceil(math.sqrt(self._view.count)) - rows = math.ceil(self._view.count / cols) - return (cols, rows) - - def _create_annotator_data(self): - # we do not need to create annotator data for the tiled camera sensor - raise RuntimeError("This function should not be called for the tiled camera sensor.") - - def _process_annotator_output(self, name: str, output: Any) -> tuple[torch.tensor, dict | None]: - # we do not need to process annotator output for the tiled camera sensor - raise RuntimeError("This function should not be called for the tiled camera sensor.") - - """ - Internal simulation callbacks. - """ - - def _invalidate_initialize_callback(self, event): - """Invalidates the scene elements.""" - # call parent - super()._invalidate_initialize_callback(event) - # set all existing views to None to invalidate them - self._view = None + super().__init__(cfg) diff --git a/source/isaaclab/isaaclab/sensors/camera/tiled_camera_cfg.py b/source/isaaclab/isaaclab/sensors/camera/tiled_camera_cfg.py index c0613406ef3e..d35ff285ff13 100644 --- a/source/isaaclab/isaaclab/sensors/camera/tiled_camera_cfg.py +++ b/source/isaaclab/isaaclab/sensors/camera/tiled_camera_cfg.py @@ -3,6 +3,7 @@ # # SPDX-License-Identifier: BSD-3-Clause +import warnings from typing import TYPE_CHECKING from isaaclab.utils import configclass @@ -15,6 +16,20 @@ @configclass class TiledCameraCfg(CameraCfg): - """Configuration for a tiled rendering-based camera sensor.""" + """Configuration for a tiled rendering-based camera sensor. + + .. deprecated:: 4.6.0 + :class:`TiledCameraCfg` is deprecated. Use :class:`CameraCfg` directly — + :class:`~isaaclab.sensors.camera.Camera` now includes TiledCamera's vectorized + rendering optimizations via the same renderer abstraction. + """ class_type: type["TiledCamera"] | str = "{DIR}.tiled_camera:TiledCamera" + + def __post_init__(self): + warnings.warn( + "TiledCameraCfg is deprecated. Use CameraCfg directly — " + "Camera now includes TiledCamera's vectorized rendering optimizations.", + DeprecationWarning, + stacklevel=2, + ) diff --git a/source/isaaclab/isaaclab/sensors/contact_sensor/base_contact_sensor.py b/source/isaaclab/isaaclab/sensors/contact_sensor/base_contact_sensor.py index b0784b77d4dd..fb2b4a59b168 100644 --- a/source/isaaclab/isaaclab/sensors/contact_sensor/base_contact_sensor.py +++ b/source/isaaclab/isaaclab/sensors/contact_sensor/base_contact_sensor.py @@ -13,6 +13,7 @@ import warp as wp import isaaclab.utils.string as string_utils +from isaaclab.utils.warp import ProxyArray from ..sensor_base import SensorBase from .base_contact_sensor_data import BaseContactSensorData @@ -136,7 +137,7 @@ def find_sensors(self, name_keys: str | Sequence[str], preserve_order: bool = Fa return string_utils.resolve_matching_names(name_keys, self.body_names, preserve_order) @abstractmethod - def compute_first_contact(self, dt: float, abs_tol: float = 1.0e-8) -> wp.array: + def compute_first_contact(self, dt: float, abs_tol: float = 1.0e-8) -> ProxyArray: """Checks if bodies that have established contact within the last :attr:`dt` seconds. This function checks if the bodies have established contact within the last :attr:`dt` seconds @@ -164,7 +165,7 @@ def compute_first_contact(self, dt: float, abs_tol: float = 1.0e-8) -> wp.array: raise NotImplementedError(f"Compute first contact is not implemented for {self.__class__.__name__}.") @abstractmethod - def compute_first_air(self, dt: float, abs_tol: float = 1.0e-8) -> wp.array: + def compute_first_air(self, dt: float, abs_tol: float = 1.0e-8) -> ProxyArray: """Checks if bodies that have broken contact within the last :attr:`dt` seconds. This function checks if the bodies have broken contact within the last :attr:`dt` seconds diff --git a/source/isaaclab/isaaclab/sensors/contact_sensor/base_contact_sensor_data.py b/source/isaaclab/isaaclab/sensors/contact_sensor/base_contact_sensor_data.py index 74acf5092761..2f5f69ef55db 100644 --- a/source/isaaclab/isaaclab/sensors/contact_sensor/base_contact_sensor_data.py +++ b/source/isaaclab/isaaclab/sensors/contact_sensor/base_contact_sensor_data.py @@ -9,7 +9,14 @@ from abc import ABC, abstractmethod -import warp as wp +from isaaclab.utils.leapp import ( + POSE7_ELEMENT_NAMES, + QUAT_XYZW_ELEMENT_NAMES, + XYZ_ELEMENT_NAMES, + InputKindEnum, + leapp_tensor_semantics, +) +from isaaclab.utils.warp import ProxyArray class BaseContactSensorData(ABC): @@ -21,7 +28,8 @@ class BaseContactSensorData(ABC): @property @abstractmethod - def pose_w(self) -> wp.array | None: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSE, element_names=POSE7_ELEMENT_NAMES) + def pose_w(self) -> ProxyArray | None: """Pose of the sensor origin in world frame. None if :attr:`ContactSensorCfg.track_pose` is False. @@ -30,7 +38,8 @@ def pose_w(self) -> wp.array | None: @property @abstractmethod - def pos_w(self) -> wp.array | None: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSITION, element_names=XYZ_ELEMENT_NAMES) + def pos_w(self) -> ProxyArray | None: """Position of the sensor origin in world frame. Shape is (num_instances, num_sensors), dtype = wp.vec3f. In torch this resolves to @@ -42,7 +51,8 @@ def pos_w(self) -> wp.array | None: @property @abstractmethod - def quat_w(self) -> wp.array | None: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ROTATION, element_names=QUAT_XYZW_ELEMENT_NAMES) + def quat_w(self) -> ProxyArray | None: """Orientation of the sensor origin in world frame. Shape is (num_instances, num_sensors), dtype = wp.quatf. In torch this resolves to @@ -54,7 +64,8 @@ def quat_w(self) -> wp.array | None: @property @abstractmethod - def net_forces_w(self) -> wp.array | None: + @leapp_tensor_semantics(kind=InputKindEnum.VECTOR3D, element_names=XYZ_ELEMENT_NAMES) + def net_forces_w(self) -> ProxyArray | None: """The net normal contact forces in world frame. Shape is (num_instances, num_sensors), dtype = wp.vec3f. In torch this resolves to @@ -64,7 +75,8 @@ def net_forces_w(self) -> wp.array | None: @property @abstractmethod - def net_forces_w_history(self) -> wp.array | None: + @leapp_tensor_semantics(kind=InputKindEnum.VECTOR3D, element_names=XYZ_ELEMENT_NAMES) + def net_forces_w_history(self) -> ProxyArray | None: """History of net normal contact forces. Shape is (num_instances, history_length, num_sensors), dtype = wp.vec3f. In torch this resolves to @@ -74,7 +86,8 @@ def net_forces_w_history(self) -> wp.array | None: @property @abstractmethod - def force_matrix_w(self) -> wp.array | None: + @leapp_tensor_semantics(kind=InputKindEnum.VECTOR3D, element_names=XYZ_ELEMENT_NAMES) + def force_matrix_w(self) -> ProxyArray | None: """Normal contact forces filtered between sensor and filtered bodies. Shape is (num_instances, num_sensors, num_filter_shapes), dtype = wp.vec3f. In torch this resolves to @@ -86,7 +99,8 @@ def force_matrix_w(self) -> wp.array | None: @property @abstractmethod - def force_matrix_w_history(self) -> wp.array | None: + @leapp_tensor_semantics(kind=InputKindEnum.VECTOR3D, element_names=XYZ_ELEMENT_NAMES) + def force_matrix_w_history(self) -> ProxyArray | None: """History of filtered contact forces. Shape is (num_instances, history_length, num_sensors, num_filter_shapes), dtype = wp.vec3f. @@ -98,7 +112,8 @@ def force_matrix_w_history(self) -> wp.array | None: @property @abstractmethod - def contact_pos_w(self) -> wp.array | None: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSITION, element_names=XYZ_ELEMENT_NAMES) + def contact_pos_w(self) -> ProxyArray | None: """Average position of contact points. Shape is (num_instances, num_sensors, num_filter_shapes), dtype = wp.vec3f. In torch this resolves to @@ -110,7 +125,8 @@ def contact_pos_w(self) -> wp.array | None: @property @abstractmethod - def friction_forces_w(self) -> wp.array | None: + @leapp_tensor_semantics(kind=InputKindEnum.VECTOR3D, element_names=XYZ_ELEMENT_NAMES) + def friction_forces_w(self) -> ProxyArray | None: """Sum of friction forces. Shape is (num_instances, num_sensors, num_filter_shapes), dtype = wp.vec3f. In torch this resolves to @@ -122,7 +138,8 @@ def friction_forces_w(self) -> wp.array | None: @property @abstractmethod - def last_air_time(self) -> wp.array | None: + @leapp_tensor_semantics() + def last_air_time(self) -> ProxyArray | None: """Time spent in air before last contact. Shape is (num_instances, num_sensors), dtype = wp.float32. @@ -133,7 +150,8 @@ def last_air_time(self) -> wp.array | None: @property @abstractmethod - def current_air_time(self) -> wp.array | None: + @leapp_tensor_semantics() + def current_air_time(self) -> ProxyArray | None: """Time spent in air since last detach. Shape is (num_instances, num_sensors), dtype = wp.float32. @@ -144,7 +162,8 @@ def current_air_time(self) -> wp.array | None: @property @abstractmethod - def last_contact_time(self) -> wp.array | None: + @leapp_tensor_semantics() + def last_contact_time(self) -> ProxyArray | None: """Time spent in contact before last detach. Shape is (num_instances, num_sensors), dtype = wp.float32. @@ -155,7 +174,8 @@ def last_contact_time(self) -> wp.array | None: @property @abstractmethod - def current_contact_time(self) -> wp.array | None: + @leapp_tensor_semantics() + def current_contact_time(self) -> ProxyArray | None: """Time spent in contact since last contact. Shape is (num_instances, num_sensors), dtype = wp.float32. diff --git a/source/isaaclab/isaaclab/sensors/frame_transformer/base_frame_transformer_data.py b/source/isaaclab/isaaclab/sensors/frame_transformer/base_frame_transformer_data.py index 3b28a7b17d00..286af6e84ea3 100644 --- a/source/isaaclab/isaaclab/sensors/frame_transformer/base_frame_transformer_data.py +++ b/source/isaaclab/isaaclab/sensors/frame_transformer/base_frame_transformer_data.py @@ -9,7 +9,17 @@ from abc import ABC, abstractmethod -import warp as wp +from isaaclab.utils.leapp import ( + POSE7_ELEMENT_NAMES, + QUAT_XYZW_ELEMENT_NAMES, + XYZ_ELEMENT_NAMES, + InputKindEnum, + leapp_tensor_semantics, + target_frame_pose_resolver, + target_frame_quat_resolver, + target_frame_xyz_resolver, +) +from isaaclab.utils.warp import ProxyArray class BaseFrameTransformerData(ABC): @@ -30,7 +40,8 @@ def target_frame_names(self) -> list[str]: @property @abstractmethod - def target_pose_source(self) -> wp.array | None: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSE, element_names_resolver=target_frame_pose_resolver) + def target_pose_source(self) -> ProxyArray | None: """Pose of the target frame(s) relative to source frame. Shape is (num_instances, num_target_frames), dtype = wp.transformf. In torch this resolves to @@ -40,7 +51,8 @@ def target_pose_source(self) -> wp.array | None: @property @abstractmethod - def target_pos_source(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSITION, element_names_resolver=target_frame_xyz_resolver) + def target_pos_source(self) -> ProxyArray: """Position of the target frame(s) relative to source frame. Shape is (num_instances, num_target_frames), dtype = wp.vec3f. In torch this resolves to @@ -50,7 +62,8 @@ def target_pos_source(self) -> wp.array: @property @abstractmethod - def target_quat_source(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ROTATION, element_names_resolver=target_frame_quat_resolver) + def target_quat_source(self) -> ProxyArray: """Orientation of the target frame(s) relative to source frame. Shape is (num_instances, num_target_frames), dtype = wp.quatf. In torch this resolves to @@ -60,7 +73,8 @@ def target_quat_source(self) -> wp.array: @property @abstractmethod - def target_pose_w(self) -> wp.array | None: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSE, element_names_resolver=target_frame_pose_resolver) + def target_pose_w(self) -> ProxyArray | None: """Pose of the target frame(s) after offset in world frame. Shape is (num_instances, num_target_frames), dtype = wp.transformf. In torch this resolves to @@ -70,7 +84,8 @@ def target_pose_w(self) -> wp.array | None: @property @abstractmethod - def target_pos_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSITION, element_names_resolver=target_frame_xyz_resolver) + def target_pos_w(self) -> ProxyArray: """Position of the target frame(s) after offset in world frame. Shape is (num_instances, num_target_frames), dtype = wp.vec3f. In torch this resolves to @@ -80,7 +95,8 @@ def target_pos_w(self) -> wp.array: @property @abstractmethod - def target_quat_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ROTATION, element_names_resolver=target_frame_quat_resolver) + def target_quat_w(self) -> ProxyArray: """Orientation of the target frame(s) after offset in world frame. Shape is (num_instances, num_target_frames), dtype = wp.quatf. In torch this resolves to @@ -90,7 +106,8 @@ def target_quat_w(self) -> wp.array: @property @abstractmethod - def source_pose_w(self) -> wp.array | None: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSE, element_names=POSE7_ELEMENT_NAMES) + def source_pose_w(self) -> ProxyArray | None: """Pose of the source frame after offset in world frame. Shape is (num_instances,), dtype = wp.transformf. In torch this resolves to (num_instances, 7). @@ -100,7 +117,8 @@ def source_pose_w(self) -> wp.array | None: @property @abstractmethod - def source_pos_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSITION, element_names=XYZ_ELEMENT_NAMES) + def source_pos_w(self) -> ProxyArray: """Position of the source frame after offset in world frame. Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). @@ -109,7 +127,8 @@ def source_pos_w(self) -> wp.array: @property @abstractmethod - def source_quat_w(self) -> wp.array: + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ROTATION, element_names=QUAT_XYZW_ELEMENT_NAMES) + def source_quat_w(self) -> ProxyArray: """Orientation of the source frame after offset in world frame. Shape is (num_instances,), dtype = wp.quatf. In torch this resolves to (num_instances, 4). diff --git a/source/isaaclab/isaaclab/sensors/frame_transformer/frame_transformer.py b/source/isaaclab/isaaclab/sensors/frame_transformer/frame_transformer.py index f01ce2e3f640..c44f991ff218 100644 --- a/source/isaaclab/isaaclab/sensors/frame_transformer/frame_transformer.py +++ b/source/isaaclab/isaaclab/sensors/frame_transformer/frame_transformer.py @@ -13,6 +13,7 @@ from .base_frame_transformer_data import BaseFrameTransformerData if TYPE_CHECKING: + from isaaclab_newton.sensors.frame_transformer import FrameTransformer as NewtonFrameTransformer from isaaclab_physx.sensors.frame_transformer import FrameTransformer as PhysXFrameTransformer from isaaclab_physx.sensors.frame_transformer import FrameTransformerData as PhysXFrameTransformerData @@ -22,6 +23,6 @@ class FrameTransformer(FactoryBase, BaseFrameTransformer): data: BaseFrameTransformerData | PhysXFrameTransformerData - def __new__(cls, *args, **kwargs) -> BaseFrameTransformer | PhysXFrameTransformer: + def __new__(cls, *args, **kwargs) -> BaseFrameTransformer | NewtonFrameTransformer | PhysXFrameTransformer: """Create a new instance of a frame transformer based on the backend.""" return super().__new__(cls, *args, **kwargs) diff --git a/source/isaaclab/isaaclab/sensors/frame_transformer/frame_transformer_data.py b/source/isaaclab/isaaclab/sensors/frame_transformer/frame_transformer_data.py index 8f202e15f40e..f6b28faea395 100644 --- a/source/isaaclab/isaaclab/sensors/frame_transformer/frame_transformer_data.py +++ b/source/isaaclab/isaaclab/sensors/frame_transformer/frame_transformer_data.py @@ -14,12 +14,17 @@ from .base_frame_transformer_data import BaseFrameTransformerData if TYPE_CHECKING: + from isaaclab_newton.sensors.frame_transformer.frame_transformer_data import ( + FrameTransformerData as NewtonFrameTransformerData, + ) from isaaclab_physx.sensors.frame_transformer import FrameTransformerData as PhysXFrameTransformerData class FrameTransformerData(FactoryBase, BaseFrameTransformerData): """Factory for creating frame transformer data instances.""" - def __new__(cls, *args, **kwargs) -> BaseFrameTransformerData | PhysXFrameTransformerData: + def __new__( + cls, *args, **kwargs + ) -> BaseFrameTransformerData | NewtonFrameTransformerData | PhysXFrameTransformerData: """Create a new instance of a frame transformer data based on the backend.""" return super().__new__(cls, *args, **kwargs) diff --git a/source/isaaclab/isaaclab/sensors/imu/base_imu.py b/source/isaaclab/isaaclab/sensors/imu/base_imu.py index 8e8945a0fbf1..2bf99b9a5e16 100644 --- a/source/isaaclab/isaaclab/sensors/imu/base_imu.py +++ b/source/isaaclab/isaaclab/sensors/imu/base_imu.py @@ -18,32 +18,22 @@ class BaseImu(SensorBase): - """The Inertia Measurement Unit (IMU) sensor. + """The Inertial Measurement Unit (IMU) sensor. - The sensor can be attached to any prim path with a rigid ancestor in its tree and produces body-frame - linear acceleration and angular velocity, along with world-frame pose and body-frame linear and angular - accelerations/velocities. + This sensor models a real IMU that measures angular velocity (gyroscope) and + proper linear acceleration (accelerometer) in the sensor's body frame. Unlike the + PVA sensor, it does not provide pose, linear velocity, angular acceleration, + or projected gravity. - If the provided path is not a rigid body, the closest rigid-body ancestor is used for simulation queries. - The fixed transform from that ancestor to the target prim is computed once during initialization and - composed with the configured sensor offset. + The sensor can be attached to any prim path with a rigid ancestor in its tree. + If the provided path is not a rigid body, the closest rigid-body ancestor is used + for simulation queries. The fixed transform from that ancestor to the target prim + is computed once during initialization and composed with the configured sensor offset. .. note:: - We are computing the accelerations using numerical differentiation from the velocities. Consequently, the - IMU sensor accuracy depends on the chosen phsyx timestep. For a sufficient accuracy, we recommend to keep the - timestep at least as 200Hz. - - .. note:: - - The user can configure the sensor offset in the configuration file. The offset is applied relative to the - rigid source prim. If the target prim is not a rigid body, the offset is composed with the fixed transform - from the rigid ancestor to the target prim. The offset is applied in the body frame of the rigid source prim. - The offset is defined as a position vector and a quaternion rotation, which - are applied in the order: position, then rotation. The position is applied as a translation - in the body frame of the rigid source prim, and the rotation is applied as a rotation - in the body frame of the rigid source prim. - + The accuracy of the acceleration readings depends on the physics backend and timestep. + For sufficient accuracy, we recommend keeping the timestep at least 200 Hz. """ cfg: ImuCfg @@ -53,12 +43,11 @@ class BaseImu(SensorBase): """The name of the backend for the IMU sensor.""" def __init__(self, cfg: ImuCfg): - """Initializes the Imu sensor. + """Initializes the IMU sensor. Args: cfg: The configuration parameters. """ - # initialize base class super().__init__(cfg) """ diff --git a/source/isaaclab/isaaclab/sensors/imu/base_imu_data.py b/source/isaaclab/isaaclab/sensors/imu/base_imu_data.py index a64eee79192f..039d5dd60f64 100644 --- a/source/isaaclab/isaaclab/sensors/imu/base_imu_data.py +++ b/source/isaaclab/isaaclab/sensors/imu/base_imu_data.py @@ -9,67 +9,29 @@ from abc import ABC, abstractmethod -import warp as wp +from isaaclab.utils.leapp import ( + XYZ_ELEMENT_NAMES, + InputKindEnum, + leapp_tensor_semantics, +) +from isaaclab.utils.warp import ProxyArray class BaseImuData(ABC): - """Data container for the Imu sensor. + """Data container for the IMU sensor. This base class defines the interface for IMU sensor data. Backend-specific implementations should inherit from this class and provide the actual data storage. - """ - - @property - @abstractmethod - def pose_w(self) -> wp.array | None: - """Pose of the sensor origin in world frame. - - Shape is (num_instances,), dtype = wp.transformf. In torch this resolves to (num_instances, 7). - The pose is provided in (x, y, z, qx, qy, qz, qw) format. - """ - raise NotImplementedError - - @property - @abstractmethod - def pos_w(self) -> wp.array: - """Position of the sensor origin in world frame. - - Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). - """ - raise NotImplementedError - - @property - @abstractmethod - def quat_w(self) -> wp.array: - """Orientation of the sensor origin in world frame. - - Shape is (num_instances,), dtype = wp.quatf. In torch this resolves to (num_instances, 4). - The orientation is provided in (x, y, z, w) format. - """ - raise NotImplementedError - @property - @abstractmethod - def projected_gravity_b(self) -> wp.array: - """Gravity direction unit vector projected on the IMU frame. - - Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). - """ - raise NotImplementedError - - @property - @abstractmethod - def lin_vel_b(self) -> wp.array: - """IMU frame linear velocity relative to the world expressed in IMU frame. - - Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). - """ - raise NotImplementedError + Unlike the PVA sensor, the IMU only provides the two physical quantities that a + real inertial measurement unit measures: angular velocity and linear acceleration. + """ @property @abstractmethod - def ang_vel_b(self) -> wp.array: - """IMU frame angular velocity relative to the world expressed in IMU frame. + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ANGULAR_VELOCITY, element_names=XYZ_ELEMENT_NAMES) + def ang_vel_b(self) -> ProxyArray: + """IMU frame angular velocity relative to the world expressed in IMU frame [rad/s]. Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). """ @@ -77,17 +39,11 @@ def ang_vel_b(self) -> wp.array: @property @abstractmethod - def lin_acc_b(self) -> wp.array: - """IMU frame linear acceleration relative to the world expressed in IMU frame. - - Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). - """ - raise NotImplementedError + @leapp_tensor_semantics(kind=InputKindEnum.BODY_LINEAR_ACCELERATION, element_names=XYZ_ELEMENT_NAMES) + def lin_acc_b(self) -> ProxyArray: + """Linear acceleration (proper) in the IMU frame [m/s^2]. - @property - @abstractmethod - def ang_acc_b(self) -> wp.array: - """IMU frame angular acceleration relative to the world expressed in IMU frame. + Zero in freefall, +g upward at rest. Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). """ diff --git a/source/isaaclab/isaaclab/sensors/imu/imu.py b/source/isaaclab/isaaclab/sensors/imu/imu.py index 5fdc1c814532..4951867fb0b0 100644 --- a/source/isaaclab/isaaclab/sensors/imu/imu.py +++ b/source/isaaclab/isaaclab/sensors/imu/imu.py @@ -13,6 +13,8 @@ from .base_imu_data import BaseImuData if TYPE_CHECKING: + from isaaclab_newton.sensors.imu import Imu as NewtonImu + from isaaclab_newton.sensors.imu import ImuData as NewtonImuData from isaaclab_physx.sensors.imu import Imu as PhysXImu from isaaclab_physx.sensors.imu import ImuData as PhysXImuData @@ -20,8 +22,8 @@ class Imu(FactoryBase, BaseImu): """Factory for creating IMU sensor instances.""" - data: BaseImuData | PhysXImuData + data: BaseImuData | PhysXImuData | NewtonImuData - def __new__(cls, *args, **kwargs) -> BaseImu | PhysXImu: + def __new__(cls, *args, **kwargs) -> BaseImu | PhysXImu | NewtonImu: """Create a new instance of an IMU sensor based on the backend.""" return super().__new__(cls, *args, **kwargs) diff --git a/source/isaaclab/isaaclab/sensors/imu/imu_cfg.py b/source/isaaclab/isaaclab/sensors/imu/imu_cfg.py index 3b3b6fb9f83e..a095c7f27642 100644 --- a/source/isaaclab/isaaclab/sensors/imu/imu_cfg.py +++ b/source/isaaclab/isaaclab/sensors/imu/imu_cfg.py @@ -7,8 +7,6 @@ from typing import TYPE_CHECKING -from isaaclab.markers import VisualizationMarkersCfg -from isaaclab.markers.config import RED_ARROW_X_MARKER_CFG from isaaclab.utils import configclass from ..sensor_base_cfg import SensorBaseCfg @@ -19,7 +17,13 @@ @configclass class ImuCfg(SensorBaseCfg): - """Configuration for an Inertial Measurement Unit (IMU) sensor.""" + """Configuration for an Inertial Measurement Unit (IMU) sensor. + + This configures a sensor that provides the two physical quantities measured by a + real IMU: angular velocity (gyroscope) and linear acceleration (accelerometer). + For a richer sensor that also provides pose, velocity, and angular acceleration, + see :class:`~isaaclab.sensors.PvaCfg`. + """ class_type: type[Imu] | str = "{DIR}.imu:Imu" @@ -28,23 +32,10 @@ class OffsetCfg: """The offset pose of the sensor's frame from the sensor's parent frame.""" pos: tuple[float, float, float] = (0.0, 0.0, 0.0) - """Translation w.r.t. the parent frame. Defaults to (0.0, 0.0, 0.0).""" + """Translation w.r.t. the parent frame [m]. Defaults to (0.0, 0.0, 0.0).""" rot: tuple[float, float, float, float] = (0.0, 0.0, 0.0, 1.0) """Quaternion rotation (x, y, z, w) w.r.t. the parent frame. Defaults to (0.0, 0.0, 0.0, 1.0).""" offset: OffsetCfg = OffsetCfg() """The offset pose of the sensor's frame from the sensor's parent frame. Defaults to identity.""" - - visualizer_cfg: VisualizationMarkersCfg = RED_ARROW_X_MARKER_CFG.replace(prim_path="/Visuals/Command/velocity_goal") - """The configuration object for the visualization markers. Defaults to RED_ARROW_X_MARKER_CFG. - - This attribute is only used when debug visualization is enabled. - """ - gravity_bias: tuple[float, float, float] = (0.0, 0.0, 9.81) - """The linear acceleration bias applied to the linear acceleration in the world frame (x,y,z). - - Imu sensors typically output a positive gravity acceleration in opposition to the direction of gravity. This - config parameter allows users to subtract that bias if set to (0.,0.,0.). By default this is set to (0.0,0.0,9.81) - which results in a positive acceleration reading in the world Z. - """ diff --git a/source/isaaclab/isaaclab/sensors/imu/imu_data.py b/source/isaaclab/isaaclab/sensors/imu/imu_data.py index 6f6ed268ad52..f23f2a3be6ca 100644 --- a/source/isaaclab/isaaclab/sensors/imu/imu_data.py +++ b/source/isaaclab/isaaclab/sensors/imu/imu_data.py @@ -3,7 +3,7 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""Re-exports the base IMU data class for backwards compatibility.""" +"""Factory class for IMU data.""" from __future__ import annotations @@ -14,12 +14,13 @@ from .base_imu_data import BaseImuData if TYPE_CHECKING: + from isaaclab_newton.sensors.imu import ImuData as NewtonImuData from isaaclab_physx.sensors.imu import ImuData as PhysXImuData class ImuData(FactoryBase, BaseImuData): """Factory for creating IMU data instances.""" - def __new__(cls, *args, **kwargs) -> BaseImuData | PhysXImuData: - """Create a new instance of an IMU data based on the backend.""" + def __new__(cls, *args, **kwargs) -> BaseImuData | PhysXImuData | NewtonImuData: + """Create a new instance of IMU data based on the backend.""" return super().__new__(cls, *args, **kwargs) diff --git a/source/isaaclab/isaaclab/sensors/joint_wrench/__init__.py b/source/isaaclab/isaaclab/sensors/joint_wrench/__init__.py new file mode 100644 index 000000000000..aae021e8e98d --- /dev/null +++ b/source/isaaclab/isaaclab/sensors/joint_wrench/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Joint Wrench Sensor.""" + +from isaaclab.utils.module import lazy_export + +lazy_export() diff --git a/source/isaaclab/isaaclab/sensors/joint_wrench/__init__.pyi b/source/isaaclab/isaaclab/sensors/joint_wrench/__init__.pyi new file mode 100644 index 000000000000..97980db01c57 --- /dev/null +++ b/source/isaaclab/isaaclab/sensors/joint_wrench/__init__.pyi @@ -0,0 +1,18 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +__all__ = [ + "BaseJointWrenchSensor", + "BaseJointWrenchSensorData", + "JointWrenchSensor", + "JointWrenchSensorCfg", + "JointWrenchSensorData", +] + +from .base_joint_wrench_sensor import BaseJointWrenchSensor +from .base_joint_wrench_sensor_data import BaseJointWrenchSensorData +from .joint_wrench_sensor import JointWrenchSensor +from .joint_wrench_sensor_cfg import JointWrenchSensorCfg +from .joint_wrench_sensor_data import JointWrenchSensorData diff --git a/source/isaaclab/isaaclab/sensors/joint_wrench/base_joint_wrench_sensor.py b/source/isaaclab/isaaclab/sensors/joint_wrench/base_joint_wrench_sensor.py new file mode 100644 index 000000000000..5ed4e0382bbe --- /dev/null +++ b/source/isaaclab/isaaclab/sensors/joint_wrench/base_joint_wrench_sensor.py @@ -0,0 +1,101 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from __future__ import annotations + +from abc import abstractmethod +from collections.abc import Sequence +from typing import TYPE_CHECKING + +import warp as wp + +import isaaclab.utils.string as string_utils + +from ..sensor_base import SensorBase +from .base_joint_wrench_sensor_data import BaseJointWrenchSensorData + +if TYPE_CHECKING: + from .joint_wrench_sensor_cfg import JointWrenchSensorCfg + + +class BaseJointWrenchSensor(SensorBase): + """The joint reaction wrench sensor. + + Reports incoming joint wrenches for the bodies selected by the backend as + split force [N] / torque [N·m] pairs expressed in the + ``INCOMING_JOINT_FRAME`` convention (child-side joint frame, child-side + joint anchor reference point). Backends convert from their native + representation to this convention internally. Use :attr:`body_names` or + :meth:`find_bodies` to map entries to articulation bodies. + """ + + cfg: JointWrenchSensorCfg + """The configuration parameters.""" + + __backend_name__: str = "base" + """The name of the backend for the joint wrench sensor.""" + + def __init__(self, cfg: JointWrenchSensorCfg): + """Initialize the joint wrench sensor. + + Args: + cfg: The configuration parameters. + """ + super().__init__(cfg) + + """ + Properties + """ + + @property + @abstractmethod + def data(self) -> BaseJointWrenchSensorData: + """The sensor data container, populated after simulation initialization.""" + raise NotImplementedError + + @property + @abstractmethod + def body_names(self) -> list[str]: + """Ordered names of the bodies whose incoming joint wrench is reported.""" + raise NotImplementedError + + @property + def num_bodies(self) -> int: + """Number of bodies whose incoming joint wrench is reported.""" + return len(self.body_names) + + """ + Operations + """ + + def find_bodies(self, name_keys: str | Sequence[str], preserve_order: bool = False) -> tuple[list[int], list[str]]: + """Find reported bodies based on name keys. + + Args: + name_keys: A regular expression or list of regular expressions to match the body names. + preserve_order: Whether to preserve the order of the name keys in the output. Defaults to False. + + Returns: + The matching body indices and names. + """ + return string_utils.resolve_matching_names(name_keys, self.body_names, preserve_order) + + """ + Implementation - Abstract methods to be implemented by backend-specific subclasses. + """ + + @abstractmethod + def _initialize_impl(self) -> None: + """Initialize the sensor handles and internal buffers. + + Subclasses should call ``super()._initialize_impl()`` first to + initialize the common sensor infrastructure from + :class:`~isaaclab.sensors.SensorBase`. + """ + super()._initialize_impl() + + @abstractmethod + def _update_buffers_impl(self, env_mask: wp.array) -> None: + raise NotImplementedError diff --git a/source/isaaclab/isaaclab/sensors/joint_wrench/base_joint_wrench_sensor_data.py b/source/isaaclab/isaaclab/sensors/joint_wrench/base_joint_wrench_sensor_data.py new file mode 100644 index 000000000000..282021a36784 --- /dev/null +++ b/source/isaaclab/isaaclab/sensors/joint_wrench/base_joint_wrench_sensor_data.py @@ -0,0 +1,42 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Base class for joint-wrench sensor data containers.""" + +from __future__ import annotations + +from abc import ABC, abstractmethod + +from isaaclab.utils.warp import ProxyArray + + +class BaseJointWrenchSensorData(ABC): + """Data container for the joint reaction wrench sensor.""" + + @property + @abstractmethod + def force(self) -> ProxyArray | None: + """Linear component of the joint reaction wrench [N]. + + Expressed in the frame selected by + :attr:`~isaaclab.sensors.JointWrenchSensorCfg.convention`. Shape is + ``(num_envs, num_bodies)``, dtype ``wp.vec3f``. In torch this resolves + to ``(num_envs, num_bodies, 3)``. ``None`` before the simulation is + initialized. + """ + raise NotImplementedError + + @property + @abstractmethod + def torque(self) -> ProxyArray | None: + """Angular component of the joint reaction wrench [N·m]. + + Expressed in the frame selected by + :attr:`~isaaclab.sensors.JointWrenchSensorCfg.convention`. Shape is + ``(num_envs, num_bodies)``, dtype ``wp.vec3f``. In torch this resolves + to ``(num_envs, num_bodies, 3)``. ``None`` before the simulation is + initialized. + """ + raise NotImplementedError diff --git a/source/isaaclab/isaaclab/sensors/joint_wrench/joint_wrench_sensor.py b/source/isaaclab/isaaclab/sensors/joint_wrench/joint_wrench_sensor.py new file mode 100644 index 000000000000..40103b20e9f1 --- /dev/null +++ b/source/isaaclab/isaaclab/sensors/joint_wrench/joint_wrench_sensor.py @@ -0,0 +1,29 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from isaaclab.utils.backend_utils import FactoryBase + +from .base_joint_wrench_sensor import BaseJointWrenchSensor +from .base_joint_wrench_sensor_data import BaseJointWrenchSensorData + +if TYPE_CHECKING: + from isaaclab_newton.sensors.joint_wrench import JointWrenchSensor as NewtonJointWrenchSensor + from isaaclab_newton.sensors.joint_wrench import JointWrenchSensorData as NewtonJointWrenchSensorData + from isaaclab_physx.sensors.joint_wrench import JointWrenchSensor as PhysXJointWrenchSensor + from isaaclab_physx.sensors.joint_wrench import JointWrenchSensorData as PhysXJointWrenchSensorData + + +class JointWrenchSensor(FactoryBase, BaseJointWrenchSensor): + """Factory for creating joint-wrench sensor instances.""" + + data: BaseJointWrenchSensorData | PhysXJointWrenchSensorData | NewtonJointWrenchSensorData + + def __new__(cls, *args, **kwargs) -> BaseJointWrenchSensor | PhysXJointWrenchSensor | NewtonJointWrenchSensor: + """Create a new instance of a joint-wrench sensor based on the backend.""" + return super().__new__(cls, *args, **kwargs) diff --git a/source/isaaclab/isaaclab/sensors/joint_wrench/joint_wrench_sensor_cfg.py b/source/isaaclab/isaaclab/sensors/joint_wrench/joint_wrench_sensor_cfg.py new file mode 100644 index 000000000000..4bdb0ab74f06 --- /dev/null +++ b/source/isaaclab/isaaclab/sensors/joint_wrench/joint_wrench_sensor_cfg.py @@ -0,0 +1,30 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from __future__ import annotations + +from typing import TYPE_CHECKING, Literal + +from isaaclab.utils import configclass + +from ..sensor_base_cfg import SensorBaseCfg + +if TYPE_CHECKING: + from .joint_wrench_sensor import JointWrenchSensor + + +@configclass +class JointWrenchSensorCfg(SensorBaseCfg): + """Configuration for a joint reaction wrench sensor.""" + + class_type: type[JointWrenchSensor] | str = "{DIR}.joint_wrench_sensor:JointWrenchSensor" + + convention: Literal["incoming_joint_frame"] = "incoming_joint_frame" + """Coordinate convention for the reported wrench. Defaults to ``"incoming_joint_frame"``. + + - ``"incoming_joint_frame"`` — child-side joint frame, child-side joint anchor as reference point. + Matches what a real 6-axis F/T sensor mounted at the joint would measure. Backends convert + their native solver outputs to this convention. + """ diff --git a/source/isaaclab/isaaclab/sensors/joint_wrench/joint_wrench_sensor_data.py b/source/isaaclab/isaaclab/sensors/joint_wrench/joint_wrench_sensor_data.py new file mode 100644 index 000000000000..5872640d143c --- /dev/null +++ b/source/isaaclab/isaaclab/sensors/joint_wrench/joint_wrench_sensor_data.py @@ -0,0 +1,28 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Factory class for joint-wrench sensor data.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from isaaclab.utils.backend_utils import FactoryBase + +from .base_joint_wrench_sensor_data import BaseJointWrenchSensorData + +if TYPE_CHECKING: + from isaaclab_newton.sensors.joint_wrench import JointWrenchSensorData as NewtonJointWrenchSensorData + from isaaclab_physx.sensors.joint_wrench import JointWrenchSensorData as PhysXJointWrenchSensorData + + +class JointWrenchSensorData(FactoryBase, BaseJointWrenchSensorData): + """Factory for creating joint-wrench sensor data instances.""" + + def __new__( + cls, *args, **kwargs + ) -> BaseJointWrenchSensorData | PhysXJointWrenchSensorData | NewtonJointWrenchSensorData: + """Create a new instance of joint-wrench sensor data based on the backend.""" + return super().__new__(cls, *args, **kwargs) diff --git a/source/isaaclab/isaaclab/sensors/pva/__init__.py b/source/isaaclab/isaaclab/sensors/pva/__init__.py new file mode 100644 index 000000000000..281802f26a76 --- /dev/null +++ b/source/isaaclab/isaaclab/sensors/pva/__init__.py @@ -0,0 +1,12 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +""" +PVA Sensor +""" + +from isaaclab.utils.module import lazy_export + +lazy_export() diff --git a/source/isaaclab/isaaclab/sensors/pva/__init__.pyi b/source/isaaclab/isaaclab/sensors/pva/__init__.pyi new file mode 100644 index 000000000000..7a8e519a6f7e --- /dev/null +++ b/source/isaaclab/isaaclab/sensors/pva/__init__.pyi @@ -0,0 +1,18 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +__all__ = [ + "BasePva", + "BasePvaData", + "Pva", + "PvaCfg", + "PvaData", +] + +from .base_pva import BasePva +from .base_pva_data import BasePvaData +from .pva import Pva +from .pva_cfg import PvaCfg +from .pva_data import PvaData diff --git a/source/isaaclab/isaaclab/sensors/pva/base_pva.py b/source/isaaclab/isaaclab/sensors/pva/base_pva.py new file mode 100644 index 000000000000..1c14ee454c65 --- /dev/null +++ b/source/isaaclab/isaaclab/sensors/pva/base_pva.py @@ -0,0 +1,88 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from __future__ import annotations + +from abc import abstractmethod +from typing import TYPE_CHECKING + +import warp as wp + +from ..sensor_base import SensorBase +from .base_pva_data import BasePvaData + +if TYPE_CHECKING: + from .pva_cfg import PvaCfg + + +class BasePva(SensorBase): + """The Pose Velocity Acceleration (PVA) sensor. + + The sensor can be attached to any prim path with a rigid ancestor in its tree and produces world-frame + pose, body-frame velocities, body-frame coordinate accelerations, and projected gravity. This differs + from the :class:`~isaaclab.sensors.imu.BaseImu` sensor, which reports proper acceleration. + + If the provided path is not a rigid body, the closest rigid-body ancestor is used for simulation queries. + The fixed transform from that ancestor to the target prim is computed once during initialization and + composed with the configured sensor offset. + + .. note:: + + Depending on the backend, accelerations may be computed via numerical differentiation of velocities + or read directly from the solver. For numerical backends, accuracy depends on the physics timestep; + we recommend at least 200 Hz. + + .. note:: + + The user can configure the sensor offset in the configuration file. The offset is applied relative to the + rigid source prim. If the target prim is not a rigid body, the offset is composed with the fixed transform + from the rigid ancestor to the target prim. The offset is applied in the body frame of the rigid source prim. + The offset is defined as a position vector and a quaternion rotation, which + are applied in the order: position, then rotation. The position is applied as a translation + in the body frame of the rigid source prim, and the rotation is applied as a rotation + in the body frame of the rigid source prim. + + """ + + cfg: PvaCfg + """The configuration parameters.""" + + __backend_name__: str = "base" + """The name of the backend for the PVA sensor.""" + + def __init__(self, cfg: PvaCfg): + """Initializes the PVA sensor. + + Args: + cfg: The configuration parameters. + """ + # initialize base class + super().__init__(cfg) + + """ + Properties + """ + + @property + @abstractmethod + def data(self) -> BasePvaData: + raise NotImplementedError + + """ + Implementation - Abstract methods to be implemented by backend-specific subclasses. + """ + + @abstractmethod + def _initialize_impl(self): + """Initializes the sensor handles and internal buffers. + + Subclasses should call ``super()._initialize_impl()`` first to initialize + the common sensor infrastructure from :class:`SensorBase`. + """ + super()._initialize_impl() + + @abstractmethod + def _update_buffers_impl(self, env_mask: wp.array): + raise NotImplementedError diff --git a/source/isaaclab/isaaclab/sensors/pva/base_pva_data.py b/source/isaaclab/isaaclab/sensors/pva/base_pva_data.py new file mode 100644 index 000000000000..07fcab62b0b6 --- /dev/null +++ b/source/isaaclab/isaaclab/sensors/pva/base_pva_data.py @@ -0,0 +1,111 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Base class for PVA sensor data containers.""" + +from __future__ import annotations + +from abc import ABC, abstractmethod + +from isaaclab.utils.leapp import ( + POSE7_ELEMENT_NAMES, + QUAT_XYZW_ELEMENT_NAMES, + XYZ_ELEMENT_NAMES, + InputKindEnum, + leapp_tensor_semantics, +) +from isaaclab.utils.warp import ProxyArray + + +class BasePvaData(ABC): + """Data container for the PVA sensor. + + This base class defines the interface for PVA sensor data. Backend-specific + implementations should inherit from this class and provide the actual data storage. + """ + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSE, element_names=POSE7_ELEMENT_NAMES) + def pose_w(self) -> ProxyArray | None: + """Pose of the sensor origin in world frame [m, unitless]. + + Shape is (num_instances,), dtype = wp.transformf. In torch this resolves to (num_instances, 7). + The pose is provided in (x, y, z, qx, qy, qz, qw) format. + """ + raise NotImplementedError + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_POSITION, element_names=XYZ_ELEMENT_NAMES) + def pos_w(self) -> ProxyArray: + """Position of the sensor origin in world frame [m]. + + Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). + """ + raise NotImplementedError + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ROTATION, element_names=QUAT_XYZW_ELEMENT_NAMES) + def quat_w(self) -> ProxyArray: + """Orientation of the sensor origin in world frame. + + Shape is (num_instances,), dtype = wp.quatf. In torch this resolves to (num_instances, 4). + The orientation is provided in (x, y, z, w) format. + """ + raise NotImplementedError + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.VECTOR3D, element_names=XYZ_ELEMENT_NAMES) + def projected_gravity_b(self) -> ProxyArray: + """Gravity direction unit vector projected on the PVA frame. + + Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). + """ + raise NotImplementedError + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_LINEAR_VELOCITY, element_names=XYZ_ELEMENT_NAMES) + def lin_vel_b(self) -> ProxyArray: + """PVA frame linear velocity relative to the world expressed in PVA frame [m/s]. + + Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). + """ + raise NotImplementedError + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ANGULAR_VELOCITY, element_names=XYZ_ELEMENT_NAMES) + def ang_vel_b(self) -> ProxyArray: + """PVA frame angular velocity relative to the world expressed in PVA frame [rad/s]. + + Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). + """ + raise NotImplementedError + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_LINEAR_ACCELERATION, element_names=XYZ_ELEMENT_NAMES) + def lin_acc_b(self) -> ProxyArray: + """Linear acceleration (coordinate) in the PVA frame [m/s^2]. + + Equal to -g in freefall, zero at rest. + + Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). + """ + raise NotImplementedError + + @property + @abstractmethod + @leapp_tensor_semantics(kind=InputKindEnum.BODY_ANGULAR_ACCELERATION, element_names=XYZ_ELEMENT_NAMES) + def ang_acc_b(self) -> ProxyArray: + """PVA frame angular acceleration relative to the world expressed in PVA frame [rad/s^2]. + + Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). + """ + raise NotImplementedError diff --git a/source/isaaclab/isaaclab/sensors/pva/pva.py b/source/isaaclab/isaaclab/sensors/pva/pva.py new file mode 100644 index 000000000000..e65e5d9bdb8b --- /dev/null +++ b/source/isaaclab/isaaclab/sensors/pva/pva.py @@ -0,0 +1,29 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from isaaclab.utils.backend_utils import FactoryBase + +from .base_pva import BasePva +from .base_pva_data import BasePvaData + +if TYPE_CHECKING: + from isaaclab_newton.sensors.pva import Pva as NewtonPva + from isaaclab_newton.sensors.pva import PvaData as NewtonPvaData + from isaaclab_physx.sensors.pva import Pva as PhysXPva + from isaaclab_physx.sensors.pva import PvaData as PhysXPvaData + + +class Pva(FactoryBase, BasePva): + """Factory for creating PVA sensor instances.""" + + data: BasePvaData | NewtonPvaData | PhysXPvaData + + def __new__(cls, *args, **kwargs) -> BasePva | NewtonPva | PhysXPva: + """Create a new instance of a PVA sensor based on the backend.""" + return super().__new__(cls, *args, **kwargs) diff --git a/source/isaaclab/isaaclab/sensors/pva/pva_cfg.py b/source/isaaclab/isaaclab/sensors/pva/pva_cfg.py new file mode 100644 index 000000000000..38f3d627608a --- /dev/null +++ b/source/isaaclab/isaaclab/sensors/pva/pva_cfg.py @@ -0,0 +1,43 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from isaaclab.markers import VisualizationMarkersCfg +from isaaclab.markers.config import RED_ARROW_X_MARKER_CFG +from isaaclab.utils import configclass + +from ..sensor_base_cfg import SensorBaseCfg + +if TYPE_CHECKING: + from .pva import Pva + + +@configclass +class PvaCfg(SensorBaseCfg): + """Configuration for a Pose Velocity Acceleration (PVA) sensor.""" + + class_type: type[Pva] | str = "{DIR}.pva:Pva" + + @configclass + class OffsetCfg: + """The offset pose of the sensor's frame from the sensor's parent frame.""" + + pos: tuple[float, float, float] = (0.0, 0.0, 0.0) + """Translation w.r.t. the parent frame [m]. Defaults to (0.0, 0.0, 0.0).""" + + rot: tuple[float, float, float, float] = (0.0, 0.0, 0.0, 1.0) + """Quaternion rotation (x, y, z, w) w.r.t. the parent frame. Defaults to (0.0, 0.0, 0.0, 1.0).""" + + offset: OffsetCfg = OffsetCfg() + """The offset pose of the sensor's frame from the sensor's parent frame. Defaults to identity.""" + + visualizer_cfg: VisualizationMarkersCfg = RED_ARROW_X_MARKER_CFG.replace(prim_path="/Visuals/Command/velocity_goal") + """The configuration object for the visualization markers. Defaults to RED_ARROW_X_MARKER_CFG. + + This attribute is only used when debug visualization is enabled. + """ diff --git a/source/isaaclab/isaaclab/sensors/pva/pva_data.py b/source/isaaclab/isaaclab/sensors/pva/pva_data.py new file mode 100644 index 000000000000..e1a614772a18 --- /dev/null +++ b/source/isaaclab/isaaclab/sensors/pva/pva_data.py @@ -0,0 +1,26 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Re-exports the base PVA data class.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from isaaclab.utils.backend_utils import FactoryBase + +from .base_pva_data import BasePvaData + +if TYPE_CHECKING: + from isaaclab_newton.sensors.pva import PvaData as NewtonPvaData + from isaaclab_physx.sensors.pva import PvaData as PhysXPvaData + + +class PvaData(FactoryBase, BasePvaData): + """Factory for creating PVA data instances.""" + + def __new__(cls, *args, **kwargs) -> BasePvaData | NewtonPvaData | PhysXPvaData: + """Create a new instance of PVA data based on the backend.""" + return super().__new__(cls, *args, **kwargs) diff --git a/source/isaaclab/isaaclab/sensors/ray_caster/kernels.py b/source/isaaclab/isaaclab/sensors/ray_caster/kernels.py new file mode 100644 index 000000000000..98c54ea7141d --- /dev/null +++ b/source/isaaclab/isaaclab/sensors/ray_caster/kernels.py @@ -0,0 +1,261 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Warp kernels for the ray caster sensor.""" + +import warp as wp + +ALIGNMENT_WORLD = wp.constant(0) +ALIGNMENT_YAW = wp.constant(1) +ALIGNMENT_BASE = wp.constant(2) + +# Upper-bound ray-cast distance [m] used by camera classes. The actual depth-clipping is applied +# as a post-process step per data type, so the kernel is always given a large budget. +CAMERA_RAYCAST_MAX_DIST: float = 1e6 + + +@wp.func +def quat_yaw_only( + # input + q: wp.quatf, +) -> wp.quatf: + """Extract the yaw-only quaternion from a general quaternion. + + Equivalent to :func:`isaaclab.utils.math.yaw_quat`: extracts the yaw angle via + ``atan2(2*(qw*qz + qx*qy), 1 - 2*(qy^2 + qz^2))`` and returns a pure-yaw quaternion + ``(0, 0, sin(yaw/2), cos(yaw/2))``. This is correct for all orientations, including + those with non-zero roll and pitch. + """ + qx = q[0] + qy = q[1] + qz = q[2] + qw = q[3] + yaw = wp.atan2(2.0 * (qw * qz + qx * qy), 1.0 - 2.0 * (qy * qy + qz * qz)) + half_yaw = yaw * 0.5 + return wp.quatf(0.0, 0.0, wp.sin(half_yaw), wp.cos(half_yaw)) + + +@wp.kernel(enable_backward=False) +def update_ray_caster_kernel( + # input + transforms: wp.array(dtype=wp.transformf), + env_mask: wp.array(dtype=wp.bool), + offset_pos: wp.array(dtype=wp.vec3f), + offset_quat: wp.array(dtype=wp.quatf), + drift: wp.array(dtype=wp.vec3f), + ray_cast_drift: wp.array(dtype=wp.vec3f), + ray_starts_local: wp.array2d(dtype=wp.vec3f), + ray_directions_local: wp.array2d(dtype=wp.vec3f), + alignment_mode: int, + # output + pos_w: wp.array(dtype=wp.vec3f), + quat_w: wp.array(dtype=wp.quatf), + ray_starts_w: wp.array2d(dtype=wp.vec3f), + ray_directions_w: wp.array2d(dtype=wp.vec3f), +): + """Compute sensor world poses and transform rays into world frame. + + Combines the PhysX view transform with the sensor offset, applies drift, + and transforms local ray starts/directions according to the alignment mode. + + Launch with dim=(num_envs, num_rays). + + Args: + transforms: World transforms from PhysX view. Shape is (num_envs,). + env_mask: Boolean mask for which environments to update. Shape is (num_envs,). + offset_pos: Per-env position offset [m] from view to sensor. Shape is (num_envs,). + offset_quat: Per-env quaternion offset from view to sensor. Shape is (num_envs,). + drift: Per-env position drift [m]. Shape is (num_envs,). + ray_cast_drift: Per-env ray cast drift [m]. Shape is (num_envs,). + After rotation by the alignment quaternion, only the x and y components + are applied to the ray start position; the z component of the sensor + position is preserved. + ray_starts_local: Per-env local ray start positions [m]. Shape is (num_envs, num_rays). + ray_directions_local: Per-env local ray directions (unit vectors). Shape is (num_envs, num_rays). + alignment_mode: 0=world, 1=yaw, 2=base. + pos_w: Output sensor position in world frame [m]. Shape is (num_envs,). + quat_w: Output sensor orientation in world frame. Shape is (num_envs,). + ray_starts_w: Output world-frame ray starts [m]. Shape is (num_envs, num_rays). + ray_directions_w: Output world-frame ray directions (unit vectors). Shape is (num_envs, num_rays). + """ + env_id, ray_id = wp.tid() + if not env_mask[env_id]: + return + + t = transforms[env_id] + view_pos = wp.transform_get_translation(t) + view_quat = wp.transform_get_rotation(t) + + # combine_frame_transforms: q02 = q01 * q12, t02 = t01 + quat_rotate(q01, t12) + combined_quat = view_quat * offset_quat[env_id] + combined_pos = view_pos + wp.quat_rotate(view_quat, offset_pos[env_id]) + + combined_pos = combined_pos + drift[env_id] + + if ray_id == 0: + pos_w[env_id] = combined_pos + quat_w[env_id] = combined_quat + + local_start = ray_starts_local[env_id, ray_id] + local_dir = ray_directions_local[env_id, ray_id] + rcd = ray_cast_drift[env_id] + + if alignment_mode == ALIGNMENT_WORLD: + pos_drifted = wp.vec3f(combined_pos[0] + rcd[0], combined_pos[1] + rcd[1], combined_pos[2]) + ray_starts_w[env_id, ray_id] = local_start + pos_drifted + ray_directions_w[env_id, ray_id] = local_dir + elif alignment_mode == ALIGNMENT_YAW: + yaw_q = quat_yaw_only(combined_quat) + rot_drift = wp.quat_rotate(yaw_q, rcd) + pos_drifted = wp.vec3f(combined_pos[0] + rot_drift[0], combined_pos[1] + rot_drift[1], combined_pos[2]) + ray_starts_w[env_id, ray_id] = wp.quat_rotate(yaw_q, local_start) + pos_drifted + # Ray DIRECTIONS are intentionally NOT rotated in yaw mode: the sensor's ray pattern + # (e.g. straight-down (0,0,-1) for a height scanner) stays fixed in world frame. + # Only ray STARTS are rotated by the yaw-only quaternion so the scan footprint + # follows the body heading without tilting when the body pitches or rolls. + ray_directions_w[env_id, ray_id] = local_dir + else: + rot_drift = wp.quat_rotate(combined_quat, rcd) + pos_drifted = wp.vec3f(combined_pos[0] + rot_drift[0], combined_pos[1] + rot_drift[1], combined_pos[2]) + ray_starts_w[env_id, ray_id] = wp.quat_rotate(combined_quat, local_start) + pos_drifted + ray_directions_w[env_id, ray_id] = wp.quat_rotate(combined_quat, local_dir) + + +@wp.kernel(enable_backward=False) +def fill_vec3_inf_kernel( + # input + env_mask: wp.array(dtype=wp.bool), + inf_val: wp.float32, + # output + data: wp.array2d(dtype=wp.vec3f), +): + """Fill a 2D vec3f array with a given value for masked environments. + + Launch with dim=(num_envs, num_rays). + + Args: + env_mask: Boolean mask for which environments to update. Shape is (num_envs,). + inf_val: Value to fill with (typically inf). + data: Array to fill. Shape is (num_envs, num_rays). + """ + env, ray = wp.tid() + if not env_mask[env]: + return + data[env, ray] = wp.vec3f(inf_val, inf_val, inf_val) + + +@wp.kernel(enable_backward=False) +def apply_z_drift_kernel( + # input + env_mask: wp.array(dtype=wp.bool), + ray_cast_drift: wp.array(dtype=wp.vec3f), + # output + ray_hits: wp.array2d(dtype=wp.vec3f), +): + """Apply vertical (z) drift to ray hit positions for masked environments. + + Launch with dim=(num_envs, num_rays). + + Args: + env_mask: Boolean mask for which environments to update. Shape is (num_envs,). + ray_cast_drift: Per-env drift vector [m]; only z-component is used. Shape is (num_envs,). + ray_hits: Ray hit positions to modify in-place. Shape is (num_envs, num_rays). + """ + env, ray = wp.tid() + if not env_mask[env]: + return + hit = ray_hits[env, ray] + ray_hits[env, ray] = wp.vec3f(hit[0], hit[1], hit[2] + ray_cast_drift[env][2]) + + +@wp.kernel(enable_backward=False) +def fill_float2d_masked_kernel( + # input + env_mask: wp.array(dtype=wp.bool), + val: wp.float32, + # output + data: wp.array2d(dtype=wp.float32), +): + """Fill a 2D float32 array with a given value for masked environments. + + Launch with dim=(num_envs, num_rays). + + Args: + env_mask: Boolean mask for which environments to update. Shape is (num_envs,). + val: Value to fill with. + data: Array to fill. Shape is (num_envs, num_rays). + """ + env, ray = wp.tid() + if not env_mask[env]: + return + data[env, ray] = val + + +@wp.kernel(enable_backward=False) +def compute_distance_to_image_plane_masked_kernel( + # input + env_mask: wp.array(dtype=wp.bool), + quat_w: wp.array(dtype=wp.quatf), + ray_distance: wp.array2d(dtype=wp.float32), + ray_directions_w: wp.array2d(dtype=wp.vec3f), + # output + distance_to_image_plane: wp.array2d(dtype=wp.float32), +): + """Compute distance-to-image-plane from ray depth and direction for masked environments. + + The distance to the image plane is the signed projection of the hit displacement + (``ray_distance * ray_direction_w``) onto the camera forward axis (+X in world convention). + This equals the x-component of the hit vector in the camera frame. + + Launch with dim=(num_envs, num_rays). + + Args: + env_mask: Boolean mask for which environments to update. Shape is (num_envs,). + quat_w: Camera orientation in world frame (x, y, z, w). Shape is (num_envs,). + ray_distance: Per-ray hit distances [m]. Shape is (num_envs, num_rays). + Contains inf for missed rays. + ray_directions_w: World-frame unit ray directions. Shape is (num_envs, num_rays). + distance_to_image_plane: Output distance-to-image-plane [m]. Shape is (num_envs, num_rays). + """ + env, ray = wp.tid() + if not env_mask[env]: + return + + depth = ray_distance[env, ray] + dir_w = ray_directions_w[env, ray] + # displacement vector in world frame + disp_w = wp.vec3f(depth * dir_w[0], depth * dir_w[1], depth * dir_w[2]) + # rotate into camera frame (quat_rotate_inv applies q^-1 * v * q) + disp_cam = wp.quat_rotate_inv(quat_w[env], disp_w) + # x-component is the forward (depth) axis of the camera in world convention + distance_to_image_plane[env, ray] = disp_cam[0] + + +@wp.kernel(enable_backward=False) +def apply_depth_clipping_masked_kernel( + # input + env_mask: wp.array(dtype=wp.bool), + max_dist: wp.float32, + fill_val: wp.float32, + # output + depth: wp.array2d(dtype=wp.float32), +): + """Clip depth values in-place, replacing values above max_dist or NaN with fill_val. + + Launch with dim=(num_envs, num_rays). + + Args: + env_mask: Boolean mask for which environments to update. Shape is (num_envs,). + max_dist: Maximum depth threshold [m]. + fill_val: Replacement value [m] written for depths exceeding max_dist or NaN. + Pass ``max_dist`` for "max" clipping or ``0.0`` for "zero" clipping. + depth: Depth buffer to clip in-place. Shape is (num_envs, num_rays). + """ + env, ray = wp.tid() + if not env_mask[env]: + return + val = depth[env, ray] + if val > max_dist or wp.isnan(val): + depth[env, ray] = fill_val diff --git a/source/isaaclab/isaaclab/sensors/ray_caster/multi_mesh_ray_caster.py b/source/isaaclab/isaaclab/sensors/ray_caster/multi_mesh_ray_caster.py index 06ce2183e2ff..f9d0493a0f61 100644 --- a/source/isaaclab/isaaclab/sensors/ray_caster/multi_mesh_ray_caster.py +++ b/source/isaaclab/isaaclab/sensors/ray_caster/multi_mesh_ray_caster.py @@ -14,22 +14,20 @@ import trimesh import warp as wp -import omni.physics.tensors.impl.api as physx - import isaaclab.sim as sim_utils -from isaaclab.sim.views import XformPrimView -from isaaclab.utils.math import matrix_from_quat, quat_mul +from isaaclab.sim.views import BaseFrameView, FrameView +from isaaclab.utils.math import matrix_from_quat from isaaclab.utils.mesh import PRIMITIVE_MESH_TYPES, create_trimesh_from_geom_mesh, create_trimesh_from_geom_shape -from isaaclab.utils.warp import convert_to_warp_mesh, raycast_dynamic_meshes +from isaaclab.utils.warp import convert_to_warp_mesh +from isaaclab.utils.warp import kernels as warp_kernels +from .kernels import fill_float2d_masked_kernel, fill_vec3_inf_kernel from .multi_mesh_ray_caster_data import MultiMeshRayCasterData -from .ray_cast_utils import obtain_world_pose_from_view from .ray_caster import RayCaster if TYPE_CHECKING: from .multi_mesh_ray_caster_cfg import MultiMeshRayCasterCfg -# import logger logger = logging.getLogger(__name__) @@ -41,8 +39,8 @@ class MultiMeshRayCaster(RayCaster): a set of meshes with a given ray pattern. The meshes are parsed from the list of primitive paths provided in the configuration. These are then - converted to warp meshes and stored in the :attr:`meshes` list. The ray-caster then ray-casts against - these warp meshes using the ray pattern provided in the configuration. + converted to warp meshes and stored in the :attr:`meshes` dictionary. The ray-caster then ray-casts + against these warp meshes using the ray pattern provided in the configuration. Compared to the default RayCaster, the MultiMeshRayCaster provides additional functionality and flexibility as an extension of the default RayCaster with the following enhancements: @@ -53,6 +51,15 @@ class MultiMeshRayCaster(RayCaster): (e.g., robot links, articulated bodies, or dynamic obstacles). - Memory-efficient caching : Avoids redundant memory usage by reusing mesh data across environments. + .. warning:: + **Known limitation (multi-mesh closest-hit resolution):** When two meshes produce a + hit at the exact same distance for a given ray, the ``atomic_min`` + equality-check + pattern in the raycasting kernel is not fully thread-safe. The hit *position* is always + correct, but auxiliary outputs (normals, face IDs, mesh IDs) may originate from + different meshes for the affected ray. This requires an exact floating-point tie and is + rare in practice. See `warp#1058 `_ for + upstream progress on a thread-safe ``atomic_min`` return value. + Example usage to raycast against the visual meshes of a robot (e.g. ANYmal): .. code-block:: python @@ -76,9 +83,7 @@ class MultiMeshRayCaster(RayCaster): cfg: MultiMeshRayCasterCfg """The configuration parameters.""" - mesh_offsets: dict[str, tuple[torch.Tensor, torch.Tensor]] = {} - - mesh_views: ClassVar[dict[str, XformPrimView | physx.ArticulationView | physx.RigidBodyView]] = {} + mesh_views: ClassVar[dict[str, BaseFrameView]] = {} """A dictionary to store mesh views for raycasting, shared across all instances. The keys correspond to the prim path for the mesh views, and values are the corresponding view objects. @@ -90,33 +95,24 @@ def __init__(self, cfg: MultiMeshRayCasterCfg): Args: cfg: The configuration parameters. """ - # Initialize base class super().__init__(cfg) - # Create empty variables for storing output data self._num_meshes_per_env: dict[str, int] = {} - """Keeps track of the number of meshes per env for each ray_cast target. - Since we allow regex indexing (e.g. env_*/object_*) they can differ - """ self._raycast_targets_cfg: list[MultiMeshRayCasterCfg.RaycastTargetCfg] = [] for target in self.cfg.mesh_prim_paths: - # Legacy support for string targets. Treat them as global targets. if isinstance(target, str): self._raycast_targets_cfg.append(cfg.RaycastTargetCfg(prim_expr=target, track_mesh_transforms=False)) else: self._raycast_targets_cfg.append(target) - # Resolve regex namespace if set for cfg in self._raycast_targets_cfg: cfg.prim_expr = cfg.prim_expr.format(ENV_REGEX_NS="/World/envs/env_.*") - # overwrite the data class self._data = MultiMeshRayCasterData() def __str__(self) -> str: """Returns: A string containing information about the instance.""" - return ( f"Ray-caster @ '{self.cfg.prim_path}': \n" f"\tview type : {self._view.__class__}\n" @@ -133,9 +129,7 @@ def __str__(self) -> str: @property def data(self) -> MultiMeshRayCasterData: - # update sensors if needed self._update_outdated_buffers() - # return the data return self._data """ @@ -163,9 +157,8 @@ def _initialize_warp_meshes(self): """ multi_mesh_ids: dict[str, list[list[int]]] = {} for target_cfg in self._raycast_targets_cfg: - # target prim path to ray cast against target_prim_path = target_cfg.prim_expr - # # check if mesh already casted into warp mesh and skip if so. + # check if mesh already casted into warp mesh and skip if so. if target_prim_path in multi_mesh_ids: logger.warning( f"Mesh at target prim path '{target_prim_path}' already exists in the mesh cache. Duplicate entries" @@ -173,32 +166,29 @@ def _initialize_warp_meshes(self): ) continue - # find all matching prim paths to provided expression of the target target_prims = sim_utils.find_matching_prims(target_prim_path) if len(target_prims) == 0: raise RuntimeError(f"Failed to find a prim at path expression: {target_prim_path}") - # If only one prim is found, treat it as a global prim. - # Either it's a single global object (e.g. ground) or we are only using one env. is_global_prim = len(target_prims) == 1 loaded_vertices: list[np.ndarray | None] = [] wp_mesh_ids = [] for target_prim in target_prims: - # Reuse previously parsed shared mesh instance if possible. if target_cfg.is_shared and len(wp_mesh_ids) > 0: # Verify if this mesh has already been registered in an earlier environment. # Note, this check may fail, if the prim path is not following the env_.* pattern # Which (worst case) leads to parsing the mesh and skipping registering it at a later stage - curr_prim_base_path = re.sub(r"env_\d+", "env_0", str(target_prim.GetPath())) # - if curr_prim_base_path in MultiMeshRayCaster.meshes: - MultiMeshRayCaster.meshes[str(target_prim.GetPath())] = MultiMeshRayCaster.meshes[ - curr_prim_base_path - ] - # Reuse mesh imported by another ray-cast sensor (global cache). - if str(target_prim.GetPath()) in MultiMeshRayCaster.meshes: - wp_mesh_ids.append(MultiMeshRayCaster.meshes[str(target_prim.GetPath())].id) + curr_prim_base_path = re.sub(r"env_\d+", "env_0", str(target_prim.GetPath())) + base_key = (curr_prim_base_path, self._device) + if base_key in MultiMeshRayCaster.meshes: + MultiMeshRayCaster.meshes[(str(target_prim.GetPath()), self._device)] = ( + MultiMeshRayCaster.meshes[base_key] + ) + prim_key = (str(target_prim.GetPath()), self._device) + if prim_key in MultiMeshRayCaster.meshes: + wp_mesh_ids.append(MultiMeshRayCaster.meshes[prim_key].id) loaded_vertices.append(None) continue @@ -219,7 +209,6 @@ def _initialize_warp_meshes(self): trimesh_meshes = [] for mesh_prim in mesh_prims: - # check if valid if mesh_prim is None or not mesh_prim.IsValid(): raise RuntimeError(f"Invalid mesh prim path: {target_prim}") @@ -240,13 +229,11 @@ def _initialize_warp_meshes(self): transform[:3, 3] = relative_pos.numpy() mesh.apply_transform(transform) - # add to list of parsed meshes trimesh_meshes.append(mesh) if len(trimesh_meshes) == 1: trimesh_mesh = trimesh_meshes[0] elif target_cfg.merge_prim_meshes: - # combine all trimesh meshes into a single mesh trimesh_mesh = trimesh.util.concatenate(trimesh_meshes) else: raise RuntimeError( @@ -254,20 +241,17 @@ def _initialize_warp_meshes(self): " enable `merge_prim_meshes` in the configuration or specify each mesh separately." ) - # check if the mesh is already registered, if so only reference the mesh registered_idx = _registered_points_idx(trimesh_mesh.vertices, loaded_vertices) if registered_idx != -1 and self.cfg.reference_meshes: logger.info("Found a duplicate mesh, only reference the mesh.") - # Found a duplicate mesh, only reference the mesh. loaded_vertices.append(None) wp_mesh_ids.append(wp_mesh_ids[registered_idx]) else: loaded_vertices.append(trimesh_mesh.vertices) - wp_mesh = convert_to_warp_mesh(trimesh_mesh.vertices, trimesh_mesh.faces, device=self.device) - MultiMeshRayCaster.meshes[str(target_prim.GetPath())] = wp_mesh + wp_mesh = convert_to_warp_mesh(trimesh_mesh.vertices, trimesh_mesh.faces, device=self._device) + MultiMeshRayCaster.meshes[(str(target_prim.GetPath()), self._device)] = wp_mesh wp_mesh_ids.append(wp_mesh.id) - # print info if registered_idx != -1: logger.info(f"Found duplicate mesh for mesh prims under path '{target_prim.GetPath()}'.") else: @@ -277,12 +261,9 @@ def _initialize_warp_meshes(self): ) if is_global_prim: - # reference the mesh for each environment to ray cast against multi_mesh_ids[target_prim_path] = [wp_mesh_ids] * self._num_envs self._num_meshes_per_env[target_prim_path] = len(wp_mesh_ids) else: - # split up the meshes for each environment. Little bit ugly, since - # the current order is interleaved (env1_obj1, env1_obj2, env2_obj1, env2_obj2, ...) multi_mesh_ids[target_prim_path] = [] mesh_idx = 0 n_meshes_per_env = len(wp_mesh_ids) // self._num_envs @@ -292,26 +273,28 @@ def _initialize_warp_meshes(self): mesh_idx += n_meshes_per_env if target_cfg.track_mesh_transforms: - MultiMeshRayCaster.mesh_views[target_prim_path], MultiMeshRayCaster.mesh_offsets[target_prim_path] = ( - self._obtain_trackable_prim_view(target_prim_path) + MultiMeshRayCaster.mesh_views[target_prim_path] = FrameView( + target_prim_path, device=self._device, stage=self.stage ) - # throw an error if no meshes are found if all([target_cfg.prim_expr not in multi_mesh_ids for target_cfg in self._raycast_targets_cfg]): raise RuntimeError( f"No meshes found for ray-casting! Please check the mesh prim paths: {self.cfg.mesh_prim_paths}" ) total_n_meshes_per_env = sum(self._num_meshes_per_env.values()) - self._mesh_positions_w = torch.zeros(self._num_envs, total_n_meshes_per_env, 3, device=self.device) - self._mesh_orientations_w = torch.zeros(self._num_envs, total_n_meshes_per_env, 4, device=self.device) + self._mesh_positions_w = wp.zeros((self._num_envs, total_n_meshes_per_env), dtype=wp.vec3, device=self.device) + self._mesh_orientations_w = wp.zeros( + (self._num_envs, total_n_meshes_per_env), dtype=wp.quat, device=self.device + ) + # Zero-copy torch views for writing from physics view results (torch tensors) + self._mesh_positions_w_torch = wp.to_torch(self._mesh_positions_w) + self._mesh_orientations_w_torch = wp.to_torch(self._mesh_orientations_w) - # Update the mesh positions and rotations mesh_idx = 0 for target_cfg in self._raycast_targets_cfg: n_meshes = self._num_meshes_per_env[target_cfg.prim_expr] - # update position of the target meshes pos_w, ori_w = [], [] for prim in sim_utils.find_matching_prims(target_cfg.prim_expr): translation, quat = sim_utils.resolve_prim_pose(prim) @@ -320,11 +303,10 @@ def _initialize_warp_meshes(self): pos_w = torch.tensor(pos_w, device=self.device, dtype=torch.float32).view(-1, n_meshes, 3) ori_w = torch.tensor(ori_w, device=self.device, dtype=torch.float32).view(-1, n_meshes, 4) - self._mesh_positions_w[:, mesh_idx : mesh_idx + n_meshes] = pos_w - self._mesh_orientations_w[:, mesh_idx : mesh_idx + n_meshes] = ori_w + self._mesh_positions_w_torch[:, mesh_idx : mesh_idx + n_meshes] = pos_w + self._mesh_orientations_w_torch[:, mesh_idx : mesh_idx + n_meshes] = ori_w mesh_idx += n_meshes - # flatten the list of meshes that are included in mesh_prim_paths of the specific ray caster multi_mesh_ids_flattened = [] for env_idx in range(self._num_envs): meshes_in_env = [] @@ -337,25 +319,30 @@ def _initialize_warp_meshes(self): for target_cfg in self._raycast_targets_cfg ] - # save a warp array with mesh ids that is passed to the raycast function self._mesh_ids_wp = wp.array2d(multi_mesh_ids_flattened, dtype=wp.uint64, device=self.device) def _initialize_rays_impl(self): super()._initialize_rays_impl() + # Persistent buffer for tracking closest-hit distance across meshes (for atomic_min) + self._ray_distance_w = wp.zeros((self._view.count, self.num_rays), dtype=wp.float32, device=self._device) if self.cfg.update_mesh_ids: - self._data.ray_mesh_ids = torch.zeros( - self._num_envs, self.num_rays, 1, device=self.device, dtype=torch.int16 - ) - - def _update_buffers_impl(self, env_mask: wp.array): - """Fills the buffers of the sensor data.""" - env_ids = wp.to_torch(env_mask).nonzero(as_tuple=False).squeeze(-1) - if len(env_ids) == 0: - return - - self._update_ray_infos(env_ids) - - # Update the mesh positions and rotations + self._ray_mesh_id_w = wp.zeros((self._view.count, self.num_rays), dtype=wp.int16, device=self._device) + # Zero-copy torch view with the trailing dim expected by consumers of ray_mesh_ids + self._data.ray_mesh_ids = wp.to_torch(self._ray_mesh_id_w).unsqueeze(-1) + else: + # Dummy 1×1 buffer so the kernel launch always has a valid array to bind + self._ray_mesh_id_w = wp.empty((1, 1), dtype=wp.int16, device=self._device) + # Persistent dummy buffers for unused kernel outputs; allocated once to avoid per-step allocations. + self._dummy_normal_w = wp.empty((1, 1), dtype=wp.vec3, device=self._device) + self._dummy_face_id_w = wp.empty((1, 1), dtype=wp.int32, device=self._device) + + def _update_mesh_transforms(self) -> None: + """Update world-frame mesh positions and orientations for dynamically tracked targets. + + Iterates over all tracked views and writes the current world poses into + ``_mesh_positions_w_torch`` and ``_mesh_orientations_w_torch``. Static (non-tracked) + targets are skipped; their initial poses were set during :meth:`_initialize_warp_meshes`. + """ mesh_idx = 0 for view, target_cfg in zip(self._mesh_views, self._raycast_targets_cfg): if not target_cfg.track_mesh_transforms: @@ -363,42 +350,75 @@ def _update_buffers_impl(self, env_mask: wp.array): continue # update position of the target meshes - pos_w, ori_w = obtain_world_pose_from_view(view, None) + pos_w, ori_w = view.get_world_poses(None) + pos_w, ori_w = pos_w.torch, ori_w.torch pos_w = pos_w.squeeze(0) if len(pos_w.shape) == 3 else pos_w ori_w = ori_w.squeeze(0) if len(ori_w.shape) == 3 else ori_w - if target_cfg.prim_expr in MultiMeshRayCaster.mesh_offsets: - pos_offset, ori_offset = MultiMeshRayCaster.mesh_offsets[target_cfg.prim_expr] - pos_w -= pos_offset - ori_w = quat_mul(ori_offset.expand(ori_w.shape[0], -1), ori_w) - count = view.count - if count != 1: # Mesh is not global, i.e. we have different meshes for each env + if count != 1: count = count // self._num_envs pos_w = pos_w.view(self._num_envs, count, 3) ori_w = ori_w.view(self._num_envs, count, 4) - self._mesh_positions_w[:, mesh_idx : mesh_idx + count] = pos_w - self._mesh_orientations_w[:, mesh_idx : mesh_idx + count] = ori_w + self._mesh_positions_w_torch[:, mesh_idx : mesh_idx + count] = pos_w + self._mesh_orientations_w_torch[:, mesh_idx : mesh_idx + count] = ori_w mesh_idx += count - self._data.ray_hits_w[env_ids], _, _, _, mesh_ids = raycast_dynamic_meshes( - self._ray_starts_w[env_ids], - self._ray_directions_w[env_ids], - mesh_ids_wp=self._mesh_ids_wp, # list with shape num_envs x num_meshes_per_env - max_dist=self.cfg.max_distance, - mesh_positions_w=self._mesh_positions_w[env_ids], - mesh_orientations_w=self._mesh_orientations_w[env_ids], - return_mesh_id=self.cfg.update_mesh_ids, + def _update_buffers_impl(self, env_mask: wp.array): + """Fills the buffers of the sensor data.""" + self._update_ray_infos(env_mask) + self._update_mesh_transforms() + + n_meshes = self._mesh_ids_wp.shape[1] + + # Fill output and distance buffers with inf for masked environments + wp.launch( + fill_vec3_inf_kernel, + dim=(self._num_envs, self.num_rays), + inputs=[env_mask, float("inf"), self._data._ray_hits_w], + device=self._device, + ) + wp.launch( + fill_float2d_masked_kernel, + dim=(self._num_envs, self.num_rays), + inputs=[env_mask, float("inf"), self._ray_distance_w], + device=self._device, ) - if self.cfg.update_mesh_ids: - self._data.ray_mesh_ids[env_ids] = mesh_ids + # Ray-cast against all meshes; closest hit wins via atomic_min on ray_distance + wp.launch( + warp_kernels.raycast_dynamic_meshes_kernel, + dim=(n_meshes, self._num_envs, self.num_rays), + inputs=[ + env_mask, + self._mesh_ids_wp, + self._ray_starts_w, + self._ray_directions_w, + self._data._ray_hits_w, + self._ray_distance_w, + self._dummy_normal_w, + self._dummy_face_id_w, + self._ray_mesh_id_w, + self._mesh_positions_w, + self._mesh_orientations_w, + float(self.cfg.max_distance), + int(False), + int(False), + int(self.cfg.update_mesh_ids), + ], + device=self._device, + ) + + def _invalidate_initialize_callback(self, event): + """Invalidates the scene elements.""" + super()._invalidate_initialize_callback(event) + # clear mesh views so they are re-created on the next initialization + MultiMeshRayCaster.mesh_views.clear() def __del__(self): super().__del__() if RayCaster._instance_count == 0: - MultiMeshRayCaster.mesh_offsets.clear() MultiMeshRayCaster.mesh_views.clear() diff --git a/source/isaaclab/isaaclab/sensors/ray_caster/multi_mesh_ray_caster_camera.py b/source/isaaclab/isaaclab/sensors/ray_caster/multi_mesh_ray_caster_camera.py index a1be3160d99b..a14c16f3d0d9 100644 --- a/source/isaaclab/isaaclab/sensors/ray_caster/multi_mesh_ray_caster_camera.py +++ b/source/isaaclab/isaaclab/sensors/ray_caster/multi_mesh_ray_caster_camera.py @@ -5,18 +5,22 @@ from __future__ import annotations -from collections.abc import Sequence from typing import TYPE_CHECKING import torch import warp as wp import isaaclab.utils.math as math_utils -from isaaclab.utils.warp import raycast_dynamic_meshes - +from isaaclab.utils.warp import kernels as warp_kernels + +from .kernels import ( + CAMERA_RAYCAST_MAX_DIST, + compute_distance_to_image_plane_masked_kernel, + fill_float2d_masked_kernel, + fill_vec3_inf_kernel, +) from .multi_mesh_ray_caster import MultiMeshRayCaster from .multi_mesh_ray_caster_camera_data import MultiMeshRayCasterCameraData -from .ray_cast_utils import obtain_world_pose_from_view from .ray_caster_camera import RayCasterCamera if TYPE_CHECKING: @@ -85,136 +89,205 @@ def _create_buffers(self): ) def _initialize_rays_impl(self): - # Create all indices buffer + # NOTE: This method intentionally does NOT call super()._initialize_rays_impl() through the MRO + # chain. The intermediate classes (RayCasterCamera, MultiMeshRayCaster) use different internal + # buffer names and orderings that are incompatible with the camera's full init path: + # - RayCasterCamera creates single-mesh ray buffers (_ray_distance, _ray_normal_w, etc.) + # - MultiMeshRayCaster creates _ray_distance_w / _ray_mesh_id_w for multi-mesh use + # The camera replaces all of these with its own camera-named equivalents below. + # If either parent class gains new shared buffers, they must be added here explicitly. + + # Camera-specific bookkeeping buffers self._ALL_INDICES = torch.arange(self._view.count, device=self._device, dtype=torch.long) - # Create frame count buffer self._frame = torch.zeros(self._view.count, device=self._device, dtype=torch.long) - # create buffers + + # Build camera output buffers (intrinsics, image data, etc.) self._create_buffers() - # compute intrinsic matrices self._compute_intrinsic_matrices() - # compute ray stars and directions - self.ray_starts, self.ray_directions = self.cfg.pattern_cfg.func( + + # Compute local ray starts/directions from the camera pattern (torch, init-time only) + ray_starts_local, ray_directions_local = self.cfg.pattern_cfg.func( self.cfg.pattern_cfg, self._data.intrinsic_matrices, self._device ) - self.num_rays = self.ray_directions.shape[1] - # create buffer to store ray hits - self.ray_hits_w = torch.zeros(self._view.count, self.num_rays, 3, device=self._device) - # set offsets - quat_w = math_utils.convert_camera_frame_orientation_convention( - torch.tensor([self.cfg.offset.rot], device=self._device), origin=self.cfg.offset.convention, target="world" + self.num_rays = ray_directions_local.shape[1] + + # Store local (sensor-frame) ray arrays as torch tensors for per-env camera-convention rotation + self.ray_starts = ray_starts_local + self.ray_directions = ray_directions_local + + # Camera-frame offset: convert from cfg convention to world convention + quat_offset = math_utils.convert_camera_frame_orientation_convention( + torch.tensor([self.cfg.offset.rot], device=self._device), + origin=self.cfg.offset.convention, + target="world", ) - self._offset_quat = quat_w.repeat(self._view.count, 1) + self._offset_quat = quat_offset.repeat(self._view.count, 1) self._offset_pos = torch.tensor(list(self.cfg.offset.pos), device=self._device).repeat(self._view.count, 1) - self._data.quat_w = torch.zeros(self._view.count, 4, device=self.device) - self._data.pos_w = torch.zeros(self._view.count, 3, device=self.device) + # Camera pose buffers (torch, part of CameraData) + self._data.pos_w = torch.zeros(self._view.count, 3, device=self._device) + self._data.quat_w_world = torch.zeros(self._view.count, 4, device=self._device) + # Warp-backed camera orientation buffer for warp kernel calls; + # updated from self._data.quat_w_world in _update_ray_infos. + self._quat_w_wp = wp.zeros(self._view.count, dtype=wp.quatf, device=self._device) + self._quat_w_wp_torch = wp.to_torch(self._quat_w_wp) + + # Warp buffer for distance_to_image_plane output (if requested) + if "distance_to_image_plane" in self.cfg.data_types: + self._distance_to_image_plane_wp = wp.zeros( + (self._view.count, self.num_rays), dtype=wp.float32, device=self._device + ) + + # World-frame ray buffers: allocate as warp arrays first, then create zero-copy torch views. + # Keeping warp arrays as primary storage avoids lifetime issues when passing to kernels. + self._ray_starts_w = wp.zeros((self._view.count, self.num_rays), dtype=wp.vec3f, device=self._device) + self._ray_directions_w = wp.zeros((self._view.count, self.num_rays), dtype=wp.vec3f, device=self._device) + # Zero-copy torch views used for indexing and post-processing + self._ray_starts_w_torch = wp.to_torch(self._ray_starts_w) + self._ray_directions_w_torch = wp.to_torch(self._ray_directions_w) + + # Ray hit positions as a warp array; expose a torch view for debug visualisation + self._ray_hits_w_cam = wp.zeros((self._view.count, self.num_rays), dtype=wp.vec3f, device=self._device) + self.ray_hits_w = wp.to_torch(self._ray_hits_w_cam) + + # Per-ray closest-hit distance for atomic_min across meshes + self._ray_distance_cam_w = wp.zeros((self._view.count, self.num_rays), dtype=wp.float32, device=self._device) + + # Optional normal buffer (always allocated; filled only when "normals" is requested) + self._ray_normal_w = wp.zeros((self._view.count, self.num_rays), dtype=wp.vec3f, device=self._device) - self._ray_starts_w = torch.zeros(self._view.count, self.num_rays, 3, device=self.device) - self._ray_directions_w = torch.zeros(self._view.count, self.num_rays, 3, device=self.device) + # Mesh-id buffers from MultiMeshRayCaster._initialize_rays_impl + if self.cfg.update_mesh_ids: + self._ray_mesh_id_w = wp.zeros((self._view.count, self.num_rays), dtype=wp.int16, device=self._device) + self._data.ray_mesh_ids = wp.to_torch(self._ray_mesh_id_w).unsqueeze(-1) + else: + self._ray_mesh_id_w = wp.empty((1, 1), dtype=wp.int16, device=self._device) + + # Dummy face-id buffer (not used by camera but required by kernel signature) + self._ray_face_id_w = wp.empty((1, 1), dtype=wp.int32, device=self._device) - def _update_ray_infos(self, env_ids: Sequence[int]): - """Updates the ray information buffers.""" + def _update_ray_infos(self, env_mask: wp.array): + """Updates camera poses and world-frame ray buffers for masked environments. + + Args: + env_mask: Boolean mask selecting which environments to update. Shape is (num_envs,). + """ + env_ids = wp.to_torch(env_mask).nonzero(as_tuple=False).squeeze(-1) + if len(env_ids) == 0: + return - # compute poses from current view - pos_w, quat_w = obtain_world_pose_from_view(self._view, env_ids) + # Compute camera world poses by composing view pose with sensor offset + indices = wp.from_torch(env_ids.to(dtype=torch.int32), dtype=wp.int32) + pos_w, quat_w = self._view.get_world_poses(indices) + pos_w, quat_w = pos_w.torch, quat_w.torch pos_w, quat_w = math_utils.combine_frame_transforms( pos_w, quat_w, self._offset_pos[env_ids], self._offset_quat[env_ids] ) - # update the data + # Store camera pose in CameraData (torch tensors) and warp-backed orientation buffer self._data.pos_w[env_ids] = pos_w self._data.quat_w_world[env_ids] = quat_w - self._data.quat_w_ros[env_ids] = quat_w + self._quat_w_wp_torch[env_ids] = quat_w - # note: full orientation is considered - ray_starts_w = math_utils.quat_apply(quat_w.repeat(1, self.num_rays), self.ray_starts[env_ids]) - ray_starts_w += pos_w.unsqueeze(1) - ray_directions_w = math_utils.quat_apply(quat_w.repeat(1, self.num_rays), self.ray_directions[env_ids]) + # Rotate local ray starts and directions into world frame using full camera orientation + quat_w_repeated = quat_w.repeat(1, self.num_rays).reshape(-1, 4) + ray_starts_local = self.ray_starts[env_ids].reshape(-1, 3) + ray_dirs_local = self.ray_directions[env_ids].reshape(-1, 3) - self._ray_starts_w[env_ids] = ray_starts_w - self._ray_directions_w[env_ids] = ray_directions_w + ray_starts_world = math_utils.quat_apply(quat_w_repeated, ray_starts_local).reshape( + len(env_ids), self.num_rays, 3 + ) + ray_starts_world += pos_w.unsqueeze(1) + ray_dirs_world = math_utils.quat_apply(quat_w_repeated, ray_dirs_local).reshape(len(env_ids), self.num_rays, 3) + + # Write back into the warp-backed buffers via zero-copy torch views + self._ray_starts_w_torch[env_ids] = ray_starts_world + self._ray_directions_w_torch[env_ids] = ray_dirs_world def _update_buffers_impl(self, env_mask: wp.array): """Fills the buffers of the sensor data.""" env_ids = wp.to_torch(env_mask).nonzero(as_tuple=False).squeeze(-1) if len(env_ids) == 0: return - self._update_ray_infos(env_ids) - # increment frame count + self._update_ray_infos(env_mask) + + # Increment frame count for updated environments self._frame[env_ids] += 1 - # Update the mesh positions and rotations - mesh_idx = 0 - for view, target_cfg in zip(self._mesh_views, self._raycast_targets_cfg): - if not target_cfg.track_mesh_transforms: - mesh_idx += self._num_meshes_per_env[target_cfg.prim_expr] - continue - - # update position of the target meshes - pos_w, ori_w = obtain_world_pose_from_view(view, None) - pos_w = pos_w.squeeze(0) if len(pos_w.shape) == 3 else pos_w - ori_w = ori_w.squeeze(0) if len(ori_w.shape) == 3 else ori_w - - if target_cfg.prim_expr in MultiMeshRayCaster.mesh_offsets: - pos_offset, ori_offset = MultiMeshRayCaster.mesh_offsets[target_cfg.prim_expr] - pos_w -= pos_offset - ori_w = math_utils.quat_mul(ori_offset.expand(ori_w.shape[0], -1), ori_w) - - count = view.count - if count != 1: # Mesh is not global, i.e. we have different meshes for each env - count = count // self._num_envs - pos_w = pos_w.view(self._num_envs, count, 3) - ori_w = ori_w.view(self._num_envs, count, 4) - - self._mesh_positions_w[:, mesh_idx : mesh_idx + count] = pos_w - self._mesh_orientations_w[:, mesh_idx : mesh_idx + count] = ori_w - mesh_idx += count - - # ray cast and store the hits - self.ray_hits_w[env_ids], ray_depth, ray_normal, _, ray_mesh_ids = raycast_dynamic_meshes( - self._ray_starts_w[env_ids], - self._ray_directions_w[env_ids], - mesh_ids_wp=self._mesh_ids_wp, # list with shape num_envs x num_meshes_per_env - max_dist=self.cfg.max_distance, - mesh_positions_w=self._mesh_positions_w[env_ids], - mesh_orientations_w=self._mesh_orientations_w[env_ids], - return_distance=any( - [name in self.cfg.data_types for name in ["distance_to_image_plane", "distance_to_camera"]] - ), - return_normal="normals" in self.cfg.data_types, - return_mesh_id=self.cfg.update_mesh_ids, + self._update_mesh_transforms() + + n_meshes = self._mesh_ids_wp.shape[1] + return_normal = "normals" in self.cfg.data_types + + # Fill ray hit and distance buffers with inf for masked environments + wp.launch( + fill_vec3_inf_kernel, + dim=(self._num_envs, self.num_rays), + inputs=[env_mask, float("inf"), self._ray_hits_w_cam], + device=self._device, + ) + wp.launch( + fill_float2d_masked_kernel, + dim=(self._num_envs, self.num_rays), + inputs=[env_mask, float("inf"), self._ray_distance_cam_w], + device=self._device, + ) + if return_normal: + wp.launch( + fill_vec3_inf_kernel, + dim=(self._num_envs, self.num_rays), + inputs=[env_mask, float("inf"), self._ray_normal_w], + device=self._device, + ) + + # Ray-cast against all meshes; closest hit wins via atomic_min on ray_distance + wp.launch( + warp_kernels.raycast_dynamic_meshes_kernel, + dim=(n_meshes, self._num_envs, self.num_rays), + inputs=[ + env_mask, + self._mesh_ids_wp, + self._ray_starts_w, + self._ray_directions_w, + self._ray_hits_w_cam, + self._ray_distance_cam_w, + self._ray_normal_w, + self._ray_face_id_w, + self._ray_mesh_id_w, + self._mesh_positions_w, + self._mesh_orientations_w, + float(CAMERA_RAYCAST_MAX_DIST), + int(return_normal), + int(False), + int(self.cfg.update_mesh_ids), + ], + device=self._device, ) - # update output buffers if "distance_to_image_plane" in self.cfg.data_types: - # note: data is in camera frame so we only take the first component (z-axis of camera frame) - distance_to_image_plane = ( - math_utils.quat_apply( - math_utils.quat_inv(self._data.quat_w_world[env_ids]).repeat(1, self.num_rays), - (ray_depth[:, :, None] * self._ray_directions_w[env_ids]), - ) - )[:, :, 0] - # apply the maximum distance after the transformation - if self.cfg.depth_clipping_behavior == "max": - distance_to_image_plane = torch.clip(distance_to_image_plane, max=self.cfg.max_distance) - distance_to_image_plane[torch.isnan(distance_to_image_plane)] = self.cfg.max_distance - elif self.cfg.depth_clipping_behavior == "zero": - distance_to_image_plane[distance_to_image_plane > self.cfg.max_distance] = 0.0 - distance_to_image_plane[torch.isnan(distance_to_image_plane)] = 0.0 - self._data.output["distance_to_image_plane"][env_ids] = distance_to_image_plane.view( - -1, *self.image_shape, 1 + wp.launch( + compute_distance_to_image_plane_masked_kernel, + dim=(self._num_envs, self.num_rays), + inputs=[env_mask, self._quat_w_wp, self._ray_distance_cam_w, self._ray_directions_w], + outputs=[self._distance_to_image_plane_wp], + device=self._device, ) + # Apply depth clipping on the intermediate buffer (leaves _ray_distance_cam_w unmodified) + self._apply_depth_clipping(env_mask, self._distance_to_image_plane_wp) + d2ip_torch = wp.to_torch(self._distance_to_image_plane_wp) + self._data.output["distance_to_image_plane"][env_ids] = d2ip_torch[env_ids].view(-1, *self.image_shape, 1) if "distance_to_camera" in self.cfg.data_types: - if self.cfg.depth_clipping_behavior == "max": - ray_depth = torch.clip(ray_depth, max=self.cfg.max_distance) - elif self.cfg.depth_clipping_behavior == "zero": - ray_depth[ray_depth > self.cfg.max_distance] = 0.0 - self._data.output["distance_to_camera"][env_ids] = ray_depth.view(-1, *self.image_shape, 1) + # d2ip (if requested) was computed before this block so _ray_distance_cam_w is still unclipped. + self._apply_depth_clipping(env_mask, self._ray_distance_cam_w) + ray_dist_torch = wp.to_torch(self._ray_distance_cam_w) + self._data.output["distance_to_camera"][env_ids] = ray_dist_torch[env_ids].view(-1, *self.image_shape, 1) - if "normals" in self.cfg.data_types: - self._data.output["normals"][env_ids] = ray_normal.view(-1, *self.image_shape, 3) + if return_normal: + ray_normal_torch = wp.to_torch(self._ray_normal_w) + self._data.output["normals"][env_ids] = ray_normal_torch[env_ids].view(-1, *self.image_shape, 3) if self.cfg.update_mesh_ids: - self._data.image_mesh_ids[env_ids] = ray_mesh_ids.view(-1, *self.image_shape, 1) + self._data.image_mesh_ids[env_ids] = wp.to_torch(self._ray_mesh_id_w)[env_ids].view( + -1, *self.image_shape, 1 + ) diff --git a/source/isaaclab/isaaclab/sensors/ray_caster/multi_mesh_ray_caster_camera_data.py b/source/isaaclab/isaaclab/sensors/ray_caster/multi_mesh_ray_caster_camera_data.py index d2f26abdbf47..21338f0a0616 100644 --- a/source/isaaclab/isaaclab/sensors/ray_caster/multi_mesh_ray_caster_camera_data.py +++ b/source/isaaclab/isaaclab/sensors/ray_caster/multi_mesh_ray_caster_camera_data.py @@ -9,11 +9,15 @@ from isaaclab.sensors.camera import CameraData -from .ray_caster_data import RayCasterData +class MultiMeshRayCasterCameraData(CameraData): + """Data container for the multi-mesh ray-cast camera sensor. -class MultiMeshRayCasterCameraData(CameraData, RayCasterData): - """Data container for the multi-mesh ray-cast sensor.""" + This class extends :class:`CameraData` with additional mesh-id information. + It does not inherit from :class:`RayCasterData` because the camera variant + manages its own torch-based pose and hit buffers independently from the + warp-native :class:`RayCasterData`. + """ image_mesh_ids: torch.Tensor = None """The mesh ids of the image pixels. diff --git a/source/isaaclab/isaaclab/sensors/ray_caster/ray_cast_utils.py b/source/isaaclab/isaaclab/sensors/ray_caster/ray_cast_utils.py deleted file mode 100644 index ac503b28bf52..000000000000 --- a/source/isaaclab/isaaclab/sensors/ray_caster/ray_cast_utils.py +++ /dev/null @@ -1,49 +0,0 @@ -# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). -# All rights reserved. -# -# SPDX-License-Identifier: BSD-3-Clause - -"""Utility functions for ray-cast sensors.""" - -from __future__ import annotations - -import torch -import warp as wp - -import omni.physics.tensors.impl.api as physx - -from isaaclab.sim.views import XformPrimView - - -def obtain_world_pose_from_view( - physx_view: XformPrimView | physx.ArticulationView | physx.RigidBodyView, - env_ids: torch.Tensor, - clone: bool = False, -) -> tuple[torch.Tensor, torch.Tensor]: - """Get the world poses of the prim referenced by the prim view. - - Args: - physx_view: The prim view to get the world poses from. - env_ids: The environment ids of the prims to get the world poses for. - clone: Whether to clone the returned tensors (default: False). - - Returns: - A tuple containing the world positions and orientations of the prims. - Orientation is in (x, y, z, w) format. - - Raises: - NotImplementedError: If the prim view is not of the supported type. - """ - if isinstance(physx_view, XformPrimView): - pos_w, quat_w = physx_view.get_world_poses(env_ids) - elif isinstance(physx_view, physx.ArticulationView): - pos_w, quat_w = wp.to_torch(physx_view.get_root_transforms())[env_ids].split([3, 4], dim=-1) - elif isinstance(physx_view, physx.RigidBodyView): - pos_w, quat_w = wp.to_torch(physx_view.get_transforms())[env_ids].split([3, 4], dim=-1) - else: - raise NotImplementedError(f"Cannot get world poses for prim view of type '{type(physx_view)}'.") - - if clone: - return pos_w.clone(), quat_w.clone() - else: - return pos_w, quat_w diff --git a/source/isaaclab/isaaclab/sensors/ray_caster/ray_caster.py b/source/isaaclab/isaaclab/sensors/ray_caster/ray_caster.py index 55a9d141132c..ab8ca8b7d4ce 100644 --- a/source/isaaclab/isaaclab/sensors/ray_caster/ray_caster.py +++ b/source/isaaclab/isaaclab/sensors/ray_caster/ray_caster.py @@ -13,24 +13,27 @@ import torch import warp as wp -from pxr import Gf, Usd, UsdGeom, UsdPhysics +from pxr import Gf, Usd, UsdGeom import isaaclab.sim as sim_utils import isaaclab.utils.math as math_utils from isaaclab.markers import VisualizationMarkers -from isaaclab.sim.views import XformPrimView +from isaaclab.sim.views import FrameView from isaaclab.terrains.trimesh.utils import make_plane -from isaaclab.utils.math import quat_apply, quat_apply_yaw -from isaaclab.utils.warp import convert_to_warp_mesh, raycast_mesh +from isaaclab.utils.warp import convert_to_warp_mesh +from isaaclab.utils.warp.kernels import raycast_mesh_masked_kernel from ..sensor_base import SensorBase -from .ray_cast_utils import obtain_world_pose_from_view +from .kernels import ( + apply_z_drift_kernel, + fill_vec3_inf_kernel, + update_ray_caster_kernel, +) from .ray_caster_data import RayCasterData if TYPE_CHECKING: from .ray_caster_cfg import RayCasterCfg -# import logger logger = logging.getLogger(__name__) @@ -42,8 +45,8 @@ class RayCaster(SensorBase): a set of meshes with a given ray pattern. The meshes are parsed from the list of primitive paths provided in the configuration. These are then - converted to warp meshes and stored in the `warp_meshes` list. The ray-caster then ray-casts against - these warp meshes using the ray pattern provided in the configuration. + converted to warp meshes and stored in the :attr:`meshes` dictionary. The ray-caster then ray-casts + against these warp meshes using the ray pattern provided in the configuration. .. note:: Currently, only static meshes are supported. Extending the warp mesh to support dynamic meshes @@ -53,11 +56,12 @@ class RayCaster(SensorBase): cfg: RayCasterCfg """The configuration parameters.""" - # Class variables to share meshes across instances - meshes: ClassVar[dict[str, wp.Mesh]] = {} + meshes: ClassVar[dict[tuple[str, str], wp.Mesh]] = {} """A dictionary to store warp meshes for raycasting, shared across all instances. - The keys correspond to the prim path for the meshes, and values are the corresponding warp Mesh objects.""" + The keys are ``(prim_path, device)`` tuples and values are the corresponding warp Mesh objects. + Including the device in the key prevents a mesh created on one device (e.g. CPU) from being + reused by a kernel running on a different device (e.g. CUDA).""" _instance_count: ClassVar[int] = 0 """A counter to track the number of RayCaster instances, used to manage class variable lifecycle.""" @@ -68,9 +72,9 @@ def __init__(self, cfg: RayCasterCfg): cfg: The configuration parameters. """ RayCaster._instance_count += 1 - # Initialize base class super().__init__(cfg) - # Create empty variables for storing output data + # Resolve physics-body paths and spawn the sensor Xform child if needed. + self._resolve_and_spawn("raycaster") self._data = RayCasterData() def __str__(self) -> str: @@ -116,10 +120,10 @@ def reset(self, env_ids: Sequence[int] | None = None, env_mask: wp.array | None else: env_ids = slice(None) num_envs_ids = self._view.count - # resample the drift + # resample drift (uses torch views for indexing) r = torch.empty(num_envs_ids, 3, device=self.device) self.drift[env_ids] = r.uniform_(*self.cfg.drift_range) - # resample the height drift + # resample the ray cast drift range_list = [self.cfg.ray_cast_drift_range.get(key, (0.0, 0.0)) for key in ["x", "y", "z"]] ranges = torch.tensor(range_list, device=self.device) self.ray_cast_drift[env_ids] = math_utils.sample_uniform( @@ -132,21 +136,28 @@ def reset(self, env_ids: Sequence[int] | None = None, env_mask: wp.array | None def _initialize_impl(self): super()._initialize_impl() - # obtain global simulation view - - self._physics_sim_view = sim_utils.SimulationContext.instance().physics_manager.get_physics_sim_view() - prim = sim_utils.find_first_matching_prim(self.cfg.prim_path) - if prim is None: - available_prims = ",".join([str(p.GetPath()) for p in sim_utils.get_current_stage().Traverse()]) - raise RuntimeError( - f"Failed to find a prim at path expression: {self.cfg.prim_path}. Available prims: {available_prims}" - ) - - self._view, self._offset = self._obtain_trackable_prim_view(self.cfg.prim_path) + # Build a FrameView over the sensor prim paths. The FrameView tracks the spawned + # (non-physics) Xform directly, so no physics-body redirect or offset resolution + # is needed at runtime — the world pose returned already includes any offset + # baked into the prim's local transform. + self._view = FrameView(self.cfg.prim_path, device=self._device, stage=self.stage) + + # Per-env identity offsets (kept for kernel ABI compatibility): the sensor frame is + # already the FrameView's tracked prim, so no additional view-to-sensor offset applies. + self._offset_pos_wp = wp.zeros(self._view.count, dtype=wp.vec3f, device=self._device) + identity_quat = torch.zeros(self._view.count, 4, device=self._device) + identity_quat[:, 3] = 1.0 + self._offset_quat_contiguous = identity_quat.contiguous() + self._offset_quat_wp = wp.from_torch(self._offset_quat_contiguous, dtype=wp.quatf) + + # Resolve alignment mode to integer constant for kernel dispatch + alignment_map = {"world": 0, "yaw": 1, "base": 2} + if self.cfg.ray_alignment not in alignment_map: + raise RuntimeError(f"Unsupported ray_alignment type: {self.cfg.ray_alignment}.") + self._alignment_mode = alignment_map[self.cfg.ray_alignment] # load the meshes by parsing the stage self._initialize_warp_meshes() - # initialize the ray start and directions self._initialize_rays_impl() def _initialize_warp_meshes(self): @@ -158,254 +169,195 @@ def _initialize_warp_meshes(self): # read prims to ray-cast for mesh_prim_path in self.cfg.mesh_prim_paths: - # check if mesh already casted into warp mesh - if mesh_prim_path in RayCaster.meshes: + mesh_key = (mesh_prim_path, self._device) + if mesh_key in RayCaster.meshes: continue - # check if the prim is a plane - handle PhysX plane as a special case - # if a plane exists then we need to create an infinite mesh that is a plane mesh_prim = sim_utils.get_first_matching_child_prim( mesh_prim_path, lambda prim: prim.GetTypeName() == "Plane" ) - # if we did not find a plane then we need to read the mesh if mesh_prim is None: - # obtain the mesh prim mesh_prim = sim_utils.get_first_matching_child_prim( mesh_prim_path, lambda prim: prim.GetTypeName() == "Mesh" ) - # check if valid if mesh_prim is None or not mesh_prim.IsValid(): raise RuntimeError(f"Invalid mesh prim path: {mesh_prim_path}") - # cast into UsdGeomMesh mesh_prim = UsdGeom.Mesh(mesh_prim) - # read the vertices and faces points = np.asarray(mesh_prim.GetPointsAttr().Get()) - # Get world transform using pure USD (UsdGeom.Xformable) xformable = UsdGeom.Xformable(mesh_prim) world_transform: Gf.Matrix4d = xformable.ComputeLocalToWorldTransform(Usd.TimeCode.Default()) transform_matrix = np.array(world_transform).T points = np.matmul(points, transform_matrix[:3, :3].T) points += transform_matrix[:3, 3] indices = np.asarray(mesh_prim.GetFaceVertexIndicesAttr().Get()) - wp_mesh = convert_to_warp_mesh(points, indices, device=self.device) - # print info + wp_mesh = convert_to_warp_mesh(points, indices, device=self._device) logger.info( f"Read mesh prim: {mesh_prim.GetPath()} with {len(points)} vertices and {len(indices)} faces." ) else: mesh = make_plane(size=(2e6, 2e6), height=0.0, center_zero=True) - wp_mesh = convert_to_warp_mesh(mesh.vertices, mesh.faces, device=self.device) - # print info + wp_mesh = convert_to_warp_mesh(mesh.vertices, mesh.faces, device=self._device) logger.info(f"Created infinite plane mesh prim: {mesh_prim.GetPath()}.") - # add the warp mesh to the list - RayCaster.meshes[mesh_prim_path] = wp_mesh + RayCaster.meshes[mesh_key] = wp_mesh - # throw an error if no meshes are found - if all([mesh_prim_path not in RayCaster.meshes for mesh_prim_path in self.cfg.mesh_prim_paths]): + if all((mesh_prim_path, self._device) not in RayCaster.meshes for mesh_prim_path in self.cfg.mesh_prim_paths): raise RuntimeError( f"No meshes found for ray-casting! Please check the mesh prim paths: {self.cfg.mesh_prim_paths}" ) def _initialize_rays_impl(self): - # compute ray stars and directions - self.ray_starts, self.ray_directions = self.cfg.pattern_cfg.func(self.cfg.pattern_cfg, self._device) - self.num_rays = len(self.ray_directions) - # apply offset transformation to the rays + # Compute ray starts and directions from pattern (torch, init-time only) + ray_starts_torch, ray_directions_torch = self.cfg.pattern_cfg.func(self.cfg.pattern_cfg, self._device) + self.num_rays = len(ray_directions_torch) + + # Apply sensor offset rotation/position to local ray pattern offset_pos = torch.tensor(list(self.cfg.offset.pos), device=self._device) offset_quat = torch.tensor(list(self.cfg.offset.rot), device=self._device) - self.ray_directions = quat_apply(offset_quat.repeat(len(self.ray_directions), 1), self.ray_directions) - self.ray_starts += offset_pos - # repeat the rays for each sensor - self.ray_starts = self.ray_starts.repeat(self._view.count, 1, 1) - self.ray_directions = self.ray_directions.repeat(self._view.count, 1, 1) - # prepare drift - self.drift = torch.zeros(self._view.count, 3, device=self.device) - self.ray_cast_drift = torch.zeros(self._view.count, 3, device=self.device) - # fill the data buffer - self._data.pos_w = torch.zeros(self._view.count, 3, device=self.device) - self._data.quat_w = torch.zeros(self._view.count, 4, device=self.device) - self._data.ray_hits_w = torch.zeros(self._view.count, self.num_rays, 3, device=self.device) - self._ray_starts_w = torch.zeros(self._view.count, self.num_rays, 3, device=self.device) - self._ray_directions_w = torch.zeros(self._view.count, self.num_rays, 3, device=self.device) - - def _update_ray_infos(self, env_ids: Sequence[int]): - """Updates the ray information buffers.""" - - pos_w, quat_w = obtain_world_pose_from_view(self._view, env_ids) - pos_w, quat_w = math_utils.combine_frame_transforms( - pos_w, quat_w, self._offset[0][env_ids], self._offset[1][env_ids] + ray_directions_torch = math_utils.quat_apply( + offset_quat.repeat(len(ray_directions_torch), 1), ray_directions_torch ) - # apply drift to ray starting position in world frame - pos_w += self.drift[env_ids] - # store the poses - self._data.pos_w[env_ids] = pos_w - self._data.quat_w[env_ids] = quat_w - - # check if user provided attach_yaw_only flag - if self.cfg.attach_yaw_only is not None: - msg = ( - "Raycaster attribute 'attach_yaw_only' property will be deprecated in a future release." - " Please use the parameter 'ray_alignment' instead." - ) - # set ray alignment to yaw - if self.cfg.attach_yaw_only: - self.cfg.ray_alignment = "yaw" - msg += " Setting ray_alignment to 'yaw'." - else: - self.cfg.ray_alignment = "base" - msg += " Setting ray_alignment to 'base'." - # log the warning - logger.warning(msg) - # ray cast based on the sensor poses - if self.cfg.ray_alignment == "world": - # apply horizontal drift to ray starting position in ray caster frame - pos_w[:, 0:2] += self.ray_cast_drift[env_ids, 0:2] - # no rotation is considered and directions are not rotated - ray_starts_w = self.ray_starts[env_ids] - ray_starts_w += pos_w.unsqueeze(1) - ray_directions_w = self.ray_directions[env_ids] - elif self.cfg.ray_alignment == "yaw": - # apply horizontal drift to ray starting position in ray caster frame - pos_w[:, 0:2] += quat_apply_yaw(quat_w, self.ray_cast_drift[env_ids])[:, 0:2] - # only yaw orientation is considered and directions are not rotated - ray_starts_w = quat_apply_yaw(quat_w.repeat(1, self.num_rays), self.ray_starts[env_ids]) - ray_starts_w += pos_w.unsqueeze(1) - ray_directions_w = self.ray_directions[env_ids] - elif self.cfg.ray_alignment == "base": - # apply horizontal drift to ray starting position in ray caster frame - pos_w[:, 0:2] += quat_apply(quat_w, self.ray_cast_drift[env_ids])[:, 0:2] - # full orientation is considered - ray_starts_w = quat_apply(quat_w.repeat(1, self.num_rays), self.ray_starts[env_ids]) - ray_starts_w += pos_w.unsqueeze(1) - ray_directions_w = quat_apply(quat_w.repeat(1, self.num_rays), self.ray_directions[env_ids]) - else: - raise RuntimeError(f"Unsupported ray_alignment type: {self.cfg.ray_alignment}.") + ray_starts_torch += offset_pos + + # Repeat for each environment + ray_starts_torch = ray_starts_torch.repeat(self._view.count, 1, 1) + ray_directions_torch = ray_directions_torch.repeat(self._view.count, 1, 1) + + # Create warp arrays from the init-time torch data + # The warp arrays own the memory; torch views provide backward-compat indexing + self._ray_starts_local = wp.from_torch(ray_starts_torch.contiguous(), dtype=wp.vec3f) + self._ray_directions_local = wp.from_torch(ray_directions_torch.contiguous(), dtype=wp.vec3f) + + # Torch views (same attribute names as before for subclass compatibility) + self.ray_starts = wp.to_torch(self._ray_starts_local) + self.ray_directions = wp.to_torch(self._ray_directions_local) - self._ray_starts_w[env_ids] = ray_starts_w - self._ray_directions_w[env_ids] = ray_directions_w + # Drift buffers (warp-owned, torch views for reset indexing) + self._drift = wp.zeros(self._view.count, dtype=wp.vec3f, device=self._device) + self._ray_cast_drift = wp.zeros(self._view.count, dtype=wp.vec3f, device=self._device) + self.drift = wp.to_torch(self._drift) + self.ray_cast_drift = wp.to_torch(self._ray_cast_drift) + + # World-frame ray buffers + self._ray_starts_w = wp.zeros((self._view.count, self.num_rays), dtype=wp.vec3f, device=self._device) + self._ray_directions_w = wp.zeros((self._view.count, self.num_rays), dtype=wp.vec3f, device=self._device) + + # Torch views for subclass compatibility + self._ray_starts_w_torch = wp.to_torch(self._ray_starts_w) + self._ray_directions_w_torch = wp.to_torch(self._ray_directions_w) + + # Data buffers + self._data.create_buffers(self._view.count, self.num_rays, self._device) + + # Dummy distance/normal buffers required by the merged raycast_mesh_masked_kernel signature. + # Sized (1, 1) even though the kernel is launched at (num_envs, num_rays): the kernel only + # writes to these buffers when return_distance==1 or return_normal==1 respectively, and + # RayCaster always passes 0 for both flags. If those flags are ever enabled here, these + # buffers must be resized to (num_envs, num_rays) to avoid an out-of-bounds write. + self._dummy_ray_distance = wp.empty((1, 1), dtype=wp.float32, device=self._device) + self._dummy_ray_normal = wp.empty((1, 1), dtype=wp.vec3f, device=self._device) + + def _get_view_transforms_wp(self) -> wp.array: + """Get world transforms from the frame view as a warp array of ``wp.transformf``. + + Returns: + Warp array of ``wp.transformf`` with shape ``(num_envs,)``. Layout is + ``(tx, ty, tz, qx, qy, qz, qw)`` per element, matching the quaternion + convention returned by :class:`~isaaclab.sim.views.FrameView`. + """ + pos_w, quat_w = self._view.get_world_poses() + pos_torch = pos_w.torch.reshape(-1, 3) + quat_torch = quat_w.torch.reshape(-1, 4) + poses = torch.cat([pos_torch, quat_torch], dim=-1).contiguous() + return wp.from_torch(poses).view(wp.transformf) + + def _update_ray_infos(self, env_mask: wp.array): + """Updates sensor poses and ray world-frame buffers via a single warp kernel.""" + transforms = self._get_view_transforms_wp() + + wp.launch( + update_ray_caster_kernel, + dim=(self._num_envs, self.num_rays), + inputs=[ + transforms, + env_mask, + self._offset_pos_wp, + self._offset_quat_wp, + self._drift, + self._ray_cast_drift, + self._ray_starts_local, + self._ray_directions_local, + self._alignment_mode, + ], + outputs=[ + self._data._pos_w, + self._data._quat_w, + self._ray_starts_w, + self._ray_directions_w, + ], + device=self._device, + ) def _update_buffers_impl(self, env_mask: wp.array): """Fills the buffers of the sensor data.""" - env_ids = wp.to_torch(env_mask).nonzero(as_tuple=False).squeeze(-1) - if len(env_ids) == 0: - return - self._update_ray_infos(env_ids) + self._update_ray_infos(env_mask) + + # Fill ray hits with inf before raycasting + wp.launch( + fill_vec3_inf_kernel, + dim=(self._num_envs, self.num_rays), + inputs=[env_mask, float("inf"), self._data._ray_hits_w], + device=self._device, + ) - # ray cast and store the hits - # TODO: Make this work for multiple meshes? - self._data.ray_hits_w[env_ids] = raycast_mesh( - self._ray_starts_w[env_ids], - self._ray_directions_w[env_ids], - max_dist=self.cfg.max_distance, - mesh=RayCaster.meshes[self.cfg.mesh_prim_paths[0]], - )[0] + # Ray-cast against the mesh + wp.launch( + raycast_mesh_masked_kernel, + dim=(self._num_envs, self.num_rays), + inputs=[ + RayCaster.meshes[(self.cfg.mesh_prim_paths[0], self._device)].id, + env_mask, + self._ray_starts_w, + self._ray_directions_w, + float(self.cfg.max_distance), + int(False), # return_distance: not needed by RayCaster + int(False), # return_normal: not needed by RayCaster + self._data._ray_hits_w, + self._dummy_ray_distance, + self._dummy_ray_normal, + ], + device=self._device, + ) - # apply vertical drift to ray starting position in ray caster frame - self._data.ray_hits_w[env_ids, :, 2] += self.ray_cast_drift[env_ids, 2].unsqueeze(-1) + # Apply vertical drift to ray hits + wp.launch( + apply_z_drift_kernel, + dim=(self._num_envs, self.num_rays), + inputs=[env_mask, self._ray_cast_drift, self._data._ray_hits_w], + device=self._device, + ) def _set_debug_vis_impl(self, debug_vis: bool): - # set visibility of markers - # note: parent only deals with callbacks. not their visibility if debug_vis: if not hasattr(self, "ray_visualizer"): self.ray_visualizer = VisualizationMarkers(self.cfg.visualizer_cfg) - # set their visibility to true self.ray_visualizer.set_visibility(True) else: if hasattr(self, "ray_visualizer"): self.ray_visualizer.set_visibility(False) def _debug_vis_callback(self, event): - if self._data.ray_hits_w is None: + if self._data._ray_hits_w is None: return + ray_hits_torch = wp.to_torch(self._data._ray_hits_w) # remove possible inf values - viz_points = self._data.ray_hits_w.reshape(-1, 3) + viz_points = ray_hits_torch.reshape(-1, 3) viz_points = viz_points[~torch.any(torch.isinf(viz_points), dim=1)] - self.ray_visualizer.visualize(viz_points) - - """ - Internal Helpers. - """ - - def _obtain_trackable_prim_view( - self, target_prim_path: str - ) -> tuple[XformPrimView | any, tuple[torch.Tensor, torch.Tensor]]: - """Obtain a prim view that can be used to track the pose of the parget prim. - - The target prim path is a regex expression that matches one or more mesh prims. While we can track its - pose directly using XFormPrim, this is not efficient and can be slow. Instead, we create a prim view - using the physics simulation view, which provides a more efficient way to track the pose of the mesh prims. - - The function additionally resolves the relative pose between the mesh and its corresponding physics prim. - This is especially useful if the mesh is not directly parented to the physics prim. - - Args: - target_prim_path: The target prim path to obtain the prim view for. - - Returns: - A tuple containing: - - - An XFormPrim or a physics prim view (ArticulationView or RigidBodyView). - - A tuple containing the positions and orientations of the mesh prims in the physics prim frame. - - """ - - mesh_prim = sim_utils.find_first_matching_prim(target_prim_path) - current_prim = mesh_prim - current_path_expr = target_prim_path - - prim_view = None - - while prim_view is None: - # TODO: Need to handle the case where API is present but it is disabled - if current_prim.HasAPI(UsdPhysics.ArticulationRootAPI): - prim_view = self._physics_sim_view.create_articulation_view(current_path_expr.replace(".*", "*")) - logger.info(f"Created articulation view for mesh prim at path: {target_prim_path}") - break - - # TODO: Need to handle the case where API is present but it is disabled - if current_prim.HasAPI(UsdPhysics.RigidBodyAPI): - prim_view = self._physics_sim_view.create_rigid_body_view(current_path_expr.replace(".*", "*")) - logger.info(f"Created rigid body view for mesh prim at path: {target_prim_path}") - break - - new_root_prim = current_prim.GetParent() - current_path_expr = current_path_expr.rsplit("/", 1)[0] - if not new_root_prim.IsValid(): - prim_view = XformPrimView(target_prim_path, device=self._device, stage=self.stage) - current_path_expr = target_prim_path - logger.warning( - f"The prim at path {target_prim_path} which is used for raycasting is not a physics prim." - " Defaulting to XFormPrim. \n The pose of the mesh will most likely not" - " be updated correctly when running in headless mode and position lookups will be much slower. \n" - " If possible, ensure that the mesh or its parent is a physics prim (rigid body or articulation)." - ) - break - - # switch the current prim to the parent prim - current_prim = new_root_prim - - # obtain the relative transforms between target prim and the view prims - mesh_prims = sim_utils.find_matching_prims(target_prim_path) - view_prims = sim_utils.find_matching_prims(current_path_expr) - if len(mesh_prims) != len(view_prims): - raise RuntimeError( - f"The number of mesh prims ({len(mesh_prims)}) does not match the number of physics prims" - f" ({len(view_prims)})Please specify the correct mesh and physics prim paths more" - " specifically in your target expressions." - ) - positions = [] - quaternions = [] - for mesh_prim, view_prim in zip(mesh_prims, view_prims): - pos, orientation = sim_utils.resolve_prim_pose(mesh_prim, view_prim) - positions.append(torch.tensor(pos, dtype=torch.float32, device=self.device)) - quaternions.append(torch.tensor(orientation, dtype=torch.float32, device=self.device)) - - positions = torch.stack(positions).to(device=self.device, dtype=torch.float32) - quaternions = torch.stack(quaternions).to(device=self.device, dtype=torch.float32) + # if no points to visualize, skip + if viz_points.shape[0] == 0: + return - return prim_view, (positions, quaternions) + self.ray_visualizer.visualize(viz_points) """ Internal simulation callbacks. @@ -413,9 +365,7 @@ def _obtain_trackable_prim_view( def _invalidate_initialize_callback(self, event): """Invalidates the scene elements.""" - # call parent super()._invalidate_initialize_callback(event) - # set all existing views to None to invalidate them self._view = None def __del__(self): diff --git a/source/isaaclab/isaaclab/sensors/ray_caster/ray_caster_camera.py b/source/isaaclab/isaaclab/sensors/ray_caster/ray_caster_camera.py index 880b81db5833..257b25698deb 100644 --- a/source/isaaclab/isaaclab/sensors/ray_caster/ray_caster_camera.py +++ b/source/isaaclab/isaaclab/sensors/ray_caster/ray_caster_camera.py @@ -16,9 +16,17 @@ import isaaclab.utils.math as math_utils from isaaclab.sensors.camera import CameraData -from isaaclab.utils.warp import raycast_mesh - -from .ray_cast_utils import obtain_world_pose_from_view +from isaaclab.utils.warp.kernels import raycast_mesh_masked_kernel + +from .kernels import ( + ALIGNMENT_BASE, + CAMERA_RAYCAST_MAX_DIST, + apply_depth_clipping_masked_kernel, + compute_distance_to_image_plane_masked_kernel, + fill_float2d_masked_kernel, + fill_vec3_inf_kernel, + update_ray_caster_kernel, +) from .ray_caster import RayCaster if TYPE_CHECKING: @@ -143,6 +151,13 @@ def set_intrinsic_matrices( self.ray_starts[env_ids], self.ray_directions[env_ids] = self.cfg.pattern_cfg.func( self.cfg.pattern_cfg, self._data.intrinsic_matrices[env_ids], self._device ) + # Refresh warp views of local ray buffers; .contiguous() may produce a copy so we store + # the contiguous tensors explicitly to prevent GC while the warp views are alive. + if hasattr(self, "_ray_starts_local"): + self._ray_starts_contiguous = self.ray_starts.contiguous() + self._ray_directions_contiguous = self.ray_directions.contiguous() + self._ray_starts_local = wp.from_torch(self._ray_starts_contiguous, dtype=wp.vec3f) + self._ray_directions_local = wp.from_torch(self._ray_directions_contiguous, dtype=wp.vec3f) def reset(self, env_ids: Sequence[int] | None = None, env_mask: wp.array | None = None): # reset the timestamps @@ -152,11 +167,14 @@ def reset(self, env_ids: Sequence[int] | None = None, env_mask: wp.array | None env_ids = wp.to_torch(env_mask).nonzero(as_tuple=False).squeeze(-1) elif env_ids is None or isinstance(env_ids, slice): env_ids = self._ALL_INDICES + if not isinstance(env_ids, torch.Tensor): + env_ids = torch.tensor(env_ids, dtype=torch.long, device=self._device) # reset the data # note: this recomputation is useful if one performs events such as randomizations on the camera poses. - pos_w, quat_w = obtain_world_pose_from_view(self._view, env_ids, clone=True) + indices = wp.from_torch(env_ids.to(dtype=torch.int32), dtype=wp.int32) if env_ids is not None else None + pos_w, quat_w = self._view.get_world_poses(indices) pos_w, quat_w = math_utils.combine_frame_transforms( - pos_w, quat_w, self._offset_pos[env_ids], self._offset_quat[env_ids] + pos_w.torch.clone(), quat_w.torch.clone(), self._offset_pos[env_ids], self._offset_quat[env_ids] ) self._data.pos_w[env_ids] = pos_w self._data.quat_w_world[env_ids] = quat_w @@ -179,7 +197,7 @@ def set_world_poses( - :obj:`"ros"` - forward axis: +Z - up axis -Y - Offset is applied in the ROS convention - :obj:`"world"` - forward axis: +X - up axis +Z - Offset is applied in the World Frame convention - See :meth:`isaaclab.utils.maths.convert_camera_frame_orientation_convention` for more details + See :meth:`isaaclab.utils.math.convert_camera_frame_orientation_convention` for more details on the conventions. Args: @@ -198,25 +216,28 @@ def set_world_poses( env_ids = self._ALL_INDICES # get current positions - pos_w, quat_w = obtain_world_pose_from_view(self._view, env_ids) + indices = wp.from_torch(env_ids.to(dtype=torch.int32), dtype=wp.int32) if env_ids is not None else None + pos_w, quat_w = self._view.get_world_poses(indices) + pos_w_torch = pos_w.torch + quat_w_torch = quat_w.torch if positions is not None: # transform to camera frame - pos_offset_world_frame = positions - pos_w - self._offset_pos[env_ids] = math_utils.quat_apply(math_utils.quat_inv(quat_w), pos_offset_world_frame) + pos_offset_world_frame = positions - pos_w_torch + self._offset_pos[env_ids] = math_utils.quat_apply(math_utils.quat_inv(quat_w_torch), pos_offset_world_frame) if orientations is not None: # convert rotation matrix from input convention to world quat_w_set = math_utils.convert_camera_frame_orientation_convention( orientations, origin=convention, target="world" ) - self._offset_quat[env_ids] = math_utils.quat_mul(math_utils.quat_inv(quat_w), quat_w_set) + self._offset_quat[env_ids] = math_utils.quat_mul(math_utils.quat_inv(quat_w_torch), quat_w_set) # update the data - pos_w, quat_w = obtain_world_pose_from_view(self._view, env_ids, clone=True) - pos_w, quat_w = math_utils.combine_frame_transforms( - pos_w, quat_w, self._offset_pos[env_ids], self._offset_quat[env_ids] + pos_w2, quat_w2 = self._view.get_world_poses(indices) + pos_w_out, quat_w_out = math_utils.combine_frame_transforms( + pos_w2.torch.clone(), quat_w2.torch.clone(), self._offset_pos[env_ids], self._offset_quat[env_ids] ) - self._data.pos_w[env_ids] = pos_w - self._data.quat_w_world[env_ids] = quat_w + self._data.pos_w[env_ids] = pos_w_out + self._data.quat_w_world[env_ids] = quat_w_out def set_world_poses_from_view( self, eyes: torch.Tensor, targets: torch.Tensor, env_ids: Sequence[int] | None = None @@ -224,7 +245,7 @@ def set_world_poses_from_view( """Set the poses of the camera from the eye position and look-at target position. Args: - eyes: The positions of the camera's eye. Shape is N, 3). + eyes: The positions of the camera's eye. Shape is (N, 3). targets: The target locations to look at. Shape is (N, 3). env_ids: A sensor ids to manipulate. Defaults to None, which means all sensor indices. @@ -253,100 +274,243 @@ def _initialize_rays_impl(self): self._create_buffers() # compute intrinsic matrices self._compute_intrinsic_matrices() - # compute ray stars and directions + # compute ray starts and directions self.ray_starts, self.ray_directions = self.cfg.pattern_cfg.func( self.cfg.pattern_cfg, self._data.intrinsic_matrices, self._device ) self.num_rays = self.ray_directions.shape[1] - # create buffer to store ray hits - self.ray_hits_w = torch.zeros(self._view.count, self.num_rays, 3, device=self._device) - # set offsets + + # Offset buffers: warp-primary so the kernel always sees the current values without re-wrapping. + # Zero-copy torch views (_offset_pos, _offset_quat) are used by set_world_poses for indexed writes. + self._offset_pos_wp = wp.zeros(self._view.count, dtype=wp.vec3f, device=self._device) + self._offset_quat_wp = wp.zeros(self._view.count, dtype=wp.quatf, device=self._device) + self._offset_pos = wp.to_torch(self._offset_pos_wp) + self._offset_quat = wp.to_torch(self._offset_quat_wp) + # Initialize from config quat_w = math_utils.convert_camera_frame_orientation_convention( torch.tensor([self.cfg.offset.rot], device=self._device), origin=self.cfg.offset.convention, target="world" ) - self._offset_quat = quat_w.repeat(self._view.count, 1) - self._offset_pos = torch.tensor(list(self.cfg.offset.pos), device=self._device).repeat(self._view.count, 1) + self._offset_pos[:] = torch.tensor(list(self.cfg.offset.pos), device=self._device) + self._offset_quat[:] = quat_w + + # Warp buffers for world-frame rays (used by update kernel) + self._ray_starts_w = wp.zeros((self._view.count, self.num_rays), dtype=wp.vec3f, device=self._device) + self._ray_directions_w = wp.zeros((self._view.count, self.num_rays), dtype=wp.vec3f, device=self._device) + + # Warp views for ray_starts and ray_directions (from torch tensors returned by pattern_cfg.func) + # These are (num_envs, num_rays, 3) torch tensors; wrap as warp vec3f arrays. + # Store contiguous tensors explicitly so they are not garbage-collected while the + # warp views are alive (mirrors the pattern in RayCaster._initialize_impl). + self._ray_starts_contiguous = self.ray_starts.contiguous() + self._ray_directions_contiguous = self.ray_directions.contiguous() + self._ray_starts_local = wp.from_torch(self._ray_starts_contiguous, dtype=wp.vec3f) + self._ray_directions_local = wp.from_torch(self._ray_directions_contiguous, dtype=wp.vec3f) + + # Wrap the torch drift buffers (created in _create_buffers) as warp arrays (zero-copy). + # Cameras do not apply positional drift, so these remain zero. + self._drift_contiguous = self.drift.contiguous() + self._ray_cast_drift_contiguous = self.ray_cast_drift.contiguous() + self._drift = wp.from_torch(self._drift_contiguous, dtype=wp.vec3f) + self._ray_cast_drift = wp.from_torch(self._ray_cast_drift_contiguous, dtype=wp.vec3f) + + # Warp buffers for camera pose outputs + self._pos_w_wp = wp.zeros(self._view.count, dtype=wp.vec3f, device=self._device) + self._quat_w_wp = wp.zeros(self._view.count, dtype=wp.quatf, device=self._device) + + # Intermediate warp buffers for ray results (filled with inf before each raycasting step) + self._ray_distance = wp.zeros((self._view.count, self.num_rays), dtype=wp.float32, device=self._device) + if "normals" in self.cfg.data_types: + self._ray_normal_w = wp.zeros((self._view.count, self.num_rays), dtype=wp.vec3f, device=self._device) + else: + self._ray_normal_w = wp.zeros((1, 1), dtype=wp.vec3f, device=self._device) + + if "distance_to_image_plane" in self.cfg.data_types: + self._distance_to_image_plane_wp = wp.zeros( + (self._view.count, self.num_rays), dtype=wp.float32, device=self._device + ) + + # Torch buffer for ray hits (used by debug visualizer) + self.ray_hits_w = torch.full((self._view.count, self.num_rays, 3), float("inf"), device=self._device) + # Warp view of ray_hits_w + self._ray_hits_w_wp = wp.from_torch(self.ray_hits_w.contiguous(), dtype=wp.vec3f) + + # Cache zero-copy torch views of warp output buffers to avoid per-step wrapper allocation. + self._pos_w_torch = wp.to_torch(self._pos_w_wp) + self._quat_w_torch = wp.to_torch(self._quat_w_wp) + self._ray_distance_torch = wp.to_torch(self._ray_distance) + if "distance_to_image_plane" in self.cfg.data_types: + self._distance_to_image_plane_torch = wp.to_torch(self._distance_to_image_plane_wp) + if "normals" in self.cfg.data_types: + self._ray_normal_w_torch = wp.to_torch(self._ray_normal_w) def _update_buffers_impl(self, env_mask: wp.array): """Fills the buffers of the sensor data.""" + # Convert mask to indices for torch-indexed writes env_ids = wp.to_torch(env_mask).nonzero(as_tuple=False).squeeze(-1) if len(env_ids) == 0: return # increment frame count self._frame[env_ids] += 1 - # compute poses from current view - pos_w, quat_w = obtain_world_pose_from_view(self._view, env_ids, clone=True) - pos_w, quat_w = math_utils.combine_frame_transforms( - pos_w, quat_w, self._offset_pos[env_ids], self._offset_quat[env_ids] + # Update world-frame ray starts/directions and camera pose via warp kernel. + # Camera always uses ALIGNMENT_BASE (full orientation) and zero drift. + transforms = self._get_view_transforms_wp() + wp.launch( + update_ray_caster_kernel, + dim=(self._num_envs, self.num_rays), + inputs=[ + transforms, + env_mask, + self._offset_pos_wp, + self._offset_quat_wp, + self._drift, + self._ray_cast_drift, + self._ray_starts_local, + self._ray_directions_local, + int(ALIGNMENT_BASE), + ], + outputs=[ + self._pos_w_wp, + self._quat_w_wp, + self._ray_starts_w, + self._ray_directions_w, + ], + device=self._device, ) - # update the data - self._data.pos_w[env_ids] = pos_w - self._data.quat_w_world[env_ids] = quat_w - # note: full orientation is considered - ray_starts_w = math_utils.quat_apply(quat_w.repeat(1, self.num_rays), self.ray_starts[env_ids]) - ray_starts_w += pos_w.unsqueeze(1) - ray_directions_w = math_utils.quat_apply(quat_w.repeat(1, self.num_rays), self.ray_directions[env_ids]) - - # ray cast and store the hits - # note: we set max distance to 1e6 during the ray-casting. THis is because we clip the distance - # to the image plane and distance to the camera to the maximum distance afterwards in-order to - # match the USD camera behavior. - - # TODO: Make ray-casting work for multiple meshes? - # necessary for regular dictionaries. - self.ray_hits_w, ray_depth, ray_normal, _ = raycast_mesh( - ray_starts_w, - ray_directions_w, - mesh=RayCaster.meshes[self.cfg.mesh_prim_paths[0]], - max_dist=1e6, - return_distance=any( - [name in self.cfg.data_types for name in ["distance_to_image_plane", "distance_to_camera"]] - ), - return_normal="normals" in self.cfg.data_types, + # Write camera pose to CameraData (torch tensors) + self._data.pos_w[env_ids] = self._pos_w_torch[env_ids] + self._data.quat_w_world[env_ids] = self._quat_w_torch[env_ids] + + # Fill ray hit positions with inf before raycasting + wp.launch( + fill_vec3_inf_kernel, + dim=(self._num_envs, self.num_rays), + inputs=[env_mask, float("inf"), self._ray_hits_w_wp], + device=self._device, ) - # update output buffers + + # Fill ray distance with inf before raycasting + wp.launch( + fill_float2d_masked_kernel, + dim=(self._num_envs, self.num_rays), + inputs=[env_mask, float("inf"), self._ray_distance], + device=self._device, + ) + + # Determine whether to compute normals + need_normal = int("normals" in self.cfg.data_types) + if need_normal: + # Fill normal buffer with inf before raycasting + wp.launch( + fill_vec3_inf_kernel, + dim=(self._num_envs, self.num_rays), + inputs=[env_mask, float("inf"), self._ray_normal_w], + device=self._device, + ) + + # Ray-cast against the mesh; use a large upper-bound max_dist so depth clipping + # can be applied per-data-type afterwards (matching the original behaviour). + wp.launch( + raycast_mesh_masked_kernel, + dim=(self._num_envs, self.num_rays), + inputs=[ + RayCaster.meshes[(self.cfg.mesh_prim_paths[0], self._device)].id, + env_mask, + self._ray_starts_w, + self._ray_directions_w, + float(CAMERA_RAYCAST_MAX_DIST), + int(True), # return_distance: always needed for depth output + need_normal, + self._ray_hits_w_wp, + self._ray_distance, + self._ray_normal_w, + ], + device=self._device, + ) + + # Compute distance_to_image_plane using a warp kernel if "distance_to_image_plane" in self.cfg.data_types: - # note: data is in camera frame so we only take the first component (z-axis of camera frame) - distance_to_image_plane = ( - math_utils.quat_apply( - math_utils.quat_inv(quat_w).repeat(1, self.num_rays), - (ray_depth[:, :, None] * ray_directions_w), - ) - )[:, :, 0] - # apply the maximum distance after the transformation - if self.cfg.depth_clipping_behavior == "max": - distance_to_image_plane = torch.clip(distance_to_image_plane, max=self.cfg.max_distance) - distance_to_image_plane[torch.isnan(distance_to_image_plane)] = self.cfg.max_distance - elif self.cfg.depth_clipping_behavior == "zero": - distance_to_image_plane[distance_to_image_plane > self.cfg.max_distance] = 0.0 - distance_to_image_plane[torch.isnan(distance_to_image_plane)] = 0.0 - self._data.output["distance_to_image_plane"][env_ids] = distance_to_image_plane.view( + wp.launch( + compute_distance_to_image_plane_masked_kernel, + dim=(self._num_envs, self.num_rays), + inputs=[ + env_mask, + self._quat_w_wp, + self._ray_distance, + self._ray_directions_w, + ], + outputs=[ + self._distance_to_image_plane_wp, + ], + device=self._device, + ) + # Apply depth clipping on the intermediate buffer (leaves _ray_distance unmodified) + self._apply_depth_clipping(env_mask, self._distance_to_image_plane_wp) + self._data.output["distance_to_image_plane"][env_ids] = self._distance_to_image_plane_torch[env_ids].view( -1, *self.image_shape, 1 ) if "distance_to_camera" in self.cfg.data_types: - if self.cfg.depth_clipping_behavior == "max": - ray_depth = torch.clip(ray_depth, max=self.cfg.max_distance) - elif self.cfg.depth_clipping_behavior == "zero": - ray_depth[ray_depth > self.cfg.max_distance] = 0.0 - self._data.output["distance_to_camera"][env_ids] = ray_depth.view(-1, *self.image_shape, 1) + # d2ip (if requested) was computed before this block so _ray_distance is still unclipped. + self._apply_depth_clipping(env_mask, self._ray_distance) + self._data.output["distance_to_camera"][env_ids] = self._ray_distance_torch[env_ids].view( + -1, *self.image_shape, 1 + ) if "normals" in self.cfg.data_types: - self._data.output["normals"][env_ids] = ray_normal.view(-1, *self.image_shape, 3) + self._data.output["normals"][env_ids] = self._ray_normal_w_torch[env_ids].view(-1, *self.image_shape, 3) def _debug_vis_callback(self, event): # in case it crashes be safe if not hasattr(self, "ray_hits_w"): return - # show ray hit positions - self.ray_visualizer.visualize(self.ray_hits_w.view(-1, 3)) + # filter out missed rays (inf values) before visualizing + ray_hits_flat = self.ray_hits_w.reshape(-1, 3) + valid_mask = ~torch.isinf(ray_hits_flat).any(dim=-1) + viz_points = ray_hits_flat[valid_mask] + # if no valid hits, skip + if viz_points.shape[0] == 0: + return + self.ray_visualizer.visualize(viz_points) """ Private Helpers """ + def _apply_depth_clipping(self, env_mask: wp.array, depth: wp.array) -> None: + """Apply depth clipping in-place on a warp float32 buffer. + + Uses :attr:`cfg.depth_clipping_behavior` to determine the fill value: + ``"max"`` replaces out-of-range and NaN values with :attr:`cfg.max_distance`; + ``"zero"`` replaces them with 0. No-op when behavior is ``"none"``. + + Args: + env_mask: Boolean mask selecting which environments to update. Shape is (num_envs,). + depth: Warp 2-D float32 buffer to clip in-place. Shape is (num_envs, num_rays). + """ + if self.cfg.depth_clipping_behavior == "max": + wp.launch( + apply_depth_clipping_masked_kernel, + dim=(self._num_envs, self.num_rays), + inputs=[env_mask, float(self.cfg.max_distance), float(self.cfg.max_distance), depth], + device=self._device, + ) + elif self.cfg.depth_clipping_behavior == "zero": + wp.launch( + apply_depth_clipping_masked_kernel, + dim=(self._num_envs, self.num_rays), + inputs=[env_mask, float(self.cfg.max_distance), float(0.0), depth], + device=self._device, + ) + elif self.cfg.depth_clipping_behavior == "none": + pass # no clipping: inf values remain as-is + else: + raise ValueError( + f"Unknown depth_clipping_behavior: {self.cfg.depth_clipping_behavior!r}." + " Valid values are 'max', 'zero', and 'none'." + ) + def _check_supported_data_types(self, cfg: RayCasterCameraCfg): """Checks if the data types are supported by the ray-caster camera.""" # check if there is any intersection in unsupported types @@ -362,7 +526,7 @@ def _check_supported_data_types(self, cfg: RayCasterCameraCfg): def _create_buffers(self): """Create buffers for storing data.""" - # prepare drift + # prepare drift (kept as torch tensors so subclasses may use torch indexing) self.drift = torch.zeros(self._view.count, 3, device=self.device) self.ray_cast_drift = torch.zeros(self._view.count, 3, device=self.device) # create the data object @@ -376,7 +540,7 @@ def _create_buffers(self): # -- output data # create the buffers to store the annotator data. self._data.output = {} - self._data.info = [{name: None for name in self.cfg.data_types}] * self._view.count + self._data.info = {name: None for name in self.cfg.data_types} for name in self.cfg.data_types: if name in ["distance_to_image_plane", "distance_to_camera"]: shape = (self.cfg.pattern_cfg.height, self.cfg.pattern_cfg.width, 1) @@ -415,21 +579,23 @@ def _compute_view_world_poses(self, env_ids: Sequence[int]) -> tuple[torch.Tenso """Obtains the pose of the view the camera is attached to in the world frame. .. deprecated v2.3.1: - This function will be removed in a future release in favor of implementation - :meth:`obtain_world_pose_from_view`. + This function will be removed in a future release. Call + ``self._view.get_world_poses(indices)`` directly instead. The returned + ProxyArray pair exposes ``.warp`` and ``.torch`` accessors. Returns: A tuple of the position (in meters) and quaternion (x, y, z, w). """ - # deprecation logger.warning( - "The function '_compute_view_world_poses' will be deprecated in favor of the util method" - " 'obtain_world_pose_from_view'. Please use 'obtain_world_pose_from_view' instead...." + "The function '_compute_view_world_poses' is deprecated." + " Call 'self._view.get_world_poses(indices)' directly instead." ) - return obtain_world_pose_from_view(self._view, env_ids, clone=True) + indices = wp.from_torch(env_ids.to(dtype=torch.int32), dtype=wp.int32) if env_ids is not None else None + pos_w, quat_w = self._view.get_world_poses(indices) + return pos_w.torch.clone(), quat_w.torch.clone() def _compute_camera_world_poses(self, env_ids: Sequence[int]) -> tuple[torch.Tensor, torch.Tensor]: """Computes the pose of the camera in the world frame. @@ -441,7 +607,10 @@ def _compute_camera_world_poses(self, env_ids: Sequence[int]) -> tuple[torch.Ten .. code-block:: python - pos_w, quat_w = obtain_world_pose_from_view(self._view, env_ids, clone=True) + indices = wp.from_torch(env_ids.to(dtype=torch.int32), dtype=wp.int32) + pos_w, quat_w = self._view.get_world_poses(indices) + # The returned ProxyArray pair exposes .warp and .torch accessors + pos_w, quat_w = pos_w.torch.clone(), quat_w.torch.clone() pos_w, quat_w = math_utils.combine_frame_transforms( pos_w, quat_w, self._offset_pos[env_ids], self._offset_quat[env_ids] ) @@ -449,14 +618,13 @@ def _compute_camera_world_poses(self, env_ids: Sequence[int]) -> tuple[torch.Ten Returns: A tuple of the position (in meters) and quaternion (x, y, z, w) in "world" convention. """ - - # deprecation logger.warning( - "The function '_compute_camera_world_poses' will be deprecated in favor of the combination of methods" - " 'obtain_world_pose_from_view' and 'math_utils.combine_frame_transforms'. Please use" - " 'obtain_world_pose_from_view' and 'math_utils.combine_frame_transforms' instead...." + "The function '_compute_camera_world_poses' is deprecated." + " Call 'self._view.get_world_poses(indices)' and 'math_utils.combine_frame_transforms' directly instead." ) - # get the pose of the view the camera is attached to - pos_w, quat_w = obtain_world_pose_from_view(self._view, env_ids, clone=True) - return math_utils.combine_frame_transforms(pos_w, quat_w, self._offset_pos[env_ids], self._offset_quat[env_ids]) + indices = wp.from_torch(env_ids.to(dtype=torch.int32), dtype=wp.int32) if env_ids is not None else None + pos_w, quat_w = self._view.get_world_poses(indices) + return math_utils.combine_frame_transforms( + pos_w.torch.clone(), quat_w.torch.clone(), self._offset_pos[env_ids], self._offset_quat[env_ids] + ) diff --git a/source/isaaclab/isaaclab/sensors/ray_caster/ray_caster_camera_cfg.py b/source/isaaclab/isaaclab/sensors/ray_caster/ray_caster_camera_cfg.py index 98020d845f82..574c95020437 100644 --- a/source/isaaclab/isaaclab/sensors/ray_caster/ray_caster_camera_cfg.py +++ b/source/isaaclab/isaaclab/sensors/ray_caster/ray_caster_camera_cfg.py @@ -54,8 +54,8 @@ class OffsetCfg: - ``"max"``: Values are clipped to the maximum value. - ``"zero"``: Values are clipped to zero. - - ``"none``: No clipping is applied. Values will be returned as ``inf`` for ``distance_to_camera`` and ``nan`` - for ``distance_to_image_plane`` data type. + - ``"none"``: No clipping is applied. Values will be returned as ``inf`` for missed rays in both + ``distance_to_camera`` and ``distance_to_image_plane`` data types. """ pattern_cfg: PinholeCameraPatternCfg = MISSING diff --git a/source/isaaclab/isaaclab/sensors/ray_caster/ray_caster_cfg.py b/source/isaaclab/isaaclab/sensors/ray_caster/ray_caster_cfg.py index 7d91e446adac..3e862e389c1e 100644 --- a/source/isaaclab/isaaclab/sensors/ray_caster/ray_caster_cfg.py +++ b/source/isaaclab/isaaclab/sensors/ray_caster/ray_caster_cfg.py @@ -12,6 +12,7 @@ from isaaclab.markers import VisualizationMarkersCfg from isaaclab.markers.config import RAY_CASTER_MARKER_CFG +from isaaclab.sim.spawners.sensors.sensors_cfg import SensorFrameCfg from isaaclab.utils import configclass from ..sensor_base_cfg import SensorBaseCfg @@ -36,6 +37,21 @@ class OffsetCfg: class_type: type[RayCaster] | str = "{DIR}.ray_caster:RayCaster" + spawn: SensorFrameCfg | None = SensorFrameCfg() + """Spawn configuration for the sensor Xform prim. + + A plain USD Xform is created at :attr:`prim_path` before initialization, matching the + pattern used by :class:`~isaaclab.sensors.camera.camera_cfg.CameraCfg` (which spawns a + Camera prim). The :attr:`prim_path` can be either: + + - A **new** child path under a parent link (e.g. ``{ENV_REGEX_NS}/Robot/base``). + - A **physics body** path (e.g. ``{ENV_REGEX_NS}/Robot/base``). In this case, the sensor + will automatically create a child Xform at ``{prim_path}``. + + If ``None``, the prim at :attr:`prim_path` must already exist on the USD stage and must + **not** be a physics body. + """ + mesh_prim_paths: list[str] = MISSING """The list of mesh primitive paths to ray cast against. @@ -47,30 +63,15 @@ class OffsetCfg: offset: OffsetCfg = OffsetCfg() """The offset pose of the sensor's frame from the sensor's parent frame. Defaults to identity.""" - attach_yaw_only: bool | None = None - """Whether the rays' starting positions and directions only track the yaw orientation. - Defaults to None, which doesn't raise a warning of deprecated usage. - - This is useful for ray-casting height maps, where only yaw rotation is needed. - - .. deprecated:: 2.1.1 - - This attribute is deprecated and will be removed in the future. Please use - :attr:`ray_alignment` instead. - - To get the same behavior as setting this parameter to ``True`` or ``False``, set - :attr:`ray_alignment` to ``"yaw"`` or "base" respectively. - - """ - ray_alignment: Literal["base", "yaw", "world"] = "base" """Specify in what frame the rays are projected onto the ground. Default is "base". The options are: * ``base`` if the rays' starting positions and directions track the full root position and orientation. - * ``yaw`` if the rays' starting positions and directions track root position and only yaw component of - the orientation. This is useful for ray-casting height maps. + * ``yaw`` if the rays' starting positions track root position and the yaw component of the orientation, + while ray directions remain fixed in world frame. This is useful for ray-casting height maps where + the scan footprint should follow the body heading without tilting when the body pitches or rolls. * ``world`` if rays' starting positions and directions are always fixed. This is useful in combination with a mapping package on the robot and querying ray-casts in a global frame. """ diff --git a/source/isaaclab/isaaclab/sensors/ray_caster/ray_caster_data.py b/source/isaaclab/isaaclab/sensors/ray_caster/ray_caster_data.py index 6103a2167d66..1265e1df0fc3 100644 --- a/source/isaaclab/isaaclab/sensors/ray_caster/ray_caster_data.py +++ b/source/isaaclab/isaaclab/sensors/ray_caster/ray_caster_data.py @@ -3,28 +3,82 @@ # # SPDX-License-Identifier: BSD-3-Clause -from dataclasses import dataclass +from __future__ import annotations -import torch +import warp as wp +from isaaclab.utils.leapp import ( + QUAT_XYZW_ELEMENT_NAMES, + XYZ_ELEMENT_NAMES, + leapp_tensor_semantics, +) +from isaaclab.utils.warp import ProxyArray -@dataclass -class RayCasterData: - """Data container for the ray-cast sensor.""" - pos_w: torch.Tensor = None - """Position of the sensor origin in world frame. +class RayCasterData: + """Data container for the ray-cast sensor. - Shape is (N, 3), where N is the number of sensors. + Public properties return :class:`~isaaclab.utils.warp.ProxyArray` wrappers. + Use ``.torch`` for a cached zero-copy :class:`torch.Tensor` view or + ``.warp`` for the underlying :class:`warp.array`. """ - quat_w: torch.Tensor = None - """Orientation of the sensor origin in quaternion (x, y, z, w) in world frame. - Shape is (N, 4), where N is the number of sensors. - """ - ray_hits_w: torch.Tensor = None - """The ray hit positions in the world frame. + def __init__(self): + self._pos_w: wp.array | None = None + self._quat_w: wp.array | None = None + self._ray_hits_w: wp.array | None = None - Shape is (N, B, 3), where N is the number of sensors, B is the number of rays - in the scan pattern per sensor. - """ + # _pos_w_ta / _quat_w_ta / _ray_hits_w_ta are created in create_buffers(). + # Accessing the public properties before create_buffers() raises AttributeError. + + @property + @leapp_tensor_semantics(kind="state/sensor/position", element_names=XYZ_ELEMENT_NAMES) + def pos_w(self) -> ProxyArray: + """Position of the sensor origin in world frame [m]. + + Shape is (N,), dtype ``wp.vec3f``. In torch this resolves to (N, 3), + where N is the number of sensors. Use ``.warp`` for the underlying + ``wp.array`` or ``.torch`` for a cached zero-copy ``torch.Tensor`` view. + """ + return self._pos_w_ta + + @property + @leapp_tensor_semantics(kind="state/sensor/rotation", element_names=QUAT_XYZW_ELEMENT_NAMES) + def quat_w(self) -> ProxyArray: + """Orientation of the sensor origin in quaternion (x, y, z, w) in world frame. + + Shape is (N,), dtype ``wp.quatf``. In torch this resolves to (N, 4), + where N is the number of sensors. Use ``.warp`` for the underlying + ``wp.array`` or ``.torch`` for a cached zero-copy ``torch.Tensor`` view. + """ + return self._quat_w_ta + + @property + @leapp_tensor_semantics(kind="state/sensor/ray_hit_position") + def ray_hits_w(self) -> ProxyArray: + """The ray hit positions in the world frame [m]. + + Shape is (N, B), dtype ``wp.vec3f``. In torch this resolves to (N, B, 3), + where N is the number of sensors and B is the number of rays per sensor. + Contains ``inf`` for missed hits. Use ``.warp`` for the underlying + ``wp.array`` or ``.torch`` for a cached zero-copy ``torch.Tensor`` view. + """ + return self._ray_hits_w_ta + + def create_buffers(self, num_envs: int, num_rays: int, device: str) -> None: + """Create internal warp buffers and their :class:`ProxyArray` wrappers. + + Args: + num_envs: Number of environments / sensors. + num_rays: Number of rays per sensor. + device: Device for tensor storage. + """ + self._device = device + + self._pos_w = wp.zeros(num_envs, dtype=wp.vec3f, device=device) + self._quat_w = wp.zeros(num_envs, dtype=wp.quatf, device=device) + self._ray_hits_w = wp.zeros((num_envs, num_rays), dtype=wp.vec3f, device=device) + + self._pos_w_ta = ProxyArray(self._pos_w) + self._quat_w_ta = ProxyArray(self._quat_w) + self._ray_hits_w_ta = ProxyArray(self._ray_hits_w) diff --git a/source/isaaclab/isaaclab/sensors/sensor_base.py b/source/isaaclab/isaaclab/sensors/sensor_base.py index 4a9fb91786e5..3b15d8a0171e 100644 --- a/source/isaaclab/isaaclab/sensors/sensor_base.py +++ b/source/isaaclab/isaaclab/sensors/sensor_base.py @@ -12,6 +12,7 @@ from __future__ import annotations import inspect +import logging import re import weakref from abc import ABC, abstractmethod @@ -29,6 +30,8 @@ if TYPE_CHECKING: from .sensor_base_cfg import SensorBaseCfg +logger = logging.getLogger(__name__) + class SensorBase(ABC): """The base class for implementing a sensor. @@ -386,3 +389,71 @@ def _resolve_indices_and_mask( self._reset_mask.zero_() self._reset_mask_torch[env_ids] = True return self._reset_mask + + def _resolve_and_spawn(self, sensor_name: str, **spawn_kwargs) -> None: + """Resolve physics-body prim paths and spawn the sensor prim if needed. + + Behavior matrix (``spawn`` refers to ``cfg.spawn``): + + +----------------+------------------+--------------------------------------------+ + | ``spawn`` | ``prim_path`` | Action | + +================+==================+============================================+ + | not ``None`` | physics body | Append ``/``, spawn child. | + +----------------+------------------+--------------------------------------------+ + | not ``None`` | non-physics prim | Use existing prim, skip spawn. | + | | (already exists) | | + +----------------+------------------+--------------------------------------------+ + | not ``None`` | does not exist | Spawn prim at ``prim_path``. | + +----------------+------------------+--------------------------------------------+ + | ``None`` | physics body | Raise ``ValueError``. | + +----------------+------------------+--------------------------------------------+ + | ``None`` | non-physics prim | Use as-is (no spawn). | + +----------------+------------------+--------------------------------------------+ + + Args: + sensor_name: Short identifier (e.g. ``"raycaster"``, ``"camera"``). + **spawn_kwargs: Extra keyword arguments forwarded to ``cfg.spawn.func`` + (e.g. ``translation``, ``orientation``). + + Raises: + ValueError: If ``spawn`` is ``None`` and ``prim_path`` is a physics body. + RuntimeError: If the prim does not exist after the spawn attempt. + """ + from pxr import UsdPhysics # noqa: PLC0415 + + spawn = getattr(self.cfg, "spawn", None) + has_spawn = spawn is not None + + # Determine the path to probe for physics-body redirect + spawn_path = (getattr(spawn, "spawn_path", None) or self.cfg.prim_path) if has_spawn else None + probe_path = spawn_path if spawn_path is not None else self.cfg.prim_path + + prim = sim_utils.find_first_matching_prim(probe_path) + if prim is not None and prim.IsValid(): + is_physics = prim.HasAPI(UsdPhysics.ArticulationRootAPI) or prim.HasAPI(UsdPhysics.RigidBodyAPI) + if is_physics: + if not has_spawn: + raise ValueError( + f"Sensor prim_path '{self.cfg.prim_path}' resolves to a physics body but" + f" no spawner is configured (spawn=None). Either set spawn or point" + f" prim_path at a non-physics child (e.g. '{self.cfg.prim_path}/{sensor_name}')." + ) + logger.info( + f"Sensor prim_path '{self.cfg.prim_path}' points at a physics body." + f" Redirecting to '{self.cfg.prim_path}/{sensor_name}'." + ) + self.cfg.prim_path = f"{self.cfg.prim_path}/{sensor_name}" + if getattr(spawn, "spawn_path", None) is not None: + spawn.spawn_path = f"{spawn.spawn_path}/{sensor_name}" + + if not has_spawn: + return + + spawn_target = getattr(spawn, "spawn_path", None) or self.cfg.prim_path + prim = sim_utils.find_first_matching_prim(spawn_target) + if prim is None or not prim.IsValid(): + spawn.func(spawn_target, spawn, **spawn_kwargs) + + check_path = getattr(spawn, "spawn_path", None) or self.cfg.prim_path + if len(sim_utils.find_matching_prims(check_path)) == 0: + raise RuntimeError(f"Could not find prim with path {check_path!r}.") diff --git a/source/isaaclab/isaaclab/sim/__init__.pyi b/source/isaaclab/isaaclab/sim/__init__.pyi index 32a5ea87e197..a718ccdcb989 100644 --- a/source/isaaclab/isaaclab/sim/__init__.pyi +++ b/source/isaaclab/isaaclab/sim/__init__.pyi @@ -22,13 +22,11 @@ __all__ = [ "activate_contact_sensors", "define_articulation_root_properties", "define_collision_properties", - "define_deformable_body_properties", "define_mass_properties", "define_mesh_collision_properties", "define_rigid_body_properties", "modify_articulation_root_properties", "modify_collision_properties", - "modify_deformable_body_properties", "modify_fixed_tendon_properties", "modify_joint_drive_properties", "modify_mass_properties", @@ -41,7 +39,6 @@ __all__ = [ "CollisionPropertiesCfg", "ConvexDecompositionPropertiesCfg", "ConvexHullPropertiesCfg", - "DeformableBodyPropertiesCfg", "FixedTendonPropertiesCfg", "JointDrivePropertiesCfg", "MassPropertiesCfg", @@ -53,7 +50,6 @@ __all__ = [ "TriangleMeshSimplificationPropertiesCfg", "SpawnerCfg", "RigidObjectSpawnerCfg", - "DeformableObjectSpawnerCfg", "spawn_from_mjcf", "spawn_from_urdf", "spawn_from_usd", @@ -71,9 +67,7 @@ __all__ = [ "DomeLightCfg", "LightCfg", "SphereLightCfg", - "spawn_deformable_body_material", "spawn_rigid_body_material", - "DeformableBodyMaterialCfg", "PhysicsMaterialCfg", "RigidBodyMaterialCfg", "spawn_from_mdl_file", @@ -87,15 +81,19 @@ __all__ = [ "spawn_mesh_cuboid", "spawn_mesh_cylinder", "spawn_mesh_sphere", + "spawn_mesh_square", "MeshCapsuleCfg", "MeshCfg", "MeshConeCfg", "MeshCuboidCfg", "MeshCylinderCfg", "MeshSphereCfg", + "MeshSquareCfg", "spawn_camera", + "spawn_sensor_frame", "FisheyeCameraCfg", "PinholeCameraCfg", + "SensorFrameCfg", "spawn_capsule", "spawn_cone", "spawn_cuboid", @@ -164,6 +162,10 @@ __all__ = [ "resolve_prim_pose", "resolve_prim_scale", "convert_world_pose_to_local", + "BaseFrameView", + "UsdFrameView", + "FrameView", + # Deprecated alias "XformPrimView", ] @@ -186,13 +188,11 @@ from .schemas import ( activate_contact_sensors, define_articulation_root_properties, define_collision_properties, - define_deformable_body_properties, define_mass_properties, define_mesh_collision_properties, define_rigid_body_properties, modify_articulation_root_properties, modify_collision_properties, - modify_deformable_body_properties, modify_fixed_tendon_properties, modify_joint_drive_properties, modify_mass_properties, @@ -205,7 +205,6 @@ from .schemas import ( CollisionPropertiesCfg, ConvexDecompositionPropertiesCfg, ConvexHullPropertiesCfg, - DeformableBodyPropertiesCfg, FixedTendonPropertiesCfg, JointDrivePropertiesCfg, MassPropertiesCfg, @@ -219,7 +218,6 @@ from .schemas import ( from .spawners import ( SpawnerCfg, RigidObjectSpawnerCfg, - DeformableObjectSpawnerCfg, spawn_from_mjcf, spawn_from_urdf, spawn_from_usd, @@ -237,9 +235,7 @@ from .spawners import ( DomeLightCfg, LightCfg, SphereLightCfg, - spawn_deformable_body_material, spawn_rigid_body_material, - DeformableBodyMaterialCfg, PhysicsMaterialCfg, RigidBodyMaterialCfg, spawn_from_mdl_file, @@ -253,15 +249,19 @@ from .spawners import ( spawn_mesh_cuboid, spawn_mesh_cylinder, spawn_mesh_sphere, + spawn_mesh_square, MeshCapsuleCfg, MeshCfg, MeshConeCfg, MeshCuboidCfg, MeshCylinderCfg, MeshSphereCfg, + MeshSquareCfg, spawn_camera, + spawn_sensor_frame, FisheyeCameraCfg, PinholeCameraCfg, + SensorFrameCfg, spawn_capsule, spawn_cone, spawn_cuboid, @@ -333,4 +333,5 @@ from .utils import ( resolve_prim_scale, convert_world_pose_to_local, ) -from .views import XformPrimView +from .views import BaseFrameView, UsdFrameView, FrameView +from .views import XformPrimView # deprecated alias diff --git a/source/isaaclab/isaaclab/sim/converters/mesh_converter.py b/source/isaaclab/isaaclab/sim/converters/mesh_converter.py index 6d2df6285e05..74ba8b470c3a 100644 --- a/source/isaaclab/isaaclab/sim/converters/mesh_converter.py +++ b/source/isaaclab/isaaclab/sim/converters/mesh_converter.py @@ -9,7 +9,7 @@ import omni import omni.kit.commands -from isaacsim.core.utils.extensions import enable_extension +from isaacsim.core.experimental.utils.app import enable_extension from pxr import Gf, Tf, Usd, UsdGeom, UsdPhysics, UsdUtils from isaaclab.sim.converters.asset_converter_base import AssetConverterBase diff --git a/source/isaaclab/isaaclab/sim/schemas/__init__.pyi b/source/isaaclab/isaaclab/sim/schemas/__init__.pyi index 947d4ab47c92..f413b3ded12d 100644 --- a/source/isaaclab/isaaclab/sim/schemas/__init__.pyi +++ b/source/isaaclab/isaaclab/sim/schemas/__init__.pyi @@ -10,13 +10,11 @@ __all__ = [ "activate_contact_sensors", "define_articulation_root_properties", "define_collision_properties", - "define_deformable_body_properties", "define_mass_properties", "define_mesh_collision_properties", "define_rigid_body_properties", "modify_articulation_root_properties", "modify_collision_properties", - "modify_deformable_body_properties", "modify_fixed_tendon_properties", "modify_joint_drive_properties", "modify_mass_properties", @@ -29,7 +27,6 @@ __all__ = [ "CollisionPropertiesCfg", "ConvexDecompositionPropertiesCfg", "ConvexHullPropertiesCfg", - "DeformableBodyPropertiesCfg", "FixedTendonPropertiesCfg", "JointDrivePropertiesCfg", "MassPropertiesCfg", @@ -48,13 +45,11 @@ from .schemas import ( activate_contact_sensors, define_articulation_root_properties, define_collision_properties, - define_deformable_body_properties, define_mass_properties, define_mesh_collision_properties, define_rigid_body_properties, modify_articulation_root_properties, modify_collision_properties, - modify_deformable_body_properties, modify_fixed_tendon_properties, modify_joint_drive_properties, modify_mass_properties, @@ -69,7 +64,6 @@ from .schemas_cfg import ( CollisionPropertiesCfg, ConvexDecompositionPropertiesCfg, ConvexHullPropertiesCfg, - DeformableBodyPropertiesCfg, FixedTendonPropertiesCfg, JointDrivePropertiesCfg, MassPropertiesCfg, diff --git a/source/isaaclab/isaaclab/sim/schemas/schemas.py b/source/isaaclab/isaaclab/sim/schemas/schemas.py index dec9de5bbada..0f97b542e031 100644 --- a/source/isaaclab/isaaclab/sim/schemas/schemas.py +++ b/source/isaaclab/isaaclab/sim/schemas/schemas.py @@ -18,7 +18,6 @@ from ..utils import ( apply_nested, find_global_fixed_joint_prim, - get_all_matching_child_prims, safe_set_attribute_on_usd_prim, safe_set_attribute_on_usd_schema, ) @@ -685,6 +684,16 @@ def modify_joint_drive_properties( # convert to dict cfg = cfg.to_dict() + # ensure_drives_exist: if both stiffness and damping are zero on the authored drive, + # set a minimal stiffness so that backends like Newton recognise the drive as active. + ensure_drives = cfg.pop("ensure_drives_exist", False) + if ensure_drives and cfg["stiffness"] is None and cfg["damping"] is None: + # read the current values from the drive + cur_stiffness = usd_drive_api.GetStiffnessAttr().Get() + cur_damping = usd_drive_api.GetDampingAttr().Get() + if (cur_stiffness is None or cur_stiffness == 0.0) and (cur_damping is None or cur_damping == 0.0): + cfg["stiffness"] = 1e-3 + # check if linear drive is_linear_drive = prim.IsA(UsdPhysics.PrismaticJoint) # convert values for angular drives from radians to degrees units @@ -844,174 +853,6 @@ def modify_spatial_tendon_properties( return True -""" -Deformable body properties. -""" - - -def define_deformable_body_properties( - prim_path: str, cfg: schemas_cfg.DeformableBodyPropertiesCfg, stage: Usd.Stage | None = None -): - """Apply the deformable body schema on the input prim and set its properties. - - See :func:`modify_deformable_body_properties` for more details on how the properties are set. - - .. note:: - If the input prim is not a mesh, this function will traverse the prim and find the first mesh - under it. If no mesh or multiple meshes are found, an error is raised. This is because the deformable - body schema can only be applied to a single mesh. - - Args: - prim_path: The prim path where to apply the deformable body schema. - cfg: The configuration for the deformable body. - stage: The stage where to find the prim. Defaults to None, in which case the - current stage is used. - - Raises: - ValueError: When the prim path is not valid. - ValueError: When the prim has no mesh or multiple meshes. - """ - # get stage handle - if stage is None: - stage = get_current_stage() - - # get USD prim - prim = stage.GetPrimAtPath(prim_path) - # check if prim path is valid - if not prim.IsValid(): - raise ValueError(f"Prim path '{prim_path}' is not valid.") - - # traverse the prim and get the mesh - matching_prims = get_all_matching_child_prims(prim_path, lambda p: p.GetTypeName() == "Mesh") - # check if the mesh is valid - if len(matching_prims) == 0: - raise ValueError(f"Could not find any mesh in '{prim_path}'. Please check asset.") - if len(matching_prims) > 1: - # get list of all meshes found - mesh_paths = [p.GetPrimPath() for p in matching_prims] - raise ValueError( - f"Found multiple meshes in '{prim_path}': {mesh_paths}." - " Deformable body schema can only be applied to one mesh." - ) - - # get deformable-body USD prim - mesh_prim = matching_prims[0] - # ensure PhysX deformable body API is applied - mesh_applied = mesh_prim.GetAppliedSchemas() - if "PhysxDeformableBodyAPI" not in mesh_applied: - mesh_prim.AddAppliedSchema("PhysxDeformableBodyAPI") - # set deformable body properties - modify_deformable_body_properties(mesh_prim.GetPrimPath(), cfg, stage) - - -@apply_nested -def modify_deformable_body_properties( - prim_path: str, cfg: schemas_cfg.DeformableBodyPropertiesCfg, stage: Usd.Stage | None = None -): - """Modify PhysX parameters for a deformable body prim. - - A `deformable body`_ is a single body that can be simulated by PhysX. Unlike rigid bodies, deformable bodies - support relative motion of the nodes in the mesh. Consequently, they can be used to simulate deformations - under applied forces. - - PhysX soft body simulation employs Finite Element Analysis (FEA) to simulate the deformations of the mesh. - It uses two tetrahedral meshes to represent the deformable body: - - 1. **Simulation mesh**: This mesh is used for the simulation and is the one that is deformed by the solver. - 2. **Collision mesh**: This mesh only needs to match the surface of the simulation mesh and is used for - collision detection. - - For most applications, we assume that the above two meshes are computed from the "render mesh" of the deformable - body. The render mesh is the mesh that is visible in the scene and is used for rendering purposes. It is composed - of triangles and is the one that is used to compute the above meshes based on PhysX cookings. - - The schema comprises of attributes that belong to the `PhysxDeformableBodyAPI`_. schemas containing the PhysX - parameters for the deformable body. - - .. caution:: - The deformable body schema is still under development by the Omniverse team. The current implementation - works with the PhysX schemas shipped with Isaac Sim 4.0.0 onwards. It may change in future releases. - - .. note:: - This function is decorated with :func:`apply_nested` that sets the properties to all the prims - (that have the schema applied on them) under the input prim path. - - .. _deformable body: https://nvidia-omniverse.github.io/PhysX/physx/5.4.1/docs/SoftBodies.html - .. _PhysxDeformableBodyAPI: https://docs.omniverse.nvidia.com/kit/docs/omni_usd_schema_physics/104.2/class_physx_schema_physx_deformable_a_p_i.html - - Args: - prim_path: The prim path to the deformable body. - cfg: The configuration for the deformable body. - stage: The stage where to find the prim. Defaults to None, in which case the - current stage is used. - - Returns: - True if the properties were successfully set, False otherwise. - """ - # get stage handle - if stage is None: - stage = get_current_stage() - - # get deformable-body USD prim - deformable_body_prim = stage.GetPrimAtPath(prim_path) - - # check if the prim is valid and has the deformable-body API - if not deformable_body_prim.IsValid(): - return False - if "PhysxDeformableBodyAPI" not in deformable_body_prim.GetAppliedSchemas(): - return False - - # convert to dict - cfg = cfg.to_dict() - # set into deformable body API - attr_kwargs = { - attr_name: cfg.pop(attr_name) - for attr_name in [ - "kinematic_enabled", - "collision_simplification", - "collision_simplification_remeshing", - "collision_simplification_remeshing_resolution", - "collision_simplification_target_triangle_count", - "collision_simplification_force_conforming", - "simulation_hexahedral_resolution", - "solver_position_iteration_count", - "vertex_velocity_damping", - "sleep_damping", - "sleep_threshold", - "settling_threshold", - "self_collision", - "self_collision_filter_distance", - ] - } - from omni.physx.scripts import deformableUtils as deformable_utils - - status = deformable_utils.add_physx_deformable_body(stage, prim_path=prim_path, **attr_kwargs) - # check if the deformable body was successfully added - if not status: - return False - - # ensure PhysX deformable API is applied (set when add_physx_deformable_body runs; apply if missing) - deformable_applied = deformable_body_prim.GetAppliedSchemas() - if "PhysxCollisionAPI" not in deformable_applied: - deformable_body_prim.AddAppliedSchema("PhysxCollisionAPI") - if "PhysxDeformableAPI" not in deformable_applied: - deformable_body_prim.AddAppliedSchema("PhysxDeformableAPI") - - # set into PhysX API (prim attributes: physxCollision:* for rest/contact offset, physxDeformable:* for rest) - for attr_name, value in cfg.items(): - if attr_name in ["rest_offset", "contact_offset"]: - safe_set_attribute_on_usd_prim( - deformable_body_prim, f"physxCollision:{to_camel_case(attr_name, 'cC')}", value, camel_case=False - ) - else: - safe_set_attribute_on_usd_prim( - deformable_body_prim, f"physxDeformable:{to_camel_case(attr_name, 'cC')}", value, camel_case=False - ) - - # success - return True - - """ Collision mesh properties. """ diff --git a/source/isaaclab/isaaclab/sim/schemas/schemas_cfg.py b/source/isaaclab/isaaclab/sim/schemas/schemas_cfg.py index df2569c57714..69cbc8bd5304 100644 --- a/source/isaaclab/isaaclab/sim/schemas/schemas_cfg.py +++ b/source/isaaclab/isaaclab/sim/schemas/schemas_cfg.py @@ -231,6 +231,18 @@ class JointDrivePropertiesCfg: * For angular joints, the unit is kg-m^2/s/rad (N-m-s/rad). """ + ensure_drives_exist: bool = False + """If True, ensure every joint has a non-zero drive so that physics backends + (e.g. Newton) create proper actuators for it. + + When a USD asset defines ``PhysicsDriveAPI`` with ``stiffness=0`` and + ``damping=0``, some backends treat the joint as passive (no PD control). + Enabling this flag writes a minimal stiffness (``1e-3``) to any drive whose + stiffness *and* damping are both zero, guaranteeing that the backend + recognises the drive as active. The actual gains are expected to be + overridden later by the actuator model. + """ + @configclass class FixedTendonPropertiesCfg: @@ -297,139 +309,6 @@ class SpatialTendonPropertiesCfg: """ -@configclass -class DeformableBodyPropertiesCfg: - """Properties to apply to a deformable body. - - A deformable body is a body that can deform under forces. The configuration allows users to specify - the properties of the deformable body, such as the solver iteration counts, damping, and self-collision. - - An FEM-based deformable body is created by providing a collision mesh and simulation mesh. The collision mesh - is used for collision detection and the simulation mesh is used for simulation. The collision mesh is usually - a simplified version of the simulation mesh. - - Based on the above, the PhysX team provides APIs to either set the simulation and collision mesh directly - (by specifying the points) or to simplify the collision mesh based on the simulation mesh. The simplification - process involves remeshing the collision mesh and simplifying it based on the target triangle count. - - Since specifying the collision mesh points directly is not a common use case, we only expose the parameters - to simplify the collision mesh based on the simulation mesh. If you want to provide the collision mesh points, - please open an issue on the repository and we can add support for it. - - See :meth:`modify_deformable_body_properties` for more information. - - .. note:: - If the values are :obj:`None`, they are not modified. This is useful when you want to set only a subset of - the properties and leave the rest as-is. - """ - - deformable_enabled: bool | None = None - """Enables deformable body.""" - - kinematic_enabled: bool = False - """Enables kinematic body. Defaults to False, which means that the body is not kinematic. - - Similar to rigid bodies, this allows setting user-driven motion for the deformable body. For more information, - please refer to the `documentation `__. - """ - - self_collision: bool | None = None - """Whether to enable or disable self-collisions for the deformable body based on the rest position distances.""" - - self_collision_filter_distance: float | None = None - """Penetration value that needs to get exceeded before contacts for self collision are generated. - - This parameter must be greater than of equal to twice the :attr:`rest_offset` value. - - This value has an effect only if :attr:`self_collision` is enabled. - """ - - settling_threshold: float | None = None - """Threshold vertex velocity (in m/s) under which sleep damping is applied in addition to velocity damping.""" - - sleep_damping: float | None = None - """Coefficient for the additional damping term if fertex velocity drops below setting threshold.""" - - sleep_threshold: float | None = None - """The velocity threshold (in m/s) under which the vertex becomes a candidate for sleeping in the next step.""" - - solver_position_iteration_count: int | None = None - """Number of the solver positional iterations per step. Range is [1,255]""" - - vertex_velocity_damping: float | None = None - """Coefficient for artificial damping on the vertex velocity. - - This parameter can be used to approximate the effect of air drag on the deformable body. - """ - - simulation_hexahedral_resolution: int = 10 - """The target resolution for the hexahedral mesh used for simulation. Defaults to 10. - - Note: - This value is ignored if the user provides the simulation mesh points directly. However, we assume that - most users will not provide the simulation mesh points directly. If you want to provide the simulation mesh - directly, please set this value to :obj:`None`. - """ - - collision_simplification: bool = True - """Whether or not to simplify the collision mesh before creating a soft body out of it. Defaults to True. - - Note: - This flag is ignored if the user provides the simulation mesh points directly. However, we assume that - most users will not provide the simulation mesh points directly. Hence, this flag is enabled by default. - - If you want to provide the simulation mesh points directly, please set this flag to False. - """ - - collision_simplification_remeshing: bool = True - """Whether or not the collision mesh should be remeshed before simplification. Defaults to True. - - This parameter is ignored if :attr:`collision_simplification` is False. - """ - - collision_simplification_remeshing_resolution: int = 0 - """The resolution used for remeshing. Defaults to 0, which means that a heuristic is used to determine the - resolution. - - This parameter is ignored if :attr:`collision_simplification_remeshing` is False. - """ - - collision_simplification_target_triangle_count: int = 0 - """The target triangle count used for the simplification. Defaults to 0, which means that a heuristic based on - the :attr:`simulation_hexahedral_resolution` is used to determine the target count. - - This parameter is ignored if :attr:`collision_simplification` is False. - """ - - collision_simplification_force_conforming: bool = True - """Whether or not the simplification should force the output mesh to conform to the input mesh. Defaults to True. - - The flag indicates that the tretrahedralizer used to generate the collision mesh should produce tetrahedra - that conform to the triangle mesh. If False, the simplifier uses the output from the tretrahedralizer used. - - This parameter is ignored if :attr:`collision_simplification` is False. - """ - - contact_offset: float | None = None - """Contact offset for the collision shape (in m). - - The collision detector generates contact points as soon as two shapes get closer than the sum of their - contact offsets. This quantity should be non-negative which means that contact generation can potentially start - before the shapes actually penetrate. - """ - - rest_offset: float | None = None - """Rest offset for the collision shape (in m). - - The rest offset quantifies how close a shape gets to others at rest, At rest, the distance between two - vertically stacked objects is the sum of their rest offsets. If a pair of shapes have a positive rest - offset, the shapes will be separated at rest by an air gap. - """ - - max_depenetration_velocity: float | None = None - """Maximum depenetration velocity permitted to be introduced by the solver (in m/s).""" - - @configclass class MeshCollisionPropertiesCfg: """Properties to apply to a mesh in regards to collision. diff --git a/source/isaaclab/isaaclab/sim/simulation_context.py b/source/isaaclab/isaaclab/sim/simulation_context.py index 91cee7d0be46..89be3163359f 100644 --- a/source/isaaclab/isaaclab/sim/simulation_context.py +++ b/source/isaaclab/isaaclab/sim/simulation_context.py @@ -11,7 +11,7 @@ import traceback from collections.abc import Iterator from contextlib import contextmanager -from typing import Any +from typing import TYPE_CHECKING, Any import toml import torch @@ -21,16 +21,21 @@ import isaaclab.sim as sim_utils import isaaclab.sim.utils.stage as stage_utils from isaaclab.app.settings_manager import SettingsManager +from isaaclab.envs.utils.recording_hooks import run_recording_hooks_after_visualizers from isaaclab.physics import BaseSceneDataProvider, PhysicsManager, SceneDataProvider from isaaclab.physics.scene_data_requirements import ( SceneDataRequirement, - VisualizerPrebuiltArtifacts, resolve_scene_data_requirements, ) +from isaaclab.renderers.render_context import RenderContext from isaaclab.sim.utils import create_new_stage +from isaaclab.utils.string import clear_resolve_matching_names_cache from isaaclab.utils.version import has_kit from isaaclab.visualizers.base_visualizer import BaseVisualizer +if TYPE_CHECKING: + from isaaclab.cloner.clone_plan import ClonePlan + from .simulation_cfg import SimulationCfg from .spawners import DomeLightCfg, GroundPlaneCfg @@ -170,7 +175,11 @@ def __init__(self, cfg: SimulationCfg | None = None): self._scene_data_provider: BaseSceneDataProvider | None = None self._visualizers: list[BaseVisualizer] = [] self._scene_data_requirements = SceneDataRequirement() - self._visualizer_prebuilt_artifact: VisualizerPrebuiltArtifacts | None = None + # Per-group clone plans published by InteractiveScene after cloning. Providers (e.g. + # the Newton visualizer model rebuilder on a PhysX backend) consume these to derive + # their own backend args. Empty dict until :meth:`InteractiveScene.clone_environments` + # runs. + self._clone_plans: dict[str, ClonePlan] = {} self._visualizer_step_counter = 0 # Default visualization dt used before/without visualizer initialization. physics_dt = getattr(self.cfg.physics, "dt", None) @@ -181,6 +190,7 @@ def __init__(self, cfg: SimulationCfg | None = None): self._has_offscreen_render = bool(self.get_setting("/isaaclab/render/offscreen")) self._xr_enabled = bool(self.get_setting("/isaaclab/xr/enabled")) # Note: has_rtx_sensors is NOT cached because it changes when Camera sensors are created + self._pending_camera_view: tuple[tuple[float, float, float], tuple[float, float, float]] | None = None # Simulation state self._is_playing = False @@ -188,6 +198,13 @@ def __init__(self, cfg: SimulationCfg | None = None): # Monotonic physics-step counter used by camera sensors for self._physics_step_count: int = 0 + # Monotonic render-generation counter. This increments whenever render() + # is executed and lets downstream camera freshness logic distinguish + # render/reset transitions that occur without advancing physics steps. + self._render_generation: int = 0 + + # Shared renderers for all Camera sensors (compatible renderer_cfg only). + self._render_context = RenderContext() type(self)._instance = self # Mark as valid singleton only after successful init @@ -289,10 +306,14 @@ def _init_usd_physics_scene(self) -> None: UsdGeom.SetStageMetersPerUnit(self.stage, 1.0) UsdPhysics.SetStageKilogramsPerUnit(self.stage, 1.0) - # Find and delete any existing physics scene - for prim in self.stage.Traverse(): - if prim.GetTypeName() == "PhysicsScene": - sim_utils.delete_prim(prim.GetPath().pathString, stage=self.stage) + # Find and delete any existing physics scene. + # Collect paths first to avoid mutating the stage while traversing, + # which can invalidate the USD iterator. + physics_scene_paths = [ + prim.GetPath().pathString for prim in self.stage.Traverse() if prim.GetTypeName() == "PhysicsScene" + ] + for path in physics_scene_paths: + sim_utils.delete_prim(path, stage=self.stage) # Create a new physics scene if self.stage.GetPrimAtPath(cfg.physics_prim_path).IsValid(): @@ -337,6 +358,16 @@ def has_offscreen_render(self) -> bool: """Returns whether offscreen rendering is enabled (cached at init).""" return self._has_offscreen_render + def has_active_visualizers(self) -> bool: + """Return whether any visualizer path is active for rendering/camera control.""" + return bool(self.get_setting("/isaaclab/visualizer/types")) or bool( + self.get_setting("/isaaclab/video/auto_start_kit") + ) + + def can_render_rgb_array(self) -> bool: + """Return whether rgb-array rendering is currently available.""" + return self.has_gui or self.has_offscreen_render or self.has_active_visualizers() + @property def is_rendering(self) -> bool: """Returns whether rendering is active (GUI, RTX sensors, visualizers, or XR).""" @@ -352,6 +383,20 @@ def get_physics_dt(self) -> float: """Returns the physics time step.""" return self.physics_manager.get_physics_dt() + def get_physics_step_count(self) -> int: + """Return the monotonic physics step counter (incremented each :meth:`step`).""" + return self._physics_step_count + + @property + def render_context(self) -> RenderContext: + """Shared :class:`~isaaclab.renderers.render_context.RenderContext` for camera renderers.""" + return self._render_context + + @property + def render_generation(self) -> int: + """Returns a monotonic counter for render() executions.""" + return self._render_generation + def _create_default_visualizer_configs(self, requested_visualizers: list[str]) -> list: """Create default visualizer configs for requested types. @@ -405,39 +450,23 @@ def _get_cli_visualizer_types(self) -> list[str]: # App launcher writes this as a single string; accept comma and/or whitespace separators. return [value for chunk in requested.split(",") for value in chunk.split() if value] - def _get_cli_visualizer_max_worlds_override(self) -> tuple[bool, int | None]: - """Return CLI override for visualizer max worlds. + def _apply_visualizer_cli_overrides(self, visualizer_cfgs: list[Any]) -> None: + """Apply ``--max_visible_envs`` to every resolved visualizer cfg when set in settings. - Returns: - Tuple of (has_override, value), where value=None means no override. + AppLauncher stores ``/isaaclab/visualizer/max_visible_envs`` as ``-1`` when the flag was + omitted; any non-negative int overrides :attr:`VisualizerCfg.max_visible_envs` on each cfg. """ - value = self.get_setting("/isaaclab/visualizer/max_worlds") - if value is None: - return False, None + raw = self.get_setting("/isaaclab/visualizer/max_visible_envs") try: - max_worlds = int(value) + max_visible = int(raw) if raw is not None else -1 except (TypeError, ValueError): - logger.warning("[SimulationContext] Invalid /isaaclab/visualizer/max_worlds setting: %r", value) - return False, None - - # -1 means no CLI override. - if max_worlds < 0: - return False, None - return True, max_worlds - - def _apply_visualizer_cli_overrides(self, visualizer_cfgs: list[Any]) -> None: - """Apply CLI visualizer overrides (e.g., max worlds) to resolved configs. - - Args: - visualizer_cfgs: Resolved visualizer configs to update in-place. - """ - has_max_worlds_override, max_worlds_override = self._get_cli_visualizer_max_worlds_override() - if not has_max_worlds_override: + logger.warning("[SimulationContext] Invalid /isaaclab/visualizer/max_visible_envs: %r", raw) + return + if max_visible < 0: return - for cfg in visualizer_cfgs: - if hasattr(cfg, "max_worlds"): - cfg.max_worlds = max_worlds_override + if hasattr(cfg, "max_visible_envs"): + cfg.max_visible_envs = max_visible def _is_cli_visualizer_explicit(self) -> bool: """Return ``True`` when visualizers were explicitly provided via CLI.""" @@ -577,6 +606,14 @@ def initialize_visualizers(self) -> None: exc, ) + # Replay any camera pose requested before visualizers were initialized. + pending = getattr(self, "_pending_camera_view", None) + if pending is not None: + eye, target = pending + for viz in self._visualizers: + viz.set_camera_view(eye, target) + self._pending_camera_view = None + if not self._visualizers and self._scene_data_provider is not None: close_provider = getattr(self._scene_data_provider, "close", None) if callable(close_provider): @@ -596,21 +633,18 @@ def update_scene_data_requirements(self, requirements: SceneDataRequirement) -> """Update scene-data requirements.""" self._scene_data_requirements = requirements - def get_scene_data_visualizer_prebuilt_artifact(self) -> VisualizerPrebuiltArtifacts | None: - """Return optional prebuilt visualizer artifact.""" - return self._visualizer_prebuilt_artifact - - def set_scene_data_visualizer_prebuilt_artifact(self, artifact: VisualizerPrebuiltArtifacts | None) -> None: - """Set or clear the optional visualizer prebuilt artifact. + def get_clone_plans(self) -> dict[str, ClonePlan]: + """Return per-group clone plans published by the scene, keyed by destination template. - The scene (clone flow) writes this once, and providers can read it - during initialization as a fast path. + Set by :meth:`InteractiveScene.clone_environments` after replication. Consumed by + scene data providers that build backend models (e.g. Newton visualizer model on a + PhysX backend) from the same plan the cloner used. Empty dict until the scene clones. """ - self._visualizer_prebuilt_artifact = artifact + return self._clone_plans - def clear_scene_data_visualizer_prebuilt_artifact(self) -> None: - """Clear optional prebuilt artifact in provider context.""" - self.set_scene_data_visualizer_prebuilt_artifact(None) + def set_clone_plans(self, plans: dict[str, ClonePlan]) -> None: + """Set the cloner's per-group clone-plan map.""" + self._clone_plans = plans @property def visualizers(self) -> list[BaseVisualizer]: @@ -627,6 +661,7 @@ def get_rendering_dt(self) -> float: def set_camera_view(self, eye: tuple, target: tuple) -> None: """Set camera view on all visualizers that support it.""" + self._pending_camera_view = (tuple(eye), tuple(target)) for viz in self._visualizers: viz.set_camera_view(eye, target) @@ -654,31 +689,65 @@ def reset(self, soft: bool = False) -> None: def step(self, render: bool = True) -> None: """Step physics and optionally render. + If the timeline is paused (e.g. via the GUI), this method blocks and keeps + the visualizer responsive until the timeline is resumed or stopped. + Args: render: Whether to render the scene after stepping. Defaults to True. """ + # Block while the GUI timeline is paused so the entire training loop freezes. + # See: https://github.com/isaac-sim/IsaacLab/issues/4279 + self.physics_manager.wait_for_playing() self._physics_step_count += 1 self.physics_manager.step() if render and self.is_rendering: self.render() - def render(self, mode: int | None = None) -> None: + def render(self, mode: int | None = None, skip_app_pumping: bool = False) -> None: """Update visualizers and render the scene. Calls update_visualizers() so visualizers run at the render cadence (not at every physics step). Camera sensors drive their configured renderer when - fetching data, so this method remains backend-agnostic. + fetching data. Recording-related follow-up (Kit/RTX headless video, Newton GL + video, etc.) runs in :mod:`isaaclab.envs.utils.recording_hooks` so it is not tied to a + specific :class:`~isaaclab.physics.PhysicsManager` subclass. + + **Kit vs. standalone visualizers:** The Kit app loop (``app.update()``) is the + only way to drive camera/RTX sensor rendering and viewport GUI updates; it + cannot be split into "cameras only" and "GUI only". Standalone visualizers + (Newton, Rerun, Viser) have self-contained ``step()`` methods that never call + ``app.update()``, so they can run independently of camera rendering. The + ``skip_app_pumping`` flag exploits this distinction: when True, Kit is skipped + while standalone visualizers continue to update. + + Args: + mode: Unused. Kept for backward compatibility. + skip_app_pumping: When True, skip visualizers whose :meth:`~BaseVisualizer.pumps_app_update` + returns True (e.g. KitVisualizer). This disables the Kit app loop and camera + updates while still stepping standalone visualizers (Newton, Rerun, Viser). + Used by environment ``step()`` when ``render_enabled`` is False. """ self.physics_manager.pre_render() - self.update_visualizers(self.get_rendering_dt()) + self.update_visualizers(self.get_rendering_dt(), skip_app_pumping=skip_app_pumping) + self.physics_manager.after_visualizers_render() + run_recording_hooks_after_visualizers(self) + self._render_generation += 1 # Call render callbacks if hasattr(self, "_render_callbacks"): for callback in self._render_callbacks.values(): callback(None) # Pass None as event data - def update_visualizers(self, dt: float) -> None: - """Update visualizers without triggering renderer/GUI.""" + def update_visualizers(self, dt: float, skip_app_pumping: bool = False) -> None: + """Update visualizers without triggering renderer/GUI. + + Args: + dt: Simulation time-step in seconds. + skip_app_pumping: When True, skip visualizers whose :meth:`~BaseVisualizer.pumps_app_update` + returns True (e.g. KitVisualizer). This is used when the environment's ``render_enabled`` + flag is False — cameras and the Kit app loop are skipped, but standalone visualizers + (Newton, Rerun, Viser) still receive updates. + """ if not self._visualizers: return @@ -687,6 +756,9 @@ def update_visualizers(self, dt: float) -> None: visualizers_to_remove = [] for viz in self._visualizers: try: + # When skip_app_pumping is set, skip Kit-like visualizers that call app.update() + if skip_app_pumping and viz.pumps_app_update(): + continue if viz.is_closed or not viz.is_running(): if viz.is_closed: logger.info("Visualizer closed: %s", type(viz).__name__) @@ -695,6 +767,11 @@ def update_visualizers(self, dt: float) -> None: visualizers_to_remove.append(viz) continue if viz.is_rendering_paused(): + # Keep non-Kit visualizer event loops responsive while rendering is paused. + # Newton/Rerun/Viser need step(0.0) so GL/UI can process input (e.g. Resume). + # Kit is skipped: step() would call app.update(), which must not run during pause. + if not viz.pumps_app_update(): + viz.step(0.0) continue while viz.is_training_paused() and viz.is_running(): viz.step(0.0) @@ -717,14 +794,7 @@ def update_scene_data_provider(self, force_require_forward: bool = False): self._visualizer_step_counter += 1 if self._scene_data_provider is None: return - provider = self._scene_data_provider - env_ids_union: list[int] = [] - for viz in self._visualizers: - ids = viz.get_visualized_env_ids() - if ids is not None: - env_ids_union.extend(ids) - env_ids = list(dict.fromkeys(env_ids_union)) if env_ids_union else None - provider.update(env_ids) + self._scene_data_provider.update() def _should_forward_before_visualizer_update(self) -> bool: """Return True if any visualizer requires pre-step forward kinematics.""" @@ -791,6 +861,9 @@ def clear_instance(cls) -> None: # close_stage() + app shutdown destroy the entire stage at once. stage_utils.close_stage() + # Discard cached name-resolution data from destroyed assets + clear_resolve_matching_names_cache() + # Clear instance cls._instance = None diff --git a/source/isaaclab/isaaclab/sim/spawners/__init__.pyi b/source/isaaclab/isaaclab/sim/spawners/__init__.pyi index 78d2c19021ee..dae1a432b47e 100644 --- a/source/isaaclab/isaaclab/sim/spawners/__init__.pyi +++ b/source/isaaclab/isaaclab/sim/spawners/__init__.pyi @@ -6,7 +6,6 @@ __all__ = [ "SpawnerCfg", "RigidObjectSpawnerCfg", - "DeformableObjectSpawnerCfg", "spawn_from_mjcf", "spawn_from_urdf", "spawn_from_usd", @@ -24,9 +23,7 @@ __all__ = [ "DomeLightCfg", "LightCfg", "SphereLightCfg", - "spawn_deformable_body_material", "spawn_rigid_body_material", - "DeformableBodyMaterialCfg", "PhysicsMaterialCfg", "RigidBodyMaterialCfg", "spawn_from_mdl_file", @@ -40,15 +37,19 @@ __all__ = [ "spawn_mesh_cuboid", "spawn_mesh_cylinder", "spawn_mesh_sphere", + "spawn_mesh_square", "MeshCapsuleCfg", "MeshCfg", "MeshConeCfg", "MeshCuboidCfg", "MeshCylinderCfg", "MeshSphereCfg", + "MeshSquareCfg", "spawn_camera", + "spawn_sensor_frame", "FisheyeCameraCfg", "PinholeCameraCfg", + "SensorFrameCfg", "spawn_capsule", "spawn_cone", "spawn_cuboid", @@ -66,7 +67,7 @@ __all__ = [ "MultiUsdFileCfg", ] -from .spawner_cfg import SpawnerCfg, RigidObjectSpawnerCfg, DeformableObjectSpawnerCfg +from .spawner_cfg import SpawnerCfg, RigidObjectSpawnerCfg from .from_files import ( spawn_from_mjcf, spawn_from_urdf, @@ -89,9 +90,7 @@ from .lights import ( SphereLightCfg, ) from .materials import ( - spawn_deformable_body_material, spawn_rigid_body_material, - DeformableBodyMaterialCfg, PhysicsMaterialCfg, RigidBodyMaterialCfg, spawn_from_mdl_file, @@ -107,14 +106,16 @@ from .meshes import ( spawn_mesh_cuboid, spawn_mesh_cylinder, spawn_mesh_sphere, + spawn_mesh_square, MeshCapsuleCfg, MeshCfg, MeshConeCfg, MeshCuboidCfg, MeshCylinderCfg, + MeshSquareCfg, MeshSphereCfg, ) -from .sensors import spawn_camera, FisheyeCameraCfg, PinholeCameraCfg +from .sensors import spawn_camera, spawn_sensor_frame, FisheyeCameraCfg, PinholeCameraCfg, SensorFrameCfg from .shapes import ( spawn_capsule, spawn_cone, diff --git a/source/isaaclab/isaaclab/sim/spawners/from_files/from_files.py b/source/isaaclab/isaaclab/sim/spawners/from_files/from_files.py index ddb7f9ff2fb3..be7bd6e7074e 100644 --- a/source/isaaclab/isaaclab/sim/spawners/from_files/from_files.py +++ b/source/isaaclab/isaaclab/sim/spawners/from_files/from_files.py @@ -11,6 +11,10 @@ import tempfile from typing import TYPE_CHECKING +# deformables only supported on PhysX backend +from isaaclab_physx.sim import schemas as schemas_physx +from isaaclab_physx.sim.spawners.materials import SurfaceDeformableBodyMaterialCfg + from pxr import Gf, Sdf, Usd, UsdGeom from isaaclab.sim import converters, schemas @@ -363,9 +367,19 @@ def _spawn_from_usd_file( if cfg.joint_drive_props is not None: schemas.modify_joint_drive_properties(prim_path, cfg.joint_drive_props) - # modify deformable body properties + # define deformable body properties, or modify if deformable body API is present (PhysX only) if cfg.deformable_props is not None: - schemas.modify_deformable_body_properties(prim_path, cfg.deformable_props) + prim = stage.GetPrimAtPath(prim_path) + deformable_type = "surface" if isinstance(cfg.physics_material, SurfaceDeformableBodyMaterialCfg) else "volume" + if "OmniPhysicsDeformableBodyAPI" in prim.GetAppliedSchemas(): + schemas_physx.modify_deformable_body_properties(prim_path, cfg.deformable_props, stage) + else: + schemas_physx.define_deformable_body_properties(prim_path, cfg.deformable_props, stage, deformable_type) + if cfg.mass_props is not None: + raise ValueError( + """MassPropertiesCfg are not supported for deformable bodies + and should be set through DeformableBodyPropertiesCfg(mass=).""" + ) # apply visual material if cfg.visual_material is not None: @@ -381,6 +395,17 @@ def _spawn_from_usd_file( # apply material bind_visual_material(prim_path, material_path, stage=stage) + # apply physics material + if cfg.physics_material is not None: + if not cfg.physics_material_path.startswith("/"): + material_path = f"{prim_path}/{cfg.physics_material_path}" + else: + material_path = cfg.physics_material_path + # create material + cfg.physics_material.func(material_path, cfg.physics_material) + # apply material + bind_physics_material(prim_path, material_path, stage=stage) + # return the prim return stage.GetPrimAtPath(prim_path) diff --git a/source/isaaclab/isaaclab/sim/spawners/from_files/from_files_cfg.py b/source/isaaclab/isaaclab/sim/spawners/from_files/from_files_cfg.py index 0de0b85911ea..78aaf1b15c94 100644 --- a/source/isaaclab/isaaclab/sim/spawners/from_files/from_files_cfg.py +++ b/source/isaaclab/isaaclab/sim/spawners/from_files/from_files_cfg.py @@ -8,9 +8,12 @@ from collections.abc import Callable from dataclasses import MISSING +# deformables only supported on PhysX backend +from isaaclab_physx.sim.spawners.spawner_cfg import DeformableObjectSpawnerCfg + from isaaclab.sim import converters, schemas from isaaclab.sim.spawners import materials -from isaaclab.sim.spawners.spawner_cfg import DeformableObjectSpawnerCfg, RigidObjectSpawnerCfg, SpawnerCfg +from isaaclab.sim.spawners.spawner_cfg import RigidObjectSpawnerCfg, SpawnerCfg from isaaclab.utils import configclass from isaaclab.utils.assets import ISAAC_NUCLEUS_DIR @@ -67,6 +70,20 @@ class FileCfg(RigidObjectSpawnerCfg, DeformableObjectSpawnerCfg): If None, then no visual material will be added. """ + physics_material_path: str = "material" + """Path to the physics material to use for the prim. Defaults to "material". + + If the path is relative, then it will be relative to the prim's path. + This parameter is ignored if `physics_material` is not None. + """ + + physics_material: materials.PhysicsMaterialCfg | None = None + """Physics material properties. + + Note: + If None, then no custom physics material will be added. + """ + @configclass class UsdFileCfg(FileCfg): diff --git a/source/isaaclab/isaaclab/sim/spawners/materials/__init__.pyi b/source/isaaclab/isaaclab/sim/spawners/materials/__init__.pyi index 294a9a7d9bf7..93142ddab389 100644 --- a/source/isaaclab/isaaclab/sim/spawners/materials/__init__.pyi +++ b/source/isaaclab/isaaclab/sim/spawners/materials/__init__.pyi @@ -4,9 +4,7 @@ # SPDX-License-Identifier: BSD-3-Clause __all__ = [ - "spawn_deformable_body_material", "spawn_rigid_body_material", - "DeformableBodyMaterialCfg", "PhysicsMaterialCfg", "RigidBodyMaterialCfg", "spawn_from_mdl_file", @@ -17,9 +15,8 @@ __all__ = [ "VisualMaterialCfg", ] -from .physics_materials import spawn_deformable_body_material, spawn_rigid_body_material +from .physics_materials import spawn_rigid_body_material from .physics_materials_cfg import ( - DeformableBodyMaterialCfg, PhysicsMaterialCfg, RigidBodyMaterialCfg, ) diff --git a/source/isaaclab/isaaclab/sim/spawners/materials/physics_materials.py b/source/isaaclab/isaaclab/sim/spawners/materials/physics_materials.py index 1577f9e134dc..240a0ff00746 100644 --- a/source/isaaclab/isaaclab/sim/spawners/materials/physics_materials.py +++ b/source/isaaclab/isaaclab/sim/spawners/materials/physics_materials.py @@ -74,58 +74,3 @@ def spawn_rigid_body_material(prim_path: str, cfg: physics_materials_cfg.RigidBo safe_set_attribute_on_usd_prim(prim, f"physxMaterial:{to_camel_case(attr_name, 'cC')}", value, camel_case=False) # return the prim return prim - - -@clone -def spawn_deformable_body_material(prim_path: str, cfg: physics_materials_cfg.DeformableBodyMaterialCfg) -> Usd.Prim: - """Create material with deformable-body physics properties. - - Deformable body materials are used to define the physical properties to meshes of a deformable body. These - include the friction and deformable body properties. For more information on deformable body material, - please refer to the documentation on `PxFEMSoftBodyMaterial`_. - - .. note:: - This function is decorated with :func:`clone` that resolves prim path into list of paths - if the input prim path is a regex pattern. This is done to support spawning multiple assets - from a single and cloning the USD prim at the given path expression. - - Args: - prim_path: The prim path or pattern to spawn the asset at. If the prim path is a regex pattern, - then the asset is spawned at all the matching prim paths. - cfg: The configuration for the physics material. - - Returns: - The spawned deformable body material prim. - - Raises: - ValueError: When a prim already exists at the specified prim path and is not a material. - - .. _PxFEMSoftBodyMaterial: https://nvidia-omniverse.github.io/PhysX/physx/5.4.1/_api_build/structPxFEMSoftBodyMaterialModel.html - """ - # get stage handle - stage = get_current_stage() - - # create material prim if no prim exists - if not stage.GetPrimAtPath(prim_path).IsValid(): - _ = UsdShade.Material.Define(stage, prim_path) - - # obtain prim - prim = stage.GetPrimAtPath(prim_path) - # check if prim is a material - if not prim.IsA(UsdShade.Material): - raise ValueError(f"A prim already exists at path: '{prim_path}' but is not a material.") - # ensure PhysX deformable body material API is applied - applied = prim.GetAppliedSchemas() - if "PhysxDeformableBodyMaterialAPI" not in applied: - prim.AddAppliedSchema("PhysxDeformableBodyMaterialAPI") - - # convert to dict - cfg = cfg.to_dict() - del cfg["func"] - # set into PhysX API (prim attributes: physxDeformableBodyMaterial:*) - for attr_name, value in cfg.items(): - safe_set_attribute_on_usd_prim( - prim, f"physxDeformableBodyMaterial:{to_camel_case(attr_name, 'cC')}", value, camel_case=False - ) - # return the prim - return prim diff --git a/source/isaaclab/isaaclab/sim/spawners/materials/physics_materials_cfg.py b/source/isaaclab/isaaclab/sim/spawners/materials/physics_materials_cfg.py index 222ebd8ce28c..dde9aec6d905 100644 --- a/source/isaaclab/isaaclab/sim/spawners/materials/physics_materials_cfg.py +++ b/source/isaaclab/isaaclab/sim/spawners/materials/physics_materials_cfg.py @@ -77,44 +77,3 @@ class RigidBodyMaterialCfg(PhysicsMaterialCfg): Irrelevant if compliant contacts are disabled when :obj:`compliant_contact_stiffness` is set to zero and rigid contacts are active. """ - - -@configclass -class DeformableBodyMaterialCfg(PhysicsMaterialCfg): - """Physics material parameters for deformable bodies. - - See :meth:`spawn_deformable_body_material` for more information. - - """ - - func: Callable | str = "{DIR}.physics_materials:spawn_deformable_body_material" - - density: float | None = None - """The material density. Defaults to None, in which case the simulation decides the default density.""" - - dynamic_friction: float = 0.25 - """The dynamic friction. Defaults to 0.25.""" - - youngs_modulus: float = 50000000.0 - """The Young's modulus, which defines the body's stiffness. Defaults to 50000000.0. - - The Young's modulus is a measure of the material's ability to deform under stress. It is measured in Pascals (Pa). - """ - - poissons_ratio: float = 0.45 - """The Poisson's ratio which defines the body's volume preservation. Defaults to 0.45. - - The Poisson's ratio is a measure of the material's ability to expand in the lateral direction when compressed - in the axial direction. It is a dimensionless number between 0 and 0.5. Using a value of 0.5 will make the - material incompressible. - """ - - elasticity_damping: float = 0.005 - """The elasticity damping for the deformable material. Defaults to 0.005.""" - - damping_scale: float = 1.0 - """The damping scale for the deformable material. Defaults to 1.0. - - A scale of 1 corresponds to default damping. A value of 0 will only apply damping to certain motions leading - to special effects that look similar to water filled soft bodies. - """ diff --git a/source/isaaclab/isaaclab/sim/spawners/meshes/__init__.pyi b/source/isaaclab/isaaclab/sim/spawners/meshes/__init__.pyi index 9bfeb4cd4327..06490befb33f 100644 --- a/source/isaaclab/isaaclab/sim/spawners/meshes/__init__.pyi +++ b/source/isaaclab/isaaclab/sim/spawners/meshes/__init__.pyi @@ -9,12 +9,14 @@ __all__ = [ "spawn_mesh_cuboid", "spawn_mesh_cylinder", "spawn_mesh_sphere", + "spawn_mesh_square", "MeshCapsuleCfg", "MeshCfg", "MeshConeCfg", "MeshCuboidCfg", "MeshCylinderCfg", "MeshSphereCfg", + "MeshSquareCfg", ] from .meshes import ( @@ -23,6 +25,7 @@ from .meshes import ( spawn_mesh_cuboid, spawn_mesh_cylinder, spawn_mesh_sphere, + spawn_mesh_square, ) from .meshes_cfg import ( MeshCapsuleCfg, @@ -31,4 +34,5 @@ from .meshes_cfg import ( MeshCuboidCfg, MeshCylinderCfg, MeshSphereCfg, + MeshSquareCfg, ) diff --git a/source/isaaclab/isaaclab/sim/spawners/meshes/meshes.py b/source/isaaclab/isaaclab/sim/spawners/meshes/meshes.py index b6f441fc22d3..75ead1c8fb67 100644 --- a/source/isaaclab/isaaclab/sim/spawners/meshes/meshes.py +++ b/source/isaaclab/isaaclab/sim/spawners/meshes/meshes.py @@ -11,12 +11,16 @@ import trimesh import trimesh.transformations +# deformables only supported on PhysX backend +from isaaclab_physx.sim import schemas as schemas_physx +from isaaclab_physx.sim.spawners.materials import DeformableBodyMaterialCfg, SurfaceDeformableBodyMaterialCfg + from pxr import Usd, UsdPhysics from isaaclab.sim import schemas from isaaclab.sim.utils import bind_physics_material, bind_visual_material, clone, create_prim, get_current_stage -from ..materials import DeformableBodyMaterialCfg, RigidBodyMaterialCfg +from ..materials import RigidBodyMaterialCfg if TYPE_CHECKING: from . import meshes_cfg @@ -256,6 +260,51 @@ def spawn_mesh_cone( return stage.GetPrimAtPath(prim_path) +@clone +def spawn_mesh_square( + prim_path: str, + cfg: meshes_cfg.MeshSquareCfg, + translation: tuple[float, float, float] | None = None, + orientation: tuple[float, float, float, float] | None = None, + **kwargs, +) -> Usd.Prim: + """Create a USD-Mesh 2D square prim with the given attributes. + + .. note:: + This function is decorated with :func:`clone` that resolves prim path into list of paths + if the input prim path is a regex pattern. This is done to support spawning multiple assets + from a single and cloning the USD prim at the given path expression. + + Args: + prim_path: The prim path or pattern to spawn the asset at. If the prim path is a regex pattern, + then the asset is spawned at all the matching prim paths. + cfg: The configuration instance. + translation: The translation to apply to the prim w.r.t. its parent prim. Defaults to None, in which case + this is set to the origin. + orientation: The orientation in (x, y, z, w) to apply to the prim w.r.t. its parent prim. Defaults to None, + in which case this is set to identity. + **kwargs: Additional keyword arguments, like ``clone_in_fabric``. + + Returns: + The created prim. + + Raises: + ValueError: If a prim already exists at the given path. + """ + # create a 2D triangle mesh grid + from omni.physx.scripts import deformableUtils + + vertices, faces = deformableUtils.create_triangle_mesh_square(cfg.resolution[0], cfg.resolution[1], scale=cfg.size) + grid = trimesh.Trimesh(vertices=vertices, faces=np.array(faces).reshape(-1, 3), process=False) + + # obtain stage handle + stage = get_current_stage() + # spawn the square as a mesh + _spawn_mesh_geom_from_mesh(prim_path, cfg, grid, translation, orientation, None, stage=stage) + # return the prim + return stage.GetPrimAtPath(prim_path) + + """ Helper functions. """ @@ -342,14 +391,17 @@ def _spawn_mesh_geom_from_mesh( stage=stage, ) - # note: in case of deformable objects, we need to apply the deformable properties to the mesh prim. - # this is different from rigid objects where we apply the properties to the parent prim. if cfg.deformable_props is not None: - # apply mass properties - if cfg.mass_props is not None: - schemas.define_mass_properties(mesh_prim_path, cfg.mass_props, stage=stage) # apply deformable body properties - schemas.define_deformable_body_properties(mesh_prim_path, cfg.deformable_props, stage=stage) + deformable_type = "surface" if isinstance(cfg.physics_material, SurfaceDeformableBodyMaterialCfg) else "volume" + schemas_physx.define_deformable_body_properties( + prim_path, cfg.deformable_props, stage=stage, deformable_type=deformable_type + ) + if cfg.mass_props is not None: + raise ValueError( + """MassPropertiesCfg are not supported for deformable bodies + and should be set through DeformableBodyPropertiesCfg(mass=).""" + ) elif cfg.collision_props is not None: # decide on type of collision approximation based on the mesh if cfg.__class__.__name__ == "MeshSphereCfg": @@ -386,7 +438,7 @@ def _spawn_mesh_geom_from_mesh( # create material cfg.physics_material.func(material_path, cfg.physics_material) # apply material - bind_physics_material(mesh_prim_path, material_path, stage=stage) + bind_physics_material(prim_path, material_path, stage=stage) # note: we apply the rigid properties to the parent prim in case of rigid objects. if cfg.rigid_props is not None: diff --git a/source/isaaclab/isaaclab/sim/spawners/meshes/meshes_cfg.py b/source/isaaclab/isaaclab/sim/spawners/meshes/meshes_cfg.py index 9cf3d45716f5..a9e7e44586d0 100644 --- a/source/isaaclab/isaaclab/sim/spawners/meshes/meshes_cfg.py +++ b/source/isaaclab/isaaclab/sim/spawners/meshes/meshes_cfg.py @@ -9,8 +9,11 @@ from dataclasses import MISSING from typing import Literal +# deformables only supported on PhysX backend +from isaaclab_physx.sim.spawners.spawner_cfg import DeformableObjectSpawnerCfg + from isaaclab.sim.spawners import materials -from isaaclab.sim.spawners.spawner_cfg import DeformableObjectSpawnerCfg, RigidObjectSpawnerCfg +from isaaclab.sim.spawners.spawner_cfg import RigidObjectSpawnerCfg from isaaclab.utils import configclass @@ -140,3 +143,18 @@ class MeshConeCfg(MeshCfg): """Height of the v (in m).""" axis: Literal["X", "Y", "Z"] = "Z" """Axis of the cone. Defaults to "Z".""" + + +@configclass +class MeshSquareCfg(MeshCfg): + """Configuration parameters for a 2D square mesh prim. + + See :meth:`spawn_mesh_square` for more information. + """ + + func: Callable | str = "{DIR}.meshes:spawn_mesh_square" + + size: float = MISSING + """Edge length of the square (in m).""" + resolution: tuple[int, int] = (5, 5) + """Resolution of the square (in elements/edges per side).""" diff --git a/source/isaaclab/isaaclab/sim/spawners/sensors/__init__.pyi b/source/isaaclab/isaaclab/sim/spawners/sensors/__init__.pyi index 46d24596932c..ba5b96a44c7d 100644 --- a/source/isaaclab/isaaclab/sim/spawners/sensors/__init__.pyi +++ b/source/isaaclab/isaaclab/sim/spawners/sensors/__init__.pyi @@ -5,9 +5,11 @@ __all__ = [ "spawn_camera", + "spawn_sensor_frame", "FisheyeCameraCfg", "PinholeCameraCfg", + "SensorFrameCfg", ] -from .sensors import spawn_camera -from .sensors_cfg import FisheyeCameraCfg, PinholeCameraCfg +from .sensors import spawn_camera, spawn_sensor_frame +from .sensors_cfg import FisheyeCameraCfg, PinholeCameraCfg, SensorFrameCfg diff --git a/source/isaaclab/isaaclab/sim/spawners/sensors/sensors.py b/source/isaaclab/isaaclab/sim/spawners/sensors/sensors.py index 4eb70005e487..db68d21d8a90 100644 --- a/source/isaaclab/isaaclab/sim/spawners/sensors/sensors.py +++ b/source/isaaclab/isaaclab/sim/spawners/sensors/sensors.py @@ -145,3 +145,46 @@ def spawn_camera( prim.GetAttribute(prim_prop_name).Set(param_value) # return the prim return prim + + +@clone +def spawn_sensor_frame( + prim_path: str, + cfg: sensors_cfg.SensorFrameCfg, + translation: tuple[float, float, float] | None = None, + orientation: tuple[float, float, float, float] | None = None, + **kwargs, +) -> Usd.Prim: + """Create a plain USD Xform prim as a sensor attachment frame. + + .. note:: + This function is decorated with :func:`clone` that resolves prim path into list of paths + if the input prim path is a regex pattern. + + Args: + prim_path: The prim path or pattern to spawn the asset at. + cfg: The configuration instance. + translation: Local translation (x, y, z) [m] w.r.t. the parent prim. Defaults to None + (origin). + orientation: Local orientation as quaternion (x, y, z, w) w.r.t. the parent prim. + Defaults to None (identity). + **kwargs: Additional keyword arguments, like ``clone_in_fabric``. + + Returns: + The created USD prim. + + Raises: + ValueError: If a prim already exists at the given path. + """ + stage = get_current_stage() + if not stage.GetPrimAtPath(prim_path).IsValid(): + prim = create_prim( + prim_path, + "Xform", + translation=translation, + orientation=orientation, + stage=stage, + ) + else: + raise ValueError(f"A prim already exists at path: '{prim_path}'.") + return prim diff --git a/source/isaaclab/isaaclab/sim/spawners/sensors/sensors_cfg.py b/source/isaaclab/isaaclab/sim/spawners/sensors/sensors_cfg.py index 56c9102cf1f1..1ad9dcd73bf2 100644 --- a/source/isaaclab/isaaclab/sim/spawners/sensors/sensors_cfg.py +++ b/source/isaaclab/isaaclab/sim/spawners/sensors/sensors_cfg.py @@ -222,3 +222,15 @@ class FisheyeCameraCfg(PinholeCameraCfg): fisheye_polynomial_f: float = 0.0 """Sixth component of fisheye polynomial. Defaults to 0.0.""" + + +@configclass +class SensorFrameCfg(SpawnerCfg): + """Spawns a plain USD Xform as a sensor attachment frame. + + The spawned prim carries no rigid body or collision API. It serves as a + non-physics child under a link so that :class:`~isaaclab.sim.views.FrameView` + can track it on all backends (including Newton, which rejects physics body prims). + """ + + func: Callable | str = "{DIR}.sensors:spawn_sensor_frame" diff --git a/source/isaaclab/isaaclab/sim/spawners/spawner_cfg.py b/source/isaaclab/isaaclab/sim/spawners/spawner_cfg.py index ba86e4937fc3..7a803ad0e0dd 100644 --- a/source/isaaclab/isaaclab/sim/spawners/spawner_cfg.py +++ b/source/isaaclab/isaaclab/sim/spawners/spawner_cfg.py @@ -100,25 +100,3 @@ class RigidObjectSpawnerCfg(SpawnerCfg): This adds the PhysxContactReporter API to all the rigid bodies in the given prim path and its children. """ - - -@configclass -class DeformableObjectSpawnerCfg(SpawnerCfg): - """Configuration parameters for spawning a deformable asset. - - Unlike rigid objects, deformable objects are affected by forces and can deform when subjected to - external forces. This class is used to configure the properties of the deformable object. - - Deformable bodies don't have a separate collision mesh. The collision mesh is the same as the visual mesh. - The collision properties such as rest and collision offsets are specified in the :attr:`deformable_props`. - - Note: - By default, all properties are set to None. This means that no properties will be added or modified - to the prim outside of the properties available by default when spawning the prim. - """ - - mass_props: schemas.MassPropertiesCfg | None = None - """Mass properties.""" - - deformable_props: schemas.DeformableBodyPropertiesCfg | None = None - """Deformable body properties.""" diff --git a/source/isaaclab/isaaclab/sim/spawners/wrappers/wrappers_cfg.py b/source/isaaclab/isaaclab/sim/spawners/wrappers/wrappers_cfg.py index 1533c29687e8..d9b7d9ed0c35 100644 --- a/source/isaaclab/isaaclab/sim/spawners/wrappers/wrappers_cfg.py +++ b/source/isaaclab/isaaclab/sim/spawners/wrappers/wrappers_cfg.py @@ -3,10 +3,27 @@ # # SPDX-License-Identifier: BSD-3-Clause +import warnings from dataclasses import MISSING +# deformables only supported in PhysX backend +try: + from isaaclab_physx.sim.spawners.spawner_cfg import DeformableObjectSpawnerCfg +except ImportError as e: + warnings.warn( + f"""Could not import DeformableObjectSpawnerCfg, is isaaclab_physx installed? + Safe to ignore if using newton only. Complete exception: {e}""" + ) + # import dummy class to avoid errors in type hints + from isaaclab.utils import configclass + + @configclass + class DeformableObjectSpawnerCfg: + deformable_props = None + + from isaaclab.sim.spawners.from_files import UsdFileCfg -from isaaclab.sim.spawners.spawner_cfg import DeformableObjectSpawnerCfg, RigidObjectSpawnerCfg, SpawnerCfg +from isaaclab.sim.spawners.spawner_cfg import RigidObjectSpawnerCfg, SpawnerCfg from isaaclab.utils import configclass diff --git a/source/isaaclab/isaaclab/sim/utils/newton_model_utils.py b/source/isaaclab/isaaclab/sim/utils/newton_model_utils.py new file mode 100644 index 000000000000..d94a309e5b55 --- /dev/null +++ b/source/isaaclab/isaaclab/sim/utils/newton_model_utils.py @@ -0,0 +1,352 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""DO NOT USE ANY FUNCTION IN THIS FILE. + +This module exists only while Isaac Lab and Isaac Sim content still relies on NVIDIA-specific MDL and OmniPBR +materials; after migration to neutral USD materials that Newton can consume directly, this module is expected +to be deprecated and removed. +""" + +from __future__ import annotations + +import logging +import os +import warnings +from typing import Any + +import numpy as np +import warp as wp + +from pxr import Usd, UsdGeom, UsdShade + +__all__ = ["replace_newton_shape_colors"] + +logger = logging.getLogger(__name__) + +# MDL OmniPBR defaults when inputs are not authored (typical MDL defaults). Keys match shader input names. +_OMNIPBR_DEFAULTS: dict[str, tuple[float, float, float]] = { + "diffuse_color_constant": (0.2, 0.2, 0.2), + "diffuse_tint": (1.0, 1.0, 1.0), +} + +# Neutral linear RGB when a shape has no material binding and no ``displayColor`` override. +_UNBOUND_DEFAULT_FALLBACK_GRAY = (0.18, 0.18, 0.18) + + +@wp.func +def _linear_channel_to_srgb_warp(c: float) -> float: + """Per-channel sRGB OETF on device: linear ``[0, 1]`` to sRGB-encoded ``[0, 1]``.""" + if c <= 0.0: + return 0.0 + if c <= 0.0031308: + return 12.92 * c + if c >= 1.0: + return 1.0 + return 1.055 * wp.pow(c, 1.0 / 2.4) - 0.055 + + +@wp.func +def _linear_rgb_to_srgb_warp(linear_rgb: wp.vec3) -> wp.vec3: + """Apply sRGB OETF per channel: linear RGB ``[0, 1]`` to sRGB-encoded ``[0, 1]``.""" + return wp.vec3( + _linear_channel_to_srgb_warp(linear_rgb[0]), + _linear_channel_to_srgb_warp(linear_rgb[1]), + _linear_channel_to_srgb_warp(linear_rgb[2]), + ) + + +@wp.kernel +def _scatter_shape_color_rows_kernel( + shape_colors: wp.array(dtype=wp.vec3), # type: ignore + row_indices: wp.array(dtype=wp.int32), # type: ignore + row_colors: wp.array(dtype=wp.vec3), # type: ignore +): + """Write per-row sRGB colors into ``shape_colors``.""" + tid = wp.tid() + index = row_indices[tid] + color = row_colors[tid] + shape_colors[index] = _linear_rgb_to_srgb_warp(color) + + +def _canonical_prim_lookup_key(prim: Usd.Prim) -> str: + """Pick a single USD path for lookup, to maximize cache hits.""" + assert prim.IsValid() + + if prim.IsInstanceProxy(): + proto = prim.GetPrimInPrototype() + if proto.IsValid(): + return proto.GetPath().pathString + + return prim.GetPath().pathString + + +def _asset_path_to_str(asset_path: Any) -> str: + """Stringify an asset path.""" + if asset_path is None: + return "" + return str(asset_path.path) if hasattr(asset_path, "path") else str(asset_path) + + +def _is_omnipbr_shader(shader_prim: Usd.Prim) -> bool: + """Return True if the shader prim references the OmniPBR MDL module (MDL-in-USD metadata).""" + if shader_prim.IsValid(): + attr = shader_prim.GetAttribute("info:mdl:sourceAsset") + if attr and attr.HasAuthoredValue() and _asset_path_to_str(attr.Get()).endswith("OmniPBR.mdl"): + return True + + attr = shader_prim.GetAttribute("info:mdl:sourceAsset:subIdentifier") + if attr and attr.HasAuthoredValue() and str(attr.Get()) == "OmniPBR": + return True + + return False + + +def _get_bound_material_prim(shape_prim: Usd.Prim) -> Usd.Prim: + """Resolve the effective bound *visual* material path for a geometry prim. + + This uses :meth:`UsdShade.MaterialBindingAPI.ComputeBoundMaterial` so inherited bindings and + binding-strength semantics (e.g. ``strongerThanDescendants``) are handled correctly. + """ + if shape_prim.IsValid(): + material, _ = UsdShade.MaterialBindingAPI(shape_prim).ComputeBoundMaterial() + if material: + material_prim = material.GetPrim() + if material_prim.IsValid(): + return material_prim + + return Usd.Prim() + + +def _get_input_value(shader: UsdShade.Shader, name: str) -> tuple[float, float, float] | None: + """Fetch the effective input value from a shader, following connections.""" + inp = shader.GetInput(name) + if inp is not None: + attrs = UsdShade.Utils.GetValueProducingAttributes(inp) + if attrs and len(attrs) > 0: + value = attrs[0].Get() + if value is not None: + return _coerce_color(value) + + return None + + +def _get_surface_shader(material_prim: Usd.Prim) -> Usd.Prim: + """Get the surface shader from a material.""" + material = UsdShade.Material(material_prim) + surface_output = material.GetSurfaceOutput() + if not surface_output: + surface_output = material.GetOutput("surface") + if not surface_output: + surface_output = material.GetOutput("mdl:surface") + + shader_prim = Usd.Prim() + + if surface_output: + connected_source = surface_output.GetConnectedSource() + if connected_source: + shader_prim = connected_source[0].GetPrim() + + if not shader_prim.IsValid(): + for child in material_prim.GetChildren(): + if child.IsA(UsdShade.Shader): + shader_prim = child + break + + return shader_prim + + +def _get_omnipbr_input(shader: UsdShade.Shader, input_name: str) -> tuple[float, float, float]: + """Return authored linear RGB for ``input_name`` if it exists, else the MDL OmniPBR default.""" + value = _get_input_value(shader, input_name) + return value or _OMNIPBR_DEFAULTS[input_name] + + +def _get_omnipbr_albedo(shader_prim: Usd.Prim) -> tuple[float, float, float]: + """Return diffuse albedo as linear RGB (``diffuse_color_constant`` × ``diffuse_tint``).""" + surface_shader = UsdShade.Shader(shader_prim) + c0, c1, c2 = _get_omnipbr_input(surface_shader, "diffuse_color_constant") + t0, t1, t2 = _get_omnipbr_input(surface_shader, "diffuse_tint") + return (c0 * t0, c1 * t1, c2 * t2) + + +def _coerce_color(value: Any) -> tuple[float, float, float] | None: + """Coerce a value to an RGB color tuple, or None if not possible.""" + if value is None: + return None + color_np = np.array(value, dtype=np.float32).reshape(-1) + if color_np.size >= 3: + return (float(color_np[0]), float(color_np[1]), float(color_np[2])) + return None + + +def _get_primvar_display_color(shape_prim: Usd.Prim) -> tuple[float, float, float] | None: + """Get authored ``primvars:displayColor`` from a shape prim as linear RGB.""" + primvars_api = UsdGeom.PrimvarsAPI(shape_prim) + if not primvars_api.HasPrimvar("displayColor"): + return None + + primvar = primvars_api.GetPrimvar("displayColor") + if primvar is None: + return None + + return _coerce_color(primvar.Get()) + + +def _resolve_shape_color( + stage: Usd.Stage, + prim_path: str, + material_color_cache: dict[str, tuple[float, float, float] | None], +) -> tuple[float, float, float] | None: + """Resolve replacement linear RGB for one prim path (sRGB encoding is applied in the scatter kernel). + + Returns: + Linear RGB to pass to :func:`_scatter_shape_color_rows_kernel`, or ``None`` to leave the row unchanged. + """ + shape_prim = stage.GetPrimAtPath(prim_path) + if not shape_prim.IsValid(): + return None + + # Newton's random color palette is designed for guide shapes so we keep them unchanged. + imageable = UsdGeom.Imageable(shape_prim) + if bool(imageable) and imageable.ComputePurpose() == UsdGeom.Tokens.guide: + return None + + material_prim = _get_bound_material_prim(shape_prim) + if not material_prim.IsValid(): + display_color = _get_primvar_display_color(shape_prim) + return display_color or _UNBOUND_DEFAULT_FALLBACK_GRAY + + material_key = _canonical_prim_lookup_key(material_prim) + if material_key in material_color_cache: + return material_color_cache[material_key] + + # We only overwrite color if the material is OmniPBR. Otherwise, we leave the existing color unchanged. + shader_prim = _get_surface_shader(material_prim) + material_color = _get_omnipbr_albedo(shader_prim) if _is_omnipbr_shader(shader_prim) else None + + material_color_cache[material_key] = material_color + return material_color + + +def replace_newton_shape_colors(model: Any, stage: Usd.Stage | None = None) -> int: + """Align Newton visualization colors with the USD stage. + + Newton assigns a per-shape palette to ``shape_color``. This overwrites those rows so rendering matches authored USD + data where supported: + + - **No bound material**: use authored ``primvars:displayColor`` (treated as linear RGB), or a neutral 18% linear + gray if ``displayColor`` is not authored; linear values are encoded to sRGB in the scatter kernel. + - **OmniPBR**: use ``diffuse_color_constant`` times ``diffuse_tint`` (linear RGB, with MDL defaults when inputs are + not authored), encoded to sRGB in the scatter kernel. + - **Other materials**: leave the existing Newton color for that shape. + - **Guide purpose** prims (``UsdGeom.Tokens.guide``): leave unchanged so guide visualization stays on the palette. + + Args: + model: Object with ``shape_label`` (``list`` of USD prim paths) and ``shape_color`` (``wp.array`` of + ``wp.vec3``), typically a finalized Newton model. + stage: USD stage to read from. If ``None``, uses :func:`~isaaclab.sim.utils.stage.get_current_stage`. + + Returns: + Number of shapes that had their colors replaced. + + Note: + Set ``ISAACLAB_REPLACE_NEWTON_SHAPE_COLORS`` to ``0``, ``false``, ``off``, or ``no`` to skip this pass + entirely (returns ``0``). + + This pass exists only while Isaac Lab and Isaac Sim content still relies on NVIDIA-specific MDL and OmniPBR + materials; after migration to neutral USD materials that Newton can consume directly, this path is expected to + be deprecated and removed. + + Wall time for USD resolution and the GPU scatter is measured with :class:`~isaaclab.utils.timer.Timer`, which + may print a timing summary when the timer is enabled. + """ + env_val = os.getenv("ISAACLAB_REPLACE_NEWTON_SHAPE_COLORS") + if env_val is not None and env_val.strip().lower() in ["false", "0", "off", "no"]: + logger.debug("Newton shape color replacement is disabled") + return 0 + + warnings.warn( + "Newton shape color replacement is enabled; this workaround will be deprecated in a future release.", + FutureWarning, + stacklevel=2, + ) + + # Use duck typing to avoid introducing hard dependencies on newton. + shape_labels = getattr(model, "shape_label", None) + shape_colors = getattr(model, "shape_color", None) + + if not isinstance(shape_labels, list): + logger.debug("shape_label must be a list, got %s", type(shape_labels)) + return 0 + + if not isinstance(shape_colors, wp.array): + logger.debug("shape_color must be a Warp array, got %s", type(shape_colors)) + return 0 + + num_shapes = len(shape_labels) + if num_shapes == 0: + logger.debug("Found empty list of shape labels") + return 0 + + if num_shapes != len(shape_colors): + logger.debug("Mismatching length of shape_labels and shape_colors: %d != %d", num_shapes, len(shape_colors)) + return 0 + + from isaaclab.utils.timer import Timer + + num_color_updates = 0 + + with Timer(f"[INFO]: Time taken for replace_newton_shape_colors for {num_shapes} shapes", enable=False): + if stage is None: + from .stage import get_current_stage + + stage = get_current_stage() + + shape_keys: list[str] = [] + + for label in shape_labels: + prim = stage.GetPrimAtPath(label) + shape_keys.append(_canonical_prim_lookup_key(prim) if prim.IsValid() else label) + + # shape_keys must stay the same length as shape labels, to guarantee the correctness of + # shape indices that will be used in the scatter kernel. + assert num_shapes == len(shape_keys) + + resolved_color_cache: dict[str, tuple[float, float, float] | None] = {} + material_color_cache: dict[str, tuple[float, float, float] | None] = {} + + unique_keys = dict.fromkeys(shape_keys) + for key in unique_keys: + color = _resolve_shape_color(stage, key, material_color_cache) + resolved_color_cache[key] = color + + # Prepare the indices and colors for the scatter kernel: + # - Indices point to the slots in the shape_colors array that should be updated + # - Colors are the new values to write into the slots + indices_np = np.empty(num_shapes, dtype=np.int32) + colors_np = np.empty((num_shapes, 3), dtype=np.float32) + + for i, shape_key in enumerate(shape_keys): + if rgb := resolved_color_cache.get(shape_key): + indices_np[num_color_updates] = i + colors_np[num_color_updates] = rgb + num_color_updates += 1 + + # If there are any color updates, launch the scatter kernel to update the shape_colors array. + if num_color_updates != 0: + indices_wp = wp.from_numpy(indices_np[:num_color_updates], dtype=wp.int32, device=shape_colors.device) + colors_wp = wp.from_numpy(colors_np[:num_color_updates], dtype=wp.vec3, device=shape_colors.device) + + wp.launch( + kernel=_scatter_shape_color_rows_kernel, + dim=num_color_updates, + inputs=[shape_colors, indices_wp, colors_wp], + device=shape_colors.device, + ) + + logger.debug("Replaced colors for %d / %d shapes", num_color_updates, num_shapes) + + return num_color_updates diff --git a/source/isaaclab/isaaclab/sim/utils/prims.py b/source/isaaclab/isaaclab/sim/utils/prims.py index f78b8ec22e0e..d54ca890d2b7 100644 --- a/source/isaaclab/isaaclab/sim/utils/prims.py +++ b/source/isaaclab/isaaclab/sim/utils/prims.py @@ -834,7 +834,7 @@ def bind_physics_material( applied = prim.GetAppliedSchemas() has_physics_scene_api = "PhysxSceneAPI" in applied has_collider = prim.HasAPI(UsdPhysics.CollisionAPI) - has_deformable_body = "PhysxDeformableBodyAPI" in applied + has_deformable_body = "OmniPhysicsDeformableBodyAPI" in applied has_particle_system = prim.GetTypeName() == "PhysxParticleSystem" if not (has_physics_scene_api or has_collider or has_deformable_body or has_particle_system): logger.debug( diff --git a/source/isaaclab/isaaclab/sim/utils/stage.py b/source/isaaclab/isaaclab/sim/utils/stage.py index eb2b54d57cbd..3b2f5eb15a9e 100644 --- a/source/isaaclab/isaaclab/sim/utils/stage.py +++ b/source/isaaclab/isaaclab/sim/utils/stage.py @@ -123,7 +123,7 @@ def _modify_path(asset_path: str) -> str: # _context is a singleton design in isaacsim and for that reason # until we fully replace all modules that references the singleton(such as XformPrim, Prim ....), we have to point # that singleton to this _context - from isaacsim.core.utils import stage as sim_stage + from isaacsim.core.experimental.utils import stage as sim_stage sim_stage._context = _context # type: ignore except ImportError: @@ -136,7 +136,7 @@ def create_new_stage() -> Usd.Stage: Creates a new stage using pure USD (``Usd.Stage.CreateInMemory()``). If Kit is running and Kit extensions need to discover this stage (e.g. - PhysX, ``isaacsim.core.prims.Articulation``), call + PhysX, ``isaacsim.core.experimental.prims.Articulation``), call :func:`attach_stage_to_usd_context` after scene setup. Returns: diff --git a/source/isaaclab/isaaclab/sim/views/__init__.pyi b/source/isaaclab/isaaclab/sim/views/__init__.pyi index a666958e4387..d578f85d6ada 100644 --- a/source/isaaclab/isaaclab/sim/views/__init__.pyi +++ b/source/isaaclab/isaaclab/sim/views/__init__.pyi @@ -4,7 +4,15 @@ # SPDX-License-Identifier: BSD-3-Clause __all__ = [ + "BaseFrameView", + "UsdFrameView", + "FrameView", + # Deprecated alias "XformPrimView", ] +from .base_frame_view import BaseFrameView +from .usd_frame_view import UsdFrameView +from .frame_view import FrameView +# Deprecated alias from .xform_prim_view import XformPrimView diff --git a/source/isaaclab/isaaclab/sim/views/base_frame_view.py b/source/isaaclab/isaaclab/sim/views/base_frame_view.py new file mode 100644 index 000000000000..d58cb0fbb534 --- /dev/null +++ b/source/isaaclab/isaaclab/sim/views/base_frame_view.py @@ -0,0 +1,120 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Abstract base class for batched prim transform views.""" + +from __future__ import annotations + +import abc + +import warp as wp + +from isaaclab.utils.warp import ProxyArray + + +class BaseFrameView(abc.ABC): + """Abstract interface for reading and writing world-space transforms of multiple prims. + + Backend-specific implementations (USD/Fabric, Newton GPU state, etc.) subclass + this to provide efficient batched pose queries. The factory + :class:`~isaaclab.sim.views.FrameView` selects the correct + implementation at runtime based on the active physics backend. + + All pose getters return :class:`~isaaclab.utils.warp.ProxyArray`. Setters accept ``wp.array``. + """ + + @property + @abc.abstractmethod + def count(self) -> int: + """Number of prims in this view.""" + ... + + @property + @abc.abstractmethod + def device(self) -> str: + """Device where arrays are allocated (``"cpu"`` or ``"cuda:0"``).""" + ... + + @abc.abstractmethod + def get_world_poses(self, indices: wp.array | None = None) -> tuple[ProxyArray, ProxyArray]: + """Get world-space positions and orientations for prims in the view. + + Args: + indices: Subset of prims to query. ``None`` means all prims. + + Returns: + A tuple ``(positions, orientations)`` of :class:`~isaaclab.utils.warp.ProxyArray` + wrappers. Use ``.warp`` for the underlying ``wp.array`` or ``.torch`` for a + cached zero-copy ``torch.Tensor`` view. + """ + ... + + @abc.abstractmethod + def set_world_poses( + self, + positions: wp.array | None = None, + orientations: wp.array | None = None, + indices: wp.array | None = None, + ) -> None: + """Set world-space positions and/or orientations for prims in the view. + + Args: + positions: World-space positions ``(M, 3)``. ``None`` leaves positions unchanged. + orientations: World-space quaternions ``(M, 4)``. ``None`` leaves orientations unchanged. + indices: Subset of prims to update. ``None`` means all prims. + """ + ... + + @abc.abstractmethod + def get_local_poses(self, indices: wp.array | None = None) -> tuple[ProxyArray, ProxyArray]: + """Get local-space positions and orientations for prims in the view. + + Args: + indices: Subset of prims to query. ``None`` means all prims. + + Returns: + A tuple ``(translations, orientations)`` of :class:`~isaaclab.utils.warp.ProxyArray` + wrappers. Use ``.warp`` for the underlying ``wp.array`` or ``.torch`` for a + cached zero-copy ``torch.Tensor`` view. + """ + ... + + @abc.abstractmethod + def set_local_poses( + self, + translations: wp.array | None = None, + orientations: wp.array | None = None, + indices: wp.array | None = None, + ) -> None: + """Set local-space translations and/or orientations for prims in the view. + + Args: + translations: Local-space translations ``(M, 3)``. ``None`` leaves translations unchanged. + orientations: Local-space quaternions ``(M, 4)``. ``None`` leaves orientations unchanged. + indices: Subset of prims to update. ``None`` means all prims. + """ + ... + + @abc.abstractmethod + def get_scales(self, indices: wp.array | None = None) -> wp.array: + """Get scales for prims in the view. + + Args: + indices: Subset of prims to query. ``None`` means all prims. + + Returns: + A ``wp.array`` of shape ``(M, 3)``. + """ + ... + + @abc.abstractmethod + def set_scales(self, scales: wp.array, indices: wp.array | None = None) -> None: + """Set scales for prims in the view. + + Args: + scales: Scales ``(M, 3)`` as ``wp.array``. + indices: Subset of prims to update. ``None`` means all prims. + """ + ... diff --git a/source/isaaclab/isaaclab/sim/views/frame_view.py b/source/isaaclab/isaaclab/sim/views/frame_view.py new file mode 100644 index 000000000000..ea9d5bfbeea9 --- /dev/null +++ b/source/isaaclab/isaaclab/sim/views/frame_view.py @@ -0,0 +1,48 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Backend-dispatching FrameView. + +``FrameView(path, device=...)`` automatically selects the right backend: +- PhysX: :class:`~isaaclab_physx.sim.views.FabricFrameView` +- Newton: :class:`~isaaclab_newton.sim.views.NewtonSiteFrameView` +""" + +from __future__ import annotations + +from isaaclab.utils.backend_utils import FactoryBase + +from .base_frame_view import BaseFrameView + + +class FrameView(FactoryBase, BaseFrameView): + """FrameView that dispatches to the active physics backend. + + Callers use ``FrameView(prim_path, device=device)`` and get the + correct implementation automatically: + + - **PhysX / no backend**: :class:`~isaaclab_physx.sim.views.FabricFrameView` + (Fabric GPU acceleration with USD fallback). + - **Newton**: :class:`~isaaclab_newton.sim.views.NewtonSiteFrameView` + (GPU-resident site-based transforms). + """ + + _backend_class_names = {"physx": "FabricFrameView", "newton": "NewtonSiteFrameView"} + + @classmethod + def _get_backend(cls, *args, **kwargs) -> str: + from isaaclab.sim.simulation_context import SimulationContext # noqa: PLC0415 + + ctx = SimulationContext.instance() + if ctx is None: + return "physx" + manager_name = ctx.physics_manager.__name__.lower() + if "newton" in manager_name: + return "newton" + return "physx" + + def __new__(cls, *args, **kwargs) -> BaseFrameView: + """Create a new FrameView for the active physics backend.""" + return super().__new__(cls, *args, **kwargs) diff --git a/source/isaaclab/isaaclab/sim/views/usd_frame_view.py b/source/isaaclab/isaaclab/sim/views/usd_frame_view.py new file mode 100644 index 000000000000..7730c3dd735d --- /dev/null +++ b/source/isaaclab/isaaclab/sim/views/usd_frame_view.py @@ -0,0 +1,362 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from __future__ import annotations + +import logging + +import numpy as np +import torch +import warp as wp + +from pxr import Gf, Sdf, Usd, UsdGeom, Vt + +import isaaclab.sim as sim_utils +from isaaclab.utils.warp import ProxyArray + +from .base_frame_view import BaseFrameView + +logger = logging.getLogger(__name__) + + +class UsdFrameView(BaseFrameView): + """Batched interface for reading and writing transforms of multiple USD prims. + + Provides batch operations for getting and setting poses (position and orientation) + of multiple prims at once via USD's ``XformCache``. + + The class supports both world-space and local-space pose operations: + + - **World poses**: Positions and orientations in the global world frame + - **Local poses**: Positions and orientations relative to each prim's parent + + For GPU-accelerated Fabric operations, use the PhysX backend variant + obtained via :class:`~isaaclab.sim.views.FrameView`. + + Pose getters return :class:`~isaaclab.utils.warp.ProxyArray`. Setters accept ``wp.array``. + + .. note:: + **Transform Requirements:** + + All prims in the view must be Xformable and have standardized transform operations: + ``[translate, orient, scale]``. Non-standard prims will raise a ValueError during + initialization if :attr:`validate_xform_ops` is True. Please use the function + :func:`isaaclab.sim.utils.standardize_xform_ops` to prepare prims before using this view. + + .. warning:: + This class operates at the USD default time code. Any animation or time-sampled data + will not be affected by write operations. For animated transforms, you need to handle + time-sampled keyframes separately. + """ + + def __init__( + self, + prim_path: str, + device: str = "cpu", + validate_xform_ops: bool = True, + stage: Usd.Stage | None = None, + **kwargs, + ): + """Initialize the view with matching prims. + + Args: + prim_path: USD prim path pattern to match prims. Supports wildcards (``*``) and + regex patterns (e.g., ``"/World/Env_.*/Robot"``). See + :func:`isaaclab.sim.utils.find_matching_prims` for pattern syntax. + device: Device to place arrays on. Can be ``"cpu"`` or CUDA devices like + ``"cuda:0"``. Defaults to ``"cpu"``. + validate_xform_ops: Whether to validate that the prims have standard xform operations. + Defaults to True. + stage: USD stage to search for prims. Defaults to None, in which case the current + active stage from the simulation context is used. + **kwargs: Additional keyword arguments (ignored). Allows forward-compatible + construction when callers pass backend-specific options like + ``sync_usd_on_fabric_write``. + + Raises: + ValueError: If any matched prim is not Xformable or doesn't have standardized + transform operations (translate, orient, scale in that order). + """ + self._prim_path = prim_path + self._device = device + + stage = sim_utils.get_current_stage() if stage is None else stage + self._prims: list[Usd.Prim] = sim_utils.find_matching_prims(prim_path, stage=stage) + + if validate_xform_ops: + for prim in self._prims: + sim_utils.standardize_xform_ops(prim) + if not sim_utils.validate_standard_xform_ops(prim): + raise ValueError( + f"Prim at path '{prim.GetPath().pathString}' is not a xformable prim with standard transform" + f" operations [translate, orient, scale]. Received type: '{prim.GetTypeName()}'." + " Use sim_utils.standardize_xform_ops() to prepare the prim." + ) + + self._ALL_INDICES = list(range(len(self._prims))) + + # ------------------------------------------------------------------ + # Properties + # ------------------------------------------------------------------ + + @property + def count(self) -> int: + """Number of prims in this view.""" + return len(self._prims) + + @property + def device(self) -> str: + """Device where arrays are allocated (cpu or cuda).""" + return self._device + + @property + def prims(self) -> list[Usd.Prim]: + """List of USD prims being managed by this view.""" + return self._prims + + @property + def prim_paths(self) -> list[str]: + """List of prim paths (as strings) for all prims being managed by this view. + + The conversion is performed lazily on first access and cached. + """ + if not hasattr(self, "_prim_paths"): + self._prim_paths = [prim.GetPath().pathString for prim in self._prims] + return self._prim_paths + + # ------------------------------------------------------------------ + # Setters + # ------------------------------------------------------------------ + + def set_world_poses( + self, + positions: wp.array | None = None, + orientations: wp.array | None = None, + indices: wp.array | None = None, + ): + """Set world-space poses for prims in the view. + + Converts the desired world pose to local-space relative to each prim's + parent before writing to USD xform ops. + + Args: + positions: World-space positions of shape ``(M, 3)``. + orientations: World-space quaternions ``(w, x, y, z)`` of shape ``(M, 4)``. + indices: Indices of prims to set poses for. Defaults to None (all prims). + """ + indices_list = self._resolve_indices(indices) + + positions_array = Vt.Vec3dArray.FromNumpy(self._to_numpy(positions)) if positions is not None else None + orientations_array = Vt.QuatdArray.FromNumpy(self._to_numpy(orientations)) if orientations is not None else None + + xform_cache = UsdGeom.XformCache(Usd.TimeCode.Default()) + + with Sdf.ChangeBlock(): + for idx, prim_idx in enumerate(indices_list): + prim = self._prims[prim_idx] + parent_prim = prim.GetParent() + + world_pos = positions_array[idx] if positions_array is not None else None + world_quat = orientations_array[idx] if orientations_array is not None else None + + if parent_prim.IsValid() and parent_prim.GetPath() != Sdf.Path.absoluteRootPath: + if positions_array is None or orientations_array is None: + prim_tf = xform_cache.GetLocalToWorldTransform(prim) + prim_tf.Orthonormalize() + if world_pos is not None: + prim_tf.SetTranslateOnly(world_pos) + if world_quat is not None: + prim_tf.SetRotateOnly(world_quat) + else: + prim_tf = Gf.Matrix4d() + prim_tf.SetTranslateOnly(world_pos) + prim_tf.SetRotateOnly(world_quat) + + parent_world_tf = xform_cache.GetLocalToWorldTransform(parent_prim) + local_tf = prim_tf * parent_world_tf.GetInverse() + local_pos = local_tf.ExtractTranslation() + local_quat = local_tf.ExtractRotationQuat() + else: + # Root-level prim: world == local + local_pos = world_pos + local_quat = world_quat + + if local_pos is not None: + prim.GetAttribute("xformOp:translate").Set(local_pos) + if local_quat is not None: + prim.GetAttribute("xformOp:orient").Set(local_quat) + + def set_local_poses( + self, + translations: wp.array | None = None, + orientations: wp.array | None = None, + indices: wp.array | None = None, + ): + """Set local-space poses for prims in the view. + + Args: + translations: Local-space translations of shape ``(M, 3)``. + orientations: Local-space quaternions ``(w, x, y, z)`` of shape ``(M, 4)``. + indices: Indices of prims to set poses for. Defaults to None (all prims). + """ + indices_list = self._resolve_indices(indices) + + translations_array = Vt.Vec3dArray.FromNumpy(self._to_numpy(translations)) if translations is not None else None + orientations_array = Vt.QuatdArray.FromNumpy(self._to_numpy(orientations)) if orientations is not None else None + + with Sdf.ChangeBlock(): + for idx, prim_idx in enumerate(indices_list): + prim = self._prims[prim_idx] + if translations_array is not None: + prim.GetAttribute("xformOp:translate").Set(translations_array[idx]) + if orientations_array is not None: + prim.GetAttribute("xformOp:orient").Set(orientations_array[idx]) + + def set_scales(self, scales: wp.array, indices: wp.array | None = None): + """Set scales for prims in the view. + + Args: + scales: Scales of shape ``(M, 3)``. + indices: Indices of prims to set scales for. Defaults to None (all prims). + """ + indices_list = self._resolve_indices(indices) + scales_array = Vt.Vec3dArray.FromNumpy(self._to_numpy(scales)) + + with Sdf.ChangeBlock(): + for idx, prim_idx in enumerate(indices_list): + prim = self._prims[prim_idx] + prim.GetAttribute("xformOp:scale").Set(scales_array[idx]) + + def set_visibility(self, visibility: torch.Tensor, indices: wp.array | None = None): + """Set visibility for prims in the view. + + Args: + visibility: Visibility as a boolean tensor of shape ``(M,)``. + indices: Indices of prims to set visibility for. Defaults to None (all prims). + """ + indices_list = self._resolve_indices(indices) + + if visibility.shape != (len(indices_list),): + raise ValueError(f"Expected visibility shape ({len(indices_list)},), got {visibility.shape}.") + + with Sdf.ChangeBlock(): + for idx, prim_idx in enumerate(indices_list): + imageable = UsdGeom.Imageable(self._prims[prim_idx]) + if visibility[idx]: + imageable.MakeVisible() + else: + imageable.MakeInvisible() + + # ------------------------------------------------------------------ + # Getters + # ------------------------------------------------------------------ + + def get_world_poses(self, indices: wp.array | None = None) -> tuple[ProxyArray, ProxyArray]: + """Get world-space poses for prims in the view. + + Args: + indices: Indices of prims to get poses for. Defaults to None (all prims). + + Returns: + A tuple ``(positions, orientations)`` of :class:`~isaaclab.utils.warp.ProxyArray` + wrappers. Use ``.warp`` for the underlying ``wp.array`` or ``.torch`` for a + cached zero-copy ``torch.Tensor`` view. + """ + indices_list = self._resolve_indices(indices) + + positions = Vt.Vec3dArray(len(indices_list)) + orientations = Vt.QuatdArray(len(indices_list)) + xform_cache = UsdGeom.XformCache(Usd.TimeCode.Default()) + + for idx, prim_idx in enumerate(indices_list): + prim = self._prims[prim_idx] + prim_tf = xform_cache.GetLocalToWorldTransform(prim) + prim_tf.Orthonormalize() + positions[idx] = prim_tf.ExtractTranslation() + orientations[idx] = prim_tf.ExtractRotationQuat() + + pos_wp = wp.array(np.array(positions, dtype=np.float32), dtype=wp.float32, device=self._device) + quat_wp = wp.array(np.array(orientations, dtype=np.float32), dtype=wp.float32, device=self._device) + return ProxyArray(pos_wp), ProxyArray(quat_wp) + + def get_local_poses(self, indices: wp.array | None = None) -> tuple[ProxyArray, ProxyArray]: + """Get local-space poses for prims in the view. + + Args: + indices: Indices of prims to get poses for. Defaults to None (all prims). + + Returns: + A tuple ``(translations, orientations)`` of :class:`~isaaclab.utils.warp.ProxyArray` + wrappers. Use ``.warp`` for the underlying ``wp.array`` or ``.torch`` for a + cached zero-copy ``torch.Tensor`` view. + """ + indices_list = self._resolve_indices(indices) + + translations = Vt.Vec3dArray(len(indices_list)) + orientations = Vt.QuatdArray(len(indices_list)) + xform_cache = UsdGeom.XformCache(Usd.TimeCode.Default()) + + for idx, prim_idx in enumerate(indices_list): + prim = self._prims[prim_idx] + prim_tf = xform_cache.GetLocalTransformation(prim)[0] + prim_tf.Orthonormalize() + translations[idx] = prim_tf.ExtractTranslation() + orientations[idx] = prim_tf.ExtractRotationQuat() + + pos_wp = wp.array(np.array(translations, dtype=np.float32), dtype=wp.float32, device=self._device) + quat_wp = wp.array(np.array(orientations, dtype=np.float32), dtype=wp.float32, device=self._device) + return ProxyArray(pos_wp), ProxyArray(quat_wp) + + def get_scales(self, indices: wp.array | None = None) -> wp.array: + """Get scales for prims in the view. + + Args: + indices: Indices of prims to get scales for. Defaults to None (all prims). + + Returns: + A ``wp.array`` of shape ``(M, 3)``. + """ + indices_list = self._resolve_indices(indices) + + scales = Vt.Vec3dArray(len(indices_list)) + for idx, prim_idx in enumerate(indices_list): + prim = self._prims[prim_idx] + scales[idx] = prim.GetAttribute("xformOp:scale").Get() + + return wp.array(np.array(scales, dtype=np.float32), dtype=wp.float32, device=self._device) + + def get_visibility(self, indices: wp.array | None = None) -> torch.Tensor: + """Get visibility for prims in the view. + + Args: + indices: Indices of prims to get visibility for. Defaults to None (all prims). + + Returns: + A tensor of shape ``(M,)`` containing the visibility of each prim (bool). + """ + indices_list = self._resolve_indices(indices) + + visibility = torch.zeros(len(indices_list), dtype=torch.bool, device=self._device) + for idx, prim_idx in enumerate(indices_list): + imageable = UsdGeom.Imageable(self._prims[prim_idx]) + visibility[idx] = imageable.ComputeVisibility() != UsdGeom.Tokens.invisible + return visibility + + # ------------------------------------------------------------------ + # Helpers + # ------------------------------------------------------------------ + + def _resolve_indices(self, indices: wp.array | None): + """Resolve warp indices to an iterable of ints for per-prim USD operations.""" + if indices is None or indices == slice(None): + return self._ALL_INDICES + return indices.numpy() + + @staticmethod + def _to_numpy(data: wp.array | torch.Tensor) -> np.ndarray: + """Convert a ``wp.array`` or ``torch.Tensor`` to a numpy array on CPU.""" + if isinstance(data, wp.array): + return data.numpy() + return data.cpu().numpy() diff --git a/source/isaaclab/isaaclab/sim/views/xform_prim_view.py b/source/isaaclab/isaaclab/sim/views/xform_prim_view.py index 211994a7226b..ce480fa65594 100644 --- a/source/isaaclab/isaaclab/sim/views/xform_prim_view.py +++ b/source/isaaclab/isaaclab/sim/views/xform_prim_view.py @@ -3,1138 +3,8 @@ # # SPDX-License-Identifier: BSD-3-Clause -from __future__ import annotations +"""Backward-compatibility alias: ``XformPrimView`` -> :class:`FrameView`.""" -import logging -from collections.abc import Sequence +from .frame_view import FrameView -import numpy as np -import torch -import warp as wp - -from pxr import Gf, Sdf, Usd, UsdGeom, Vt - -import isaaclab.sim as sim_utils -from isaaclab.app.settings_manager import SettingsManager -from isaaclab.utils.warp import fabric as fabric_utils - -logger = logging.getLogger(__name__) - - -class XformPrimView: - """Optimized batched interface for reading and writing transforms of multiple USD prims. - - This class provides efficient batch operations for getting and setting poses (position and orientation) - of multiple prims at once using torch tensors. It is designed for scenarios where you need to manipulate - many prims simultaneously, such as in multi-agent simulations or large-scale procedural generation. - - The class supports both world-space and local-space pose operations: - - - **World poses**: Positions and orientations in the global world frame - - **Local poses**: Positions and orientations relative to each prim's parent - - When Fabric is enabled, the class leverages NVIDIA's Fabric API for GPU-accelerated batch operations: - - - Uses `omni:fabric:worldMatrix` and `omni:fabric:localMatrix` attributes for all Boundable prims - - Performs batch matrix decomposition/composition using Warp kernels on GPU - - Achieves performance comparable to Isaac Sim's XFormPrim implementation - - Works for both physics-enabled and non-physics prims (cameras, meshes, etc.). - Note: renderers typically consume USD-authored camera transforms. - - .. warning:: - **Fabric requires CUDA**: Fabric is only supported with on CUDA devices. - Warp's CPU backend for fabric-array writes has known issues, so attempting to use - Fabric with CPU device (``device="cpu"``) will raise a ValueError at initialization. - - .. note:: - **Fabric Support:** - - When Fabric is enabled, this view ensures prims have the required Fabric hierarchy - attributes (``omni:fabric:localMatrix`` and ``omni:fabric:worldMatrix``). On first Fabric - read, USD-authored transforms initialize Fabric state. Fabric writes can optionally - be mirrored back to USD via :attr:`sync_usd_on_fabric_write`. - - For more information, see the `Fabric Hierarchy documentation`_. - - .. _Fabric Hierarchy documentation: https://docs.omniverse.nvidia.com/kit/docs/usdrt/latest/docs/fabric_hierarchy.html - - .. note:: - **Performance Considerations:** - - * Tensor operations are performed on the specified device (CPU/CUDA) - * USD write operations use ``Sdf.ChangeBlock`` for batched updates - * Fabric operations use GPU-accelerated Warp kernels for maximum performance - * For maximum performance, minimize get/set operations within tight loops - - .. note:: - **Transform Requirements:** - - All prims in the view must be Xformable and have standardized transform operations: - ``[translate, orient, scale]``. Non-standard prims will raise a ValueError during - initialization if :attr:`validate_xform_ops` is True. Please use the function - :func:`isaaclab.sim.utils.standardize_xform_ops` to prepare prims before using this view. - - .. warning:: - This class operates at the USD default time code. Any animation or time-sampled data - will not be affected by write operations. For animated transforms, you need to handle - time-sampled keyframes separately. - """ - - def __init__( - self, - prim_path: str, - device: str = "cpu", - validate_xform_ops: bool = True, - sync_usd_on_fabric_write: bool = False, - stage: Usd.Stage | None = None, - ): - """Initialize the view with matching prims. - - This method searches the USD stage for all prims matching the provided path pattern, - validates that they are Xformable with standard transform operations, and stores - references for efficient batch operations. - - We generally recommend to validate the xform operations, as it ensures that the prims are in a consistent state - and have the standard transform operations (translate, orient, scale in that order). - However, if you are sure that the prims are in a consistent state, you can set this to False to improve - performance. This can save around 45-50% of the time taken to initialize the view. - - Args: - prim_path: USD prim path pattern to match prims. Supports wildcards (``*``) and - regex patterns (e.g., ``"/World/Env_.*/Robot"``). See - :func:`isaaclab.sim.utils.find_matching_prims` for pattern syntax. - device: Device to place the tensors on. Can be ``"cpu"`` or CUDA devices like - ``"cuda:0"``. Defaults to ``"cpu"``. - validate_xform_ops: Whether to validate that the prims have standard xform operations. - Defaults to True. - sync_usd_on_fabric_write: Whether to mirror Fabric transform writes back to USD. - When True, transform updates are synchronized to USD so that USD data readers (e.g., rendering - cameras) can observe these changes. Defaults to False for better performance. - stage: USD stage to search for prims. Defaults to None, in which case the current active stage - from the simulation context is used. - - Raises: - ValueError: If any matched prim is not Xformable or doesn't have standardized - transform operations (translate, orient, scale in that order). - """ - # Store configuration - self._prim_path = prim_path - self._device = device - - # Find and validate matching prims - stage = sim_utils.get_current_stage() if stage is None else stage - self._prims: list[Usd.Prim] = sim_utils.find_matching_prims(prim_path, stage=stage) - - # Validate all prims have standard xform operations - if validate_xform_ops: - for prim in self._prims: - sim_utils.standardize_xform_ops(prim) - if not sim_utils.validate_standard_xform_ops(prim): - raise ValueError( - f"Prim at path '{prim.GetPath().pathString}' is not a xformable prim with standard transform" - f" operations [translate, orient, scale]. Received type: '{prim.GetTypeName()}'." - " Use sim_utils.standardize_xform_ops() to prepare the prim." - ) - - # Determine if Fabric is supported on the device - settings = SettingsManager.instance() - self._use_fabric = bool(settings.get("/physics/fabricEnabled", False)) - - # Check for unsupported Fabric + CPU combination - if self._use_fabric and self._device == "cpu": - logger.warning( - "Fabric mode with Warp fabric-array operations is not supported on CPU devices. " - "While Fabric itself can run on both CPU and GPU, our batch Warp kernels for " - "fabric-array operations require CUDA and are not reliable on the CPU backend. " - "To ensure stability, Fabric is being disabled and execution will fall back " - "to standard USD operations on the CPU. This may impact performance." - ) - self._use_fabric = False - - # Check for unsupported Fabric + non-primary CUDA device combination. - # USDRT SelectPrims and Warp fabric arrays only support cuda:0 internally. - # When running on cuda:1 or higher, SelectPrims raises a C++ error regardless of - # the device argument, because USDRT uses the active CUDA context (which is cuda:1). - if self._use_fabric and self._device not in ("cuda", "cuda:0"): - logger.warning( - f"Fabric mode is not supported on device '{self._device}'. " - "USDRT SelectPrims and Warp fabric arrays only support cuda:0. " - "Falling back to standard USD operations. This may impact performance." - ) - self._use_fabric = False - - # Create indices buffer - # Since we iterate over the indices, we need to use range instead of torch tensor - self._ALL_INDICES = list(range(len(self._prims))) - - # Some prims (e.g., Cameras) require USD-authored transforms for rendering. - # When enabled, mirror Fabric pose writes to USD for those prims. - self._sync_usd_on_fabric_write = sync_usd_on_fabric_write - - # Fabric batch infrastructure (initialized lazily on first use) - self._fabric_initialized = False - self._fabric_usd_sync_done = False - self._fabric_selection = None - self._fabric_to_view: wp.array | None = None - self._view_to_fabric: wp.array | None = None - self._default_view_indices: wp.array | None = None - self._fabric_hierarchy = None - # Create a valid USD attribute name: namespace:name - # Use "isaaclab" namespace to identify our custom attributes - self._view_index_attr = f"isaaclab:view_index:{abs(hash(self))}" - - """ - Properties. - """ - - @property - def count(self) -> int: - """Number of prims in this view.""" - return len(self._prims) - - @property - def device(self) -> str: - """Device where tensors are allocated (cpu or cuda).""" - return self._device - - @property - def prims(self) -> list[Usd.Prim]: - """List of USD prims being managed by this view.""" - return self._prims - - @property - def prim_paths(self) -> list[str]: - """List of prim paths (as strings) for all prims being managed by this view. - - This property converts each prim to its path string representation. The conversion is - performed lazily on first access and cached for subsequent accesses. - - Note: - For most use cases, prefer using :attr:`prims` directly as it provides direct access - to the USD prim objects without the conversion overhead. This property is mainly useful - for logging, debugging, or when string paths are explicitly required. - """ - # we cache it the first time it is accessed. - # we don't compute it in constructor because it is expensive and we don't need it most of the time. - # users should usually deal with prims directly as they typically need to access the prims directly. - if not hasattr(self, "_prim_paths"): - self._prim_paths = [prim.GetPath().pathString for prim in self._prims] - return self._prim_paths - - """ - Operations - Setters. - """ - - def set_world_poses( - self, - positions: torch.Tensor | None = None, - orientations: torch.Tensor | None = None, - indices: Sequence[int] | None = None, - ): - """Set world-space poses for prims in the view. - - This method sets the position and/or orientation of each prim in world space. - - - When Fabric is enabled, the function writes directly to Fabric's ``omni:fabric:worldMatrix`` - attribute using GPU-accelerated batch operations. - - When Fabric is disabled, the function converts to local space and writes to USD's ``xformOp:translate`` - and ``xformOp:orient`` attributes. - - Args: - positions: World-space positions as a tensor of shape (M, 3) where M is the number of prims - to set (either all prims if indices is None, or the number of indices provided). - Defaults to None, in which case positions are not modified. - orientations: World-space orientations as quaternions (w, x, y, z) with shape (M, 4). - Defaults to None, in which case orientations are not modified. - indices: Indices of prims to set poses for. Defaults to None, in which case poses are set - for all prims in the view. - - Raises: - ValueError: If positions shape is not (M, 3) or orientations shape is not (M, 4). - ValueError: If the number of poses doesn't match the number of indices provided. - """ - if self._use_fabric: - self._set_world_poses_fabric(positions, orientations, indices) - else: - self._set_world_poses_usd(positions, orientations, indices) - - def set_local_poses( - self, - translations: torch.Tensor | None = None, - orientations: torch.Tensor | None = None, - indices: Sequence[int] | None = None, - ): - """Set local-space poses for prims in the view. - - This method sets the position and/or orientation of each prim in local space (relative to - their parent prims). - - The function writes directly to USD's ``xformOp:translate`` and ``xformOp:orient`` attributes. - - Note: - Even in Fabric mode, local pose operations use USD. This behavior is based on Isaac Sim's design - where Fabric is only used for world pose operations. - - Rationale: - - Local pose writes need correct parent-child hierarchy relationships - - USD maintains these relationships correctly and efficiently - - Fabric is optimized for world pose operations, not local hierarchies - - Args: - translations: Local-space translations as a tensor of shape (M, 3) where M is the number of prims - to set (either all prims if indices is None, or the number of indices provided). - Defaults to None, in which case translations are not modified. - orientations: Local-space orientations as quaternions (w, x, y, z) with shape (M, 4). - Defaults to None, in which case orientations are not modified. - indices: Indices of prims to set poses for. Defaults to None, in which case poses are set - for all prims in the view. - - Raises: - ValueError: If translations shape is not (M, 3) or orientations shape is not (M, 4). - ValueError: If the number of poses doesn't match the number of indices provided. - """ - if self._use_fabric: - self._set_local_poses_fabric(translations, orientations, indices) - else: - self._set_local_poses_usd(translations, orientations, indices) - - def set_scales(self, scales: torch.Tensor, indices: Sequence[int] | None = None): - """Set scales for prims in the view. - - This method sets the scale of each prim in the view. - - - When Fabric is enabled, the function updates scales in Fabric matrices using GPU-accelerated batch operations. - - When Fabric is disabled, the function writes to USD's ``xformOp:scale`` attributes. - - Args: - scales: Scales as a tensor of shape (M, 3) where M is the number of prims - to set (either all prims if indices is None, or the number of indices provided). - indices: Indices of prims to set scales for. Defaults to None, in which case scales are set - for all prims in the view. - - Raises: - ValueError: If scales shape is not (M, 3). - """ - if self._use_fabric: - self._set_scales_fabric(scales, indices) - else: - self._set_scales_usd(scales, indices) - - def set_visibility(self, visibility: torch.Tensor, indices: Sequence[int] | None = None): - """Set visibility for prims in the view. - - This method sets the visibility of each prim in the view. - - Args: - visibility: Visibility as a boolean tensor of shape (M,) where M is the - number of prims to set (either all prims if indices is None, or the number of indices provided). - indices: Indices of prims to set visibility for. Defaults to None, in which case visibility is set - for all prims in the view. - - Raises: - ValueError: If visibility shape is not (M,). - """ - # Resolve indices - if indices is None or indices == slice(None): - indices_list = self._ALL_INDICES - else: - indices_list = indices.tolist() if isinstance(indices, torch.Tensor) else list(indices) - - # Validate inputs - if visibility.shape != (len(indices_list),): - raise ValueError(f"Expected visibility shape ({len(indices_list)},), got {visibility.shape}.") - - # Set visibility for each prim - with Sdf.ChangeBlock(): - for idx, prim_idx in enumerate(indices_list): - # Convert prim to imageable - imageable = UsdGeom.Imageable(self._prims[prim_idx]) - # Set visibility - if visibility[idx]: - imageable.MakeVisible() - else: - imageable.MakeInvisible() - - """ - Operations - Getters. - """ - - def get_world_poses(self, indices: Sequence[int] | None = None) -> tuple[torch.Tensor, torch.Tensor]: - """Get world-space poses for prims in the view. - - This method retrieves the position and orientation of each prim in world space by computing - the full transform hierarchy from the prim to the world root. - - - When Fabric is enabled, the function uses Fabric batch operations with Warp kernels. - - When Fabric is disabled, the function uses USD XformCache. - - Note: - Scale and skew are ignored. The returned poses contain only translation and rotation. - - Args: - indices: Indices of prims to get poses for. Defaults to None, in which case poses are retrieved - for all prims in the view. - - Returns: - A tuple of (positions, orientations) where: - - - positions: Torch tensor of shape (M, 3) containing world-space positions (x, y, z), - where M is the number of prims queried. - - orientations: Torch tensor of shape (M, 4) containing world-space quaternions (w, x, y, z) - """ - if self._use_fabric: - return self._get_world_poses_fabric(indices) - else: - return self._get_world_poses_usd(indices) - - def get_local_poses(self, indices: Sequence[int] | None = None) -> tuple[torch.Tensor, torch.Tensor]: - """Get local-space poses for prims in the view. - - This method retrieves the position and orientation of each prim in local space (relative to - their parent prims). It reads directly from USD's ``xformOp:translate`` and ``xformOp:orient`` attributes. - - Note: - Even in Fabric mode, local pose operations use USD. This behavior is based on Isaac Sim's design - where Fabric is only used for world pose operations. - - Rationale: - - Local pose reads need correct parent-child hierarchy relationships - - USD maintains these relationships correctly and efficiently - - Fabric is optimized for world pose operations, not local hierarchies - - Note: - Scale is ignored. The returned poses contain only translation and rotation. - - Args: - indices: Indices of prims to get poses for. Defaults to None, in which case poses are retrieved - for all prims in the view. - - Returns: - A tuple of (translations, orientations) where: - - - translations: Torch tensor of shape (M, 3) containing local-space translations (x, y, z), - where M is the number of prims queried. - - orientations: Torch tensor of shape (M, 4) containing local-space quaternions (w, x, y, z) - """ - if self._use_fabric: - return self._get_local_poses_fabric(indices) - else: - return self._get_local_poses_usd(indices) - - def get_scales(self, indices: Sequence[int] | None = None) -> torch.Tensor: - """Get scales for prims in the view. - - This method retrieves the scale of each prim in the view. - - - When Fabric is enabled, the function extracts scales from Fabric matrices using batch operations with - Warp kernels. - - When Fabric is disabled, the function reads from USD's ``xformOp:scale`` attributes. - - Args: - indices: Indices of prims to get scales for. Defaults to None, in which case scales are retrieved - for all prims in the view. - - Returns: - A tensor of shape (M, 3) containing the scales of each prim, where M is the number of prims queried. - """ - if self._use_fabric: - return self._get_scales_fabric(indices) - else: - return self._get_scales_usd(indices) - - def get_visibility(self, indices: Sequence[int] | None = None) -> torch.Tensor: - """Get visibility for prims in the view. - - This method retrieves the visibility of each prim in the view. - - Args: - indices: Indices of prims to get visibility for. Defaults to None, in which case visibility is retrieved - for all prims in the view. - - Returns: - A tensor of shape (M,) containing the visibility of each prim, where M is the number of prims queried. - The tensor is of type bool. - """ - # Resolve indices - if indices is None or indices == slice(None): - indices_list = self._ALL_INDICES - else: - # Convert to list if it is a tensor array - indices_list = indices.tolist() if isinstance(indices, torch.Tensor) else list(indices) - - # Create buffers - visibility = torch.zeros(len(indices_list), dtype=torch.bool, device=self._device) - - for idx, prim_idx in enumerate(indices_list): - # Get prim - imageable = UsdGeom.Imageable(self._prims[prim_idx]) - # Get visibility - visibility[idx] = imageable.ComputeVisibility() != UsdGeom.Tokens.invisible - - return visibility - - """ - Internal Functions - USD. - """ - - def _set_world_poses_usd( - self, - positions: torch.Tensor | None = None, - orientations: torch.Tensor | None = None, - indices: Sequence[int] | None = None, - ): - """Set world poses to USD.""" - # Resolve indices - if indices is None or indices == slice(None): - indices_list = self._ALL_INDICES - else: - # Convert to list if it is a tensor array - indices_list = indices.tolist() if isinstance(indices, torch.Tensor) else list(indices) - - # Validate inputs - if positions is not None: - if positions.shape != (len(indices_list), 3): - raise ValueError( - f"Expected positions shape ({len(indices_list)}, 3), got {positions.shape}. " - "Number of positions must match the number of prims in the view." - ) - positions_array = Vt.Vec3dArray.FromNumpy(positions.cpu().numpy()) - else: - positions_array = None - if orientations is not None: - if orientations.shape != (len(indices_list), 4): - raise ValueError( - f"Expected orientations shape ({len(indices_list)}, 4), got {orientations.shape}. " - "Number of orientations must match the number of prims in the view." - ) - # Vt expects quaternions in xyzw order - orientations_array = Vt.QuatdArray.FromNumpy(orientations.cpu().numpy()) - else: - orientations_array = None - - # Create xform cache instance - xform_cache = UsdGeom.XformCache(Usd.TimeCode.Default()) - - # Set poses for each prim - # We use Sdf.ChangeBlock to minimize notification overhead. - with Sdf.ChangeBlock(): - for idx, prim_idx in enumerate(indices_list): - # Get prim - prim = self._prims[prim_idx] - # Get parent prim for local space conversion - parent_prim = prim.GetParent() - - # Determine what to set - world_pos = positions_array[idx] if positions_array is not None else None - world_quat = orientations_array[idx] if orientations_array is not None else None - - # Convert world pose to local if we have a valid parent - # Note: We don't use :func:`isaaclab.sim.utils.transforms.convert_world_pose_to_local` - # here since it isn't optimized for batch operations. - if parent_prim.IsValid() and parent_prim.GetPath() != Sdf.Path.absoluteRootPath: - # Get current world pose if we're only setting one component - if positions_array is None or orientations_array is None: - # get prim xform - prim_tf = xform_cache.GetLocalToWorldTransform(prim) - # sanitize quaternion - # this is needed, otherwise the quaternion might be non-normalized - prim_tf.Orthonormalize() - # populate desired world transform - if world_pos is not None: - prim_tf.SetTranslateOnly(world_pos) - if world_quat is not None: - prim_tf.SetRotateOnly(world_quat) - else: - # Both position and orientation are provided, create new transform - prim_tf = Gf.Matrix4d() - prim_tf.SetTranslateOnly(world_pos) - prim_tf.SetRotateOnly(world_quat) - - # Convert to local space - parent_world_tf = xform_cache.GetLocalToWorldTransform(parent_prim) - local_tf = prim_tf * parent_world_tf.GetInverse() - local_pos = local_tf.ExtractTranslation() - local_quat = local_tf.ExtractRotationQuat() - else: - # No parent or parent is root, world == local - local_pos = world_pos - local_quat = world_quat - - # Get or create the standard transform operations - if local_pos is not None: - prim.GetAttribute("xformOp:translate").Set(local_pos) - if local_quat is not None: - prim.GetAttribute("xformOp:orient").Set(local_quat) - - def _set_local_poses_usd( - self, - translations: torch.Tensor | None = None, - orientations: torch.Tensor | None = None, - indices: Sequence[int] | None = None, - ): - """Set local poses to USD.""" - # Resolve indices - if indices is None or indices == slice(None): - indices_list = self._ALL_INDICES - else: - indices_list = indices.tolist() if isinstance(indices, torch.Tensor) else list(indices) - - # Validate inputs - if translations is not None: - if translations.shape != (len(indices_list), 3): - raise ValueError(f"Expected translations shape ({len(indices_list)}, 3), got {translations.shape}.") - translations_array = Vt.Vec3dArray.FromNumpy(translations.cpu().numpy()) - else: - translations_array = None - if orientations is not None: - if orientations.shape != (len(indices_list), 4): - raise ValueError(f"Expected orientations shape ({len(indices_list)}, 4), got {orientations.shape}.") - orientations_array = Vt.QuatdArray.FromNumpy(orientations.cpu().numpy()) - else: - orientations_array = None - - # Set local poses - with Sdf.ChangeBlock(): - for idx, prim_idx in enumerate(indices_list): - prim = self._prims[prim_idx] - if translations_array is not None: - prim.GetAttribute("xformOp:translate").Set(translations_array[idx]) - if orientations_array is not None: - prim.GetAttribute("xformOp:orient").Set(orientations_array[idx]) - - def _set_scales_usd(self, scales: torch.Tensor, indices: Sequence[int] | None = None): - """Set scales to USD.""" - # Resolve indices - if indices is None or indices == slice(None): - indices_list = self._ALL_INDICES - else: - indices_list = indices.tolist() if isinstance(indices, torch.Tensor) else list(indices) - - # Validate inputs - if scales.shape != (len(indices_list), 3): - raise ValueError(f"Expected scales shape ({len(indices_list)}, 3), got {scales.shape}.") - - scales_array = Vt.Vec3dArray.FromNumpy(scales.cpu().numpy()) - # Set scales for each prim - with Sdf.ChangeBlock(): - for idx, prim_idx in enumerate(indices_list): - prim = self._prims[prim_idx] - prim.GetAttribute("xformOp:scale").Set(scales_array[idx]) - - def _get_world_poses_usd(self, indices: Sequence[int] | None = None) -> tuple[torch.Tensor, torch.Tensor]: - """Get world poses from USD.""" - # Resolve indices - if indices is None or indices == slice(None): - indices_list = self._ALL_INDICES - else: - # Convert to list if it is a tensor array - indices_list = indices.tolist() if isinstance(indices, torch.Tensor) else list(indices) - - # Create buffers - positions = Vt.Vec3dArray(len(indices_list)) - orientations = Vt.QuatdArray(len(indices_list)) - # Create xform cache instance - xform_cache = UsdGeom.XformCache(Usd.TimeCode.Default()) - - # Note: We don't use :func:`isaaclab.sim.utils.transforms.resolve_prim_pose` - # here since it isn't optimized for batch operations. - for idx, prim_idx in enumerate(indices_list): - # Get prim - prim = self._prims[prim_idx] - # get prim xform - prim_tf = xform_cache.GetLocalToWorldTransform(prim) - # sanitize quaternion - # this is needed, otherwise the quaternion might be non-normalized - prim_tf.Orthonormalize() - # extract position and orientation - positions[idx] = prim_tf.ExtractTranslation() - orientations[idx] = prim_tf.ExtractRotationQuat() - - # move to torch tensors - positions = torch.tensor(np.array(positions), dtype=torch.float32, device=self._device) - orientations = torch.tensor(np.array(orientations), dtype=torch.float32, device=self._device) - return positions, orientations # type: ignore - - def _get_local_poses_usd(self, indices: Sequence[int] | None = None) -> tuple[torch.Tensor, torch.Tensor]: - """Get local poses from USD.""" - # Resolve indices - if indices is None or indices == slice(None): - indices_list = self._ALL_INDICES - else: - indices_list = indices.tolist() if isinstance(indices, torch.Tensor) else list(indices) - - # Create buffers - translations = Vt.Vec3dArray(len(indices_list)) - orientations = Vt.QuatdArray(len(indices_list)) - - # Create a fresh XformCache to avoid stale cached values - xform_cache = UsdGeom.XformCache(Usd.TimeCode.Default()) - - for idx, prim_idx in enumerate(indices_list): - prim = self._prims[prim_idx] - prim_tf = xform_cache.GetLocalTransformation(prim)[0] - prim_tf.Orthonormalize() - translations[idx] = prim_tf.ExtractTranslation() - orientations[idx] = prim_tf.ExtractRotationQuat() - - translations = torch.tensor(np.array(translations), dtype=torch.float32, device=self._device) - orientations = torch.tensor(np.array(orientations), dtype=torch.float32, device=self._device) - return translations, orientations # type: ignore - - def _get_scales_usd(self, indices: Sequence[int] | None = None) -> torch.Tensor: - """Get scales from USD.""" - # Resolve indices - if indices is None or indices == slice(None): - indices_list = self._ALL_INDICES - else: - indices_list = indices.tolist() if isinstance(indices, torch.Tensor) else list(indices) - - # Create buffers - scales = Vt.Vec3dArray(len(indices_list)) - - for idx, prim_idx in enumerate(indices_list): - prim = self._prims[prim_idx] - scales[idx] = prim.GetAttribute("xformOp:scale").Get() - - # Convert to tensor - return torch.tensor(np.array(scales), dtype=torch.float32, device=self._device) - - """ - Internal Functions - Fabric. - """ - - def _set_world_poses_fabric( - self, - positions: torch.Tensor | None = None, - orientations: torch.Tensor | None = None, - indices: Sequence[int] | None = None, - ): - """Set world poses using Fabric GPU batch operations. - - Writes directly to Fabric's ``omni:fabric:worldMatrix`` attribute using Warp kernels. - Changes are propagated through Fabric's hierarchy system but remain GPU-resident. - - For workflows mixing Fabric world pose writes with USD local pose queries, note - that local poses read from USD's xformOp:* attributes, which may not immediately - reflect Fabric changes. For best performance and consistency, use Fabric methods - exclusively (get_world_poses/set_world_poses with Fabric enabled). - """ - # Lazy initialization - if not self._fabric_initialized: - self._initialize_fabric() - - # Resolve indices (treat slice(None) as None for consistency with USD path) - indices_wp = self._resolve_indices_wp(indices) - - count = indices_wp.shape[0] - - # Convert torch to warp (if provided), use dummy arrays for None to avoid Warp kernel issues - if positions is not None: - positions_wp = wp.from_torch(positions) - else: - positions_wp = wp.zeros((0, 3), dtype=wp.float32).to(self._device) - - if orientations is not None: - orientations_wp = wp.from_torch(orientations) - else: - orientations_wp = wp.zeros((0, 4), dtype=wp.float32).to(self._device) - - # Dummy array for scales (not modifying) - scales_wp = wp.zeros((0, 3), dtype=wp.float32).to(self._device) - - # Use cached fabricarray for world matrices - world_matrices = self._fabric_world_matrices - - # Batch compose matrices with a single kernel launch - # Note: world_matrices is a fabricarray on fabric_device, so we must launch on fabric_device - wp.launch( - kernel=fabric_utils.compose_fabric_transformation_matrix_from_warp_arrays, - dim=count, - inputs=[ - world_matrices, - positions_wp, - orientations_wp, - scales_wp, # dummy array instead of None - False, # broadcast_positions - False, # broadcast_orientations - False, # broadcast_scales - indices_wp, - self._view_to_fabric, - ], - device=self._fabric_device, - ) - - # Synchronize to ensure kernel completes - wp.synchronize() - - # Update world transforms within Fabric hierarchy - self._fabric_hierarchy.update_world_xforms() - # Fabric now has authoritative data; skip future USD syncs - self._fabric_usd_sync_done = True - # Mirror to USD for renderer-facing prims when enabled. - if self._sync_usd_on_fabric_write: - self._set_world_poses_usd(positions, orientations, indices) - - # Fabric writes are GPU-resident; local pose operations still use USD. - - def _set_local_poses_fabric( - self, - translations: torch.Tensor | None = None, - orientations: torch.Tensor | None = None, - indices: Sequence[int] | None = None, - ): - """Set local poses using USD (matches Isaac Sim's design). - - Note: Even in Fabric mode, local pose operations use USD. - This is Isaac Sim's design: the ``usd=False`` parameter only affects world poses. - - Rationale: - - Local pose writes need correct parent-child hierarchy relationships - - USD maintains these relationships correctly and efficiently - - Fabric is optimized for world pose operations, not local hierarchies - """ - self._set_local_poses_usd(translations, orientations, indices) - - def _set_scales_fabric(self, scales: torch.Tensor, indices: Sequence[int] | None = None): - """Set scales using Fabric GPU batch operations.""" - # Lazy initialization - if not self._fabric_initialized: - self._initialize_fabric() - - # Resolve indices (treat slice(None) as None for consistency with USD path) - indices_wp = self._resolve_indices_wp(indices) - - count = indices_wp.shape[0] - - # Convert torch to warp - scales_wp = wp.from_torch(scales) - - # Dummy arrays for positions and orientations (not modifying) - positions_wp = wp.zeros((0, 3), dtype=wp.float32).to(self._device) - orientations_wp = wp.zeros((0, 4), dtype=wp.float32).to(self._device) - - # Use cached fabricarray for world matrices - world_matrices = self._fabric_world_matrices - - # Batch compose matrices on GPU with a single kernel launch - # Note: world_matrices is a fabricarray on fabric_device, so we must launch on fabric_device - wp.launch( - kernel=fabric_utils.compose_fabric_transformation_matrix_from_warp_arrays, - dim=count, - inputs=[ - world_matrices, - positions_wp, # dummy array instead of None - orientations_wp, # dummy array instead of None - scales_wp, - False, # broadcast_positions - False, # broadcast_orientations - False, # broadcast_scales - indices_wp, - self._view_to_fabric, - ], - device=self._fabric_device, - ) - - # Synchronize to ensure kernel completes before syncing - wp.synchronize() - - # Update world transforms to propagate changes - self._fabric_hierarchy.update_world_xforms() - # Fabric now has authoritative data; skip future USD syncs - self._fabric_usd_sync_done = True - # Mirror to USD for renderer-facing prims when enabled. - if self._sync_usd_on_fabric_write: - self._set_scales_usd(scales, indices) - - def _get_world_poses_fabric(self, indices: Sequence[int] | None = None) -> tuple[torch.Tensor, torch.Tensor]: - """Get world poses from Fabric using GPU batch operations.""" - # Lazy initialization of Fabric infrastructure - if not self._fabric_initialized: - self._initialize_fabric() - # Sync once from USD to ensure reads see the latest authored transforms - if not self._fabric_usd_sync_done: - self._sync_fabric_from_usd_once() - - # Resolve indices (treat slice(None) as None for consistency with USD path) - indices_wp = self._resolve_indices_wp(indices) - - count = indices_wp.shape[0] - - # Use pre-allocated buffers for full reads, allocate only for partial reads - use_cached_buffers = indices is None or indices == slice(None) - if use_cached_buffers: - # Full read: Use cached buffers (zero allocation overhead!) - positions_wp = self._fabric_positions_buffer - orientations_wp = self._fabric_orientations_buffer - scales_wp = self._fabric_dummy_buffer - else: - # Partial read: Need to allocate buffers of appropriate size - positions_wp = wp.zeros((count, 3), dtype=wp.float32).to(self._device) - orientations_wp = wp.zeros((count, 4), dtype=wp.float32).to(self._device) - scales_wp = self._fabric_dummy_buffer # Always use dummy for scales - - # Use cached fabricarray for world matrices - # This eliminates the 0.06-0.30ms variability from creating fabricarray each call - world_matrices = self._fabric_world_matrices - - # Launch GPU kernel to decompose matrices in parallel - # Note: world_matrices is a fabricarray on fabric_device, so we must launch on fabric_device - wp.launch( - kernel=fabric_utils.decompose_fabric_transformation_matrix_to_warp_arrays, - dim=count, - inputs=[ - world_matrices, - positions_wp, - orientations_wp, - scales_wp, # dummy array instead of None - indices_wp, - self._view_to_fabric, - ], - device=self._fabric_device, - ) - - # Return tensors: zero-copy for cached buffers, conversion for partial reads - if use_cached_buffers: - # Zero-copy! The Warp kernel wrote directly into the PyTorch tensors - # We just need to synchronize to ensure the kernel is done - wp.synchronize() - return self._fabric_positions_torch, self._fabric_orientations_torch - else: - # Partial read: Need to convert from Warp to torch - positions = wp.to_torch(positions_wp) - orientations = wp.to_torch(orientations_wp) - return positions, orientations - - def _get_local_poses_fabric(self, indices: Sequence[int] | None = None) -> tuple[torch.Tensor, torch.Tensor]: - """Get local poses using USD (matches Isaac Sim's design). - - Note: - Even in Fabric mode, local pose operations use USD's XformCache. - This is Isaac Sim's design: the ``usd=False`` parameter only affects world poses. - - Rationale: - - Local pose computation requires parent transforms which may not be in the view - - USD's XformCache provides efficient hierarchy-aware local transform queries - - Fabric is optimized for world pose operations, not local hierarchies - """ - return self._get_local_poses_usd(indices) - - def _get_scales_fabric(self, indices: Sequence[int] | None = None) -> torch.Tensor: - """Get scales from Fabric using GPU batch operations.""" - # Lazy initialization - if not self._fabric_initialized: - self._initialize_fabric() - # Sync once from USD to ensure reads see the latest authored transforms - if not self._fabric_usd_sync_done: - self._sync_fabric_from_usd_once() - - # Resolve indices (treat slice(None) as None for consistency with USD path) - indices_wp = self._resolve_indices_wp(indices) - - count = indices_wp.shape[0] - - # Use pre-allocated buffers for full reads, allocate only for partial reads - use_cached_buffers = indices is None or indices == slice(None) - if use_cached_buffers: - # Full read: Use cached buffers (zero allocation overhead!) - scales_wp = self._fabric_scales_buffer - else: - # Partial read: Need to allocate buffer of appropriate size - scales_wp = wp.zeros((count, 3), dtype=wp.float32).to(self._device) - - # Always use dummy buffers for positions and orientations (not needed for scales) - positions_wp = self._fabric_dummy_buffer - orientations_wp = self._fabric_dummy_buffer - - # Use cached fabricarray for world matrices - world_matrices = self._fabric_world_matrices - - # Launch GPU kernel to decompose matrices in parallel - # Note: world_matrices is a fabricarray on fabric_device, so we must launch on fabric_device - wp.launch( - kernel=fabric_utils.decompose_fabric_transformation_matrix_to_warp_arrays, - dim=count, - inputs=[ - world_matrices, - positions_wp, # dummy array instead of None - orientations_wp, # dummy array instead of None - scales_wp, - indices_wp, - self._view_to_fabric, - ], - device=self._fabric_device, - ) - - # Return tensor: zero-copy for cached buffers, conversion for partial reads - if use_cached_buffers: - # Zero-copy! The Warp kernel wrote directly into the PyTorch tensor - wp.synchronize() - return self._fabric_scales_torch - else: - # Partial read: Need to convert from Warp to torch - return wp.to_torch(scales_wp) - - """ - Internal Functions - Initialization. - """ - - def _initialize_fabric(self) -> None: - """Initialize Fabric batch infrastructure for GPU-accelerated pose queries. - - This method ensures all prims have the required Fabric hierarchy attributes - (``omni:fabric:localMatrix`` and ``omni:fabric:worldMatrix``) and creates the necessary - infrastructure for batch GPU operations using Warp. - - Based on the Fabric Hierarchy documentation, when Fabric Scene Delegate is enabled, - all boundable prims should have these attributes. This method ensures they exist - and are properly synchronized with USD. - """ - import usdrt - from usdrt import Rt - - # Get USDRT (Fabric) stage - stage_id = sim_utils.get_current_stage_id() - fabric_stage = usdrt.Usd.Stage.Attach(stage_id) - - # Step 1: Ensure all prims have Fabric hierarchy attributes - # According to the documentation, these attributes are created automatically - # when Fabric Scene Delegate is enabled, but we ensure they exist - for i in range(self.count): - rt_prim = fabric_stage.GetPrimAtPath(self.prim_paths[i]) - rt_xformable = Rt.Xformable(rt_prim) - - # Create Fabric hierarchy world matrix attribute if it doesn't exist - has_attr = ( - rt_xformable.HasFabricHierarchyWorldMatrixAttr() - if hasattr(rt_xformable, "HasFabricHierarchyWorldMatrixAttr") - else False - ) - if not has_attr: - rt_xformable.CreateFabricHierarchyWorldMatrixAttr() - - # Best-effort USD->Fabric sync; authoritative initialization happens on first read. - rt_xformable.SetWorldXformFromUsd() - - # Create view index attribute for batch operations - rt_prim.CreateAttribute(self._view_index_attr, usdrt.Sdf.ValueTypeNames.UInt, custom=True) - rt_prim.GetAttribute(self._view_index_attr).Set(i) - - # After syncing all prims, update the Fabric hierarchy to ensure world matrices are computed - self._fabric_hierarchy = usdrt.hierarchy.IFabricHierarchy().get_fabric_hierarchy( - fabric_stage.GetFabricId(), fabric_stage.GetStageIdAsStageId() - ) - self._fabric_hierarchy.update_world_xforms() - - # Step 2: Create index arrays for batch operations - self._default_view_indices = wp.zeros((self.count,), dtype=wp.uint32).to(self._device) - wp.launch( - kernel=fabric_utils.arange_k, - dim=self.count, - inputs=[self._default_view_indices], - device=self._device, - ) - wp.synchronize() # Ensure indices are ready - - # Step 3: Create Fabric selection with attribute filtering - # SelectPrims expects device format like "cuda:0" not "cuda" - # - # KNOWN ISSUE: SelectPrims may return prims in a different order than self._prims - # (which comes from USD's find_matching_prims). We create a bidirectional mapping - # (_view_to_fabric and _fabric_to_view) to handle this ordering difference. - # This works correctly for full-view operations but partial indexing still has issues. - # - # NOTE: SelectPrims only supports "cuda:0" regardless of which GPU the simulation - # is running on. In multi-GPU setups, we must use "cuda:0" for SelectPrims even if - # the simulation device is "cuda:1" or higher. - fabric_device = self._device - if self._device == "cuda": - logger.warning("Fabric device is not specified, defaulting to 'cuda:0'.") - fabric_device = "cuda:0" - elif self._device.startswith("cuda:"): - # SelectPrims only supports cuda:0, so we always use cuda:0 for SelectPrims - # even if the simulation is running on a different GPU - if self._device != "cuda:0": - logger.debug( - f"SelectPrims only supports cuda:0. Using cuda:0 for SelectPrims " - f"even though simulation device is {self._device}." - ) - fabric_device = "cuda:0" - - self._fabric_selection = fabric_stage.SelectPrims( - require_attrs=[ - (usdrt.Sdf.ValueTypeNames.UInt, self._view_index_attr, usdrt.Usd.Access.Read), - (usdrt.Sdf.ValueTypeNames.Matrix4d, "omni:fabric:worldMatrix", usdrt.Usd.Access.ReadWrite), - ], - device=fabric_device, - ) - - # Step 4: Create bidirectional mapping between view and fabric indices - # Note: fabric_to_view is tied to fabric_device (cuda:0) because it's created from SelectPrims. - # view_to_fabric must also be on fabric_device since it's always used with fabricarrays in kernels. - self._view_to_fabric = wp.zeros((self.count,), dtype=wp.uint32).to(fabric_device) - self._fabric_to_view = wp.fabricarray(self._fabric_selection, self._view_index_attr) - - wp.launch( - kernel=fabric_utils.set_view_to_fabric_array, - dim=self._fabric_to_view.shape[0], - inputs=[self._fabric_to_view, self._view_to_fabric], - device=fabric_device, - ) - # Synchronize to ensure mapping is ready before any operations - wp.synchronize() - - # Pre-allocate reusable output buffers for read operations - self._fabric_positions_torch = torch.zeros((self.count, 3), dtype=torch.float32, device=self._device) - self._fabric_orientations_torch = torch.zeros((self.count, 4), dtype=torch.float32, device=self._device) - self._fabric_scales_torch = torch.zeros((self.count, 3), dtype=torch.float32, device=self._device) - - # Create Warp views of the PyTorch tensors - self._fabric_positions_buffer = wp.from_torch(self._fabric_positions_torch, dtype=wp.float32) - self._fabric_orientations_buffer = wp.from_torch(self._fabric_orientations_torch, dtype=wp.float32) - self._fabric_scales_buffer = wp.from_torch(self._fabric_scales_torch, dtype=wp.float32) - - # Dummy array for unused outputs (always empty) - self._fabric_dummy_buffer = wp.zeros((0, 3), dtype=wp.float32).to(self._device) - - # Cache fabricarray for world matrices to avoid recreation overhead - # Refs: https://docs.omniverse.nvidia.com/kit/docs/usdrt/latest/docs/usdrt_prim_selection.html - # https://docs.omniverse.nvidia.com/kit/docs/usdrt/latest/docs/scenegraph_use.html - self._fabric_world_matrices = wp.fabricarray(self._fabric_selection, "omni:fabric:worldMatrix") - - # Cache Fabric stage to avoid expensive get_current_stage() calls - self._fabric_stage = fabric_stage - - # Store fabric_device for use in kernel launches that involve fabricarrays - self._fabric_device = fabric_device - - self._fabric_initialized = True - # Force a one-time USD->Fabric sync on first read to pick up any USD edits - # made after the view was constructed. - self._fabric_usd_sync_done = False - - def _sync_fabric_from_usd_once(self) -> None: - """Sync Fabric world matrices from USD once, on the first read.""" - # Ensure Fabric is initialized - if not self._fabric_initialized: - self._initialize_fabric() - - # Read authoritative transforms from USD and write once into Fabric. - positions_usd, orientations_usd = self._get_world_poses_usd() - scales_usd = self._get_scales_usd() - - prev_sync = self._sync_usd_on_fabric_write - self._sync_usd_on_fabric_write = False - self._set_world_poses_fabric(positions_usd, orientations_usd) - self._set_scales_fabric(scales_usd) - self._sync_usd_on_fabric_write = prev_sync - - self._fabric_usd_sync_done = True - - def _resolve_indices_wp(self, indices: Sequence[int] | None) -> wp.array: - """Resolve view indices as a Warp array.""" - if indices is None or indices == slice(None): - if self._default_view_indices is None: - raise RuntimeError("Fabric indices are not initialized.") - return self._default_view_indices - indices_list = indices.tolist() if isinstance(indices, torch.Tensor) else list(indices) - return wp.array(indices_list, dtype=wp.uint32).to(self._device) +XformPrimView = FrameView diff --git a/source/isaaclab/isaaclab/test/benchmark/backends.py b/source/isaaclab/isaaclab/test/benchmark/backends.py index f9187bf5b181..6b6c0acacb10 100644 --- a/source/isaaclab/isaaclab/test/benchmark/backends.py +++ b/source/isaaclab/isaaclab/test/benchmark/backends.py @@ -276,6 +276,33 @@ def _print_summary(self) -> None: self._print_box_line(f"{label}: {value}") self._print_box_separator() + # Render any phases not handled above (e.g. profiling phases from benchmark_startup) + known_phases = { + "benchmark_info", + "runtime", + "startup", + "train", + "frametime", + "hardware_info", + "version_info", + } + for phase_name, phase in phases.items(): + if phase_name in known_phases or not phase.measurements: + continue + self._print_box_line(f"Phase: {phase_name}") + for measurement in phase.measurements: + label = measurement.name + if isinstance(measurement, StatisticalMeasurement): + unit_str = f" {measurement.unit.strip()}" if (measurement.unit and measurement.unit.strip()) else "" + value = f"{self._format_scalar(measurement.mean)}{unit_str}" + elif isinstance(measurement, SingleMeasurement): + unit_str = f" {measurement.unit.strip()}" if (measurement.unit and measurement.unit.strip()) else "" + value = f"{self._format_scalar(measurement.value)}{unit_str}" + else: + continue + self._print_box_line(f"{label}: {value}") + self._print_box_separator() + if hardware_meta: self._print_box_line("System:") self._print_box_kv("cpu_name", hardware_meta.get("cpu_name")) diff --git a/source/isaaclab/isaaclab/test/benchmark/benchmark_core.py b/source/isaaclab/isaaclab/test/benchmark/benchmark_core.py index bf6e66495d6c..7daedbc132a8 100644 --- a/source/isaaclab/isaaclab/test/benchmark/benchmark_core.py +++ b/source/isaaclab/isaaclab/test/benchmark/benchmark_core.py @@ -119,7 +119,7 @@ def __init__( if self._use_frametime_recorders: try: # Enable the benchmark services extension first - from isaacsim.core.utils.extensions import enable_extension + from isaacsim.core.experimental.utils.app import enable_extension enable_extension("isaacsim.benchmark.services") diff --git a/source/isaaclab/isaaclab/test/benchmark/recorders/record_version_info.py b/source/isaaclab/isaaclab/test/benchmark/recorders/record_version_info.py index d297dffbb86d..a4396371b3d3 100644 --- a/source/isaaclab/isaaclab/test/benchmark/recorders/record_version_info.py +++ b/source/isaaclab/isaaclab/test/benchmark/recorders/record_version_info.py @@ -10,6 +10,9 @@ from isaaclab.test.benchmark.interfaces import MeasurementData, MeasurementDataRecorder from isaaclab.test.benchmark.measurements import DictMetadata, StringMetadata +# Path to the repository root. +_REPO_ROOT = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), *[".."] * 6)) + class VersionInfoRecorder(MeasurementDataRecorder): def __init__(self): @@ -96,6 +99,14 @@ def _get_version_info(self) -> None: self._record("cuda_bindings", self._get_pkg_version("cuda-bindings")) self._record("usd_core", self._get_pkg_version("usd-core")) + # Release version from root VERSION file + version_file = os.path.join(_REPO_ROOT, "VERSION") + try: + with open(version_file) as f: + self._record("isaaclab_release", f.read().strip()) + except Exception: + pass + def _get_git_info(self) -> None: """Get git repository information.""" script_dir = os.path.dirname(os.path.abspath(__file__)) diff --git a/source/isaaclab/isaaclab/test/mock_interfaces/assets/mock_articulation.py b/source/isaaclab/isaaclab/test/mock_interfaces/assets/mock_articulation.py index ddbee003152c..b7a29a55b389 100644 --- a/source/isaaclab/isaaclab/test/mock_interfaces/assets/mock_articulation.py +++ b/source/isaaclab/isaaclab/test/mock_interfaces/assets/mock_articulation.py @@ -14,6 +14,8 @@ import torch import warp as wp +from isaaclab.utils.warp import ProxyArray + try: from isaaclab.assets.articulation.base_articulation_data import BaseArticulationData except (ImportError, ModuleNotFoundError): @@ -132,7 +134,6 @@ def __init__( # Body properties self._body_mass: wp.array | None = None self._body_inertia: wp.array | None = None - self._body_incoming_joint_wrench_b: wp.array | None = None # Tendon properties (fixed) self._fixed_tendon_stiffness: wp.array | None = None @@ -148,6 +149,54 @@ def __init__( self._spatial_tendon_limit_stiffness: wp.array | None = None self._spatial_tendon_offset: wp.array | None = None + # ProxyArray caches + self._default_root_pose_ta: ProxyArray | None = None + self._default_root_vel_ta: ProxyArray | None = None + self._default_joint_pos_ta: ProxyArray | None = None + self._default_joint_vel_ta: ProxyArray | None = None + self._joint_pos_target_ta: ProxyArray | None = None + self._joint_vel_target_ta: ProxyArray | None = None + self._joint_effort_target_ta: ProxyArray | None = None + self._computed_torque_ta: ProxyArray | None = None + self._applied_torque_ta: ProxyArray | None = None + self._joint_stiffness_ta: ProxyArray | None = None + self._joint_damping_ta: ProxyArray | None = None + self._joint_armature_ta: ProxyArray | None = None + self._joint_friction_coeff_ta: ProxyArray | None = None + self._joint_dynamic_friction_coeff_ta: ProxyArray | None = None + self._joint_viscous_friction_coeff_ta: ProxyArray | None = None + self._joint_pos_limits_ta: ProxyArray | None = None + self._joint_vel_limits_ta: ProxyArray | None = None + self._joint_effort_limits_ta: ProxyArray | None = None + self._soft_joint_pos_limits_ta: ProxyArray | None = None + self._soft_joint_vel_limits_ta: ProxyArray | None = None + self._gear_ratio_ta: ProxyArray | None = None + self._joint_pos_ta: ProxyArray | None = None + self._joint_vel_ta: ProxyArray | None = None + self._joint_acc_ta: ProxyArray | None = None + self._root_link_pose_w_ta: ProxyArray | None = None + self._root_link_vel_w_ta: ProxyArray | None = None + self._root_com_pose_w_ta: ProxyArray | None = None + self._root_com_vel_w_ta: ProxyArray | None = None + self._body_link_pose_w_ta: ProxyArray | None = None + self._body_link_vel_w_ta: ProxyArray | None = None + self._body_com_pose_w_ta: ProxyArray | None = None + self._body_com_vel_w_ta: ProxyArray | None = None + self._body_com_acc_w_ta: ProxyArray | None = None + self._body_com_pose_b_ta: ProxyArray | None = None + self._body_mass_ta: ProxyArray | None = None + self._body_inertia_ta: ProxyArray | None = None + self._fixed_tendon_stiffness_ta: ProxyArray | None = None + self._fixed_tendon_damping_ta: ProxyArray | None = None + self._fixed_tendon_limit_stiffness_ta: ProxyArray | None = None + self._fixed_tendon_rest_length_ta: ProxyArray | None = None + self._fixed_tendon_offset_ta: ProxyArray | None = None + self._fixed_tendon_pos_limits_ta: ProxyArray | None = None + self._spatial_tendon_stiffness_ta: ProxyArray | None = None + self._spatial_tendon_damping_ta: ProxyArray | None = None + self._spatial_tendon_limit_stiffness_ta: ProxyArray | None = None + self._spatial_tendon_offset_ta: ProxyArray | None = None + # -- Helper for identity quaternion -- def _identity_quat(self, *shape: int) -> wp.array: """Create identity quaternion array (w, x, y, z) = (1, 0, 0, 0).""" @@ -158,515 +207,660 @@ def _identity_quat(self, *shape: int) -> wp.array: # -- Default state properties -- @property - def default_root_pose(self) -> wp.array: + def default_root_pose(self) -> ProxyArray: """Default root pose. dtype=wp.transformf, shape: (N,).""" if self._default_root_pose is None: pose_np = np.zeros((self._num_instances, 7), dtype=np.float32) pose_np[..., 6] = 1.0 # identity quat qw=1, transformf layout: (px,py,pz,qx,qy,qz,qw) self._default_root_pose = wp.array(pose_np, dtype=wp.float32, device=self.device).view(wp.transformf) - return self._default_root_pose + self._default_root_pose_ta = None + if self._default_root_pose_ta is None: + self._default_root_pose_ta = ProxyArray(self._default_root_pose) + return self._default_root_pose_ta @property - def default_root_vel(self) -> wp.array: + def default_root_vel(self) -> ProxyArray: """Default root velocity. dtype=wp.spatial_vectorf, shape: (N,).""" if self._default_root_vel is None: self._default_root_vel = wp.zeros((self._num_instances, 6), dtype=wp.float32, device=self.device).view( wp.spatial_vectorf ) - return self._default_root_vel + self._default_root_vel_ta = None + if self._default_root_vel_ta is None: + self._default_root_vel_ta = ProxyArray(self._default_root_vel) + return self._default_root_vel_ta @property - def default_root_state(self) -> wp.array: + def default_root_state(self) -> ProxyArray: """Default root state [pose(7), vel(6)]. Shape: (N, 13).""" - pose_t = wp.to_torch(self.default_root_pose) - vel_t = wp.to_torch(self.default_root_vel) - return wp.from_torch(torch.cat([pose_t, vel_t], dim=-1)) + pose_t = self.default_root_pose.torch + vel_t = self.default_root_vel.torch + return ProxyArray(wp.from_torch(torch.cat([pose_t, vel_t], dim=-1))) @property - def default_joint_pos(self) -> wp.array: + def default_joint_pos(self) -> ProxyArray: """Default joint positions. Shape: (N, num_joints).""" if self._default_joint_pos is None: - return wp.zeros((self._num_instances, self._num_joints), dtype=wp.float32, device=self.device) - return self._default_joint_pos + self._default_joint_pos = wp.zeros( + (self._num_instances, self._num_joints), dtype=wp.float32, device=self.device + ) + self._default_joint_pos_ta = None + if self._default_joint_pos_ta is None: + self._default_joint_pos_ta = ProxyArray(self._default_joint_pos) + return self._default_joint_pos_ta @property - def default_joint_vel(self) -> wp.array: + def default_joint_vel(self) -> ProxyArray: """Default joint velocities. Shape: (N, num_joints).""" if self._default_joint_vel is None: - return wp.zeros((self._num_instances, self._num_joints), dtype=wp.float32, device=self.device) - return self._default_joint_vel + self._default_joint_vel = wp.zeros( + (self._num_instances, self._num_joints), dtype=wp.float32, device=self.device + ) + self._default_joint_vel_ta = None + if self._default_joint_vel_ta is None: + self._default_joint_vel_ta = ProxyArray(self._default_joint_vel) + return self._default_joint_vel_ta # -- Joint command properties -- @property - def joint_pos_target(self) -> wp.array: + def joint_pos_target(self) -> ProxyArray: """Joint position targets. Shape: (N, num_joints).""" if self._joint_pos_target is None: - return wp.zeros((self._num_instances, self._num_joints), dtype=wp.float32, device=self.device) - return self._joint_pos_target + self._joint_pos_target = wp.zeros( + (self._num_instances, self._num_joints), dtype=wp.float32, device=self.device + ) + self._joint_pos_target_ta = None + if self._joint_pos_target_ta is None: + self._joint_pos_target_ta = ProxyArray(self._joint_pos_target) + return self._joint_pos_target_ta @property - def joint_vel_target(self) -> wp.array: + def joint_vel_target(self) -> ProxyArray: """Joint velocity targets. Shape: (N, num_joints).""" if self._joint_vel_target is None: - return wp.zeros((self._num_instances, self._num_joints), dtype=wp.float32, device=self.device) - return self._joint_vel_target + self._joint_vel_target = wp.zeros( + (self._num_instances, self._num_joints), dtype=wp.float32, device=self.device + ) + self._joint_vel_target_ta = None + if self._joint_vel_target_ta is None: + self._joint_vel_target_ta = ProxyArray(self._joint_vel_target) + return self._joint_vel_target_ta @property - def joint_effort_target(self) -> wp.array: + def joint_effort_target(self) -> ProxyArray: """Joint effort targets. Shape: (N, num_joints).""" if self._joint_effort_target is None: - return wp.zeros((self._num_instances, self._num_joints), dtype=wp.float32, device=self.device) - return self._joint_effort_target + self._joint_effort_target = wp.zeros( + (self._num_instances, self._num_joints), dtype=wp.float32, device=self.device + ) + self._joint_effort_target_ta = None + if self._joint_effort_target_ta is None: + self._joint_effort_target_ta = ProxyArray(self._joint_effort_target) + return self._joint_effort_target_ta @property - def computed_torque(self) -> wp.array: + def computed_torque(self) -> ProxyArray: """Computed torques before clipping. Shape: (N, num_joints).""" if self._computed_torque is None: - return wp.zeros((self._num_instances, self._num_joints), dtype=wp.float32, device=self.device) - return self._computed_torque + self._computed_torque = wp.zeros( + (self._num_instances, self._num_joints), dtype=wp.float32, device=self.device + ) + self._computed_torque_ta = None + if self._computed_torque_ta is None: + self._computed_torque_ta = ProxyArray(self._computed_torque) + return self._computed_torque_ta @property - def applied_torque(self) -> wp.array: + def applied_torque(self) -> ProxyArray: """Applied torques after clipping. Shape: (N, num_joints).""" if self._applied_torque is None: - return wp.zeros((self._num_instances, self._num_joints), dtype=wp.float32, device=self.device) - return self._applied_torque + self._applied_torque = wp.zeros( + (self._num_instances, self._num_joints), dtype=wp.float32, device=self.device + ) + self._applied_torque_ta = None + if self._applied_torque_ta is None: + self._applied_torque_ta = ProxyArray(self._applied_torque) + return self._applied_torque_ta # -- Joint properties -- @property - def joint_stiffness(self) -> wp.array: + def joint_stiffness(self) -> ProxyArray: """Joint stiffness. Shape: (N, num_joints).""" if self._joint_stiffness is None: - return wp.zeros((self._num_instances, self._num_joints), dtype=wp.float32, device=self.device) - return self._joint_stiffness + self._joint_stiffness = wp.zeros( + (self._num_instances, self._num_joints), dtype=wp.float32, device=self.device + ) + self._joint_stiffness_ta = None + if self._joint_stiffness_ta is None: + self._joint_stiffness_ta = ProxyArray(self._joint_stiffness) + return self._joint_stiffness_ta @property - def joint_damping(self) -> wp.array: + def joint_damping(self) -> ProxyArray: """Joint damping. Shape: (N, num_joints).""" if self._joint_damping is None: - return wp.zeros((self._num_instances, self._num_joints), dtype=wp.float32, device=self.device) - return self._joint_damping + self._joint_damping = wp.zeros( + (self._num_instances, self._num_joints), dtype=wp.float32, device=self.device + ) + self._joint_damping_ta = None + if self._joint_damping_ta is None: + self._joint_damping_ta = ProxyArray(self._joint_damping) + return self._joint_damping_ta @property - def joint_armature(self) -> wp.array: + def joint_armature(self) -> ProxyArray: """Joint armature. Shape: (N, num_joints).""" if self._joint_armature is None: - return wp.zeros((self._num_instances, self._num_joints), dtype=wp.float32, device=self.device) - return self._joint_armature + self._joint_armature = wp.zeros( + (self._num_instances, self._num_joints), dtype=wp.float32, device=self.device + ) + self._joint_armature_ta = None + if self._joint_armature_ta is None: + self._joint_armature_ta = ProxyArray(self._joint_armature) + return self._joint_armature_ta @property - def joint_friction_coeff(self) -> wp.array: + def joint_friction_coeff(self) -> ProxyArray: """Joint static friction coefficient. Shape: (N, num_joints).""" if self._joint_friction_coeff is None: - return wp.zeros((self._num_instances, self._num_joints), dtype=wp.float32, device=self.device) - return self._joint_friction_coeff + self._joint_friction_coeff = wp.zeros( + (self._num_instances, self._num_joints), dtype=wp.float32, device=self.device + ) + self._joint_friction_coeff_ta = None + if self._joint_friction_coeff_ta is None: + self._joint_friction_coeff_ta = ProxyArray(self._joint_friction_coeff) + return self._joint_friction_coeff_ta @property - def joint_dynamic_friction_coeff(self) -> wp.array: + def joint_dynamic_friction_coeff(self) -> ProxyArray: """Joint dynamic friction coefficient. Shape: (N, num_joints).""" if self._joint_dynamic_friction_coeff is None: - return wp.zeros((self._num_instances, self._num_joints), dtype=wp.float32, device=self.device) - return self._joint_dynamic_friction_coeff + self._joint_dynamic_friction_coeff = wp.zeros( + (self._num_instances, self._num_joints), dtype=wp.float32, device=self.device + ) + self._joint_dynamic_friction_coeff_ta = None + if self._joint_dynamic_friction_coeff_ta is None: + self._joint_dynamic_friction_coeff_ta = ProxyArray(self._joint_dynamic_friction_coeff) + return self._joint_dynamic_friction_coeff_ta @property - def joint_viscous_friction_coeff(self) -> wp.array: + def joint_viscous_friction_coeff(self) -> ProxyArray: """Joint viscous friction coefficient. Shape: (N, num_joints).""" if self._joint_viscous_friction_coeff is None: - return wp.zeros((self._num_instances, self._num_joints), dtype=wp.float32, device=self.device) - return self._joint_viscous_friction_coeff + self._joint_viscous_friction_coeff = wp.zeros( + (self._num_instances, self._num_joints), dtype=wp.float32, device=self.device + ) + self._joint_viscous_friction_coeff_ta = None + if self._joint_viscous_friction_coeff_ta is None: + self._joint_viscous_friction_coeff_ta = ProxyArray(self._joint_viscous_friction_coeff) + return self._joint_viscous_friction_coeff_ta @property - def joint_pos_limits(self) -> wp.array: + def joint_pos_limits(self) -> ProxyArray: """Joint position limits [lower, upper]. dtype=wp.vec2f, shape: (N, num_joints).""" if self._joint_pos_limits is None: np_limits = np.zeros((self._num_instances, self._num_joints, 2), dtype=np.float32) np_limits[..., 0] = -float("inf") np_limits[..., 1] = float("inf") - return wp.array(np_limits, dtype=wp.float32, device=self.device).view(wp.vec2f) - return self._joint_pos_limits + self._joint_pos_limits = wp.array(np_limits, dtype=wp.float32, device=self.device).view(wp.vec2f) + self._joint_pos_limits_ta = None + if self._joint_pos_limits_ta is None: + self._joint_pos_limits_ta = ProxyArray(self._joint_pos_limits) + return self._joint_pos_limits_ta @property - def joint_vel_limits(self) -> wp.array: + def joint_vel_limits(self) -> ProxyArray: """Joint velocity limits. Shape: (N, num_joints).""" if self._joint_vel_limits is None: - return wp.full( + self._joint_vel_limits = wp.full( (self._num_instances, self._num_joints), dtype=wp.float32, value=float("inf"), device=self.device ) - return self._joint_vel_limits + self._joint_vel_limits_ta = None + if self._joint_vel_limits_ta is None: + self._joint_vel_limits_ta = ProxyArray(self._joint_vel_limits) + return self._joint_vel_limits_ta @property - def joint_effort_limits(self) -> wp.array: + def joint_effort_limits(self) -> ProxyArray: """Joint effort limits. Shape: (N, num_joints).""" if self._joint_effort_limits is None: - return wp.full( + self._joint_effort_limits = wp.full( (self._num_instances, self._num_joints), dtype=wp.float32, value=float("inf"), device=self.device ) - return self._joint_effort_limits + self._joint_effort_limits_ta = None + if self._joint_effort_limits_ta is None: + self._joint_effort_limits_ta = ProxyArray(self._joint_effort_limits) + return self._joint_effort_limits_ta @property - def soft_joint_pos_limits(self) -> wp.array: + def soft_joint_pos_limits(self) -> ProxyArray: """Soft joint position limits. Shape: (N, num_joints, 2).""" if self._soft_joint_pos_limits is None: - return wp.clone(self.joint_pos_limits, self.device) - return self._soft_joint_pos_limits + self._soft_joint_pos_limits = wp.clone(self.joint_pos_limits.warp, self.device) + self._soft_joint_pos_limits_ta = None + if self._soft_joint_pos_limits_ta is None: + self._soft_joint_pos_limits_ta = ProxyArray(self._soft_joint_pos_limits) + return self._soft_joint_pos_limits_ta @property - def soft_joint_vel_limits(self) -> wp.array: + def soft_joint_vel_limits(self) -> ProxyArray: """Soft joint velocity limits. Shape: (N, num_joints).""" if self._soft_joint_vel_limits is None: - return wp.clone(self.joint_vel_limits, self.device) - return self._soft_joint_vel_limits + self._soft_joint_vel_limits = wp.clone(self.joint_vel_limits.warp, self.device) + self._soft_joint_vel_limits_ta = None + if self._soft_joint_vel_limits_ta is None: + self._soft_joint_vel_limits_ta = ProxyArray(self._soft_joint_vel_limits) + return self._soft_joint_vel_limits_ta @property - def gear_ratio(self) -> wp.array: + def gear_ratio(self) -> ProxyArray: """Gear ratio. Shape: (N, num_joints).""" if self._gear_ratio is None: - return wp.ones((self._num_instances, self._num_joints), dtype=wp.float32, device=self.device) - return self._gear_ratio + self._gear_ratio = wp.ones((self._num_instances, self._num_joints), dtype=wp.float32, device=self.device) + self._gear_ratio_ta = None + if self._gear_ratio_ta is None: + self._gear_ratio_ta = ProxyArray(self._gear_ratio) + return self._gear_ratio_ta # -- Joint state properties -- @property - def joint_pos(self) -> wp.array: + def joint_pos(self) -> ProxyArray: """Joint positions. Shape: (N, num_joints).""" if self._joint_pos is None: - return wp.zeros((self._num_instances, self._num_joints), dtype=wp.float32, device=self.device) - return self._joint_pos + self._joint_pos = wp.zeros((self._num_instances, self._num_joints), dtype=wp.float32, device=self.device) + self._joint_pos_ta = None + if self._joint_pos_ta is None: + self._joint_pos_ta = ProxyArray(self._joint_pos) + return self._joint_pos_ta @property - def joint_vel(self) -> wp.array: + def joint_vel(self) -> ProxyArray: """Joint velocities. Shape: (N, num_joints).""" if self._joint_vel is None: - return wp.zeros((self._num_instances, self._num_joints), dtype=wp.float32, device=self.device) - return self._joint_vel + self._joint_vel = wp.zeros((self._num_instances, self._num_joints), dtype=wp.float32, device=self.device) + self._joint_vel_ta = None + if self._joint_vel_ta is None: + self._joint_vel_ta = ProxyArray(self._joint_vel) + return self._joint_vel_ta @property - def joint_acc(self) -> wp.array: + def joint_acc(self) -> ProxyArray: """Joint accelerations. Shape: (N, num_joints).""" if self._joint_acc is None: - return wp.zeros((self._num_instances, self._num_joints), dtype=wp.float32, device=self.device) - return self._joint_acc + self._joint_acc = wp.zeros((self._num_instances, self._num_joints), dtype=wp.float32, device=self.device) + self._joint_acc_ta = None + if self._joint_acc_ta is None: + self._joint_acc_ta = ProxyArray(self._joint_acc) + return self._joint_acc_ta # -- Root state properties (link frame) -- @property - def root_link_pose_w(self) -> wp.array: + def root_link_pose_w(self) -> ProxyArray: """Root link pose in world frame. dtype=wp.transformf, shape: (N,).""" if self._root_link_pose_w is None: pose_np = np.zeros((self._num_instances, 7), dtype=np.float32) pose_np[..., 6] = 1.0 # identity quat qw=1, transformf layout: (px,py,pz,qx,qy,qz,qw) self._root_link_pose_w = wp.array(pose_np, dtype=wp.float32, device=self.device).view(wp.transformf) - return self._root_link_pose_w + self._root_link_pose_w_ta = None + if self._root_link_pose_w_ta is None: + self._root_link_pose_w_ta = ProxyArray(self._root_link_pose_w) + return self._root_link_pose_w_ta @property - def root_link_vel_w(self) -> wp.array: + def root_link_vel_w(self) -> ProxyArray: """Root link velocity in world frame. dtype=wp.spatial_vectorf, shape: (N,).""" if self._root_link_vel_w is None: self._root_link_vel_w = wp.zeros((self._num_instances, 6), dtype=wp.float32, device=self.device).view( wp.spatial_vectorf ) - return self._root_link_vel_w + self._root_link_vel_w_ta = None + if self._root_link_vel_w_ta is None: + self._root_link_vel_w_ta = ProxyArray(self._root_link_vel_w) + return self._root_link_vel_w_ta @property - def root_link_state_w(self) -> wp.array: + def root_link_state_w(self) -> ProxyArray: """Root link state in world frame. Shape: (N, 13).""" - pose_t = wp.to_torch(self.root_link_pose_w) - vel_t = wp.to_torch(self.root_link_vel_w) - return wp.from_torch(torch.cat([pose_t, vel_t], dim=-1)) + pose_t = self.root_link_pose_w.torch + vel_t = self.root_link_vel_w.torch + return ProxyArray(wp.from_torch(torch.cat([pose_t, vel_t], dim=-1).contiguous())) # Sliced properties (zero-copy pointer arithmetic on transformf) @property - def root_link_pos_w(self) -> wp.array: + def root_link_pos_w(self) -> ProxyArray: """Root link position in world frame. Shape: (N,), dtype=wp.vec3f.""" - t = self.root_link_pose_w - return wp.array(ptr=t.ptr, shape=t.shape, dtype=wp.vec3f, strides=t.strides, device=self.device) + t = self.root_link_pose_w.warp + return ProxyArray(wp.array(ptr=t.ptr, shape=t.shape, dtype=wp.vec3f, strides=t.strides, device=self.device)) @property - def root_link_quat_w(self) -> wp.array: + def root_link_quat_w(self) -> ProxyArray: """Root link orientation in world frame (x, y, z, w). Shape: (N,), dtype=wp.quatf.""" - t = self.root_link_pose_w - return wp.array(ptr=t.ptr + 3 * 4, shape=t.shape, dtype=wp.quatf, strides=t.strides, device=self.device) + t = self.root_link_pose_w.warp + return ProxyArray( + wp.array(ptr=t.ptr + 3 * 4, shape=t.shape, dtype=wp.quatf, strides=t.strides, device=self.device) + ) @property - def root_link_lin_vel_w(self) -> wp.array: + def root_link_lin_vel_w(self) -> ProxyArray: """Root link linear velocity in world frame. Shape: (N,), dtype=wp.vec3f.""" - v = self.root_link_vel_w - return wp.array(ptr=v.ptr, shape=v.shape, dtype=wp.vec3f, strides=v.strides, device=self.device) + v = self.root_link_vel_w.warp + return ProxyArray(wp.array(ptr=v.ptr, shape=v.shape, dtype=wp.vec3f, strides=v.strides, device=self.device)) @property - def root_link_ang_vel_w(self) -> wp.array: + def root_link_ang_vel_w(self) -> ProxyArray: """Root link angular velocity in world frame. Shape: (N,), dtype=wp.vec3f.""" - v = self.root_link_vel_w - return wp.array(ptr=v.ptr + 3 * 4, shape=v.shape, dtype=wp.vec3f, strides=v.strides, device=self.device) + v = self.root_link_vel_w.warp + return ProxyArray( + wp.array(ptr=v.ptr + 3 * 4, shape=v.shape, dtype=wp.vec3f, strides=v.strides, device=self.device) + ) # -- Root state properties (CoM frame) -- @property - def root_com_pose_w(self) -> wp.array: + def root_com_pose_w(self) -> ProxyArray: """Root CoM pose in world frame. dtype=wp.transformf, shape: (N,).""" if self._root_com_pose_w is None: - self._root_com_pose_w = wp.clone(self.root_link_pose_w, self.device) - return self._root_com_pose_w + self._root_com_pose_w = wp.clone(self.root_link_pose_w.warp, self.device) + self._root_com_pose_w_ta = None + if self._root_com_pose_w_ta is None: + self._root_com_pose_w_ta = ProxyArray(self._root_com_pose_w) + return self._root_com_pose_w_ta @property - def root_com_vel_w(self) -> wp.array: + def root_com_vel_w(self) -> ProxyArray: """Root CoM velocity in world frame. dtype=wp.spatial_vectorf, shape: (N,).""" if self._root_com_vel_w is None: - self._root_com_vel_w = wp.clone(self.root_link_vel_w, self.device) - return self._root_com_vel_w + self._root_com_vel_w = wp.clone(self.root_link_vel_w.warp, self.device) + self._root_com_vel_w_ta = None + if self._root_com_vel_w_ta is None: + self._root_com_vel_w_ta = ProxyArray(self._root_com_vel_w) + return self._root_com_vel_w_ta @property - def root_com_state_w(self) -> wp.array: + def root_com_state_w(self) -> ProxyArray: """Root CoM state in world frame. Shape: (N, 13).""" - pose_t = wp.to_torch(self.root_com_pose_w) - vel_t = wp.to_torch(self.root_com_vel_w) - return wp.from_torch(torch.cat([pose_t, vel_t], dim=-1)) + pose_t = self.root_com_pose_w.torch + vel_t = self.root_com_vel_w.torch + return ProxyArray(wp.from_torch(torch.cat([pose_t, vel_t], dim=-1).contiguous())) @property - def root_state_w(self) -> wp.array: + def root_state_w(self) -> ProxyArray: """Root state (link pose + CoM velocity). Shape: (N, 13).""" - pose_t = wp.to_torch(self.root_link_pose_w) - vel_t = wp.to_torch(self.root_com_vel_w) - return wp.from_torch(torch.cat([pose_t, vel_t], dim=-1)) + pose_t = self.root_link_pose_w.torch + vel_t = self.root_com_vel_w.torch + return ProxyArray(wp.from_torch(torch.cat([pose_t, vel_t], dim=-1).contiguous())) # Sliced properties (zero-copy pointer arithmetic on transformf) @property - def root_com_pos_w(self) -> wp.array: + def root_com_pos_w(self) -> ProxyArray: """Root CoM position in world frame. Shape: (N,), dtype=wp.vec3f.""" - t = self.root_com_pose_w - return wp.array(ptr=t.ptr, shape=t.shape, dtype=wp.vec3f, strides=t.strides, device=self.device) + t = self.root_com_pose_w.warp + return ProxyArray(wp.array(ptr=t.ptr, shape=t.shape, dtype=wp.vec3f, strides=t.strides, device=self.device)) @property - def root_com_quat_w(self) -> wp.array: + def root_com_quat_w(self) -> ProxyArray: """Root CoM orientation in world frame. Shape: (N,), dtype=wp.quatf.""" - t = self.root_com_pose_w - return wp.array(ptr=t.ptr + 3 * 4, shape=t.shape, dtype=wp.quatf, strides=t.strides, device=self.device) + t = self.root_com_pose_w.warp + return ProxyArray( + wp.array(ptr=t.ptr + 3 * 4, shape=t.shape, dtype=wp.quatf, strides=t.strides, device=self.device) + ) @property - def root_com_lin_vel_w(self) -> wp.array: + def root_com_lin_vel_w(self) -> ProxyArray: """Root CoM linear velocity in world frame. Shape: (N,), dtype=wp.vec3f.""" - v = self.root_com_vel_w - return wp.array(ptr=v.ptr, shape=v.shape, dtype=wp.vec3f, strides=v.strides, device=self.device) + v = self.root_com_vel_w.warp + return ProxyArray(wp.array(ptr=v.ptr, shape=v.shape, dtype=wp.vec3f, strides=v.strides, device=self.device)) @property - def root_com_ang_vel_w(self) -> wp.array: + def root_com_ang_vel_w(self) -> ProxyArray: """Root CoM angular velocity in world frame. Shape: (N,), dtype=wp.vec3f.""" - v = self.root_com_vel_w - return wp.array(ptr=v.ptr + 3 * 4, shape=v.shape, dtype=wp.vec3f, strides=v.strides, device=self.device) + v = self.root_com_vel_w.warp + return ProxyArray( + wp.array(ptr=v.ptr + 3 * 4, shape=v.shape, dtype=wp.vec3f, strides=v.strides, device=self.device) + ) # -- Body state properties (link frame) -- @property - def body_link_pose_w(self) -> wp.array: + def body_link_pose_w(self) -> ProxyArray: """Body link poses in world frame. dtype=wp.transformf, shape: (N, num_bodies).""" if self._body_link_pose_w is None: pose_np = np.zeros((self._num_instances, self._num_bodies, 7), dtype=np.float32) pose_np[..., 6] = 1.0 # identity quat qw=1, transformf layout: (px,py,pz,qx,qy,qz,qw) self._body_link_pose_w = wp.array(pose_np, dtype=wp.float32, device=self.device).view(wp.transformf) - return self._body_link_pose_w + self._body_link_pose_w_ta = None + if self._body_link_pose_w_ta is None: + self._body_link_pose_w_ta = ProxyArray(self._body_link_pose_w) + return self._body_link_pose_w_ta @property - def body_link_vel_w(self) -> wp.array: + def body_link_vel_w(self) -> ProxyArray: """Body link velocities in world frame. dtype=wp.spatial_vectorf, shape: (N, num_bodies).""" if self._body_link_vel_w is None: self._body_link_vel_w = wp.zeros( (self._num_instances, self._num_bodies, 6), dtype=wp.float32, device=self.device ).view(wp.spatial_vectorf) - return self._body_link_vel_w + self._body_link_vel_w_ta = None + if self._body_link_vel_w_ta is None: + self._body_link_vel_w_ta = ProxyArray(self._body_link_vel_w) + return self._body_link_vel_w_ta @property - def body_link_state_w(self) -> wp.array: + def body_link_state_w(self) -> ProxyArray: """Body link states in world frame. Shape: (N, num_bodies, 13).""" - pose_t = wp.to_torch(self.body_link_pose_w) - vel_t = wp.to_torch(self.body_link_vel_w) - return wp.from_torch(torch.cat([pose_t, vel_t], dim=-1)) + pose_t = self.body_link_pose_w.torch + vel_t = self.body_link_vel_w.torch + return ProxyArray(wp.from_torch(torch.cat([pose_t, vel_t], dim=-1).contiguous())) # Sliced properties (zero-copy pointer arithmetic on transformf) @property - def body_link_pos_w(self) -> wp.array: + def body_link_pos_w(self) -> ProxyArray: """Body link positions. Shape: (N, num_bodies), dtype=wp.vec3f.""" - t = self.body_link_pose_w - return wp.array(ptr=t.ptr, shape=t.shape, dtype=wp.vec3f, strides=t.strides, device=self.device) + t = self.body_link_pose_w.warp + return ProxyArray(wp.array(ptr=t.ptr, shape=t.shape, dtype=wp.vec3f, strides=t.strides, device=self.device)) @property - def body_link_quat_w(self) -> wp.array: + def body_link_quat_w(self) -> ProxyArray: """Body link orientations. Shape: (N, num_bodies), dtype=wp.quatf.""" - t = self.body_link_pose_w - return wp.array(ptr=t.ptr + 3 * 4, shape=t.shape, dtype=wp.quatf, strides=t.strides, device=self.device) + t = self.body_link_pose_w.warp + return ProxyArray( + wp.array(ptr=t.ptr + 3 * 4, shape=t.shape, dtype=wp.quatf, strides=t.strides, device=self.device) + ) @property - def body_link_lin_vel_w(self) -> wp.array: + def body_link_lin_vel_w(self) -> ProxyArray: """Body link linear velocities in world frame. Shape: (N, num_bodies), dtype=wp.vec3f.""" - v = self.body_link_vel_w - return wp.array(ptr=v.ptr, shape=v.shape, dtype=wp.vec3f, strides=v.strides, device=self.device) + v = self.body_link_vel_w.warp + return ProxyArray(wp.array(ptr=v.ptr, shape=v.shape, dtype=wp.vec3f, strides=v.strides, device=self.device)) @property - def body_link_ang_vel_w(self) -> wp.array: + def body_link_ang_vel_w(self) -> ProxyArray: """Body link angular velocities in world frame. Shape: (N, num_bodies), dtype=wp.vec3f.""" - v = self.body_link_vel_w - return wp.array(ptr=v.ptr + 3 * 4, shape=v.shape, dtype=wp.vec3f, strides=v.strides, device=self.device) + v = self.body_link_vel_w.warp + return ProxyArray( + wp.array(ptr=v.ptr + 3 * 4, shape=v.shape, dtype=wp.vec3f, strides=v.strides, device=self.device) + ) # -- Body state properties (CoM frame) -- @property - def body_com_pose_w(self) -> wp.array: + def body_com_pose_w(self) -> ProxyArray: """Body CoM poses in world frame. dtype=wp.transformf, shape: (N, num_bodies).""" if self._body_com_pose_w is None: - self._body_com_pose_w = wp.clone(self.body_link_pose_w, self.device) - return self._body_com_pose_w + self._body_com_pose_w = wp.clone(self.body_link_pose_w.warp, self.device) + self._body_com_pose_w_ta = None + if self._body_com_pose_w_ta is None: + self._body_com_pose_w_ta = ProxyArray(self._body_com_pose_w) + return self._body_com_pose_w_ta @property - def body_com_vel_w(self) -> wp.array: + def body_com_vel_w(self) -> ProxyArray: """Body CoM velocities in world frame. dtype=wp.spatial_vectorf, shape: (N, num_bodies).""" if self._body_com_vel_w is None: - self._body_com_vel_w = wp.clone(self.body_link_vel_w, self.device) - return self._body_com_vel_w + self._body_com_vel_w = wp.clone(self.body_link_vel_w.warp, self.device) + self._body_com_vel_w_ta = None + if self._body_com_vel_w_ta is None: + self._body_com_vel_w_ta = ProxyArray(self._body_com_vel_w) + return self._body_com_vel_w_ta @property - def body_com_state_w(self) -> wp.array: + def body_com_state_w(self) -> ProxyArray: """Body CoM states in world frame. Shape: (N, num_bodies, 13).""" - pose_t = wp.to_torch(self.body_com_pose_w) - vel_t = wp.to_torch(self.body_com_vel_w) - return wp.from_torch(torch.cat([pose_t, vel_t], dim=-1)) + pose_t = self.body_com_pose_w.torch + vel_t = self.body_com_vel_w.torch + return ProxyArray(wp.from_torch(torch.cat([pose_t, vel_t], dim=-1).contiguous())) @property - def body_state_w(self) -> wp.array: + def body_state_w(self) -> ProxyArray: """Body states (link pose + CoM velocity). Shape: (N, num_bodies, 13).""" - pose_t = wp.to_torch(self.body_link_pose_w) - vel_t = wp.to_torch(self.body_com_vel_w) - return wp.from_torch(torch.cat([pose_t, vel_t], dim=-1)) + pose_t = self.body_link_pose_w.torch + vel_t = self.body_com_vel_w.torch + return ProxyArray(wp.from_torch(torch.cat([pose_t, vel_t], dim=-1).contiguous())) @property - def body_com_acc_w(self) -> wp.array: + def body_com_acc_w(self) -> ProxyArray: """Body CoM accelerations in world frame. dtype=wp.spatial_vectorf, shape: (N, num_bodies).""" if self._body_com_acc_w is None: self._body_com_acc_w = wp.zeros( (self._num_instances, self._num_bodies, 6), dtype=wp.float32, device=self.device ).view(wp.spatial_vectorf) - return self._body_com_acc_w + self._body_com_acc_w_ta = None + if self._body_com_acc_w_ta is None: + self._body_com_acc_w_ta = ProxyArray(self._body_com_acc_w) + return self._body_com_acc_w_ta @property - def body_com_pose_b(self) -> wp.array: + def body_com_pose_b(self) -> ProxyArray: """Body CoM poses in body frame. dtype=wp.transformf, shape: (N, num_bodies).""" if self._body_com_pose_b is None: pose_np = np.zeros((self._num_instances, self._num_bodies, 7), dtype=np.float32) pose_np[..., 6] = 1.0 # identity quat qw=1, transformf layout: (px,py,pz,qx,qy,qz,qw) self._body_com_pose_b = wp.array(pose_np, dtype=wp.float32, device=self.device).view(wp.transformf) - return self._body_com_pose_b + self._body_com_pose_b_ta = None + if self._body_com_pose_b_ta is None: + self._body_com_pose_b_ta = ProxyArray(self._body_com_pose_b) + return self._body_com_pose_b_ta # Sliced properties (zero-copy pointer arithmetic on transformf) @property - def body_com_pos_w(self) -> wp.array: + def body_com_pos_w(self) -> ProxyArray: """Body CoM positions. Shape: (N, num_bodies), dtype=wp.vec3f.""" - t = self.body_com_pose_w - return wp.array(ptr=t.ptr, shape=t.shape, dtype=wp.vec3f, strides=t.strides, device=self.device) + t = self.body_com_pose_w.warp + return ProxyArray(wp.array(ptr=t.ptr, shape=t.shape, dtype=wp.vec3f, strides=t.strides, device=self.device)) @property - def body_com_quat_w(self) -> wp.array: + def body_com_quat_w(self) -> ProxyArray: """Body CoM orientations. Shape: (N, num_bodies), dtype=wp.quatf.""" - t = self.body_com_pose_w - return wp.array(ptr=t.ptr + 3 * 4, shape=t.shape, dtype=wp.quatf, strides=t.strides, device=self.device) + t = self.body_com_pose_w.warp + return ProxyArray( + wp.array(ptr=t.ptr + 3 * 4, shape=t.shape, dtype=wp.quatf, strides=t.strides, device=self.device) + ) @property - def body_com_lin_vel_w(self) -> wp.array: + def body_com_lin_vel_w(self) -> ProxyArray: """Body CoM linear velocities in world frame. Shape: (N, num_bodies), dtype=wp.vec3f.""" - v = self.body_com_vel_w - return wp.array(ptr=v.ptr, shape=v.shape, dtype=wp.vec3f, strides=v.strides, device=self.device) + v = self.body_com_vel_w.warp + return ProxyArray(wp.array(ptr=v.ptr, shape=v.shape, dtype=wp.vec3f, strides=v.strides, device=self.device)) @property - def body_com_ang_vel_w(self) -> wp.array: + def body_com_ang_vel_w(self) -> ProxyArray: """Body CoM angular velocities in world frame. Shape: (N, num_bodies), dtype=wp.vec3f.""" - v = self.body_com_vel_w - return wp.array(ptr=v.ptr + 3 * 4, shape=v.shape, dtype=wp.vec3f, strides=v.strides, device=self.device) + v = self.body_com_vel_w.warp + return ProxyArray( + wp.array(ptr=v.ptr + 3 * 4, shape=v.shape, dtype=wp.vec3f, strides=v.strides, device=self.device) + ) @property - def body_com_lin_acc_w(self) -> wp.array: + def body_com_lin_acc_w(self) -> ProxyArray: """Body CoM linear accelerations in world frame. Shape: (N, num_bodies), dtype=wp.vec3f.""" - a = self.body_com_acc_w - return wp.array(ptr=a.ptr, shape=a.shape, dtype=wp.vec3f, strides=a.strides, device=self.device) + a = self.body_com_acc_w.warp + return ProxyArray(wp.array(ptr=a.ptr, shape=a.shape, dtype=wp.vec3f, strides=a.strides, device=self.device)) @property - def body_com_ang_acc_w(self) -> wp.array: + def body_com_ang_acc_w(self) -> ProxyArray: """Body CoM angular accelerations in world frame. Shape: (N, num_bodies), dtype=wp.vec3f.""" - a = self.body_com_acc_w - return wp.array(ptr=a.ptr + 3 * 4, shape=a.shape, dtype=wp.vec3f, strides=a.strides, device=self.device) + a = self.body_com_acc_w.warp + return ProxyArray( + wp.array(ptr=a.ptr + 3 * 4, shape=a.shape, dtype=wp.vec3f, strides=a.strides, device=self.device) + ) @property - def body_com_pos_b(self) -> wp.array: + def body_com_pos_b(self) -> ProxyArray: """Body CoM positions in body frame. Shape: (N, num_bodies), dtype=wp.vec3f.""" - t = self.body_com_pose_b - return wp.array(ptr=t.ptr, shape=t.shape, dtype=wp.vec3f, strides=t.strides, device=self.device) + t = self.body_com_pose_b.warp + return ProxyArray(wp.array(ptr=t.ptr, shape=t.shape, dtype=wp.vec3f, strides=t.strides, device=self.device)) @property - def body_com_quat_b(self) -> wp.array: + def body_com_quat_b(self) -> ProxyArray: """Body CoM orientations in body frame. Shape: (N, num_bodies), dtype=wp.quatf.""" - t = self.body_com_pose_b - return wp.array(ptr=t.ptr + 3 * 4, shape=t.shape, dtype=wp.quatf, strides=t.strides, device=self.device) + t = self.body_com_pose_b.warp + return ProxyArray( + wp.array(ptr=t.ptr + 3 * 4, shape=t.shape, dtype=wp.quatf, strides=t.strides, device=self.device) + ) # -- Body properties -- @property - def body_mass(self) -> wp.array: + def body_mass(self) -> ProxyArray: """Body masses. Shape: (N, num_bodies).""" if self._body_mass is None: - return wp.ones((self._num_instances, self._num_bodies), dtype=wp.float32, device=self.device) - return self._body_mass + self._body_mass = wp.ones((self._num_instances, self._num_bodies), dtype=wp.float32, device=self.device) + self._body_mass_ta = None + if self._body_mass_ta is None: + self._body_mass_ta = ProxyArray(self._body_mass) + return self._body_mass_ta @property - def body_inertia(self) -> wp.array: + def body_inertia(self) -> ProxyArray: """Body inertias (flattened 3x3). Shape: (N, num_bodies, 9).""" if self._body_inertia is None: np_inertia = np.zeros((self._num_instances, self._num_bodies, 9), dtype=np.float32) np_inertia[..., 0] = 1.0 # Ixx np_inertia[..., 4] = 1.0 # Iyy np_inertia[..., 8] = 1.0 # Izz - return wp.array(np_inertia, dtype=wp.float32, device=self.device) - return self._body_inertia - - @property - def body_incoming_joint_wrench_b(self) -> wp.array: - """Body incoming joint wrenches. dtype=wp.spatial_vectorf, shape: (N, num_bodies).""" - if self._body_incoming_joint_wrench_b is None: - return wp.zeros((self._num_instances, self._num_bodies, 6), dtype=wp.float32, device=self.device).view( - wp.spatial_vectorf - ) - return self._body_incoming_joint_wrench_b + self._body_inertia = wp.array(np_inertia, dtype=wp.float32, device=self.device) + self._body_inertia_ta = None + if self._body_inertia_ta is None: + self._body_inertia_ta = ProxyArray(self._body_inertia) + return self._body_inertia_ta # -- Derived properties -- @property - def projected_gravity_b(self) -> wp.array: + def projected_gravity_b(self) -> ProxyArray: """Gravity projection on base. Shape: (N,), dtype=wp.vec3f.""" np_gravity = np.zeros((self._num_instances, 3), dtype=np.float32) np_gravity[:, 2] = -1.0 - return wp.array(np_gravity, dtype=wp.float32, device=self.device).view(wp.vec3f) + return ProxyArray(wp.array(np_gravity, dtype=wp.float32, device=self.device).view(wp.vec3f)) @property - def heading_w(self) -> wp.array: + def heading_w(self) -> ProxyArray: """Yaw heading in world frame. Shape: (N,).""" - return wp.zeros((self._num_instances,), dtype=wp.float32, device=self.device) + return ProxyArray(wp.zeros((self._num_instances,), dtype=wp.float32, device=self.device)) @property - def root_link_lin_vel_b(self) -> wp.array: + def root_link_lin_vel_b(self) -> ProxyArray: """Root link linear velocity in body frame. Shape: (N,), dtype=wp.vec3f.""" - return wp.clone(self.root_link_lin_vel_w, self.device) + return ProxyArray(wp.clone(self.root_link_lin_vel_w.warp, self.device)) @property - def root_link_ang_vel_b(self) -> wp.array: + def root_link_ang_vel_b(self) -> ProxyArray: """Root link angular velocity in body frame. Shape: (N,), dtype=wp.vec3f.""" - return wp.clone(self.root_link_ang_vel_w, self.device) + return ProxyArray(wp.clone(self.root_link_ang_vel_w.warp, self.device)) @property - def root_com_lin_vel_b(self) -> wp.array: + def root_com_lin_vel_b(self) -> ProxyArray: """Root CoM linear velocity in body frame. Shape: (N,), dtype=wp.vec3f.""" - return wp.clone(self.root_com_lin_vel_w, self.device) + return ProxyArray(wp.clone(self.root_com_lin_vel_w.warp, self.device)) @property - def root_com_ang_vel_b(self) -> wp.array: + def root_com_ang_vel_b(self) -> ProxyArray: """Root CoM angular velocity in body frame. Shape: (N,), dtype=wp.vec3f.""" - return wp.clone(self.root_com_ang_vel_w, self.device) + return ProxyArray(wp.clone(self.root_com_ang_vel_w.warp, self.device)) # com_pos_b and com_quat_b are inherited from BaseArticulationData # (they delegate to body_com_pos_b and body_com_quat_b respectively) @@ -674,99 +868,147 @@ def root_com_ang_vel_b(self) -> wp.array: # -- Fixed tendon properties -- @property - def fixed_tendon_stiffness(self) -> wp.array: + def fixed_tendon_stiffness(self) -> ProxyArray: """Fixed tendon stiffness. Shape: (N, num_fixed_tendons).""" if self._num_fixed_tendons == 0: - return wp.zeros((self._num_instances, 0), dtype=wp.float32, device=self.device) + return ProxyArray(wp.zeros((self._num_instances, 0), dtype=wp.float32, device=self.device)) if self._fixed_tendon_stiffness is None: - return wp.zeros((self._num_instances, self._num_fixed_tendons), dtype=wp.float32, device=self.device) - return self._fixed_tendon_stiffness + self._fixed_tendon_stiffness = wp.zeros( + (self._num_instances, self._num_fixed_tendons), dtype=wp.float32, device=self.device + ) + self._fixed_tendon_stiffness_ta = None + if self._fixed_tendon_stiffness_ta is None: + self._fixed_tendon_stiffness_ta = ProxyArray(self._fixed_tendon_stiffness) + return self._fixed_tendon_stiffness_ta @property - def fixed_tendon_damping(self) -> wp.array: + def fixed_tendon_damping(self) -> ProxyArray: """Fixed tendon damping. Shape: (N, num_fixed_tendons).""" if self._num_fixed_tendons == 0: - return wp.zeros((self._num_instances, 0), dtype=wp.float32, device=self.device) + return ProxyArray(wp.zeros((self._num_instances, 0), dtype=wp.float32, device=self.device)) if self._fixed_tendon_damping is None: - return wp.zeros((self._num_instances, self._num_fixed_tendons), dtype=wp.float32, device=self.device) - return self._fixed_tendon_damping + self._fixed_tendon_damping = wp.zeros( + (self._num_instances, self._num_fixed_tendons), dtype=wp.float32, device=self.device + ) + self._fixed_tendon_damping_ta = None + if self._fixed_tendon_damping_ta is None: + self._fixed_tendon_damping_ta = ProxyArray(self._fixed_tendon_damping) + return self._fixed_tendon_damping_ta @property - def fixed_tendon_limit_stiffness(self) -> wp.array: + def fixed_tendon_limit_stiffness(self) -> ProxyArray: """Fixed tendon limit stiffness. Shape: (N, num_fixed_tendons).""" if self._num_fixed_tendons == 0: - return wp.zeros((self._num_instances, 0), dtype=wp.float32, device=self.device) + return ProxyArray(wp.zeros((self._num_instances, 0), dtype=wp.float32, device=self.device)) if self._fixed_tendon_limit_stiffness is None: - return wp.zeros((self._num_instances, self._num_fixed_tendons), dtype=wp.float32, device=self.device) - return self._fixed_tendon_limit_stiffness + self._fixed_tendon_limit_stiffness = wp.zeros( + (self._num_instances, self._num_fixed_tendons), dtype=wp.float32, device=self.device + ) + self._fixed_tendon_limit_stiffness_ta = None + if self._fixed_tendon_limit_stiffness_ta is None: + self._fixed_tendon_limit_stiffness_ta = ProxyArray(self._fixed_tendon_limit_stiffness) + return self._fixed_tendon_limit_stiffness_ta @property - def fixed_tendon_rest_length(self) -> wp.array: + def fixed_tendon_rest_length(self) -> ProxyArray: """Fixed tendon rest length. Shape: (N, num_fixed_tendons).""" if self._num_fixed_tendons == 0: - return wp.zeros((self._num_instances, 0), dtype=wp.float32, device=self.device) + return ProxyArray(wp.zeros((self._num_instances, 0), dtype=wp.float32, device=self.device)) if self._fixed_tendon_rest_length is None: - return wp.zeros((self._num_instances, self._num_fixed_tendons), dtype=wp.float32, device=self.device) - return self._fixed_tendon_rest_length + self._fixed_tendon_rest_length = wp.zeros( + (self._num_instances, self._num_fixed_tendons), dtype=wp.float32, device=self.device + ) + self._fixed_tendon_rest_length_ta = None + if self._fixed_tendon_rest_length_ta is None: + self._fixed_tendon_rest_length_ta = ProxyArray(self._fixed_tendon_rest_length) + return self._fixed_tendon_rest_length_ta @property - def fixed_tendon_offset(self) -> wp.array: + def fixed_tendon_offset(self) -> ProxyArray: """Fixed tendon offset. Shape: (N, num_fixed_tendons).""" if self._num_fixed_tendons == 0: - return wp.zeros((self._num_instances, 0), dtype=wp.float32, device=self.device) + return ProxyArray(wp.zeros((self._num_instances, 0), dtype=wp.float32, device=self.device)) if self._fixed_tendon_offset is None: - return wp.zeros((self._num_instances, self._num_fixed_tendons), dtype=wp.float32, device=self.device) - return self._fixed_tendon_offset + self._fixed_tendon_offset = wp.zeros( + (self._num_instances, self._num_fixed_tendons), dtype=wp.float32, device=self.device + ) + self._fixed_tendon_offset_ta = None + if self._fixed_tendon_offset_ta is None: + self._fixed_tendon_offset_ta = ProxyArray(self._fixed_tendon_offset) + return self._fixed_tendon_offset_ta @property - def fixed_tendon_pos_limits(self) -> wp.array: + def fixed_tendon_pos_limits(self) -> ProxyArray: """Fixed tendon position limits. dtype=wp.vec2f, shape: (N, num_fixed_tendons).""" if self._num_fixed_tendons == 0: - return wp.zeros((self._num_instances, 0, 2), dtype=wp.float32, device=self.device) + return ProxyArray(wp.zeros((self._num_instances, 0, 2), dtype=wp.float32, device=self.device)) if self._fixed_tendon_pos_limits is None: np_limits = np.zeros((self._num_instances, self._num_fixed_tendons, 2), dtype=np.float32) np_limits[..., 0] = -float("inf") np_limits[..., 1] = float("inf") - return wp.array(np_limits, dtype=wp.float32, device=self.device).view(wp.vec2f) - return self._fixed_tendon_pos_limits + self._fixed_tendon_pos_limits = wp.array(np_limits, dtype=wp.float32, device=self.device).view(wp.vec2f) + self._fixed_tendon_pos_limits_ta = None + if self._fixed_tendon_pos_limits_ta is None: + self._fixed_tendon_pos_limits_ta = ProxyArray(self._fixed_tendon_pos_limits) + return self._fixed_tendon_pos_limits_ta # -- Spatial tendon properties -- @property - def spatial_tendon_stiffness(self) -> wp.array: + def spatial_tendon_stiffness(self) -> ProxyArray: """Spatial tendon stiffness. Shape: (N, num_spatial_tendons).""" if self._num_spatial_tendons == 0: - return wp.zeros((self._num_instances, 0), dtype=wp.float32, device=self.device) + return ProxyArray(wp.zeros((self._num_instances, 0), dtype=wp.float32, device=self.device)) if self._spatial_tendon_stiffness is None: - return wp.zeros((self._num_instances, self._num_spatial_tendons), dtype=wp.float32, device=self.device) - return self._spatial_tendon_stiffness + self._spatial_tendon_stiffness = wp.zeros( + (self._num_instances, self._num_spatial_tendons), dtype=wp.float32, device=self.device + ) + self._spatial_tendon_stiffness_ta = None + if self._spatial_tendon_stiffness_ta is None: + self._spatial_tendon_stiffness_ta = ProxyArray(self._spatial_tendon_stiffness) + return self._spatial_tendon_stiffness_ta @property - def spatial_tendon_damping(self) -> wp.array: + def spatial_tendon_damping(self) -> ProxyArray: """Spatial tendon damping. Shape: (N, num_spatial_tendons).""" if self._num_spatial_tendons == 0: - return wp.zeros((self._num_instances, 0), dtype=wp.float32, device=self.device) + return ProxyArray(wp.zeros((self._num_instances, 0), dtype=wp.float32, device=self.device)) if self._spatial_tendon_damping is None: - return wp.zeros((self._num_instances, self._num_spatial_tendons), dtype=wp.float32, device=self.device) - return self._spatial_tendon_damping + self._spatial_tendon_damping = wp.zeros( + (self._num_instances, self._num_spatial_tendons), dtype=wp.float32, device=self.device + ) + self._spatial_tendon_damping_ta = None + if self._spatial_tendon_damping_ta is None: + self._spatial_tendon_damping_ta = ProxyArray(self._spatial_tendon_damping) + return self._spatial_tendon_damping_ta @property - def spatial_tendon_limit_stiffness(self) -> wp.array: + def spatial_tendon_limit_stiffness(self) -> ProxyArray: """Spatial tendon limit stiffness. Shape: (N, num_spatial_tendons).""" if self._num_spatial_tendons == 0: - return wp.zeros((self._num_instances, 0), dtype=wp.float32, device=self.device) + return ProxyArray(wp.zeros((self._num_instances, 0), dtype=wp.float32, device=self.device)) if self._spatial_tendon_limit_stiffness is None: - return wp.zeros((self._num_instances, self._num_spatial_tendons), dtype=wp.float32, device=self.device) - return self._spatial_tendon_limit_stiffness + self._spatial_tendon_limit_stiffness = wp.zeros( + (self._num_instances, self._num_spatial_tendons), dtype=wp.float32, device=self.device + ) + self._spatial_tendon_limit_stiffness_ta = None + if self._spatial_tendon_limit_stiffness_ta is None: + self._spatial_tendon_limit_stiffness_ta = ProxyArray(self._spatial_tendon_limit_stiffness) + return self._spatial_tendon_limit_stiffness_ta @property - def spatial_tendon_offset(self) -> wp.array: + def spatial_tendon_offset(self) -> ProxyArray: """Spatial tendon offset. Shape: (N, num_spatial_tendons).""" if self._num_spatial_tendons == 0: - return wp.zeros((self._num_instances, 0), dtype=wp.float32, device=self.device) + return ProxyArray(wp.zeros((self._num_instances, 0), dtype=wp.float32, device=self.device)) if self._spatial_tendon_offset is None: - return wp.zeros((self._num_instances, self._num_spatial_tendons), dtype=wp.float32, device=self.device) - return self._spatial_tendon_offset + self._spatial_tendon_offset = wp.zeros( + (self._num_instances, self._num_spatial_tendons), dtype=wp.float32, device=self.device + ) + self._spatial_tendon_offset_ta = None + if self._spatial_tendon_offset_ta is None: + self._spatial_tendon_offset_ta = ProxyArray(self._spatial_tendon_offset) + return self._spatial_tendon_offset_ta # -- Update method -- @@ -786,138 +1028,179 @@ def _identity_quat_np(self, *shape: int) -> np.ndarray: def set_default_root_pose(self, value: torch.Tensor) -> None: self._default_root_pose = wp.from_torch(value.to(self.device).contiguous()).view(wp.transformf) + self._default_root_pose_ta = None def set_default_root_vel(self, value: torch.Tensor) -> None: self._default_root_vel = wp.from_torch(value.to(self.device).contiguous()) + self._default_root_vel_ta = None def set_default_joint_pos(self, value: torch.Tensor) -> None: self._default_joint_pos = wp.from_torch(value.to(self.device).contiguous()) + self._default_joint_pos_ta = None def set_default_joint_vel(self, value: torch.Tensor) -> None: self._default_joint_vel = wp.from_torch(value.to(self.device).contiguous()) + self._default_joint_vel_ta = None def set_joint_pos_target(self, value: torch.Tensor) -> None: self._joint_pos_target = wp.from_torch(value.to(self.device).contiguous()) + self._joint_pos_target_ta = None def set_joint_vel_target(self, value: torch.Tensor) -> None: self._joint_vel_target = wp.from_torch(value.to(self.device).contiguous()) + self._joint_vel_target_ta = None def set_joint_effort_target(self, value: torch.Tensor) -> None: self._joint_effort_target = wp.from_torch(value.to(self.device).contiguous()) + self._joint_effort_target_ta = None def set_computed_torque(self, value: torch.Tensor) -> None: self._computed_torque = wp.from_torch(value.to(self.device).contiguous()) + self._computed_torque_ta = None def set_applied_torque(self, value: torch.Tensor) -> None: self._applied_torque = wp.from_torch(value.to(self.device).contiguous()) + self._applied_torque_ta = None def set_joint_stiffness(self, value: torch.Tensor) -> None: self._joint_stiffness = wp.from_torch(value.to(self.device).contiguous()) + self._joint_stiffness_ta = None def set_joint_damping(self, value: torch.Tensor) -> None: self._joint_damping = wp.from_torch(value.to(self.device).contiguous()) + self._joint_damping_ta = None def set_joint_armature(self, value: torch.Tensor) -> None: self._joint_armature = wp.from_torch(value.to(self.device).contiguous()) + self._joint_armature_ta = None def set_joint_friction_coeff(self, value: torch.Tensor) -> None: self._joint_friction_coeff = wp.from_torch(value.to(self.device).contiguous()) + self._joint_friction_coeff_ta = None def set_joint_pos_limits(self, value: torch.Tensor) -> None: self._joint_pos_limits = wp.from_torch(value.to(self.device).contiguous()) + self._joint_pos_limits_ta = None def set_joint_vel_limits(self, value: torch.Tensor) -> None: self._joint_vel_limits = wp.from_torch(value.to(self.device).contiguous()) + self._joint_vel_limits_ta = None def set_joint_effort_limits(self, value: torch.Tensor) -> None: self._joint_effort_limits = wp.from_torch(value.to(self.device).contiguous()) + self._joint_effort_limits_ta = None def set_soft_joint_pos_limits(self, value: torch.Tensor) -> None: self._soft_joint_pos_limits = wp.from_torch(value.to(self.device).contiguous()) + self._soft_joint_pos_limits_ta = None def set_soft_joint_vel_limits(self, value: torch.Tensor) -> None: self._soft_joint_vel_limits = wp.from_torch(value.to(self.device).contiguous()) + self._soft_joint_vel_limits_ta = None def set_gear_ratio(self, value: torch.Tensor) -> None: self._gear_ratio = wp.from_torch(value.to(self.device).contiguous()) + self._gear_ratio_ta = None def set_joint_pos(self, value: torch.Tensor) -> None: self._joint_pos = wp.from_torch(value.to(self.device).contiguous()) + self._joint_pos_ta = None def set_joint_vel(self, value: torch.Tensor) -> None: self._joint_vel = wp.from_torch(value.to(self.device).contiguous()) + self._joint_vel_ta = None def set_joint_acc(self, value: torch.Tensor) -> None: self._joint_acc = wp.from_torch(value.to(self.device).contiguous()) + self._joint_acc_ta = None def set_root_link_pose_w(self, value: torch.Tensor) -> None: self._root_link_pose_w = wp.from_torch(value.to(self.device).contiguous()).view(wp.transformf) + self._root_link_pose_w_ta = None def set_root_link_vel_w(self, value: torch.Tensor) -> None: self._root_link_vel_w = wp.from_torch(value.to(self.device).contiguous()) + self._root_link_vel_w_ta = None def set_root_com_pose_w(self, value: torch.Tensor) -> None: self._root_com_pose_w = wp.from_torch(value.to(self.device).contiguous()).view(wp.transformf) + self._root_com_pose_w_ta = None def set_root_com_vel_w(self, value: torch.Tensor) -> None: self._root_com_vel_w = wp.from_torch(value.to(self.device).contiguous()) + self._root_com_vel_w_ta = None def set_body_link_pose_w(self, value: torch.Tensor) -> None: self._body_link_pose_w = wp.from_torch(value.to(self.device).contiguous()).view(wp.transformf) + self._body_link_pose_w_ta = None def set_body_link_vel_w(self, value: torch.Tensor) -> None: self._body_link_vel_w = wp.from_torch(value.to(self.device).contiguous()) + self._body_link_vel_w_ta = None def set_body_com_pose_w(self, value: torch.Tensor) -> None: self._body_com_pose_w = wp.from_torch(value.to(self.device).contiguous()).view(wp.transformf) + self._body_com_pose_w_ta = None def set_body_com_vel_w(self, value: torch.Tensor) -> None: self._body_com_vel_w = wp.from_torch(value.to(self.device).contiguous()) + self._body_com_vel_w_ta = None def set_body_com_acc_w(self, value: torch.Tensor) -> None: self._body_com_acc_w = wp.from_torch(value.to(self.device).contiguous()) + self._body_com_acc_w_ta = None def set_body_com_pose_b(self, value: torch.Tensor) -> None: self._body_com_pose_b = wp.from_torch(value.to(self.device).contiguous()).view(wp.transformf) + self._body_com_pose_b_ta = None def set_body_mass(self, value: torch.Tensor) -> None: self._body_mass = wp.from_torch(value.to(self.device).contiguous()) + self._body_mass_ta = None def set_body_inertia(self, value: torch.Tensor) -> None: self._body_inertia = wp.from_torch(value.to(self.device).contiguous()) - - def set_body_incoming_joint_wrench_b(self, value: torch.Tensor) -> None: - self._body_incoming_joint_wrench_b = wp.from_torch(value.to(self.device).contiguous()) + self._body_inertia_ta = None def set_fixed_tendon_stiffness(self, value: torch.Tensor) -> None: self._fixed_tendon_stiffness = wp.from_torch(value.to(self.device).contiguous()) + self._fixed_tendon_stiffness_ta = None def set_fixed_tendon_damping(self, value: torch.Tensor) -> None: self._fixed_tendon_damping = wp.from_torch(value.to(self.device).contiguous()) + self._fixed_tendon_damping_ta = None def set_fixed_tendon_limit_stiffness(self, value: torch.Tensor) -> None: self._fixed_tendon_limit_stiffness = wp.from_torch(value.to(self.device).contiguous()) + self._fixed_tendon_limit_stiffness_ta = None def set_fixed_tendon_rest_length(self, value: torch.Tensor) -> None: self._fixed_tendon_rest_length = wp.from_torch(value.to(self.device).contiguous()) + self._fixed_tendon_rest_length_ta = None def set_fixed_tendon_offset(self, value: torch.Tensor) -> None: self._fixed_tendon_offset = wp.from_torch(value.to(self.device).contiguous()) + self._fixed_tendon_offset_ta = None def set_fixed_tendon_pos_limits(self, value: torch.Tensor) -> None: self._fixed_tendon_pos_limits = wp.from_torch(value.to(self.device).contiguous()) + self._fixed_tendon_pos_limits_ta = None def set_spatial_tendon_stiffness(self, value: torch.Tensor) -> None: self._spatial_tendon_stiffness = wp.from_torch(value.to(self.device).contiguous()) + self._spatial_tendon_stiffness_ta = None def set_spatial_tendon_damping(self, value: torch.Tensor) -> None: self._spatial_tendon_damping = wp.from_torch(value.to(self.device).contiguous()) + self._spatial_tendon_damping_ta = None def set_spatial_tendon_limit_stiffness(self, value: torch.Tensor) -> None: self._spatial_tendon_limit_stiffness = wp.from_torch(value.to(self.device).contiguous()) + self._spatial_tendon_limit_stiffness_ta = None def set_spatial_tendon_offset(self, value: torch.Tensor) -> None: self._spatial_tendon_offset = wp.from_torch(value.to(self.device).contiguous()) + self._spatial_tendon_offset_ta = None def set_mock_data(self, **kwargs) -> None: """Bulk setter for mock data. @@ -1415,6 +1698,7 @@ def set_joint_position_target( pos_target = wp.to_torch(self._data._joint_pos_target) pos_target[env_ids, joint_ids] = target.to(self._device) self._data._joint_pos_target = wp.from_torch(pos_target) + self._data._joint_pos_target_ta = None def set_joint_velocity_target( self, @@ -1434,6 +1718,7 @@ def set_joint_velocity_target( vel_target = wp.to_torch(self._data._joint_vel_target) vel_target[env_ids, joint_ids] = target.to(self._device) self._data._joint_vel_target = wp.from_torch(vel_target) + self._data._joint_vel_target_ta = None def set_joint_effort_target( self, @@ -1453,6 +1738,7 @@ def set_joint_effort_target( effort_target = wp.to_torch(self._data._joint_effort_target) effort_target[env_ids, joint_ids] = target.to(self._device) self._data._joint_effort_target = wp.from_torch(effort_target) + self._data._joint_effort_target_ta = None # -- Tendon methods (fixed) -- diff --git a/source/isaaclab/isaaclab/test/mock_interfaces/assets/mock_rigid_object.py b/source/isaaclab/isaaclab/test/mock_interfaces/assets/mock_rigid_object.py index 9d2543e14bdc..32f5f2bc3017 100644 --- a/source/isaaclab/isaaclab/test/mock_interfaces/assets/mock_rigid_object.py +++ b/source/isaaclab/isaaclab/test/mock_interfaces/assets/mock_rigid_object.py @@ -14,6 +14,8 @@ import torch import warp as wp +from isaaclab.utils.warp import ProxyArray + try: from isaaclab.assets.rigid_object.base_rigid_object_data import BaseRigidObjectData except (ImportError, ModuleNotFoundError): @@ -83,6 +85,22 @@ def __init__( self._body_mass: wp.array | None = None self._body_inertia: wp.array | None = None + # ProxyArray caches + self._default_root_pose_ta: ProxyArray | None = None + self._default_root_vel_ta: ProxyArray | None = None + self._root_link_pose_w_ta: ProxyArray | None = None + self._root_link_vel_w_ta: ProxyArray | None = None + self._root_com_pose_w_ta: ProxyArray | None = None + self._root_com_vel_w_ta: ProxyArray | None = None + self._body_link_pose_w_ta: ProxyArray | None = None + self._body_link_vel_w_ta: ProxyArray | None = None + self._body_com_pose_w_ta: ProxyArray | None = None + self._body_com_vel_w_ta: ProxyArray | None = None + self._body_com_acc_w_ta: ProxyArray | None = None + self._body_com_pose_b_ta: ProxyArray | None = None + self._body_mass_ta: ProxyArray | None = None + self._body_inertia_ta: ProxyArray | None = None + def _identity_quat(self, *shape: int) -> wp.array: """Create identity quaternion warp array (w, x, y, z) = (1, 0, 0, 0).""" quat_np = np.zeros((*shape, 4), dtype=np.float32) @@ -92,342 +110,404 @@ def _identity_quat(self, *shape: int) -> wp.array: # -- Default state properties -- @property - def default_root_pose(self) -> wp.array: + def default_root_pose(self) -> ProxyArray: """Default root pose. dtype=wp.transformf, shape: (N,).""" if self._default_root_pose is None: pose_np = np.zeros((self._num_instances, 7), dtype=np.float32) pose_np[..., 6] = 1.0 # identity quat qw=1, transformf layout: (px,py,pz,qx,qy,qz,qw) self._default_root_pose = wp.array(pose_np, dtype=wp.float32, device=self.device).view(wp.transformf) - return self._default_root_pose + self._default_root_pose_ta = None + if self._default_root_pose_ta is None: + self._default_root_pose_ta = ProxyArray(self._default_root_pose) + return self._default_root_pose_ta @property - def default_root_vel(self) -> wp.array: + def default_root_vel(self) -> ProxyArray: """Default root velocity. dtype=wp.spatial_vectorf, shape: (N,).""" if self._default_root_vel is None: self._default_root_vel = wp.zeros((self._num_instances, 6), dtype=wp.float32, device=self.device).view( wp.spatial_vectorf ) - return self._default_root_vel + self._default_root_vel_ta = None + if self._default_root_vel_ta is None: + self._default_root_vel_ta = ProxyArray(self._default_root_vel) + return self._default_root_vel_ta @property - def default_root_state(self) -> wp.array: + def default_root_state(self) -> ProxyArray: """Default root state. Shape: (N, 13).""" - pose = wp.to_torch(self.default_root_pose) - vel = wp.to_torch(self.default_root_vel) - return wp.from_torch(torch.cat([pose, vel], dim=-1)) + pose = self.default_root_pose.torch + vel = self.default_root_vel.torch + return ProxyArray(wp.from_torch(torch.cat([pose, vel], dim=-1))) # -- Root state properties (link frame) -- @property - def root_link_pose_w(self) -> wp.array: + def root_link_pose_w(self) -> ProxyArray: """Root link pose in world frame. dtype=wp.transformf, shape: (N,).""" if self._root_link_pose_w is None: pose_np = np.zeros((self._num_instances, 7), dtype=np.float32) pose_np[..., 6] = 1.0 # identity quat qw=1, transformf layout: (px,py,pz,qx,qy,qz,qw) self._root_link_pose_w = wp.array(pose_np, dtype=wp.float32, device=self.device).view(wp.transformf) - return self._root_link_pose_w + self._root_link_pose_w_ta = None + if self._root_link_pose_w_ta is None: + self._root_link_pose_w_ta = ProxyArray(self._root_link_pose_w) + return self._root_link_pose_w_ta @property - def root_link_vel_w(self) -> wp.array: + def root_link_vel_w(self) -> ProxyArray: """Root link velocity in world frame. dtype=wp.spatial_vectorf, shape: (N,).""" if self._root_link_vel_w is None: self._root_link_vel_w = wp.zeros((self._num_instances, 6), dtype=wp.float32, device=self.device).view( wp.spatial_vectorf ) - return self._root_link_vel_w + self._root_link_vel_w_ta = None + if self._root_link_vel_w_ta is None: + self._root_link_vel_w_ta = ProxyArray(self._root_link_vel_w) + return self._root_link_vel_w_ta @property - def root_link_state_w(self) -> wp.array: + def root_link_state_w(self) -> ProxyArray: """Root link state in world frame. Shape: (N, 13).""" - pose = wp.to_torch(self.root_link_pose_w) - vel = wp.to_torch(self.root_link_vel_w) - return wp.from_torch(torch.cat([pose, vel], dim=-1)) + pose = self.root_link_pose_w.torch + vel = self.root_link_vel_w.torch + return ProxyArray(wp.from_torch(torch.cat([pose, vel], dim=-1))) # Sliced properties (zero-copy pointer arithmetic on transformf) @property - def root_link_pos_w(self) -> wp.array: + def root_link_pos_w(self) -> ProxyArray: """Root link position. Shape: (N,), dtype=wp.vec3f.""" - t = self.root_link_pose_w - return wp.array(ptr=t.ptr, shape=t.shape, dtype=wp.vec3f, strides=t.strides, device=self.device) + t = self.root_link_pose_w.warp + return ProxyArray(wp.array(ptr=t.ptr, shape=t.shape, dtype=wp.vec3f, strides=t.strides, device=self.device)) # Sliced properties (convert through torch for simplicity in mock) @property - def root_link_quat_w(self) -> wp.array: + def root_link_quat_w(self) -> ProxyArray: """Root link orientation. Shape: (N,), dtype=wp.quatf.""" - t = self.root_link_pose_w - return wp.array(ptr=t.ptr + 3 * 4, shape=t.shape, dtype=wp.quatf, strides=t.strides, device=self.device) + t = self.root_link_pose_w.warp + return ProxyArray( + wp.array(ptr=t.ptr + 3 * 4, shape=t.shape, dtype=wp.quatf, strides=t.strides, device=self.device) + ) @property - def root_link_lin_vel_w(self) -> wp.array: + def root_link_lin_vel_w(self) -> ProxyArray: """Root link linear velocity. Shape: (N,), dtype=wp.vec3f.""" - v = self.root_link_vel_w - return wp.array(ptr=v.ptr, shape=v.shape, dtype=wp.vec3f, strides=v.strides, device=self.device) + v = self.root_link_vel_w.warp + return ProxyArray(wp.array(ptr=v.ptr, shape=v.shape, dtype=wp.vec3f, strides=v.strides, device=self.device)) @property - def root_link_ang_vel_w(self) -> wp.array: + def root_link_ang_vel_w(self) -> ProxyArray: """Root link angular velocity. Shape: (N,), dtype=wp.vec3f.""" - v = self.root_link_vel_w - return wp.array(ptr=v.ptr + 3 * 4, shape=v.shape, dtype=wp.vec3f, strides=v.strides, device=self.device) + v = self.root_link_vel_w.warp + return ProxyArray( + wp.array(ptr=v.ptr + 3 * 4, shape=v.shape, dtype=wp.vec3f, strides=v.strides, device=self.device) + ) # -- Root state properties (CoM frame) -- @property - def root_com_pose_w(self) -> wp.array: + def root_com_pose_w(self) -> ProxyArray: """Root CoM pose in world frame. dtype=wp.transformf, shape: (N,).""" if self._root_com_pose_w is None: - self._root_com_pose_w = wp.clone(self.root_link_pose_w, self.device) - return self._root_com_pose_w + self._root_com_pose_w = wp.clone(self.root_link_pose_w.warp, self.device) + self._root_com_pose_w_ta = None + if self._root_com_pose_w_ta is None: + self._root_com_pose_w_ta = ProxyArray(self._root_com_pose_w) + return self._root_com_pose_w_ta @property - def root_com_vel_w(self) -> wp.array: + def root_com_vel_w(self) -> ProxyArray: """Root CoM velocity in world frame. dtype=wp.spatial_vectorf, shape: (N,).""" if self._root_com_vel_w is None: - self._root_com_vel_w = wp.clone(self.root_link_vel_w, self.device) - return self._root_com_vel_w + self._root_com_vel_w = wp.clone(self.root_link_vel_w.warp, self.device) + self._root_com_vel_w_ta = None + if self._root_com_vel_w_ta is None: + self._root_com_vel_w_ta = ProxyArray(self._root_com_vel_w) + return self._root_com_vel_w_ta @property - def root_com_state_w(self) -> wp.array: + def root_com_state_w(self) -> ProxyArray: """Root CoM state in world frame. Shape: (N, 13).""" - pose = wp.to_torch(self.root_com_pose_w) - vel = wp.to_torch(self.root_com_vel_w) - return wp.from_torch(torch.cat([pose, vel], dim=-1)) + pose = self.root_com_pose_w.torch + vel = self.root_com_vel_w.torch + return ProxyArray(wp.from_torch(torch.cat([pose, vel], dim=-1))) @property - def root_state_w(self) -> wp.array: + def root_state_w(self) -> ProxyArray: """Root state (link pose + CoM velocity). Shape: (N, 13).""" - pose = wp.to_torch(self.root_link_pose_w) - vel = wp.to_torch(self.root_com_vel_w) - return wp.from_torch(torch.cat([pose, vel], dim=-1)) + pose = self.root_link_pose_w.torch + vel = self.root_com_vel_w.torch + return ProxyArray(wp.from_torch(torch.cat([pose, vel], dim=-1))) # Sliced properties (zero-copy pointer arithmetic on transformf) @property - def root_com_pos_w(self) -> wp.array: + def root_com_pos_w(self) -> ProxyArray: """Root CoM position. Shape: (N,), dtype=wp.vec3f.""" - t = self.root_com_pose_w - return wp.array(ptr=t.ptr, shape=t.shape, dtype=wp.vec3f, strides=t.strides, device=self.device) + t = self.root_com_pose_w.warp + return ProxyArray(wp.array(ptr=t.ptr, shape=t.shape, dtype=wp.vec3f, strides=t.strides, device=self.device)) # Sliced properties (convert through torch for simplicity in mock) @property - def root_com_quat_w(self) -> wp.array: + def root_com_quat_w(self) -> ProxyArray: """Root CoM orientation. Shape: (N,), dtype=wp.quatf.""" - t = self.root_com_pose_w - return wp.array(ptr=t.ptr + 3 * 4, shape=t.shape, dtype=wp.quatf, strides=t.strides, device=self.device) + t = self.root_com_pose_w.warp + return ProxyArray( + wp.array(ptr=t.ptr + 3 * 4, shape=t.shape, dtype=wp.quatf, strides=t.strides, device=self.device) + ) @property - def root_com_lin_vel_w(self) -> wp.array: + def root_com_lin_vel_w(self) -> ProxyArray: """Root CoM linear velocity. Shape: (N,), dtype=wp.vec3f.""" - v = self.root_com_vel_w - return wp.array(ptr=v.ptr, shape=v.shape, dtype=wp.vec3f, strides=v.strides, device=self.device) + v = self.root_com_vel_w.warp + return ProxyArray(wp.array(ptr=v.ptr, shape=v.shape, dtype=wp.vec3f, strides=v.strides, device=self.device)) @property - def root_com_ang_vel_w(self) -> wp.array: + def root_com_ang_vel_w(self) -> ProxyArray: """Root CoM angular velocity. Shape: (N,), dtype=wp.vec3f.""" - v = self.root_com_vel_w - return wp.array(ptr=v.ptr + 3 * 4, shape=v.shape, dtype=wp.vec3f, strides=v.strides, device=self.device) + v = self.root_com_vel_w.warp + return ProxyArray( + wp.array(ptr=v.ptr + 3 * 4, shape=v.shape, dtype=wp.vec3f, strides=v.strides, device=self.device) + ) # -- Body state properties (link frame) -- @property - def body_link_pose_w(self) -> wp.array: + def body_link_pose_w(self) -> ProxyArray: """Body link pose in world frame. dtype=wp.transformf, shape: (N, 1).""" if self._body_link_pose_w is None: pose_np = np.zeros((self._num_instances, 1, 7), dtype=np.float32) pose_np[..., 6] = 1.0 # identity quat qw=1, transformf layout: (px,py,pz,qx,qy,qz,qw) self._body_link_pose_w = wp.array(pose_np, dtype=wp.float32, device=self.device).view(wp.transformf) - return self._body_link_pose_w + self._body_link_pose_w_ta = None + if self._body_link_pose_w_ta is None: + self._body_link_pose_w_ta = ProxyArray(self._body_link_pose_w) + return self._body_link_pose_w_ta @property - def body_link_vel_w(self) -> wp.array: + def body_link_vel_w(self) -> ProxyArray: """Body link velocity in world frame. dtype=wp.spatial_vectorf, shape: (N, 1).""" if self._body_link_vel_w is None: self._body_link_vel_w = wp.zeros((self._num_instances, 1, 6), dtype=wp.float32, device=self.device).view( wp.spatial_vectorf ) - return self._body_link_vel_w + self._body_link_vel_w_ta = None + if self._body_link_vel_w_ta is None: + self._body_link_vel_w_ta = ProxyArray(self._body_link_vel_w) + return self._body_link_vel_w_ta @property - def body_link_state_w(self) -> wp.array: + def body_link_state_w(self) -> ProxyArray: """Body link state in world frame. Shape: (N, 1, 13).""" - pose = wp.to_torch(self.body_link_pose_w) - vel = wp.to_torch(self.body_link_vel_w) - return wp.from_torch(torch.cat([pose, vel], dim=-1)) + pose = self.body_link_pose_w.torch + vel = self.body_link_vel_w.torch + return ProxyArray(wp.from_torch(torch.cat([pose, vel], dim=-1))) # Sliced properties (zero-copy pointer arithmetic on transformf) @property - def body_link_pos_w(self) -> wp.array: + def body_link_pos_w(self) -> ProxyArray: """Body link position. Shape: (N, 1), dtype=wp.vec3f.""" - t = self.body_link_pose_w - return wp.array(ptr=t.ptr, shape=t.shape, dtype=wp.vec3f, strides=t.strides, device=self.device) + t = self.body_link_pose_w.warp + return ProxyArray(wp.array(ptr=t.ptr, shape=t.shape, dtype=wp.vec3f, strides=t.strides, device=self.device)) # Sliced properties (convert through torch for simplicity in mock) @property - def body_link_quat_w(self) -> wp.array: + def body_link_quat_w(self) -> ProxyArray: """Body link orientation. Shape: (N, 1), dtype=wp.quatf.""" - t = self.body_link_pose_w - return wp.array(ptr=t.ptr + 3 * 4, shape=t.shape, dtype=wp.quatf, strides=t.strides, device=self.device) + t = self.body_link_pose_w.warp + return ProxyArray( + wp.array(ptr=t.ptr + 3 * 4, shape=t.shape, dtype=wp.quatf, strides=t.strides, device=self.device) + ) @property - def body_link_lin_vel_w(self) -> wp.array: + def body_link_lin_vel_w(self) -> ProxyArray: """Body link linear velocity. Shape: (N, 1), dtype=wp.vec3f.""" - v = self.body_link_vel_w - return wp.array(ptr=v.ptr, shape=v.shape, dtype=wp.vec3f, strides=v.strides, device=self.device) + v = self.body_link_vel_w.warp + return ProxyArray(wp.array(ptr=v.ptr, shape=v.shape, dtype=wp.vec3f, strides=v.strides, device=self.device)) @property - def body_link_ang_vel_w(self) -> wp.array: + def body_link_ang_vel_w(self) -> ProxyArray: """Body link angular velocity. Shape: (N, 1), dtype=wp.vec3f.""" - v = self.body_link_vel_w - return wp.array(ptr=v.ptr + 3 * 4, shape=v.shape, dtype=wp.vec3f, strides=v.strides, device=self.device) + v = self.body_link_vel_w.warp + return ProxyArray( + wp.array(ptr=v.ptr + 3 * 4, shape=v.shape, dtype=wp.vec3f, strides=v.strides, device=self.device) + ) # -- Body state properties (CoM frame) -- @property - def body_com_pose_w(self) -> wp.array: + def body_com_pose_w(self) -> ProxyArray: """Body CoM pose in world frame. dtype=wp.transformf, shape: (N, 1).""" if self._body_com_pose_w is None: - self._body_com_pose_w = wp.clone(self.body_link_pose_w, self.device) - return self._body_com_pose_w + self._body_com_pose_w = wp.clone(self.body_link_pose_w.warp, self.device) + self._body_com_pose_w_ta = None + if self._body_com_pose_w_ta is None: + self._body_com_pose_w_ta = ProxyArray(self._body_com_pose_w) + return self._body_com_pose_w_ta @property - def body_com_vel_w(self) -> wp.array: + def body_com_vel_w(self) -> ProxyArray: """Body CoM velocity in world frame. dtype=wp.spatial_vectorf, shape: (N, 1).""" if self._body_com_vel_w is None: - self._body_com_vel_w = wp.clone(self.body_link_vel_w, self.device) - return self._body_com_vel_w + self._body_com_vel_w = wp.clone(self.body_link_vel_w.warp, self.device) + self._body_com_vel_w_ta = None + if self._body_com_vel_w_ta is None: + self._body_com_vel_w_ta = ProxyArray(self._body_com_vel_w) + return self._body_com_vel_w_ta @property - def body_com_state_w(self) -> wp.array: + def body_com_state_w(self) -> ProxyArray: """Body CoM state in world frame. Shape: (N, 1, 13).""" - pose = wp.to_torch(self.body_com_pose_w) - vel = wp.to_torch(self.body_com_vel_w) - return wp.from_torch(torch.cat([pose, vel], dim=-1)) + pose = self.body_com_pose_w.torch + vel = self.body_com_vel_w.torch + return ProxyArray(wp.from_torch(torch.cat([pose, vel], dim=-1))) @property - def body_state_w(self) -> wp.array: + def body_state_w(self) -> ProxyArray: """Body state (link pose + CoM vel). Shape: (N, 1, 13).""" - pose = wp.to_torch(self.body_link_pose_w) - vel = wp.to_torch(self.body_com_vel_w) - return wp.from_torch(torch.cat([pose, vel], dim=-1)) + pose = self.body_link_pose_w.torch + vel = self.body_com_vel_w.torch + return ProxyArray(wp.from_torch(torch.cat([pose, vel], dim=-1))) @property - def body_com_acc_w(self) -> wp.array: + def body_com_acc_w(self) -> ProxyArray: """Body CoM acceleration in world frame. dtype=wp.spatial_vectorf, shape: (N, 1).""" if self._body_com_acc_w is None: self._body_com_acc_w = wp.zeros((self._num_instances, 1, 6), dtype=wp.float32, device=self.device).view( wp.spatial_vectorf ) - return self._body_com_acc_w + self._body_com_acc_w_ta = None + if self._body_com_acc_w_ta is None: + self._body_com_acc_w_ta = ProxyArray(self._body_com_acc_w) + return self._body_com_acc_w_ta @property - def body_com_pose_b(self) -> wp.array: + def body_com_pose_b(self) -> ProxyArray: """Body CoM pose in body frame. dtype=wp.transformf, shape: (N, 1).""" if self._body_com_pose_b is None: pose_np = np.zeros((self._num_instances, 1, 7), dtype=np.float32) pose_np[..., 6] = 1.0 # identity quat qw=1, transformf layout: (px,py,pz,qx,qy,qz,qw) self._body_com_pose_b = wp.array(pose_np, dtype=wp.float32, device=self.device).view(wp.transformf) - return self._body_com_pose_b + self._body_com_pose_b_ta = None + if self._body_com_pose_b_ta is None: + self._body_com_pose_b_ta = ProxyArray(self._body_com_pose_b) + return self._body_com_pose_b_ta # Sliced properties (zero-copy pointer arithmetic on transformf) @property - def body_com_pos_w(self) -> wp.array: + def body_com_pos_w(self) -> ProxyArray: """Body CoM position. Shape: (N, 1), dtype=wp.vec3f.""" - t = self.body_com_pose_w - return wp.array(ptr=t.ptr, shape=t.shape, dtype=wp.vec3f, strides=t.strides, device=self.device) + t = self.body_com_pose_w.warp + return ProxyArray(wp.array(ptr=t.ptr, shape=t.shape, dtype=wp.vec3f, strides=t.strides, device=self.device)) @property - def body_com_quat_w(self) -> wp.array: + def body_com_quat_w(self) -> ProxyArray: """Body CoM orientation. Shape: (N, 1), dtype=wp.quatf.""" - t = self.body_com_pose_w - return wp.array(ptr=t.ptr + 3 * 4, shape=t.shape, dtype=wp.quatf, strides=t.strides, device=self.device) + t = self.body_com_pose_w.warp + return ProxyArray( + wp.array(ptr=t.ptr + 3 * 4, shape=t.shape, dtype=wp.quatf, strides=t.strides, device=self.device) + ) @property - def body_com_lin_vel_w(self) -> wp.array: + def body_com_lin_vel_w(self) -> ProxyArray: """Body CoM linear velocity. Shape: (N, 1), dtype=wp.vec3f.""" - v = self.body_com_vel_w - return wp.array(ptr=v.ptr, shape=v.shape, dtype=wp.vec3f, strides=v.strides, device=self.device) + v = self.body_com_vel_w.warp + return ProxyArray(wp.array(ptr=v.ptr, shape=v.shape, dtype=wp.vec3f, strides=v.strides, device=self.device)) @property - def body_com_ang_vel_w(self) -> wp.array: + def body_com_ang_vel_w(self) -> ProxyArray: """Body CoM angular velocity. Shape: (N, 1), dtype=wp.vec3f.""" - v = self.body_com_vel_w - return wp.array(ptr=v.ptr + 3 * 4, shape=v.shape, dtype=wp.vec3f, strides=v.strides, device=self.device) + v = self.body_com_vel_w.warp + return ProxyArray( + wp.array(ptr=v.ptr + 3 * 4, shape=v.shape, dtype=wp.vec3f, strides=v.strides, device=self.device) + ) @property - def body_com_lin_acc_w(self) -> wp.array: + def body_com_lin_acc_w(self) -> ProxyArray: """Body CoM linear acceleration. Shape: (N, 1), dtype=wp.vec3f.""" - a = self.body_com_acc_w - return wp.array(ptr=a.ptr, shape=a.shape, dtype=wp.vec3f, strides=a.strides, device=self.device) + a = self.body_com_acc_w.warp + return ProxyArray(wp.array(ptr=a.ptr, shape=a.shape, dtype=wp.vec3f, strides=a.strides, device=self.device)) @property - def body_com_ang_acc_w(self) -> wp.array: + def body_com_ang_acc_w(self) -> ProxyArray: """Body CoM angular acceleration. Shape: (N, 1), dtype=wp.vec3f.""" - a = self.body_com_acc_w - return wp.array(ptr=a.ptr + 3 * 4, shape=a.shape, dtype=wp.vec3f, strides=a.strides, device=self.device) + a = self.body_com_acc_w.warp + return ProxyArray( + wp.array(ptr=a.ptr + 3 * 4, shape=a.shape, dtype=wp.vec3f, strides=a.strides, device=self.device) + ) @property - def body_com_pos_b(self) -> wp.array: + def body_com_pos_b(self) -> ProxyArray: """Body CoM position in body frame. Shape: (N, 1), dtype=wp.vec3f.""" - t = self.body_com_pose_b - return wp.array(ptr=t.ptr, shape=t.shape, dtype=wp.vec3f, strides=t.strides, device=self.device) + t = self.body_com_pose_b.warp + return ProxyArray(wp.array(ptr=t.ptr, shape=t.shape, dtype=wp.vec3f, strides=t.strides, device=self.device)) @property - def body_com_quat_b(self) -> wp.array: + def body_com_quat_b(self) -> ProxyArray: """Body CoM orientation in body frame. Shape: (N, 1), dtype=wp.quatf.""" - t = self.body_com_pose_b - return wp.array(ptr=t.ptr + 3 * 4, shape=t.shape, dtype=wp.quatf, strides=t.strides, device=self.device) + t = self.body_com_pose_b.warp + return ProxyArray( + wp.array(ptr=t.ptr + 3 * 4, shape=t.shape, dtype=wp.quatf, strides=t.strides, device=self.device) + ) # -- Body properties -- @property - def body_mass(self) -> wp.array: + def body_mass(self) -> ProxyArray: """Body mass. Shape: (N, 1).""" if self._body_mass is None: - return wp.ones((self._num_instances, 1), dtype=wp.float32, device=self.device) - return self._body_mass + self._body_mass = wp.ones((self._num_instances, 1), dtype=wp.float32, device=self.device) + self._body_mass_ta = None + if self._body_mass_ta is None: + self._body_mass_ta = ProxyArray(self._body_mass) + return self._body_mass_ta @property - def body_inertia(self) -> wp.array: + def body_inertia(self) -> ProxyArray: """Body inertia (flattened 3x3). Shape: (N, 1, 9).""" if self._body_inertia is None: inertia_np = np.zeros((self._num_instances, 1, 9), dtype=np.float32) inertia_np[..., 0] = 1.0 # Ixx inertia_np[..., 4] = 1.0 # Iyy inertia_np[..., 8] = 1.0 # Izz - return wp.array(inertia_np, dtype=wp.float32, device=self.device) - return self._body_inertia + self._body_inertia = wp.array(inertia_np, dtype=wp.float32, device=self.device) + self._body_inertia_ta = None + if self._body_inertia_ta is None: + self._body_inertia_ta = ProxyArray(self._body_inertia) + return self._body_inertia_ta # -- Derived properties -- @property - def projected_gravity_b(self) -> wp.array: + def projected_gravity_b(self) -> ProxyArray: """Gravity projection on body. Shape: (N,), dtype=wp.vec3f.""" gravity_np = np.zeros((self._num_instances, 3), dtype=np.float32) gravity_np[:, 2] = -1.0 - return wp.array(gravity_np, dtype=wp.float32, device=self.device).view(wp.vec3f) + return ProxyArray(wp.array(gravity_np, dtype=wp.float32, device=self.device).view(wp.vec3f)) @property - def heading_w(self) -> wp.array: + def heading_w(self) -> ProxyArray: """Yaw heading in world frame. Shape: (N,).""" - return wp.zeros((self._num_instances,), dtype=wp.float32, device=self.device) + return ProxyArray(wp.zeros((self._num_instances,), dtype=wp.float32, device=self.device)) @property - def root_link_lin_vel_b(self) -> wp.array: + def root_link_lin_vel_b(self) -> ProxyArray: """Root link linear velocity in body frame. Shape: (N,), dtype=wp.vec3f.""" - return wp.clone(self.root_link_lin_vel_w, self.device) + return ProxyArray(wp.clone(self.root_link_lin_vel_w.warp, self.device)) @property - def root_link_ang_vel_b(self) -> wp.array: + def root_link_ang_vel_b(self) -> ProxyArray: """Root link angular velocity in body frame. Shape: (N,), dtype=wp.vec3f.""" - return wp.clone(self.root_link_ang_vel_w, self.device) + return ProxyArray(wp.clone(self.root_link_ang_vel_w.warp, self.device)) @property - def root_com_lin_vel_b(self) -> wp.array: + def root_com_lin_vel_b(self) -> ProxyArray: """Root CoM linear velocity in body frame. Shape: (N,), dtype=wp.vec3f.""" - return wp.clone(self.root_com_lin_vel_w, self.device) + return ProxyArray(wp.clone(self.root_com_lin_vel_w.warp, self.device)) @property - def root_com_ang_vel_b(self) -> wp.array: + def root_com_ang_vel_b(self) -> ProxyArray: """Root CoM angular velocity in body frame. Shape: (N,), dtype=wp.vec3f.""" - return wp.clone(self.root_com_ang_vel_w, self.device) + return ProxyArray(wp.clone(self.root_com_ang_vel_w.warp, self.device)) # -- Shorthand properties (root_pose_w, body_pos_w, com_pos_b, etc.) -- @@ -449,45 +529,59 @@ def update(self, dt: float) -> None: def set_default_root_pose(self, value: torch.Tensor) -> None: self._default_root_pose = wp.from_torch(value.to(self.device).contiguous()).view(wp.transformf) + self._default_root_pose_ta = None def set_default_root_vel(self, value: torch.Tensor) -> None: self._default_root_vel = wp.from_torch(value.to(self.device).contiguous()) + self._default_root_vel_ta = None def set_root_link_pose_w(self, value: torch.Tensor) -> None: self._root_link_pose_w = wp.from_torch(value.to(self.device).contiguous()).view(wp.transformf) + self._root_link_pose_w_ta = None def set_root_link_vel_w(self, value: torch.Tensor) -> None: self._root_link_vel_w = wp.from_torch(value.to(self.device).contiguous()) + self._root_link_vel_w_ta = None def set_root_com_pose_w(self, value: torch.Tensor) -> None: self._root_com_pose_w = wp.from_torch(value.to(self.device).contiguous()).view(wp.transformf) + self._root_com_pose_w_ta = None def set_root_com_vel_w(self, value: torch.Tensor) -> None: self._root_com_vel_w = wp.from_torch(value.to(self.device).contiguous()) + self._root_com_vel_w_ta = None def set_body_link_pose_w(self, value: torch.Tensor) -> None: self._body_link_pose_w = wp.from_torch(value.to(self.device).contiguous()).view(wp.transformf) + self._body_link_pose_w_ta = None def set_body_link_vel_w(self, value: torch.Tensor) -> None: self._body_link_vel_w = wp.from_torch(value.to(self.device).contiguous()) + self._body_link_vel_w_ta = None def set_body_com_pose_w(self, value: torch.Tensor) -> None: self._body_com_pose_w = wp.from_torch(value.to(self.device).contiguous()).view(wp.transformf) + self._body_com_pose_w_ta = None def set_body_com_vel_w(self, value: torch.Tensor) -> None: self._body_com_vel_w = wp.from_torch(value.to(self.device).contiguous()) + self._body_com_vel_w_ta = None def set_body_com_acc_w(self, value: torch.Tensor) -> None: self._body_com_acc_w = wp.from_torch(value.to(self.device).contiguous()) + self._body_com_acc_w_ta = None def set_body_com_pose_b(self, value: torch.Tensor) -> None: self._body_com_pose_b = wp.from_torch(value.to(self.device).contiguous()).view(wp.transformf) + self._body_com_pose_b_ta = None def set_body_mass(self, value: torch.Tensor) -> None: self._body_mass = wp.from_torch(value.to(self.device).contiguous()) + self._body_mass_ta = None def set_body_inertia(self, value: torch.Tensor) -> None: self._body_inertia = wp.from_torch(value.to(self.device).contiguous()) + self._body_inertia_ta = None def set_mock_data(self, **kwargs) -> None: """Bulk setter for mock data.""" diff --git a/source/isaaclab/isaaclab/test/mock_interfaces/assets/mock_rigid_object_collection.py b/source/isaaclab/isaaclab/test/mock_interfaces/assets/mock_rigid_object_collection.py index c9533ba2fc5c..0af998188a89 100644 --- a/source/isaaclab/isaaclab/test/mock_interfaces/assets/mock_rigid_object_collection.py +++ b/source/isaaclab/isaaclab/test/mock_interfaces/assets/mock_rigid_object_collection.py @@ -14,6 +14,8 @@ import torch import warp as wp +from isaaclab.utils.warp import ProxyArray + try: from isaaclab.assets.rigid_object_collection.base_rigid_object_collection_data import BaseRigidObjectCollectionData except (ImportError, ModuleNotFoundError): @@ -82,6 +84,18 @@ def __init__( self._body_mass: wp.array | None = None self._body_inertia: wp.array | None = None + # ProxyArray caches + self._default_body_pose_ta: ProxyArray | None = None + self._default_body_vel_ta: ProxyArray | None = None + self._body_link_pose_w_ta: ProxyArray | None = None + self._body_link_vel_w_ta: ProxyArray | None = None + self._body_com_pose_w_ta: ProxyArray | None = None + self._body_com_vel_w_ta: ProxyArray | None = None + self._body_com_acc_w_ta: ProxyArray | None = None + self._body_com_pose_b_ta: ProxyArray | None = None + self._body_mass_ta: ProxyArray | None = None + self._body_inertia_ta: ProxyArray | None = None + def _identity_quat(self, *shape: int) -> wp.array: """Create identity quaternion warp array (w, x, y, z) = (1, 0, 0, 0).""" quat_np = np.zeros((*shape, 4), dtype=np.float32) @@ -91,234 +105,276 @@ def _identity_quat(self, *shape: int) -> wp.array: # -- Default state properties -- @property - def default_body_pose(self) -> wp.array: + def default_body_pose(self) -> ProxyArray: """Default body poses. dtype=wp.transformf, shape: (N, num_bodies).""" if self._default_body_pose is None: pose_np = np.zeros((self._num_instances, self._num_bodies, 7), dtype=np.float32) pose_np[..., 6] = 1.0 # identity quat qw=1, transformf layout self._default_body_pose = wp.array(pose_np, dtype=wp.float32, device=self.device).view(wp.transformf) - return self._default_body_pose + self._default_body_pose_ta = None + if self._default_body_pose_ta is None: + self._default_body_pose_ta = ProxyArray(self._default_body_pose) + return self._default_body_pose_ta @property - def default_body_vel(self) -> wp.array: + def default_body_vel(self) -> ProxyArray: """Default body velocities. dtype=wp.spatial_vectorf, shape: (N, num_bodies).""" if self._default_body_vel is None: self._default_body_vel = wp.zeros( (self._num_instances, self._num_bodies, 6), dtype=wp.float32, device=self.device ).view(wp.spatial_vectorf) - return self._default_body_vel + self._default_body_vel_ta = None + if self._default_body_vel_ta is None: + self._default_body_vel_ta = ProxyArray(self._default_body_vel) + return self._default_body_vel_ta @property - def default_body_state(self) -> wp.array: + def default_body_state(self) -> ProxyArray: """Default body states. Shape: (N, num_bodies, 13).""" - pose = wp.to_torch(self.default_body_pose) - vel = wp.to_torch(self.default_body_vel) - return wp.from_torch(torch.cat([pose, vel], dim=-1)) + pose = self.default_body_pose.torch + vel = self.default_body_vel.torch + return ProxyArray(wp.from_torch(torch.cat([pose, vel], dim=-1))) # -- Body state properties (link frame) -- @property - def body_link_pose_w(self) -> wp.array: + def body_link_pose_w(self) -> ProxyArray: """Body link poses in world frame. dtype=wp.transformf, shape: (N, num_bodies).""" if self._body_link_pose_w is None: pose_np = np.zeros((self._num_instances, self._num_bodies, 7), dtype=np.float32) pose_np[..., 6] = 1.0 # identity quat qw=1, transformf layout: (px,py,pz,qx,qy,qz,qw) self._body_link_pose_w = wp.array(pose_np, dtype=wp.float32, device=self.device).view(wp.transformf) - return self._body_link_pose_w + self._body_link_pose_w_ta = None + if self._body_link_pose_w_ta is None: + self._body_link_pose_w_ta = ProxyArray(self._body_link_pose_w) + return self._body_link_pose_w_ta @property - def body_link_vel_w(self) -> wp.array: + def body_link_vel_w(self) -> ProxyArray: """Body link velocities in world frame. dtype=wp.spatial_vectorf, shape: (N, num_bodies).""" if self._body_link_vel_w is None: self._body_link_vel_w = wp.zeros( (self._num_instances, self._num_bodies, 6), dtype=wp.float32, device=self.device ).view(wp.spatial_vectorf) - return self._body_link_vel_w + self._body_link_vel_w_ta = None + if self._body_link_vel_w_ta is None: + self._body_link_vel_w_ta = ProxyArray(self._body_link_vel_w) + return self._body_link_vel_w_ta @property - def body_link_state_w(self) -> wp.array: + def body_link_state_w(self) -> ProxyArray: """Body link states in world frame. Shape: (N, num_bodies, 13).""" - pose = wp.to_torch(self.body_link_pose_w) - vel = wp.to_torch(self.body_link_vel_w) - return wp.from_torch(torch.cat([pose, vel], dim=-1)) + pose = self.body_link_pose_w.torch + vel = self.body_link_vel_w.torch + return ProxyArray(wp.from_torch(torch.cat([pose, vel], dim=-1))) # Sliced properties (zero-copy pointer arithmetic on transformf) @property - def body_link_pos_w(self) -> wp.array: + def body_link_pos_w(self) -> ProxyArray: """Body link positions. Shape: (N, num_bodies), dtype=wp.vec3f.""" - t = self.body_link_pose_w - return wp.array(ptr=t.ptr, shape=t.shape, dtype=wp.vec3f, strides=t.strides, device=self.device) + t = self.body_link_pose_w.warp + return ProxyArray(wp.array(ptr=t.ptr, shape=t.shape, dtype=wp.vec3f, strides=t.strides, device=self.device)) @property - def body_link_quat_w(self) -> wp.array: + def body_link_quat_w(self) -> ProxyArray: """Body link orientations. Shape: (N, num_bodies), dtype=wp.quatf.""" - t = self.body_link_pose_w - return wp.array(ptr=t.ptr + 3 * 4, shape=t.shape, dtype=wp.quatf, strides=t.strides, device=self.device) + t = self.body_link_pose_w.warp + return ProxyArray( + wp.array(ptr=t.ptr + 3 * 4, shape=t.shape, dtype=wp.quatf, strides=t.strides, device=self.device) + ) @property - def body_link_lin_vel_w(self) -> wp.array: + def body_link_lin_vel_w(self) -> ProxyArray: """Body link linear velocities. Shape: (N, num_bodies), dtype=wp.vec3f.""" - v = self.body_link_vel_w - return wp.array(ptr=v.ptr, shape=v.shape, dtype=wp.vec3f, strides=v.strides, device=self.device) + v = self.body_link_vel_w.warp + return ProxyArray(wp.array(ptr=v.ptr, shape=v.shape, dtype=wp.vec3f, strides=v.strides, device=self.device)) @property - def body_link_ang_vel_w(self) -> wp.array: + def body_link_ang_vel_w(self) -> ProxyArray: """Body link angular velocities. Shape: (N, num_bodies), dtype=wp.vec3f.""" - v = self.body_link_vel_w - return wp.array(ptr=v.ptr + 3 * 4, shape=v.shape, dtype=wp.vec3f, strides=v.strides, device=self.device) + v = self.body_link_vel_w.warp + return ProxyArray( + wp.array(ptr=v.ptr + 3 * 4, shape=v.shape, dtype=wp.vec3f, strides=v.strides, device=self.device) + ) # -- Body state properties (CoM frame) -- @property - def body_com_pose_w(self) -> wp.array: + def body_com_pose_w(self) -> ProxyArray: """Body CoM poses in world frame. dtype=wp.transformf, shape: (N, num_bodies).""" if self._body_com_pose_w is None: - self._body_com_pose_w = wp.clone(self.body_link_pose_w, self.device) - return self._body_com_pose_w + self._body_com_pose_w = wp.clone(self.body_link_pose_w.warp, self.device) + self._body_com_pose_w_ta = None + if self._body_com_pose_w_ta is None: + self._body_com_pose_w_ta = ProxyArray(self._body_com_pose_w) + return self._body_com_pose_w_ta @property - def body_com_vel_w(self) -> wp.array: + def body_com_vel_w(self) -> ProxyArray: """Body CoM velocities in world frame. dtype=wp.spatial_vectorf, shape: (N, num_bodies).""" if self._body_com_vel_w is None: - self._body_com_vel_w = wp.clone(self.body_link_vel_w, self.device) - return self._body_com_vel_w + self._body_com_vel_w = wp.clone(self.body_link_vel_w.warp, self.device) + self._body_com_vel_w_ta = None + if self._body_com_vel_w_ta is None: + self._body_com_vel_w_ta = ProxyArray(self._body_com_vel_w) + return self._body_com_vel_w_ta @property - def body_com_state_w(self) -> wp.array: + def body_com_state_w(self) -> ProxyArray: """Body CoM states in world frame. Shape: (N, num_bodies, 13).""" - pose = wp.to_torch(self.body_com_pose_w) - vel = wp.to_torch(self.body_com_vel_w) - return wp.from_torch(torch.cat([pose, vel], dim=-1)) + pose = self.body_com_pose_w.torch + vel = self.body_com_vel_w.torch + return ProxyArray(wp.from_torch(torch.cat([pose, vel], dim=-1))) @property - def body_com_acc_w(self) -> wp.array: + def body_com_acc_w(self) -> ProxyArray: """Body CoM accelerations in world frame. dtype=wp.spatial_vectorf, shape: (N, num_bodies).""" if self._body_com_acc_w is None: self._body_com_acc_w = wp.zeros( (self._num_instances, self._num_bodies, 6), dtype=wp.float32, device=self.device ).view(wp.spatial_vectorf) - return self._body_com_acc_w + self._body_com_acc_w_ta = None + if self._body_com_acc_w_ta is None: + self._body_com_acc_w_ta = ProxyArray(self._body_com_acc_w) + return self._body_com_acc_w_ta @property - def body_com_pose_b(self) -> wp.array: + def body_com_pose_b(self) -> ProxyArray: """Body CoM poses in body frame. dtype=wp.transformf, shape: (N, num_bodies).""" if self._body_com_pose_b is None: pose_np = np.zeros((self._num_instances, self._num_bodies, 7), dtype=np.float32) pose_np[..., 6] = 1.0 # identity quat qw=1, transformf layout: (px,py,pz,qx,qy,qz,qw) self._body_com_pose_b = wp.array(pose_np, dtype=wp.float32, device=self.device).view(wp.transformf) - return self._body_com_pose_b + self._body_com_pose_b_ta = None + if self._body_com_pose_b_ta is None: + self._body_com_pose_b_ta = ProxyArray(self._body_com_pose_b) + return self._body_com_pose_b_ta # Sliced properties (zero-copy pointer arithmetic on transformf) @property - def body_com_pos_w(self) -> wp.array: + def body_com_pos_w(self) -> ProxyArray: """Body CoM positions. Shape: (N, num_bodies), dtype=wp.vec3f.""" - t = self.body_com_pose_w - return wp.array(ptr=t.ptr, shape=t.shape, dtype=wp.vec3f, strides=t.strides, device=self.device) + t = self.body_com_pose_w.warp + return ProxyArray(wp.array(ptr=t.ptr, shape=t.shape, dtype=wp.vec3f, strides=t.strides, device=self.device)) @property - def body_com_quat_w(self) -> wp.array: + def body_com_quat_w(self) -> ProxyArray: """Body CoM orientations. Shape: (N, num_bodies), dtype=wp.quatf.""" - t = self.body_com_pose_w - return wp.array(ptr=t.ptr + 3 * 4, shape=t.shape, dtype=wp.quatf, strides=t.strides, device=self.device) + t = self.body_com_pose_w.warp + return ProxyArray( + wp.array(ptr=t.ptr + 3 * 4, shape=t.shape, dtype=wp.quatf, strides=t.strides, device=self.device) + ) @property - def body_com_lin_vel_w(self) -> wp.array: + def body_com_lin_vel_w(self) -> ProxyArray: """Body CoM linear velocities. Shape: (N, num_bodies), dtype=wp.vec3f.""" - v = self.body_com_vel_w - return wp.array(ptr=v.ptr, shape=v.shape, dtype=wp.vec3f, strides=v.strides, device=self.device) + v = self.body_com_vel_w.warp + return ProxyArray(wp.array(ptr=v.ptr, shape=v.shape, dtype=wp.vec3f, strides=v.strides, device=self.device)) @property - def body_com_ang_vel_w(self) -> wp.array: + def body_com_ang_vel_w(self) -> ProxyArray: """Body CoM angular velocities. Shape: (N, num_bodies), dtype=wp.vec3f.""" - v = self.body_com_vel_w - return wp.array(ptr=v.ptr + 3 * 4, shape=v.shape, dtype=wp.vec3f, strides=v.strides, device=self.device) + v = self.body_com_vel_w.warp + return ProxyArray( + wp.array(ptr=v.ptr + 3 * 4, shape=v.shape, dtype=wp.vec3f, strides=v.strides, device=self.device) + ) @property - def body_com_lin_acc_w(self) -> wp.array: + def body_com_lin_acc_w(self) -> ProxyArray: """Body CoM linear accelerations. Shape: (N, num_bodies), dtype=wp.vec3f.""" - v = self.body_com_acc_w - return wp.array(ptr=v.ptr, shape=v.shape, dtype=wp.vec3f, strides=v.strides, device=self.device) + v = self.body_com_acc_w.warp + return ProxyArray(wp.array(ptr=v.ptr, shape=v.shape, dtype=wp.vec3f, strides=v.strides, device=self.device)) @property - def body_com_ang_acc_w(self) -> wp.array: + def body_com_ang_acc_w(self) -> ProxyArray: """Body CoM angular accelerations. Shape: (N, num_bodies), dtype=wp.vec3f.""" - v = self.body_com_acc_w - return wp.array(ptr=v.ptr + 3 * 4, shape=v.shape, dtype=wp.vec3f, strides=v.strides, device=self.device) + v = self.body_com_acc_w.warp + return ProxyArray( + wp.array(ptr=v.ptr + 3 * 4, shape=v.shape, dtype=wp.vec3f, strides=v.strides, device=self.device) + ) @property - def body_com_pos_b(self) -> wp.array: + def body_com_pos_b(self) -> ProxyArray: """Body CoM positions in body frame. Shape: (N, num_bodies), dtype=wp.vec3f.""" - t = self.body_com_pose_b - return wp.array(ptr=t.ptr, shape=t.shape, dtype=wp.vec3f, strides=t.strides, device=self.device) + t = self.body_com_pose_b.warp + return ProxyArray(wp.array(ptr=t.ptr, shape=t.shape, dtype=wp.vec3f, strides=t.strides, device=self.device)) @property - def body_com_quat_b(self) -> wp.array: + def body_com_quat_b(self) -> ProxyArray: """Body CoM orientations in body frame. Shape: (N, num_bodies), dtype=wp.quatf.""" - t = self.body_com_pose_b - return wp.array(ptr=t.ptr + 3 * 4, shape=t.shape, dtype=wp.quatf, strides=t.strides, device=self.device) + t = self.body_com_pose_b.warp + return ProxyArray( + wp.array(ptr=t.ptr + 3 * 4, shape=t.shape, dtype=wp.quatf, strides=t.strides, device=self.device) + ) # -- Body properties -- @property - def body_mass(self) -> wp.array: + def body_mass(self) -> ProxyArray: """Body masses. Shape: (N, num_bodies).""" if self._body_mass is None: - return wp.ones((self._num_instances, self._num_bodies), dtype=wp.float32, device=self.device) - return self._body_mass + self._body_mass = wp.ones((self._num_instances, self._num_bodies), dtype=wp.float32, device=self.device) + self._body_mass_ta = None + if self._body_mass_ta is None: + self._body_mass_ta = ProxyArray(self._body_mass) + return self._body_mass_ta @property - def body_inertia(self) -> wp.array: + def body_inertia(self) -> ProxyArray: """Body inertias (flattened 3x3). Shape: (N, num_bodies, 9).""" if self._body_inertia is None: inertia_np = np.zeros((self._num_instances, self._num_bodies, 9), dtype=np.float32) inertia_np[..., 0] = 1.0 # Ixx inertia_np[..., 4] = 1.0 # Iyy inertia_np[..., 8] = 1.0 # Izz - return wp.array(inertia_np, dtype=wp.float32, device=self.device) - return self._body_inertia + self._body_inertia = wp.array(inertia_np, dtype=wp.float32, device=self.device) + self._body_inertia_ta = None + if self._body_inertia_ta is None: + self._body_inertia_ta = ProxyArray(self._body_inertia) + return self._body_inertia_ta # -- Derived properties -- @property - def projected_gravity_b(self) -> wp.array: + def projected_gravity_b(self) -> ProxyArray: """Gravity projection on bodies. Shape: (N, num_bodies), dtype=wp.vec3f.""" gravity_np = np.zeros((self._num_instances, self._num_bodies, 3), dtype=np.float32) gravity_np[..., 2] = -1.0 - return wp.array(gravity_np, dtype=wp.float32, device=self.device).view(wp.vec3f) + return ProxyArray(wp.array(gravity_np, dtype=wp.float32, device=self.device).view(wp.vec3f)) @property - def heading_w(self) -> wp.array: + def heading_w(self) -> ProxyArray: """Yaw heading per body. Shape: (N, num_bodies).""" - return wp.zeros((self._num_instances, self._num_bodies), dtype=wp.float32, device=self.device) + return ProxyArray(wp.zeros((self._num_instances, self._num_bodies), dtype=wp.float32, device=self.device)) @property - def body_link_lin_vel_b(self) -> wp.array: + def body_link_lin_vel_b(self) -> ProxyArray: """Body link linear velocities in body frame. Shape: (N, num_bodies), dtype=wp.vec3f.""" - return wp.clone(self.body_link_lin_vel_w, self.device) + return ProxyArray(wp.clone(self.body_link_lin_vel_w.warp, self.device)) @property - def body_link_ang_vel_b(self) -> wp.array: + def body_link_ang_vel_b(self) -> ProxyArray: """Body link angular velocities in body frame. Shape: (N, num_bodies), dtype=wp.vec3f.""" - return wp.clone(self.body_link_ang_vel_w, self.device) + return ProxyArray(wp.clone(self.body_link_ang_vel_w.warp, self.device)) @property - def body_com_lin_vel_b(self) -> wp.array: + def body_com_lin_vel_b(self) -> ProxyArray: """Body CoM linear velocities in body frame. Shape: (N, num_bodies), dtype=wp.vec3f.""" - return wp.clone(self.body_com_lin_vel_w, self.device) + return ProxyArray(wp.clone(self.body_com_lin_vel_w.warp, self.device)) @property - def body_com_ang_vel_b(self) -> wp.array: + def body_com_ang_vel_b(self) -> ProxyArray: """Body CoM angular velocities in body frame. Shape: (N, num_bodies), dtype=wp.vec3f.""" - return wp.clone(self.body_com_ang_vel_w, self.device) + return ProxyArray(wp.clone(self.body_com_ang_vel_w.warp, self.device)) # -- Body state (abstract) -- @property - def body_state_w(self) -> wp.array: + def body_state_w(self) -> ProxyArray: """Body states (link pose + CoM velocity). Shape: (N, num_bodies, 13).""" - pose = wp.to_torch(self.body_link_pose_w) - vel = wp.to_torch(self.body_com_vel_w) - return wp.from_torch(torch.cat([pose, vel], dim=-1)) + pose = self.body_link_pose_w.torch + vel = self.body_com_vel_w.torch + return ProxyArray(wp.from_torch(torch.cat([pose, vel], dim=-1))) # -- Shorthand properties (body_pose_w, body_pos_w, com_pos_b, etc.) -- # Inherited from BaseRigidObjectCollectionData @@ -336,33 +392,43 @@ def update(self, dt: float) -> None: def set_default_body_pose(self, value: torch.Tensor) -> None: self._default_body_pose = wp.from_torch(value.to(self.device).contiguous()).view(wp.transformf) + self._default_body_pose_ta = None def set_default_body_vel(self, value: torch.Tensor) -> None: self._default_body_vel = wp.from_torch(value.to(self.device).contiguous()).view(wp.spatial_vectorf) + self._default_body_vel_ta = None def set_body_link_pose_w(self, value: torch.Tensor) -> None: self._body_link_pose_w = wp.from_torch(value.to(self.device).contiguous()).view(wp.transformf) + self._body_link_pose_w_ta = None def set_body_link_vel_w(self, value: torch.Tensor) -> None: self._body_link_vel_w = wp.from_torch(value.to(self.device).contiguous()).view(wp.spatial_vectorf) + self._body_link_vel_w_ta = None def set_body_com_pose_w(self, value: torch.Tensor) -> None: self._body_com_pose_w = wp.from_torch(value.to(self.device).contiguous()).view(wp.transformf) + self._body_com_pose_w_ta = None def set_body_com_vel_w(self, value: torch.Tensor) -> None: self._body_com_vel_w = wp.from_torch(value.to(self.device).contiguous()).view(wp.spatial_vectorf) + self._body_com_vel_w_ta = None def set_body_com_acc_w(self, value: torch.Tensor) -> None: self._body_com_acc_w = wp.from_torch(value.to(self.device).contiguous()).view(wp.spatial_vectorf) + self._body_com_acc_w_ta = None def set_body_com_pose_b(self, value: torch.Tensor) -> None: self._body_com_pose_b = wp.from_torch(value.to(self.device).contiguous()).view(wp.transformf) + self._body_com_pose_b_ta = None def set_body_mass(self, value: torch.Tensor) -> None: self._body_mass = wp.from_torch(value.to(self.device).contiguous()) + self._body_mass_ta = None def set_body_inertia(self, value: torch.Tensor) -> None: self._body_inertia = wp.from_torch(value.to(self.device).contiguous()) + self._body_inertia_ta = None def set_mock_data(self, **kwargs) -> None: """Bulk setter for mock data.""" diff --git a/source/isaaclab/isaaclab/test/mock_interfaces/sensors/__init__.pyi b/source/isaaclab/isaaclab/test/mock_interfaces/sensors/__init__.pyi index 9339ba2266d5..61ea41691655 100644 --- a/source/isaaclab/isaaclab/test/mock_interfaces/sensors/__init__.pyi +++ b/source/isaaclab/isaaclab/test/mock_interfaces/sensors/__init__.pyi @@ -10,18 +10,23 @@ __all__ = [ "MockFrameTransformerData", "MockImu", "MockImuData", + "MockPva", + "MockPvaData", "create_mock_contact_sensor", "create_mock_foot_contact_sensor", "create_mock_frame_transformer", "create_mock_imu", + "create_mock_pva", ] from .mock_contact_sensor import MockContactSensor, MockContactSensorData from .mock_frame_transformer import MockFrameTransformer, MockFrameTransformerData from .mock_imu import MockImu, MockImuData +from .mock_pva import MockPva, MockPvaData from .factories import ( create_mock_contact_sensor, create_mock_foot_contact_sensor, create_mock_frame_transformer, create_mock_imu, + create_mock_pva, ) diff --git a/source/isaaclab/isaaclab/test/mock_interfaces/sensors/factories.py b/source/isaaclab/isaaclab/test/mock_interfaces/sensors/factories.py index 8f99a4854adc..b16ca53f1128 100644 --- a/source/isaaclab/isaaclab/test/mock_interfaces/sensors/factories.py +++ b/source/isaaclab/isaaclab/test/mock_interfaces/sensors/factories.py @@ -12,26 +12,43 @@ from .mock_contact_sensor import MockContactSensor from .mock_frame_transformer import MockFrameTransformer from .mock_imu import MockImu +from .mock_pva import MockPva def create_mock_imu( num_instances: int = 1, device: str = "cpu", - gravity: tuple[float, float, float] = (0.0, 0.0, -1.0), ) -> MockImu: """Create a mock IMU sensor with default configuration. Args: num_instances: Number of sensor instances. device: Device for tensor allocation. - gravity: Default gravity direction in body frame. Returns: Configured MockImu instance. """ - imu = MockImu(num_instances=num_instances, device=device) - imu.data.set_projected_gravity_b(torch.tensor([gravity], device=device).expand(num_instances, -1).clone()) - return imu + return MockImu(num_instances=num_instances, device=device) + + +def create_mock_pva( + num_instances: int = 1, + device: str = "cpu", + gravity: tuple[float, float, float] = (0.0, 0.0, -1.0), +) -> MockPva: + """Create a mock PVA sensor with default configuration. + + Args: + num_instances: Number of sensor instances. + device: Device for tensor allocation. + gravity: Default gravity direction in body frame. + + Returns: + Configured MockPva instance. + """ + pva = MockPva(num_instances=num_instances, device=device) + pva.data.set_projected_gravity_b(torch.tensor([gravity], device=device).expand(num_instances, -1).clone()) + return pva def create_mock_contact_sensor( diff --git a/source/isaaclab/isaaclab/test/mock_interfaces/sensors/mock_contact_sensor.py b/source/isaaclab/isaaclab/test/mock_interfaces/sensors/mock_contact_sensor.py index 82e134ccd6e9..4c6c9ad8c0b1 100644 --- a/source/isaaclab/isaaclab/test/mock_interfaces/sensors/mock_contact_sensor.py +++ b/source/isaaclab/isaaclab/test/mock_interfaces/sensors/mock_contact_sensor.py @@ -14,6 +14,8 @@ import torch import warp as wp +from isaaclab.utils.warp import ProxyArray + try: from isaaclab.sensors.contact_sensor.base_contact_sensor_data import BaseContactSensorData except (ImportError, ModuleNotFoundError): @@ -72,65 +74,97 @@ def __init__( self._last_contact_time: wp.array | None = None self._current_contact_time: wp.array | None = None + # ProxyArray caches + self._pos_w_ta: ProxyArray | None = None + self._quat_w_ta: ProxyArray | None = None + self._net_forces_w_ta: ProxyArray | None = None + self._net_forces_w_history_ta: ProxyArray | None = None + self._force_matrix_w_ta: ProxyArray | None = None + self._contact_pos_w_ta: ProxyArray | None = None + self._friction_forces_w_ta: ProxyArray | None = None + self._last_air_time_ta: ProxyArray | None = None + self._current_air_time_ta: ProxyArray | None = None + self._last_contact_time_ta: ProxyArray | None = None + self._current_contact_time_ta: ProxyArray | None = None + # -- Properties -- @property - def pos_w(self) -> wp.array | None: + def pos_w(self) -> ProxyArray | None: """Position of sensor origins in world frame. Shape: (N, B, 3).""" if self._pos_w is None: - return wp.zeros(shape=(self._num_instances, self._num_bodies, 3), dtype=wp.float32, device=self.device) - return self._pos_w + self._pos_w = wp.zeros( + shape=(self._num_instances, self._num_bodies, 3), dtype=wp.float32, device=self.device + ) + self._pos_w_ta = None + if self._pos_w_ta is None: + self._pos_w_ta = ProxyArray(self._pos_w) + return self._pos_w_ta @property - def quat_w(self) -> wp.array | None: + def quat_w(self) -> ProxyArray | None: """Orientation (w, x, y, z) in world frame. Shape: (N, B, 4).""" if self._quat_w is None: # Default to identity quaternion quat_np = np.zeros((self._num_instances, self._num_bodies, 4), dtype=np.float32) quat_np[..., 0] = 1.0 - return wp.array(quat_np, dtype=wp.float32, device=self.device) - return self._quat_w + self._quat_w = wp.array(quat_np, dtype=wp.float32, device=self.device) + self._quat_w_ta = None + if self._quat_w_ta is None: + self._quat_w_ta = ProxyArray(self._quat_w) + return self._quat_w_ta @property - def pose_w(self) -> wp.array | None: + def pose_w(self) -> ProxyArray | None: """Pose in world frame (pos + quat). Shape: (N, B, 7).""" - pos_t = wp.to_torch(self.pos_w) - quat_t = wp.to_torch(self.quat_w) + pos_t = self.pos_w.torch + quat_t = self.quat_w.torch pose_t = torch.cat([pos_t, quat_t], dim=-1) - return wp.from_torch(pose_t.contiguous(), dtype=wp.float32) + return ProxyArray(wp.from_torch(pose_t.contiguous(), dtype=wp.float32)) @property - def net_forces_w(self) -> wp.array: + def net_forces_w(self) -> ProxyArray: """Net normal contact forces in world frame. Shape: (N, B, 3).""" if self._net_forces_w is None: - return wp.zeros(shape=(self._num_instances, self._num_bodies, 3), dtype=wp.float32, device=self.device) - return self._net_forces_w + self._net_forces_w = wp.zeros( + shape=(self._num_instances, self._num_bodies, 3), dtype=wp.float32, device=self.device + ) + self._net_forces_w_ta = None + if self._net_forces_w_ta is None: + self._net_forces_w_ta = ProxyArray(self._net_forces_w) + return self._net_forces_w_ta @property - def net_forces_w_history(self) -> wp.array | None: + def net_forces_w_history(self) -> ProxyArray | None: """History of net forces. Shape: (N, T, B, 3).""" if self._history_length == 0: return None if self._net_forces_w_history is None: - return wp.zeros( + self._net_forces_w_history = wp.zeros( shape=(self._num_instances, self._history_length, self._num_bodies, 3), dtype=wp.float32, device=self.device, ) - return self._net_forces_w_history + self._net_forces_w_history_ta = None + if self._net_forces_w_history_ta is None: + self._net_forces_w_history_ta = ProxyArray(self._net_forces_w_history) + return self._net_forces_w_history_ta @property - def force_matrix_w(self) -> wp.array | None: + def force_matrix_w(self) -> ProxyArray | None: """Filtered contact forces. Shape: (N, B, M, 3).""" if self._num_filter_bodies == 0: return None if self._force_matrix_w is None: - return wp.zeros( + self._force_matrix_w = wp.zeros( shape=(self._num_instances, self._num_bodies, self._num_filter_bodies, 3), dtype=wp.float32, device=self.device, ) - return self._force_matrix_w + self._force_matrix_w_ta = None + if self._force_matrix_w_ta is None: + self._force_matrix_w_ta = ProxyArray(self._force_matrix_w) + return self._force_matrix_w_ta @property def force_matrix_w_history(self) -> torch.Tensor | None: @@ -149,80 +183,111 @@ def force_matrix_w_history(self) -> torch.Tensor | None: return self._force_matrix_w_history @property - def contact_pos_w(self) -> wp.array | None: + def contact_pos_w(self) -> ProxyArray | None: """Contact point positions in world frame. Shape: (N, B, M, 3).""" if self._num_filter_bodies == 0: return None if self._contact_pos_w is None: - return wp.zeros( + self._contact_pos_w = wp.zeros( shape=(self._num_instances, self._num_bodies, self._num_filter_bodies, 3), dtype=wp.float32, device=self.device, ) - return self._contact_pos_w + self._contact_pos_w_ta = None + if self._contact_pos_w_ta is None: + self._contact_pos_w_ta = ProxyArray(self._contact_pos_w) + return self._contact_pos_w_ta @property - def friction_forces_w(self) -> wp.array | None: + def friction_forces_w(self) -> ProxyArray | None: """Friction forces in world frame. Shape: (N, B, M, 3).""" if self._num_filter_bodies == 0: return None if self._friction_forces_w is None: - return wp.zeros( + self._friction_forces_w = wp.zeros( shape=(self._num_instances, self._num_bodies, self._num_filter_bodies, 3), dtype=wp.float32, device=self.device, ) - return self._friction_forces_w + self._friction_forces_w_ta = None + if self._friction_forces_w_ta is None: + self._friction_forces_w_ta = ProxyArray(self._friction_forces_w) + return self._friction_forces_w_ta @property - def last_air_time(self) -> wp.array: + def last_air_time(self) -> ProxyArray: """Time in air before last contact. Shape: (N, B).""" if self._last_air_time is None: - return wp.zeros(shape=(self._num_instances, self._num_bodies), dtype=wp.float32, device=self.device) - return self._last_air_time + self._last_air_time = wp.zeros( + shape=(self._num_instances, self._num_bodies), dtype=wp.float32, device=self.device + ) + self._last_air_time_ta = None + if self._last_air_time_ta is None: + self._last_air_time_ta = ProxyArray(self._last_air_time) + return self._last_air_time_ta @property - def current_air_time(self) -> wp.array: + def current_air_time(self) -> ProxyArray: """Current time in air. Shape: (N, B).""" if self._current_air_time is None: - return wp.zeros(shape=(self._num_instances, self._num_bodies), dtype=wp.float32, device=self.device) - return self._current_air_time + self._current_air_time = wp.zeros( + shape=(self._num_instances, self._num_bodies), dtype=wp.float32, device=self.device + ) + self._current_air_time_ta = None + if self._current_air_time_ta is None: + self._current_air_time_ta = ProxyArray(self._current_air_time) + return self._current_air_time_ta @property - def last_contact_time(self) -> wp.array: + def last_contact_time(self) -> ProxyArray: """Time in contact before last detach. Shape: (N, B).""" if self._last_contact_time is None: - return wp.zeros(shape=(self._num_instances, self._num_bodies), dtype=wp.float32, device=self.device) - return self._last_contact_time + self._last_contact_time = wp.zeros( + shape=(self._num_instances, self._num_bodies), dtype=wp.float32, device=self.device + ) + self._last_contact_time_ta = None + if self._last_contact_time_ta is None: + self._last_contact_time_ta = ProxyArray(self._last_contact_time) + return self._last_contact_time_ta @property - def current_contact_time(self) -> wp.array: + def current_contact_time(self) -> ProxyArray: """Current time in contact. Shape: (N, B).""" if self._current_contact_time is None: - return wp.zeros(shape=(self._num_instances, self._num_bodies), dtype=wp.float32, device=self.device) - return self._current_contact_time + self._current_contact_time = wp.zeros( + shape=(self._num_instances, self._num_bodies), dtype=wp.float32, device=self.device + ) + self._current_contact_time_ta = None + if self._current_contact_time_ta is None: + self._current_contact_time_ta = ProxyArray(self._current_contact_time) + return self._current_contact_time_ta # -- Setters -- def set_pos_w(self, value: torch.Tensor) -> None: """Set position in world frame.""" self._pos_w = wp.from_torch(value.to(self.device).contiguous(), dtype=wp.float32) + self._pos_w_ta = None def set_quat_w(self, value: torch.Tensor) -> None: """Set orientation in world frame.""" self._quat_w = wp.from_torch(value.to(self.device).contiguous(), dtype=wp.float32) + self._quat_w_ta = None def set_net_forces_w(self, value: torch.Tensor) -> None: """Set net contact forces.""" self._net_forces_w = wp.from_torch(value.to(self.device).contiguous(), dtype=wp.float32) + self._net_forces_w_ta = None def set_net_forces_w_history(self, value: torch.Tensor) -> None: """Set net forces history.""" self._net_forces_w_history = wp.from_torch(value.to(self.device).contiguous(), dtype=wp.float32) + self._net_forces_w_history_ta = None def set_force_matrix_w(self, value: torch.Tensor) -> None: """Set filtered contact forces.""" self._force_matrix_w = wp.from_torch(value.to(self.device).contiguous(), dtype=wp.float32) + self._force_matrix_w_ta = None def set_force_matrix_w_history(self, value: torch.Tensor) -> None: """Set filtered forces history. @@ -234,26 +299,32 @@ def set_force_matrix_w_history(self, value: torch.Tensor) -> None: def set_contact_pos_w(self, value: torch.Tensor) -> None: """Set contact point positions.""" self._contact_pos_w = wp.from_torch(value.to(self.device).contiguous(), dtype=wp.float32) + self._contact_pos_w_ta = None def set_friction_forces_w(self, value: torch.Tensor) -> None: """Set friction forces.""" self._friction_forces_w = wp.from_torch(value.to(self.device).contiguous(), dtype=wp.float32) + self._friction_forces_w_ta = None def set_last_air_time(self, value: torch.Tensor) -> None: """Set last air time.""" self._last_air_time = wp.from_torch(value.to(self.device).contiguous(), dtype=wp.float32) + self._last_air_time_ta = None def set_current_air_time(self, value: torch.Tensor) -> None: """Set current air time.""" self._current_air_time = wp.from_torch(value.to(self.device).contiguous(), dtype=wp.float32) + self._current_air_time_ta = None def set_last_contact_time(self, value: torch.Tensor) -> None: """Set last contact time.""" self._last_contact_time = wp.from_torch(value.to(self.device).contiguous(), dtype=wp.float32) + self._last_contact_time_ta = None def set_current_contact_time(self, value: torch.Tensor) -> None: """Set current contact time.""" self._current_contact_time = wp.from_torch(value.to(self.device).contiguous(), dtype=wp.float32) + self._current_contact_time_ta = None def set_mock_data( self, @@ -439,7 +510,7 @@ def compute_first_contact(self, dt: float, abs_tol: float = 1.0e-8) -> wp.array: Returns: Boolean warp array of shape (N, B) indicating first contact. """ - result = wp.to_torch(self._data.current_contact_time) < (dt + abs_tol) + result = self._data.current_contact_time.torch < (dt + abs_tol) return wp.from_torch(result) def compute_first_air(self, dt: float, abs_tol: float = 1.0e-8) -> wp.array: @@ -452,7 +523,7 @@ def compute_first_air(self, dt: float, abs_tol: float = 1.0e-8) -> wp.array: Returns: Boolean warp array of shape (N, B) indicating first air. """ - result = wp.to_torch(self._data.current_air_time) < (dt + abs_tol) + result = self._data.current_air_time.torch < (dt + abs_tol) return wp.from_torch(result) def reset(self, env_ids: Sequence[int] | None = None) -> None: diff --git a/source/isaaclab/isaaclab/test/mock_interfaces/sensors/mock_frame_transformer.py b/source/isaaclab/isaaclab/test/mock_interfaces/sensors/mock_frame_transformer.py index e79f571642a2..5d4b9cad6153 100644 --- a/source/isaaclab/isaaclab/test/mock_interfaces/sensors/mock_frame_transformer.py +++ b/source/isaaclab/isaaclab/test/mock_interfaces/sensors/mock_frame_transformer.py @@ -14,6 +14,8 @@ import torch import warp as wp +from isaaclab.utils.warp import ProxyArray + try: from isaaclab.sensors.frame_transformer.base_frame_transformer_data import BaseFrameTransformerData except (ImportError, ModuleNotFoundError): @@ -63,6 +65,14 @@ def __init__( self._target_pos_source: wp.array | None = None self._target_quat_source: wp.array | None = None + # ProxyArray caches + self._source_pos_w_ta: ProxyArray | None = None + self._source_quat_w_ta: ProxyArray | None = None + self._target_pos_w_ta: ProxyArray | None = None + self._target_quat_w_ta: ProxyArray | None = None + self._target_pos_source_ta: ProxyArray | None = None + self._target_quat_source_ta: ProxyArray | None = None + # -- Properties -- @property @@ -71,106 +81,130 @@ def target_frame_names(self) -> list[str]: return self._target_frame_names @property - def source_pos_w(self) -> wp.array: + def source_pos_w(self) -> ProxyArray: """Position of source frame in world frame. Shape: (N, 3).""" if self._source_pos_w is None: - return wp.zeros(shape=(self._num_instances, 3), dtype=wp.float32, device=self.device) - return self._source_pos_w + self._source_pos_w = wp.zeros(shape=(self._num_instances, 3), dtype=wp.float32, device=self.device) + self._source_pos_w_ta = None + if self._source_pos_w_ta is None: + self._source_pos_w_ta = ProxyArray(self._source_pos_w) + return self._source_pos_w_ta @property - def source_quat_w(self) -> wp.array: + def source_quat_w(self) -> ProxyArray: """Orientation (w, x, y, z) of source frame in world frame. Shape: (N, 4).""" if self._source_quat_w is None: quat_np = np.zeros((self._num_instances, 4), dtype=np.float32) quat_np[:, 0] = 1.0 - return wp.array(quat_np, dtype=wp.float32, device=self.device) - return self._source_quat_w + self._source_quat_w = wp.array(quat_np, dtype=wp.float32, device=self.device) + self._source_quat_w_ta = None + if self._source_quat_w_ta is None: + self._source_quat_w_ta = ProxyArray(self._source_quat_w) + return self._source_quat_w_ta @property - def source_pose_w(self) -> wp.array: + def source_pose_w(self) -> ProxyArray: """Pose of source frame in world frame. Shape: (N, 7).""" - pos_t = wp.to_torch(self.source_pos_w) - quat_t = wp.to_torch(self.source_quat_w) + pos_t = self.source_pos_w.torch + quat_t = self.source_quat_w.torch pose_t = torch.cat([pos_t, quat_t], dim=-1) - return wp.from_torch(pose_t.contiguous(), dtype=wp.float32) + return ProxyArray(wp.from_torch(pose_t.contiguous(), dtype=wp.float32)) @property - def target_pos_w(self) -> wp.array: + def target_pos_w(self) -> ProxyArray: """Position of target frames in world frame. Shape: (N, M, 3).""" if self._target_pos_w is None: - return wp.zeros( + self._target_pos_w = wp.zeros( shape=(self._num_instances, self._num_target_frames, 3), dtype=wp.float32, device=self.device ) - return self._target_pos_w + self._target_pos_w_ta = None + if self._target_pos_w_ta is None: + self._target_pos_w_ta = ProxyArray(self._target_pos_w) + return self._target_pos_w_ta @property - def target_quat_w(self) -> wp.array: + def target_quat_w(self) -> ProxyArray: """Orientation (w, x, y, z) of target frames in world frame. Shape: (N, M, 4).""" if self._target_quat_w is None: quat_np = np.zeros((self._num_instances, self._num_target_frames, 4), dtype=np.float32) quat_np[..., 0] = 1.0 - return wp.array(quat_np, dtype=wp.float32, device=self.device) - return self._target_quat_w + self._target_quat_w = wp.array(quat_np, dtype=wp.float32, device=self.device) + self._target_quat_w_ta = None + if self._target_quat_w_ta is None: + self._target_quat_w_ta = ProxyArray(self._target_quat_w) + return self._target_quat_w_ta @property - def target_pose_w(self) -> wp.array: + def target_pose_w(self) -> ProxyArray: """Pose of target frames in world frame. Shape: (N, M, 7).""" - pos_t = wp.to_torch(self.target_pos_w) - quat_t = wp.to_torch(self.target_quat_w) + pos_t = self.target_pos_w.torch + quat_t = self.target_quat_w.torch pose_t = torch.cat([pos_t, quat_t], dim=-1) - return wp.from_torch(pose_t.contiguous(), dtype=wp.float32) + return ProxyArray(wp.from_torch(pose_t.contiguous(), dtype=wp.float32)) @property - def target_pos_source(self) -> wp.array: + def target_pos_source(self) -> ProxyArray: """Position of target frames relative to source frame. Shape: (N, M, 3).""" if self._target_pos_source is None: - return wp.zeros( + self._target_pos_source = wp.zeros( shape=(self._num_instances, self._num_target_frames, 3), dtype=wp.float32, device=self.device ) - return self._target_pos_source + self._target_pos_source_ta = None + if self._target_pos_source_ta is None: + self._target_pos_source_ta = ProxyArray(self._target_pos_source) + return self._target_pos_source_ta @property - def target_quat_source(self) -> wp.array: + def target_quat_source(self) -> ProxyArray: """Orientation (w, x, y, z) of target frames relative to source frame. Shape: (N, M, 4).""" if self._target_quat_source is None: quat_np = np.zeros((self._num_instances, self._num_target_frames, 4), dtype=np.float32) quat_np[..., 0] = 1.0 - return wp.array(quat_np, dtype=wp.float32, device=self.device) - return self._target_quat_source + self._target_quat_source = wp.array(quat_np, dtype=wp.float32, device=self.device) + self._target_quat_source_ta = None + if self._target_quat_source_ta is None: + self._target_quat_source_ta = ProxyArray(self._target_quat_source) + return self._target_quat_source_ta @property - def target_pose_source(self) -> wp.array: + def target_pose_source(self) -> ProxyArray: """Pose of target frames relative to source frame. Shape: (N, M, 7).""" - pos_t = wp.to_torch(self.target_pos_source) - quat_t = wp.to_torch(self.target_quat_source) + pos_t = self.target_pos_source.torch + quat_t = self.target_quat_source.torch pose_t = torch.cat([pos_t, quat_t], dim=-1) - return wp.from_torch(pose_t.contiguous(), dtype=wp.float32) + return ProxyArray(wp.from_torch(pose_t.contiguous(), dtype=wp.float32)) # -- Setters -- def set_source_pos_w(self, value: torch.Tensor) -> None: """Set source position in world frame.""" self._source_pos_w = wp.from_torch(value.to(self.device).contiguous(), dtype=wp.float32) + self._source_pos_w_ta = None def set_source_quat_w(self, value: torch.Tensor) -> None: """Set source orientation in world frame.""" self._source_quat_w = wp.from_torch(value.to(self.device).contiguous(), dtype=wp.float32) + self._source_quat_w_ta = None def set_target_pos_w(self, value: torch.Tensor) -> None: """Set target positions in world frame.""" self._target_pos_w = wp.from_torch(value.to(self.device).contiguous(), dtype=wp.float32) + self._target_pos_w_ta = None def set_target_quat_w(self, value: torch.Tensor) -> None: """Set target orientations in world frame.""" self._target_quat_w = wp.from_torch(value.to(self.device).contiguous(), dtype=wp.float32) + self._target_quat_w_ta = None def set_target_pos_source(self, value: torch.Tensor) -> None: """Set target positions relative to source.""" self._target_pos_source = wp.from_torch(value.to(self.device).contiguous(), dtype=wp.float32) + self._target_pos_source_ta = None def set_target_quat_source(self, value: torch.Tensor) -> None: """Set target orientations relative to source.""" self._target_quat_source = wp.from_torch(value.to(self.device).contiguous(), dtype=wp.float32) + self._target_quat_source_ta = None def set_mock_data( self, diff --git a/source/isaaclab/isaaclab/test/mock_interfaces/sensors/mock_imu.py b/source/isaaclab/isaaclab/test/mock_interfaces/sensors/mock_imu.py index 6d077bb53934..f32f0a5f567a 100644 --- a/source/isaaclab/isaaclab/test/mock_interfaces/sensors/mock_imu.py +++ b/source/isaaclab/isaaclab/test/mock_interfaces/sensors/mock_imu.py @@ -9,10 +9,11 @@ from collections.abc import Sequence -import numpy as np import torch import warp as wp +from isaaclab.utils.warp import ProxyArray + try: from isaaclab.sensors.imu.base_imu_data import BaseImuData except (ImportError, ModuleNotFoundError): @@ -31,7 +32,7 @@ class MockImuData(BaseImuData): """Mock data container for IMU sensor. This class mimics the interface of BaseImuData for testing purposes. - All tensor properties return zero warp arrays with correct shapes if not explicitly set. + The IMU only provides angular velocity and linear acceleration. """ def __init__(self, num_instances: int, device: str = "cpu"): @@ -44,145 +45,62 @@ def __init__(self, num_instances: int, device: str = "cpu"): self._num_instances = num_instances self.device = device - # Internal storage for mock data - self._pos_w: wp.array | None = None - self._quat_w: wp.array | None = None - self._projected_gravity_b: wp.array | None = None - self._lin_vel_b: wp.array | None = None self._ang_vel_b: wp.array | None = None self._lin_acc_b: wp.array | None = None - self._ang_acc_b: wp.array | None = None - - # -- Properties -- - - @property - def pos_w(self) -> wp.array: - """Position of sensor origin in world frame. Shape: (N, 3).""" - if self._pos_w is None: - return wp.zeros(shape=(self._num_instances, 3), dtype=wp.float32, device=self.device) - return self._pos_w - @property - def quat_w(self) -> wp.array: - """Orientation (x, y, z, w) in world frame. Shape: (N, 4).""" - if self._quat_w is None: - # Default to identity quaternion (x, y, z, w) = (0, 0, 0, 1) - quat_np = np.zeros((self._num_instances, 4), dtype=np.float32) - quat_np[:, 3] = 1.0 # w component is at index 3 in XYZW format - return wp.array(quat_np, dtype=wp.float32, device=self.device) - return self._quat_w - - @property - def pose_w(self) -> wp.array: - """Pose in world frame (pos + quat). Shape: (N, 7).""" - pos_t = wp.to_torch(self.pos_w) - quat_t = wp.to_torch(self.quat_w) - pose_t = torch.cat([pos_t, quat_t], dim=-1) - return wp.from_torch(pose_t.contiguous(), dtype=wp.float32) - - @property - def projected_gravity_b(self) -> wp.array: - """Gravity direction in IMU body frame. Shape: (N, 3).""" - if self._projected_gravity_b is None: - # Default gravity pointing down in body frame - gravity_np = np.zeros((self._num_instances, 3), dtype=np.float32) - gravity_np[:, 2] = -1.0 - return wp.array(gravity_np, dtype=wp.float32, device=self.device) - return self._projected_gravity_b + # ProxyArray caches + self._ang_vel_b_ta: ProxyArray | None = None + self._lin_acc_b_ta: ProxyArray | None = None - @property - def lin_vel_b(self) -> wp.array: - """Linear velocity in IMU body frame. Shape: (N, 3).""" - if self._lin_vel_b is None: - return wp.zeros(shape=(self._num_instances, 3), dtype=wp.float32, device=self.device) - return self._lin_vel_b + # -- Properties -- @property - def ang_vel_b(self) -> wp.array: - """Angular velocity in IMU body frame. Shape: (N, 3).""" + def ang_vel_b(self) -> ProxyArray: + """Angular velocity in IMU body frame [rad/s]. Shape: (N, 3).""" if self._ang_vel_b is None: - return wp.zeros(shape=(self._num_instances, 3), dtype=wp.float32, device=self.device) - return self._ang_vel_b + self._ang_vel_b = wp.zeros(shape=(self._num_instances, 3), dtype=wp.float32, device=self.device) + self._ang_vel_b_ta = None + if self._ang_vel_b_ta is None: + self._ang_vel_b_ta = ProxyArray(self._ang_vel_b) + return self._ang_vel_b_ta @property - def lin_acc_b(self) -> wp.array: - """Linear acceleration in IMU body frame. Shape: (N, 3).""" + def lin_acc_b(self) -> ProxyArray: + """Linear acceleration in IMU body frame [m/s^2]. Shape: (N, 3).""" if self._lin_acc_b is None: - return wp.zeros(shape=(self._num_instances, 3), dtype=wp.float32, device=self.device) - return self._lin_acc_b - - @property - def ang_acc_b(self) -> wp.array: - """Angular acceleration in IMU body frame. Shape: (N, 3).""" - if self._ang_acc_b is None: - return wp.zeros(shape=(self._num_instances, 3), dtype=wp.float32, device=self.device) - return self._ang_acc_b + self._lin_acc_b = wp.zeros(shape=(self._num_instances, 3), dtype=wp.float32, device=self.device) + self._lin_acc_b_ta = None + if self._lin_acc_b_ta is None: + self._lin_acc_b_ta = ProxyArray(self._lin_acc_b) + return self._lin_acc_b_ta # -- Setters -- - def set_pos_w(self, value: torch.Tensor) -> None: - """Set position in world frame.""" - self._pos_w = wp.from_torch(value.to(self.device).contiguous(), dtype=wp.float32) - - def set_quat_w(self, value: torch.Tensor) -> None: - """Set orientation in world frame.""" - self._quat_w = wp.from_torch(value.to(self.device).contiguous(), dtype=wp.float32) - - def set_projected_gravity_b(self, value: torch.Tensor) -> None: - """Set projected gravity in body frame.""" - self._projected_gravity_b = wp.from_torch(value.to(self.device).contiguous(), dtype=wp.float32) - - def set_lin_vel_b(self, value: torch.Tensor) -> None: - """Set linear velocity in body frame.""" - self._lin_vel_b = wp.from_torch(value.to(self.device).contiguous(), dtype=wp.float32) - def set_ang_vel_b(self, value: torch.Tensor) -> None: """Set angular velocity in body frame.""" self._ang_vel_b = wp.from_torch(value.to(self.device).contiguous(), dtype=wp.float32) + self._ang_vel_b_ta = None def set_lin_acc_b(self, value: torch.Tensor) -> None: """Set linear acceleration in body frame.""" self._lin_acc_b = wp.from_torch(value.to(self.device).contiguous(), dtype=wp.float32) - - def set_ang_acc_b(self, value: torch.Tensor) -> None: - """Set angular acceleration in body frame.""" - self._ang_acc_b = wp.from_torch(value.to(self.device).contiguous(), dtype=wp.float32) + self._lin_acc_b_ta = None def set_mock_data( self, - pos_w: torch.Tensor | None = None, - quat_w: torch.Tensor | None = None, - projected_gravity_b: torch.Tensor | None = None, - lin_vel_b: torch.Tensor | None = None, ang_vel_b: torch.Tensor | None = None, lin_acc_b: torch.Tensor | None = None, - ang_acc_b: torch.Tensor | None = None, ) -> None: """Bulk setter for mock data. Args: - pos_w: Position in world frame. Shape: (N, 3). - quat_w: Orientation (x, y, z, w) in world frame. Shape: (N, 4). - projected_gravity_b: Gravity direction in body frame. Shape: (N, 3). - lin_vel_b: Linear velocity in body frame. Shape: (N, 3). - ang_vel_b: Angular velocity in body frame. Shape: (N, 3). - lin_acc_b: Linear acceleration in body frame. Shape: (N, 3). - ang_acc_b: Angular acceleration in body frame. Shape: (N, 3). + ang_vel_b: Angular velocity in body frame [rad/s]. Shape: (N, 3). + lin_acc_b: Linear acceleration in body frame [m/s^2]. Shape: (N, 3). """ - if pos_w is not None: - self.set_pos_w(pos_w) - if quat_w is not None: - self.set_quat_w(quat_w) - if projected_gravity_b is not None: - self.set_projected_gravity_b(projected_gravity_b) - if lin_vel_b is not None: - self.set_lin_vel_b(lin_vel_b) if ang_vel_b is not None: self.set_ang_vel_b(ang_vel_b) if lin_acc_b is not None: self.set_lin_acc_b(lin_acc_b) - if ang_acc_b is not None: - self.set_ang_acc_b(ang_acc_b) class MockImu: @@ -232,7 +150,6 @@ def reset(self, env_ids: Sequence[int] | None = None) -> None: Args: env_ids: Environment indices to reset. If None, resets all. """ - # No-op for mock - data persists until explicitly changed pass def update(self, dt: float, force_recompute: bool = False) -> None: @@ -242,5 +159,4 @@ def update(self, dt: float, force_recompute: bool = False) -> None: dt: Time step since last update. force_recompute: Force recomputation of buffers. """ - # No-op for mock - data is set explicitly pass diff --git a/source/isaaclab/isaaclab/test/mock_interfaces/sensors/mock_pva.py b/source/isaaclab/isaaclab/test/mock_interfaces/sensors/mock_pva.py new file mode 100644 index 000000000000..0fb24b551b1f --- /dev/null +++ b/source/isaaclab/isaaclab/test/mock_interfaces/sensors/mock_pva.py @@ -0,0 +1,283 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Mock PVA sensor for testing without Isaac Sim.""" + +from __future__ import annotations + +from collections.abc import Sequence + +import numpy as np +import torch +import warp as wp + +from isaaclab.utils.warp import ProxyArray + +try: + from isaaclab.sensors.pva.base_pva_data import BasePvaData +except (ImportError, ModuleNotFoundError): + # Direct import bypassing isaaclab.sensors.__init__.py (which needs omni) + import importlib.util + from pathlib import Path + + _file = Path(__file__).resolve().parents[3] / "sensors" / "pva" / "base_pva_data.py" + _spec = importlib.util.spec_from_file_location("_base_pva_data", str(_file)) + _mod = importlib.util.module_from_spec(_spec) + _spec.loader.exec_module(_mod) + BasePvaData = _mod.BasePvaData + + +class MockPvaData(BasePvaData): + """Mock data container for PVA sensor. + + This class mimics the interface of BasePvaData for testing purposes. + All tensor properties return zero warp arrays with correct shapes if not explicitly set. + """ + + def __init__(self, num_instances: int, device: str = "cpu"): + """Initialize mock PVA data. + + Args: + num_instances: Number of sensor instances. + device: Device for tensor allocation. + """ + self._num_instances = num_instances + self.device = device + + # Internal storage for mock data + self._pos_w: wp.array | None = None + self._quat_w: wp.array | None = None + self._projected_gravity_b: wp.array | None = None + self._lin_vel_b: wp.array | None = None + self._ang_vel_b: wp.array | None = None + self._lin_acc_b: wp.array | None = None + self._ang_acc_b: wp.array | None = None + + # ProxyArray caches + self._pos_w_ta: ProxyArray | None = None + self._quat_w_ta: ProxyArray | None = None + self._projected_gravity_b_ta: ProxyArray | None = None + self._lin_vel_b_ta: ProxyArray | None = None + self._ang_vel_b_ta: ProxyArray | None = None + self._lin_acc_b_ta: ProxyArray | None = None + self._ang_acc_b_ta: ProxyArray | None = None + + # -- Properties -- + + @property + def pos_w(self) -> ProxyArray: + """Position of sensor origin in world frame. Shape: (N, 3).""" + if self._pos_w is None: + self._pos_w = wp.zeros(shape=(self._num_instances, 3), dtype=wp.float32, device=self.device) + self._pos_w_ta = None + if self._pos_w_ta is None: + self._pos_w_ta = ProxyArray(self._pos_w) + return self._pos_w_ta + + @property + def quat_w(self) -> ProxyArray: + """Orientation (x, y, z, w) in world frame. Shape: (N, 4).""" + if self._quat_w is None: + # Default to identity quaternion (x, y, z, w) = (0, 0, 0, 1) + quat_np = np.zeros((self._num_instances, 4), dtype=np.float32) + quat_np[:, 3] = 1.0 # w component is at index 3 in XYZW format + self._quat_w = wp.array(quat_np, dtype=wp.float32, device=self.device) + self._quat_w_ta = None + if self._quat_w_ta is None: + self._quat_w_ta = ProxyArray(self._quat_w) + return self._quat_w_ta + + @property + def pose_w(self) -> ProxyArray: + """Pose in world frame (pos + quat). Shape: (N, 7).""" + pos_t = self.pos_w.torch + quat_t = self.quat_w.torch + pose_t = torch.cat([pos_t, quat_t], dim=-1) + return ProxyArray(wp.from_torch(pose_t.contiguous(), dtype=wp.float32)) + + @property + def projected_gravity_b(self) -> ProxyArray: + """Gravity direction in PVA body frame. Shape: (N, 3).""" + if self._projected_gravity_b is None: + # Default gravity pointing down in body frame + gravity_np = np.zeros((self._num_instances, 3), dtype=np.float32) + gravity_np[:, 2] = -1.0 + self._projected_gravity_b = wp.array(gravity_np, dtype=wp.float32, device=self.device) + self._projected_gravity_b_ta = None + if self._projected_gravity_b_ta is None: + self._projected_gravity_b_ta = ProxyArray(self._projected_gravity_b) + return self._projected_gravity_b_ta + + @property + def lin_vel_b(self) -> ProxyArray: + """Linear velocity in PVA body frame. Shape: (N, 3).""" + if self._lin_vel_b is None: + self._lin_vel_b = wp.zeros(shape=(self._num_instances, 3), dtype=wp.float32, device=self.device) + self._lin_vel_b_ta = None + if self._lin_vel_b_ta is None: + self._lin_vel_b_ta = ProxyArray(self._lin_vel_b) + return self._lin_vel_b_ta + + @property + def ang_vel_b(self) -> ProxyArray: + """Angular velocity in PVA body frame. Shape: (N, 3).""" + if self._ang_vel_b is None: + self._ang_vel_b = wp.zeros(shape=(self._num_instances, 3), dtype=wp.float32, device=self.device) + self._ang_vel_b_ta = None + if self._ang_vel_b_ta is None: + self._ang_vel_b_ta = ProxyArray(self._ang_vel_b) + return self._ang_vel_b_ta + + @property + def lin_acc_b(self) -> ProxyArray: + """Linear acceleration in PVA body frame. Shape: (N, 3).""" + if self._lin_acc_b is None: + self._lin_acc_b = wp.zeros(shape=(self._num_instances, 3), dtype=wp.float32, device=self.device) + self._lin_acc_b_ta = None + if self._lin_acc_b_ta is None: + self._lin_acc_b_ta = ProxyArray(self._lin_acc_b) + return self._lin_acc_b_ta + + @property + def ang_acc_b(self) -> ProxyArray: + """Angular acceleration in PVA body frame. Shape: (N, 3).""" + if self._ang_acc_b is None: + self._ang_acc_b = wp.zeros(shape=(self._num_instances, 3), dtype=wp.float32, device=self.device) + self._ang_acc_b_ta = None + if self._ang_acc_b_ta is None: + self._ang_acc_b_ta = ProxyArray(self._ang_acc_b) + return self._ang_acc_b_ta + + # -- Setters -- + + def set_pos_w(self, value: torch.Tensor) -> None: + """Set position in world frame.""" + self._pos_w = wp.from_torch(value.to(self.device).contiguous(), dtype=wp.float32) + self._pos_w_ta = None + + def set_quat_w(self, value: torch.Tensor) -> None: + """Set orientation in world frame.""" + self._quat_w = wp.from_torch(value.to(self.device).contiguous(), dtype=wp.float32) + self._quat_w_ta = None + + def set_projected_gravity_b(self, value: torch.Tensor) -> None: + """Set projected gravity in body frame.""" + self._projected_gravity_b = wp.from_torch(value.to(self.device).contiguous(), dtype=wp.float32) + self._projected_gravity_b_ta = None + + def set_lin_vel_b(self, value: torch.Tensor) -> None: + """Set linear velocity in body frame.""" + self._lin_vel_b = wp.from_torch(value.to(self.device).contiguous(), dtype=wp.float32) + self._lin_vel_b_ta = None + + def set_ang_vel_b(self, value: torch.Tensor) -> None: + """Set angular velocity in body frame.""" + self._ang_vel_b = wp.from_torch(value.to(self.device).contiguous(), dtype=wp.float32) + self._ang_vel_b_ta = None + + def set_lin_acc_b(self, value: torch.Tensor) -> None: + """Set linear acceleration in body frame.""" + self._lin_acc_b = wp.from_torch(value.to(self.device).contiguous(), dtype=wp.float32) + self._lin_acc_b_ta = None + + def set_ang_acc_b(self, value: torch.Tensor) -> None: + """Set angular acceleration in body frame.""" + self._ang_acc_b = wp.from_torch(value.to(self.device).contiguous(), dtype=wp.float32) + self._ang_acc_b_ta = None + + def set_mock_data( + self, + pos_w: torch.Tensor | None = None, + quat_w: torch.Tensor | None = None, + projected_gravity_b: torch.Tensor | None = None, + lin_vel_b: torch.Tensor | None = None, + ang_vel_b: torch.Tensor | None = None, + lin_acc_b: torch.Tensor | None = None, + ang_acc_b: torch.Tensor | None = None, + ) -> None: + """Bulk setter for mock data. + + Args: + pos_w: Position in world frame. Shape: (N, 3). + quat_w: Orientation (x, y, z, w) in world frame. Shape: (N, 4). + projected_gravity_b: Gravity direction in body frame. Shape: (N, 3). + lin_vel_b: Linear velocity in body frame. Shape: (N, 3). + ang_vel_b: Angular velocity in body frame. Shape: (N, 3). + lin_acc_b: Linear acceleration in body frame. Shape: (N, 3). + ang_acc_b: Angular acceleration in body frame. Shape: (N, 3). + """ + if pos_w is not None: + self.set_pos_w(pos_w) + if quat_w is not None: + self.set_quat_w(quat_w) + if projected_gravity_b is not None: + self.set_projected_gravity_b(projected_gravity_b) + if lin_vel_b is not None: + self.set_lin_vel_b(lin_vel_b) + if ang_vel_b is not None: + self.set_ang_vel_b(ang_vel_b) + if lin_acc_b is not None: + self.set_lin_acc_b(lin_acc_b) + if ang_acc_b is not None: + self.set_ang_acc_b(ang_acc_b) + + +class MockPva: + """Mock PVA sensor for testing without Isaac Sim. + + This class mimics the interface of BasePva for testing purposes. + It provides the same properties and methods but without simulation dependencies. + """ + + def __init__( + self, + num_instances: int, + device: str = "cpu", + ): + """Initialize mock PVA sensor. + + Args: + num_instances: Number of sensor instances. + device: Device for tensor allocation. + """ + self._num_instances = num_instances + self._device = device + self._data = MockPvaData(num_instances, device) + + # -- Properties -- + + @property + def data(self) -> MockPvaData: + """Data container for the sensor.""" + return self._data + + @property + def num_instances(self) -> int: + """Number of sensor instances.""" + return self._num_instances + + @property + def device(self) -> str: + """Device for tensor allocation.""" + return self._device + + # -- Methods -- + + def reset(self, env_ids: Sequence[int] | None = None) -> None: + """Reset sensor state for specified environments. + + Args: + env_ids: Environment indices to reset. If None, resets all. + """ + pass + + def update(self, dt: float, force_recompute: bool = False) -> None: + """Update sensor. + + Args: + dt: Time step since last update. + force_recompute: Force recomputation of buffers. + """ + pass diff --git a/source/isaaclab/isaaclab/test/mock_interfaces/utils/mock_generator.py b/source/isaaclab/isaaclab/test/mock_interfaces/utils/mock_generator.py index fb139fe1e1b7..830751b58c40 100644 --- a/source/isaaclab/isaaclab/test/mock_interfaces/utils/mock_generator.py +++ b/source/isaaclab/isaaclab/test/mock_interfaces/utils/mock_generator.py @@ -13,7 +13,7 @@ if TYPE_CHECKING: from ..assets import MockArticulation - from ..sensors import MockContactSensor, MockFrameTransformer, MockImu + from ..sensors import MockContactSensor, MockFrameTransformer, MockImu, MockPva class MockArticulationBuilder: @@ -223,9 +223,9 @@ def __init__(self, sensor_type: str): """Initialize the builder. Args: - sensor_type: Type of sensor ("contact", "imu", or "frame_transformer"). + sensor_type: Type of sensor ("contact", "imu", "pva", or "frame_transformer"). """ - if sensor_type not in ("contact", "imu", "frame_transformer"): + if sensor_type not in ("contact", "imu", "pva", "frame_transformer"): raise ValueError(f"Unknown sensor type: {sensor_type}") self._sensor_type = sensor_type self._num_instances = 1 @@ -311,7 +311,7 @@ def with_target_frames(self, frame_names: list[str]) -> MockSensorBuilder: self._target_frame_names = frame_names return self - def build(self) -> MockContactSensor | MockImu | MockFrameTransformer: + def build(self) -> MockContactSensor | MockImu | MockPva | MockFrameTransformer: """Build the mock sensor instance. Returns: @@ -336,6 +336,13 @@ def build(self) -> MockContactSensor | MockImu | MockFrameTransformer: num_instances=self._num_instances, device=self._device, ) + elif self._sensor_type == "pva": + from ..sensors import MockPva + + return MockPva( + num_instances=self._num_instances, + device=self._device, + ) elif self._sensor_type == "frame_transformer": from ..sensors import MockFrameTransformer diff --git a/source/isaaclab/isaaclab/test/mock_interfaces/utils/mock_wrench_composer.py b/source/isaaclab/isaaclab/test/mock_interfaces/utils/mock_wrench_composer.py index f35228ea6dcc..a20dbeb01274 100644 --- a/source/isaaclab/isaaclab/test/mock_interfaces/utils/mock_wrench_composer.py +++ b/source/isaaclab/isaaclab/test/mock_interfaces/utils/mock_wrench_composer.py @@ -11,6 +11,7 @@ from __future__ import annotations +import warnings from typing import TYPE_CHECKING import torch @@ -21,14 +22,16 @@ class MockWrenchComposer: - """Mock WrenchComposer for testing. + """Mock WrenchComposer matching the dual-buffer API for testing. This class provides a mock implementation of WrenchComposer that matches the real interface but does not launch Warp kernels. It can be used for testing and benchmarking asset classes without requiring the full simulation environment. - The mock maintains simple buffers and sets the active flag when forces/torques are added, - but does not perform actual force composition computations. + The mock maintains the 5 input buffers and 2 output buffers matching the real WrenchComposer, + and sets the active flag when forces/torques are added. The ``compose_to_body_frame()`` method + simply copies the local buffers to the output buffers (since mock assets typically use identity + transforms). """ def __init__(self, asset: BaseArticulation | BaseRigidObject | BaseRigidObjectCollection) -> None: @@ -44,15 +47,23 @@ def __init__(self, asset: BaseArticulation | BaseRigidObject | BaseRigidObjectCo raise ValueError(f"Unsupported asset type: {asset.__class__.__name__}") self.device = asset.device self._asset = asset - self._active = False - # Create buffers using Warp (matching real WrenchComposer) - self._composed_force_b = wp.zeros((self.num_envs, self.num_bodies), dtype=wp.vec3f, device=self.device) - self._composed_torque_b = wp.zeros((self.num_envs, self.num_bodies), dtype=wp.vec3f, device=self.device) + # -- Tracking flags -- + self._active: bool = False + self._dirty: bool = False - # Create torch views (matching real WrenchComposer) - self._composed_force_b_torch = wp.to_torch(self._composed_force_b) - self._composed_torque_b_torch = wp.to_torch(self._composed_torque_b) + shape = (self.num_envs, self.num_bodies) + + # -- 5 input buffers -- + self._global_force_w = wp.zeros(shape, dtype=wp.vec3f, device=self.device) + self._global_torque_w = wp.zeros(shape, dtype=wp.vec3f, device=self.device) + self._global_force_at_com_w = wp.zeros(shape, dtype=wp.vec3f, device=self.device) + self._local_force_b = wp.zeros(shape, dtype=wp.vec3f, device=self.device) + self._local_torque_b = wp.zeros(shape, dtype=wp.vec3f, device=self.device) + + # -- 2 output buffers -- + self._out_force_b = wp.zeros(shape, dtype=wp.vec3f, device=self.device) + self._out_torque_b = wp.zeros(shape, dtype=wp.vec3f, device=self.device) # Create index arrays self._ALL_ENV_INDICES_WP = wp.from_torch( @@ -64,46 +75,145 @@ def __init__(self, asset: BaseArticulation | BaseRigidObject | BaseRigidObjectCo self._ALL_ENV_INDICES_TORCH = wp.to_torch(self._ALL_ENV_INDICES_WP) self._ALL_BODY_INDICES_TORCH = wp.to_torch(self._ALL_BODY_INDICES_WP) + # ------------------------------------------------------------------ + # Properties + # ------------------------------------------------------------------ + @property def active(self) -> bool: - """Whether the wrench composer is active.""" + """Whether any forces or torques have been written since the last full reset.""" return self._active + # -- Input buffer accessors (read-only) -- + + @property + def global_force_w(self) -> wp.array: + """Positional global forces buffer. Shape ``(num_envs, num_bodies)``, dtype ``wp.vec3f``.""" + return self._global_force_w + + @property + def global_torque_w(self) -> wp.array: + """Global torques buffer (about world origin). Shape ``(num_envs, num_bodies)``, dtype ``wp.vec3f``.""" + return self._global_torque_w + + @property + def global_force_at_com_w(self) -> wp.array: + """Global forces at CoM buffer (no positional torque). Shape ``(num_envs, num_bodies)``, dtype ``wp.vec3f``.""" + return self._global_force_at_com_w + + @property + def local_force_b(self) -> wp.array: + """Body-frame forces buffer. Shape ``(num_envs, num_bodies)``, dtype ``wp.vec3f``.""" + return self._local_force_b + + @property + def local_torque_b(self) -> wp.array: + """Body-frame torques buffer. Shape ``(num_envs, num_bodies)``, dtype ``wp.vec3f``.""" + return self._local_torque_b + + # -- Output buffer accessors -- + + @property + def out_force_b(self) -> wp.array: + """Composed force in the body (link) frame. Shape ``(num_envs, num_bodies)``, dtype ``wp.vec3f``. + + Triggers composition from input buffers if dirty. + """ + self._ensure_composed() + return self._out_force_b + + @property + def out_torque_b(self) -> wp.array: + """Composed torque in the body (link) frame. Shape ``(num_envs, num_bodies)``, dtype ``wp.vec3f``. + + Triggers composition from input buffers if dirty. + """ + self._ensure_composed() + return self._out_torque_b + + # -- Legacy composed_force / composed_torque properties for backward compat -- + @property def composed_force(self) -> wp.array: """Composed force at the body's link frame. - Returns: - wp.array: Composed force at the body's link frame. (num_envs, num_bodies, 3) + .. deprecated:: 4.5.33 + Use :attr:`out_force_b` instead. """ - return self._composed_force_b + warnings.warn( + "The property 'composed_force' is deprecated. Use 'out_force_b' instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.out_force_b @property def composed_torque(self) -> wp.array: """Composed torque at the body's link frame. - Returns: - wp.array: Composed torque at the body's link frame. (num_envs, num_bodies, 3) + .. deprecated:: 4.5.33 + Use :attr:`out_torque_b` instead. """ - return self._composed_torque_b + warnings.warn( + "The property 'composed_torque' is deprecated. Use 'out_torque_b' instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.out_torque_b - @property - def composed_force_as_torch(self) -> torch.Tensor: - """Composed force at the body's link frame as torch tensor. + # ------------------------------------------------------------------ + # Composition + # ------------------------------------------------------------------ + + def compose_to_body_frame(self): + """Mock composition: sums all input buffers to output assuming identity transforms. - Returns: - torch.Tensor: Composed force at the body's link frame. (num_envs, num_bodies, 3) + Under identity transforms (no rotation), global-frame values equal body-frame values, + so all five input buffers are summed directly into the two output buffers. """ - return self._composed_force_b_torch + # Zero output buffers + self._out_force_b.zero_() + self._out_torque_b.zero_() - @property - def composed_torque_as_torch(self) -> torch.Tensor: - """Composed torque at the body's link frame as torch tensor. + # Use torch views for the accumulation + out_force_torch = wp.to_torch(self._out_force_b) + out_torque_torch = wp.to_torch(self._out_torque_b) + + # Sum all force contributions (identity: no rotation needed) + out_force_torch.add_(wp.to_torch(self._local_force_b)) + out_force_torch.add_(wp.to_torch(self._global_force_w)) + out_force_torch.add_(wp.to_torch(self._global_force_at_com_w)) - Returns: - torch.Tensor: Composed torque at the body's link frame. (num_envs, num_bodies, 3) + # Sum all torque contributions + out_torque_torch.add_(wp.to_torch(self._local_torque_b)) + out_torque_torch.add_(wp.to_torch(self._global_torque_w)) + + self._dirty = False + + # ------------------------------------------------------------------ + # Buffer merging + # ------------------------------------------------------------------ + + def add_raw_buffers_from(self, other: MockWrenchComposer): + """Element-wise add another composer's five input buffers into this one. + + Args: + other: Another :class:`MockWrenchComposer` whose input buffers will be added into this one. """ - return self._composed_torque_b_torch + # Use torch views for element-wise addition + wp.to_torch(self._global_force_w).add_(wp.to_torch(other._global_force_w)) + wp.to_torch(self._global_torque_w).add_(wp.to_torch(other._global_torque_w)) + wp.to_torch(self._global_force_at_com_w).add_(wp.to_torch(other._global_force_at_com_w)) + wp.to_torch(self._local_force_b).add_(wp.to_torch(other._local_force_b)) + wp.to_torch(self._local_torque_b).add_(wp.to_torch(other._local_torque_b)) + + if other._active: + self._active = True + self._dirty = True + + # ------------------------------------------------------------------ + # Add / Set methods + # ------------------------------------------------------------------ def add_forces_and_torques( self, @@ -172,9 +282,10 @@ def add_forces_and_torques_index( env_ids: torch.Tensor | None = None, is_global: bool = False, ) -> None: - """Add forces and torques by index (mock - just sets active flag).""" + """Add forces and torques by index (mock - sets active/dirty flags).""" if forces is not None or torques is not None: self._active = True + self._dirty = True def add_forces_and_torques_mask( self, @@ -185,9 +296,10 @@ def add_forces_and_torques_mask( env_mask: wp.array | torch.Tensor | None = None, is_global: bool = False, ) -> None: - """Add forces and torques by mask (mock - just sets active flag).""" + """Add forces and torques by mask (mock - sets active/dirty flags).""" if forces is not None or torques is not None: self._active = True + self._dirty = True def set_forces_and_torques_index( self, @@ -198,9 +310,10 @@ def set_forces_and_torques_index( env_ids: wp.array | torch.Tensor | None = None, is_global: bool = False, ) -> None: - """Set forces and torques by index (mock - just sets active flag).""" + """Set forces and torques by index (mock - sets active/dirty flags).""" if forces is not None or torques is not None: self._active = True + self._dirty = True def set_forces_and_torques_mask( self, @@ -211,28 +324,65 @@ def set_forces_and_torques_mask( env_mask: wp.array | torch.Tensor | None = None, is_global: bool = False, ) -> None: - """Set forces and torques by mask (mock - just sets active flag).""" + """Set forces and torques by mask (mock - sets active/dirty flags).""" if forces is not None or torques is not None: self._active = True + self._dirty = True + + # ------------------------------------------------------------------ + # Reset + # ------------------------------------------------------------------ def reset(self, env_ids: wp.array | torch.Tensor | None = None, env_mask: wp.array | None = None) -> None: - """Reset the composed force and torque. + """Reset all 7 buffers (5 input + 2 output) and clear all flags. Args: env_ids: Environment ids to reset. Defaults to None (all environments). env_mask: Environment mask to reset. Defaults to None (all environments). """ - if env_ids is None: - self._composed_force_b.zero_() - self._composed_torque_b.zero_() + if env_ids is None and env_mask is None: + # Full reset: zero all 7 buffers and clear flags + self._global_force_w.zero_() + self._global_torque_w.zero_() + self._global_force_at_com_w.zero_() + self._local_force_b.zero_() + self._local_torque_b.zero_() + self._out_force_b.zero_() + self._out_torque_b.zero_() self._active = False + self._dirty = False else: - # For partial reset, just zero the specified environments + # For partial reset, just zero the specified environments across all 7 buffers if isinstance(env_ids, torch.Tensor): indices = wp.from_torch(env_ids.to(torch.int32), dtype=wp.int32) elif isinstance(env_ids, list): indices = wp.array(env_ids, dtype=wp.int32, device=self.device) else: indices = env_ids - self._composed_force_b[indices].zero_() - self._composed_torque_b[indices].zero_() + + # Zero all 7 buffers for the specified environments + # Use torch views for the indexing operation + for buf in [ + self._global_force_w, + self._global_torque_w, + self._global_force_at_com_w, + self._local_force_b, + self._local_torque_b, + self._out_force_b, + self._out_torque_b, + ]: + buf_torch = wp.to_torch(buf) + if isinstance(env_ids, torch.Tensor): + buf_torch[env_ids.long()] = 0.0 + else: + idx_torch = wp.to_torch(indices).long() + buf_torch[idx_torch] = 0.0 + + # ------------------------------------------------------------------ + # Internal helpers + # ------------------------------------------------------------------ + + def _ensure_composed(self): + """Compose input buffers into output buffers if dirty.""" + if self._dirty: + self.compose_to_body_frame() diff --git a/source/isaaclab/isaaclab/test/mock_interfaces/utils/patching.py b/source/isaaclab/isaaclab/test/mock_interfaces/utils/patching.py index 15941ce51225..c330e932f070 100644 --- a/source/isaaclab/isaaclab/test/mock_interfaces/utils/patching.py +++ b/source/isaaclab/isaaclab/test/mock_interfaces/utils/patching.py @@ -81,7 +81,7 @@ def patch_sensor( Args: target: The target to patch (e.g., "my_module.ContactSensor"). - sensor_type: Type of sensor ("contact", "imu", or "frame_transformer"). + sensor_type: Type of sensor ("contact", "imu", "pva", or "frame_transformer"). num_instances: Number of sensor instances. device: Device for tensor allocation. **kwargs: Additional keyword arguments for the mock sensor. @@ -117,6 +117,15 @@ def create_mock(*args: Any, **create_kwargs: Any) -> MockImu: device=create_kwargs.get("device", device), ) + elif sensor_type == "pva": + from ..sensors import MockPva + + def create_mock(*args: Any, **create_kwargs: Any) -> MockPva: + return MockPva( + num_instances=create_kwargs.get("num_instances", num_instances), + device=create_kwargs.get("device", device), + ) + elif sensor_type == "frame_transformer": from ..sensors import MockFrameTransformer @@ -202,7 +211,7 @@ def mock_sensor( The mock sensor is passed as the first argument to the decorated function. Args: - sensor_type: Type of sensor ("contact", "imu", or "frame_transformer"). + sensor_type: Type of sensor ("contact", "imu", "pva", or "frame_transformer"). num_instances: Number of sensor instances. device: Device for tensor allocation. **kwargs: Additional keyword arguments for the mock sensor. @@ -239,6 +248,13 @@ def wrapper(*args: Any, **wrap_kwargs: Any) -> Any: num_instances=num_instances, device=device, ) + elif sensor_type == "pva": + from ..sensors import MockPva + + mock = MockPva( + num_instances=num_instances, + device=device, + ) elif sensor_type == "frame_transformer": from ..sensors import MockFrameTransformer diff --git a/source/isaaclab/isaaclab/utils/__init__.pyi b/source/isaaclab/isaaclab/utils/__init__.pyi index 84d6e8b7f098..e9f5e201ca21 100644 --- a/source/isaaclab/isaaclab/utils/__init__.pyi +++ b/source/isaaclab/isaaclab/utils/__init__.pyi @@ -46,6 +46,7 @@ __all__ = [ "string_to_callable", "ResolvableString", "resolve_matching_names", + "clear_resolve_matching_names_cache", "resolve_matching_names_values", "find_unique_string_name", "find_root_prim_path_from_regex", @@ -55,6 +56,7 @@ __all__ = [ "compare_versions", "configclass", "resolve_cfg_presets", + "checked_apply", ] from .timer import Timer @@ -98,10 +100,11 @@ from .string import ( string_to_callable, ResolvableString, resolve_matching_names, + clear_resolve_matching_names_cache, resolve_matching_names_values, find_unique_string_name, find_root_prim_path_from_regex, ) from .types import ArticulationActions from .version import has_kit, get_isaac_sim_version, compare_versions -from .configclass import configclass, resolve_cfg_presets +from .configclass import checked_apply, configclass, resolve_cfg_presets diff --git a/source/isaaclab/isaaclab/utils/backend_utils.py b/source/isaaclab/isaaclab/utils/backend_utils.py index 2e4ee55c62df..9f69a66aa04d 100644 --- a/source/isaaclab/isaaclab/utils/backend_utils.py +++ b/source/isaaclab/isaaclab/utils/backend_utils.py @@ -44,9 +44,11 @@ def _get_backend(cls, *args, **kwargs) -> str: from isaaclab.sim.simulation_context import SimulationContext manager_name = SimulationContext.instance().physics_manager.__name__.lower() - if "newton" in manager_name: + if manager_name.startswith("newton"): return "newton" - if "physx" in manager_name: + if manager_name.startswith("ovphysx"): + return "ovphysx" + if manager_name.startswith("physx"): return "physx" else: raise ValueError(f"Unknown physics manager: {manager_name}") diff --git a/source/isaaclab/isaaclab/utils/buffers/circular_buffer.py b/source/isaaclab/isaaclab/utils/buffers/circular_buffer.py index c5c9fe9ff6ad..c72907b176b3 100644 --- a/source/isaaclab/isaaclab/utils/buffers/circular_buffer.py +++ b/source/isaaclab/isaaclab/utils/buffers/circular_buffer.py @@ -11,10 +11,11 @@ class CircularBuffer: """Circular buffer for storing a history of batched tensor data. - This class implements a circular buffer for storing a history of batched tensor data. The buffer is - initialized with a maximum length and a batch size. The data is stored in a circular fashion, and the - data can be retrieved in a LIFO (Last-In-First-Out) fashion. The buffer is designed to be used in - multi-environment settings, where each environment has its own data. + This class stores a history of batched tensor data with the oldest entry at + index 0 and the most recent entry at index ``max_len - 1`` of the internal + buffer. The public indexing API remains LIFO (last-in-first-out), while the + ordered internal layout keeps ``buffer`` retrieval cheap and makes the + implementation compatible with tracing-based export flows. The shape of the appended data is expected to be (batch_size, ...), where the first dimension is the batch dimension. Correspondingly, the shape of the ring buffer is (max_len, batch_size, ...). @@ -42,8 +43,6 @@ def __init__(self, max_len: int, batch_size: int, device: str): self._max_len = torch.full((batch_size,), max_len, dtype=torch.int, device=device) # number of data pushes passed since the last call to :meth:`reset` self._num_pushes = torch.zeros(batch_size, dtype=torch.long, device=device) - # the pointer to the current head of the circular buffer (-1 means not initialized) - self._pointer: int = -1 # the actual buffer for data storage # note: this is initialized on the first call to :meth:`append` self._buffer: torch.Tensor = None # type: ignore @@ -80,14 +79,11 @@ def current_length(self) -> torch.Tensor: def buffer(self) -> torch.Tensor: """Complete circular buffer with most recent entry at the end and oldest entry at the beginning. - The shape of the buffer is (batch_size, max_length, ...). - - Note: - The oldest entry is at the beginning of dimension 1. + Returns: + Complete circular buffer with most recent entry at the end and oldest entry at the beginning of + dimension 1. The shape is [batch_size, max_length, data.shape[1:]]. """ - buf = self._buffer.clone() - buf = torch.roll(buf, shifts=self.max_length - self._pointer - 1, dims=0) - return torch.transpose(buf, dim0=0, dim1=1) + return torch.transpose(self._buffer, dim0=0, dim1=1) """ Operations. @@ -99,15 +95,17 @@ def reset(self, batch_ids: Sequence[int] | None = None): Args: batch_ids: Elements to reset in the batch dimension. Default is None, which resets all the batch indices. """ - # resolve all indices + batch_ids_resolved: Sequence[int] | slice if batch_ids is None: - batch_ids = slice(None) + batch_ids_resolved = slice(None) + else: + batch_ids_resolved = batch_ids # reset the number of pushes for the specified batch indices - self._num_pushes[batch_ids] = 0 + self._num_pushes[batch_ids_resolved] = 0 if self._buffer is not None: - # set buffer at batch_id reset indices to 0.0 so that the buffer() - # getter returns the cleared circular buffer after reset. - self._buffer[:, batch_ids, :] = 0.0 + # set buffer at batch_id reset indices to 0.0 so that the buffer() getter returns + # the cleared circular buffer after reset. + self._buffer[:, batch_ids_resolved] = 0.0 def append(self, data: torch.Tensor): """Append the data to the circular buffer. @@ -125,21 +123,19 @@ def append(self, data: torch.Tensor): # move the data to the device data = data.to(self._device) - # at the first call, initialize the buffer size - if self._buffer is None: - self._pointer = -1 - self._buffer = torch.empty((self.max_length, *data.shape), dtype=data.dtype, device=self._device) - # move the head to the next slot - self._pointer = (self._pointer + 1) % self.max_length - # add the new data to the last layer - self._buffer[self._pointer] = data - # Check for batches with zero pushes and initialize all values in batch to first append is_first_push = self._num_pushes == 0 + if self._buffer is None: + self._buffer = data.unsqueeze(0).expand(self.max_length, *data.shape).clone() if torch.any(is_first_push): self._buffer[:, is_first_push] = data[is_first_push] # increment number of number of pushes for all batches + self._append(data) self._num_pushes += 1 + def _append(self, data: torch.Tensor): + self._buffer = torch.roll(self._buffer, shifts=-1, dims=0) + self._buffer[-1] = data + def __getitem__(self, key: torch.Tensor) -> torch.Tensor: """Retrieve the data from the circular buffer in last-in-first-out (LIFO) fashion. @@ -160,13 +156,14 @@ def __getitem__(self, key: torch.Tensor) -> torch.Tensor: # check the batch size if len(key) != self.batch_size: raise ValueError(f"The argument 'key' has length {key.shape[0]}, while expecting {self.batch_size}") - # check if the buffer is empty - if torch.any(self._num_pushes == 0) or self._buffer is None: - raise RuntimeError("Attempting to retrieve data on an empty circular buffer. Please append data first.") - - # admissible lag - valid_keys = torch.minimum(key, self._num_pushes - 1) - # the index in the circular buffer (pointer points to the last+1 index) - index_in_buffer = torch.remainder(self._pointer - valid_keys, self.max_length) + if self._buffer is None: + raise RuntimeError("The buffer is empty. Please append data before retrieving.") + + # admissible lag — clamp to [0, ..] so batches with _num_pushes == 0 + # return the zeroed-out slot instead of indexing out of bounds. + valid_keys = torch.clamp(torch.minimum(key, self._num_pushes - 1), min=0) + # The buffer is stored oldest->newest along dimension 0, so the most + # recent item lives at the last index. + index_in_buffer = (self.max_length - 1 - valid_keys).to(dtype=torch.long) # return output return self._buffer[index_in_buffer, self._ALL_INDICES] diff --git a/source/isaaclab/isaaclab/utils/configclass.py b/source/isaaclab/isaaclab/utils/configclass.py index 7b0ed789bceb..59605f2797cc 100644 --- a/source/isaaclab/isaaclab/utils/configclass.py +++ b/source/isaaclab/isaaclab/utils/configclass.py @@ -5,6 +5,7 @@ """Sub-module that provides a wrapper around the Python 3.7 onwards ``dataclasses`` module.""" +import dataclasses import inspect import re import types @@ -633,3 +634,37 @@ def resolve_cfg_presets(cfg: object) -> object: else: resolve_cfg_presets(value) return cfg + + +def checked_apply(src: Any, target: Any) -> None: + """Forward every declared field on ``src`` (a dataclass) onto ``target``. + + Used by Isaac Lab configclasses that mirror an upstream/external dataclass + (for example, Newton's ``ShapeConfig``): declare the overridable fields + once on the wrapper, then forward them to the upstream object via this + helper instead of writing ``setattr`` lines per field. + + Raises :class:`AttributeError` if ``target`` is missing a field declared + on ``src``. The two structures must match — the check guards against + silent no-ops when the upstream API drifts (the bug class PR #5289 fixed + for Newton ``ShapeConfig.contact_margin`` → ``margin``). + + Args: + src: Dataclass instance whose declared fields will be forwarded. + Field names live here; this is the single source of truth. + target: Object to receive the field values. Must already expose + an attribute for every declared field on ``src``. + + Raises: + AttributeError: If ``target`` does not already have an attribute + matching one of ``src``'s declared field names. + """ + if not hasattr(src, "__dataclass_fields__"): + raise TypeError(f"checked_apply: src must be a dataclass, got {type(src).__name__}") + for f in dataclasses.fields(src): + if not hasattr(target, f.name): + target_path = f"{type(target).__module__}.{type(target).__name__}" + raise AttributeError( + f"{target_path} has no attribute `{f.name}`. {type(src).__name__} is out of sync with target." + ) + setattr(target, f.name, getattr(src, f.name)) diff --git a/source/isaaclab/isaaclab/utils/datasets/episode_data.py b/source/isaaclab/isaaclab/utils/datasets/episode_data.py index 55df8ebbcbe7..dcb4791457f5 100644 --- a/source/isaaclab/isaaclab/utils/datasets/episode_data.py +++ b/source/isaaclab/isaaclab/utils/datasets/episode_data.py @@ -3,11 +3,6 @@ # # SPDX-License-Identifier: BSD-3-Clause -# Copyright (c) 2024-2025, The Isaac Lab Project Developers. -# All rights reserved. -# -# SPDX-License-Identifier: BSD-3-Clause - from __future__ import annotations import torch @@ -90,7 +85,7 @@ def is_empty(self): """Check if the episode data is empty.""" return not bool(self._data) - def add(self, key: str, value: torch.Tensor | dict): + def add(self, key: str, value: torch.Tensor | dict, clone: bool = True): """Add a key-value pair to the dataset. The key can be nested by using the "/" character. @@ -99,13 +94,15 @@ def add(self, key: str, value: torch.Tensor | dict): Args: key: The key name. value: The corresponding value of tensor type or of dict type. + clone: Whether to clone the tensor value before storing it in the episode data. """ # check datatype if isinstance(value, dict): for sub_key, sub_value in value.items(): - self.add(f"{key}/{sub_key}", sub_value) + self.add(f"{key}/{sub_key}", sub_value, clone=clone) return + stored = value.clone() if (clone and isinstance(value, torch.Tensor)) else value sub_keys = key.split("/") current_dataset_pointer = self._data for sub_key_index in range(len(sub_keys)): @@ -113,9 +110,9 @@ def add(self, key: str, value: torch.Tensor | dict): # Add value to the final dict layer # Use lists to prevent slow tensor copy during concatenation if sub_keys[sub_key_index] not in current_dataset_pointer: - current_dataset_pointer[sub_keys[sub_key_index]] = [value.clone()] + current_dataset_pointer[sub_keys[sub_key_index]] = [stored] else: - current_dataset_pointer[sub_keys[sub_key_index]].append(value.clone()) + current_dataset_pointer[sub_keys[sub_key_index]].append(stored) break # key index if sub_keys[sub_key_index] not in current_dataset_pointer: diff --git a/source/isaaclab/isaaclab/utils/datasets/hdf5_dataset_file_handler.py b/source/isaaclab/isaaclab/utils/datasets/hdf5_dataset_file_handler.py index 281b681d8834..1977527b2cdf 100644 --- a/source/isaaclab/isaaclab/utils/datasets/hdf5_dataset_file_handler.py +++ b/source/isaaclab/isaaclab/utils/datasets/hdf5_dataset_file_handler.py @@ -3,11 +3,6 @@ # # SPDX-License-Identifier: BSD-3-Clause -# Copyright (c) 2024-2025, The Isaac Lab Project Developers. -# All rights reserved. -# -# SPDX-License-Identifier: BSD-3-Clause - from __future__ import annotations import json @@ -210,7 +205,7 @@ def load_dataset_helper(group, path=""): return episode - def write_episode(self, episode: EpisodeData, demo_id: int | None = None): + def write_episode(self, episode: EpisodeData, demo_id: int | None = None, dataset_compression: bool = True): """Add an episode to the dataset. Args: @@ -251,7 +246,10 @@ def create_dataset_helper(group, key, value): for sub_key, sub_value in value.items(): create_dataset_helper(key_group, sub_key, sub_value) else: - group.create_dataset(key, data=value.cpu().numpy(), compression="gzip") + if dataset_compression: + group.create_dataset(key, data=value.cpu().numpy(), compression="gzip", compression_opts=2) + else: + group.create_dataset(key, data=value.cpu().numpy()) for key, value in episode.data.items(): create_dataset_helper(h5_episode_group, key, value) diff --git a/source/isaaclab/isaaclab/utils/leapp/__init__.py b/source/isaaclab/isaaclab/utils/leapp/__init__.py new file mode 100644 index 000000000000..f39b0e4d7eea --- /dev/null +++ b/source/isaaclab/isaaclab/utils/leapp/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Sub-module for LEAPP export annotation and proxy-based policy tracing.""" + +from isaaclab.utils.module import lazy_export + +lazy_export() diff --git a/source/isaaclab/isaaclab/utils/leapp/__init__.pyi b/source/isaaclab/isaaclab/utils/leapp/__init__.pyi new file mode 100644 index 000000000000..e2b8f497b5f3 --- /dev/null +++ b/source/isaaclab/isaaclab/utils/leapp/__init__.pyi @@ -0,0 +1,61 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +__all__ = [ + "ExportPatcher", + "InputKindEnum", + "LeappTensorSemantics", + "OutputKindEnum", + "POSE6_ELEMENT_NAMES", + "POSE7_ELEMENT_NAMES", + "QUAT_XYZW_ELEMENT_NAMES", + "WRENCH6_ELEMENT_NAMES", + "XYZ_ELEMENT_NAMES", + "body_names_resolver", + "body_pose6_resolver", + "body_pose_resolver", + "body_quat_resolver", + "body_wrench_resolver", + "body_xyz_resolver", + "build_command_connection", + "build_state_connection", + "build_write_connection", + "joint_names_resolver", + "leapp_tensor_semantics", + "patch_env_for_export", + "resolve_leapp_element_names", + "target_frame_pose_resolver", + "target_frame_quat_resolver", + "target_frame_xyz_resolver", +] + +from .export_annotator import ExportPatcher, patch_env_for_export +from .leapp_semantics import ( + InputKindEnum, + OutputKindEnum, + POSE6_ELEMENT_NAMES, + POSE7_ELEMENT_NAMES, + QUAT_XYZW_ELEMENT_NAMES, + WRENCH6_ELEMENT_NAMES, + XYZ_ELEMENT_NAMES, + LeappTensorSemantics, + body_names_resolver, + body_pose6_resolver, + body_pose_resolver, + body_quat_resolver, + body_wrench_resolver, + body_xyz_resolver, + joint_names_resolver, + leapp_tensor_semantics, + resolve_leapp_element_names, + target_frame_pose_resolver, + target_frame_quat_resolver, + target_frame_xyz_resolver, +) +from .utils import ( + build_command_connection, + build_state_connection, + build_write_connection, +) diff --git a/source/isaaclab/isaaclab/utils/leapp/export_annotator.py b/source/isaaclab/isaaclab/utils/leapp/export_annotator.py new file mode 100644 index 000000000000..fb335811535a --- /dev/null +++ b/source/isaaclab/isaaclab/utils/leapp/export_annotator.py @@ -0,0 +1,708 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Export annotations for Isaac Lab policies using proxy-based patching. + +Observation and action annotation share a unified dedup cache so that a +state property (e.g. ``joint_pos``) read by both an observation term and +an action term resolves to one LEAPP input edge. + +- Observation term functions see an ``_EnvProxy`` whose scene returns + ``_EntityProxy`` objects with annotating data proxies. + +- Action terms have their ``_asset`` attribute replaced with an + _ArticulationWriteProxy that intercepts ``_leapp_semantics``-decorated + write methods **and** routes ``.data`` reads through the same annotating + data proxy used by observations. + +Cache lifecycle (assuming single-env play-mode export): + + compute() clear cache → obs terms populate cache + policy inference TracedTensors propagate through NN + process_action() register_buffer for raw_actions + apply_action() [tracing] reuse cached TracedTensors for state reads, + capture write outputs, call output_tensors(), + then clear cache + apply_action() [decim.] clear cache → fresh reads for simulation + ... + compute() clear cache → fresh reads for next obs +""" + +from __future__ import annotations + +import inspect +import logging +from collections.abc import Callable +from contextlib import suppress +from typing import TYPE_CHECKING, Any + +import torch +from leapp import annotate +from leapp.utils.tensor_description import TensorSemantics + +from isaaclab.assets.articulation.base_articulation import BaseArticulation +from isaaclab.managers import ManagerTermBase + +from .leapp_semantics import select_element_names +from .proxy import _ArticulationWriteProxy, _DataProxy, _EnvProxy, _ManagerTermProxy +from .utils import ( + TracedProxyArray, + build_command_connection, + build_write_connection, +) + +if TYPE_CHECKING: + from isaaclab.envs import ManagerBasedEnv + + +VARIABLE_IMPEDANCE_MODES = frozenset({"variable", "variable_kp"}) + + +# ══════════════════════════════════════════════════════════════════ +# ExportPatcher +# ══════════════════════════════════════════════════════════════════ + + +class ExportPatcher: + """Unified patcher that annotates observation inputs and action outputs for LEAPP export. + + Observation-side property semantics are resolved lazily inside + ``_DataProxy`` by combining: + + - the concrete runtime getter from the backend data class + - the nearest ``_leapp_semantics`` metadata found while walking the MRO + + This lets backends override property implementations without duplicating + decorators from the abstract API. + + - The observation proxy chain (``_EnvProxy`` → ``_SceneProxy`` → + ``_EntityProxy`` → ``_DataProxy``) for state reads + by observation term functions. + - The ``_ArticulationWriteProxy`` on each action term, which intercepts + target writes **and** routes ``.data`` reads through the same + ``_DataProxy`` / cache. + + """ + + def __init__(self, export_method: str, required_obs_groups: set[str] | None = None): + """Initialize the export patcher. + + Args: + export_method: LEAPP export backend passed to + :func:`annotate.output_tensors`. + required_obs_groups: Observation groups that should be patched, or + ``None`` to patch all groups. + """ + self.task_name: str | None = None + self.export_method = export_method + self.required_obs_groups = required_obs_groups + self._annotated_tensor_cache: dict[tuple[int, str], TracedProxyArray] = {} + self._data_property_resolution_cache: dict[tuple[type, str], tuple[Callable, object] | None] = {} + self._write_method_resolution_cache: dict[ + tuple[type, str], tuple[Callable, object, inspect.Signature] | None + ] = {} + self._action_output_cache: list[TensorSemantics] = [] + self._captured_write_term_names: set[str] = set() + self._fallback_term_names: set[str] = set() + self._pending_action_output_export: bool = False + self._uses_last_action_state: bool = False + self._action_term_scene_keys: dict[str, str] = {} + + def setup(self, env): + """Patch the environment in place for LEAPP-aware export. + + Args: + env: Wrapped manager-based environment whose unwrapped instance + should be patched. + """ + unwrapped = env.env.unwrapped + task_name = str(unwrapped.spec.id) + self.task_name = task_name + + proxy_env = _EnvProxy( + unwrapped, + task_name, + self._data_property_resolution_cache, + self._annotated_tensor_cache, + ) + + self._disable_training_managers(unwrapped) + self._patch_observation_manager(unwrapped.observation_manager, proxy_env) + self._patch_history_buffers(unwrapped.observation_manager) + self._patch_action_manager( + unwrapped.action_manager, + self._annotated_tensor_cache, + ) + + # ── Disable training-only managers ───────────────────────────── + + @staticmethod + def _disable_training_managers(unwrapped): + """Replace training-only manager methods with no-ops. + + During export the curriculum, reward, termination, and recorder + managers serve no purpose. Disabling them avoids side-effect + crashes (e.g. ADR curriculum terms accessing nullified noise + configs) and removes unnecessary computation. + + Args: + unwrapped: Unwrapped environment whose training-only managers + should be disabled. + """ + num_envs = unwrapped.num_envs + device = unwrapped.device + _zero_reward = torch.zeros(num_envs, device=device) + _no_termination = torch.zeros(num_envs, dtype=torch.bool, device=device) + + def _noop_curriculum(env_ids=None): + return None + + def _zero_reward_compute(dt): + return _zero_reward + + def _no_termination_compute(): + return _no_termination + + def _noop(*args, **kwargs): + return None + + if hasattr(unwrapped, "curriculum_manager"): + unwrapped.curriculum_manager.compute = _noop_curriculum + + if hasattr(unwrapped, "reward_manager"): + unwrapped.reward_manager.compute = _zero_reward_compute + + if hasattr(unwrapped, "termination_manager"): + unwrapped.termination_manager.compute = _no_termination_compute + + if hasattr(unwrapped, "recorder_manager"): + rm = unwrapped.recorder_manager + + rm.record_pre_step = _noop + rm.record_post_step = _noop + rm.record_pre_reset = _noop + rm.record_post_reset = _noop + rm.record_post_physics_decimation_step = _noop + + @staticmethod + def _resolve_scene_entity_key(scene, entity: Any) -> str | None: + """Return the scene dictionary key for an entity. + + Args: + scene: Scene object that stores entity dictionaries. + entity: Entity instance to locate. + + Returns: + The scene key for ``entity`` if found, otherwise ``None``. + """ + for attr_value in vars(scene).values(): + if not isinstance(attr_value, dict): + continue + for key, candidate in attr_value.items(): + if candidate is entity: + return key + return None + + # ── Observation manager patches ─────────────────────────────── + + def _patch_history_buffers(self, obs_manager): + """Patch history-enabled observation buffers to export as LEAPP state. + + Args: + obs_manager: Observation manager whose history buffers should be + wrapped. + """ + history_buffers = getattr(obs_manager, "_group_obs_term_history_buffer", {}) + term_names_by_group = getattr(obs_manager, "_group_obs_term_names", {}) + + for group_name, term_cfgs in obs_manager._group_obs_term_cfgs.items(): + if self.required_obs_groups is not None and group_name not in self.required_obs_groups: + continue + group_buffers = history_buffers.get(group_name, {}) + group_term_names = term_names_by_group.get(group_name, []) + + for index, term_cfg in enumerate(term_cfgs): + history_length = getattr(term_cfg, "history_length", 0) or 0 + if history_length <= 0: + continue + + if index >= len(group_term_names): + continue + + term_name = group_term_names[index] + circular_buffer = group_buffers.get(term_name) + if circular_buffer is None: + continue + + state_name = f"h_{group_name}_{term_name}" + self._patch_history_buffer_append(circular_buffer, state_name) + + def _patch_history_buffer_append(self, circular_buffer, state_name: str): + """Wrap ``_append`` so history buffers become explicit LEAPP state. + + Args: + circular_buffer: Circular buffer instance to patch. + state_name: LEAPP state tensor name for the buffer contents. + """ + if hasattr(circular_buffer, "_leapp_original_append"): + return + + task_name = self.task_name + original_append = circular_buffer._append + + def patched_append(data: torch.Tensor): + """Annotate history buffer updates as LEAPP state transitions. + + Args: + data: New observation slice appended to the buffer. + + Returns: + ``None``. + """ + if circular_buffer._buffer is not None: + circular_buffer._buffer = annotate.state_tensors(task_name, {state_name: circular_buffer._buffer}) + + original_append(data) + + if circular_buffer._buffer is not None: + circular_buffer._buffer = annotate.update_state(task_name, {state_name: circular_buffer._buffer}) + + circular_buffer._leapp_original_append = original_append + circular_buffer._append = patched_append + + def _patch_observation_manager(self, obs_manager, proxy_env): + """Patch observation terms to use annotating proxies and disable noise. + + Args: + obs_manager: Observation manager instance to patch. + proxy_env: Proxy environment routed into observation terms. + """ + for group_name, term_cfgs in obs_manager._group_obs_term_cfgs.items(): + if self.required_obs_groups is not None and group_name not in self.required_obs_groups: + continue + for term_cfg in term_cfgs: + original_func = term_cfg.func + func_name = getattr(original_func, "__name__", None) + + if func_name == "last_action": + self._uses_last_action_state = True + term_cfg.func = self._wrap_last_action(original_func) + elif func_name == "generated_commands": + term_cfg.func = self._wrap_generated_commands(original_func, term_cfg) + else: + term_cfg.func = self._wrap_with_proxy(original_func, proxy_env) + + term_cfg.noise = None + + original_compute = obs_manager.compute + cache = self._annotated_tensor_cache + + def patched_compute(*args, **kwargs): + """Clear the tensor dedup cache once per full observation pass.""" + cache.clear() + return original_compute(*args, **kwargs) + + obs_manager.compute = patched_compute + + # ── Action manager patches ──────────────────────────────────── + + def _patch_action_manager(self, action_manager, cache): + """Patch action terms with write/read proxies and manager hooks. + + Args: + action_manager: Action manager instance to patch. + cache: Shared tensor dedup cache for annotated state reads. + """ + assert self.task_name is not None + scene = action_manager._env.scene + for term_name, term in action_manager._terms.items(): + asset = getattr(term, "_asset", None) + if isinstance(asset, BaseArticulation): + real_asset: BaseArticulation = asset + scene_key = self._resolve_scene_entity_key(scene, real_asset) or "ego" + data_proxy = _DataProxy( + real_asset.data, + scene_key, + self.task_name, + self._data_property_resolution_cache, + cache, + input_name_resolver=lambda prop_name, k=scene_key: f"{k}_{prop_name}", + ) + term._asset = _ArticulationWriteProxy( + real_asset=real_asset, + entity_name=scene_key, + term_name=term_name, + output_cache=self._action_output_cache, + method_resolution_cache=self._write_method_resolution_cache, + captured_write_term_names=self._captured_write_term_names, + data_proxy=data_proxy, + ) + self._action_term_scene_keys[term_name] = scene_key + + self._patch_action_manager_methods(action_manager) + + def _patch_action_manager_methods(self, action_manager): + """Patch ``process_action`` and ``apply_action`` on the action manager instance. + + ``process_action`` registers raw_action buffers for LEAPP tracing and + preserves the action tensor clone. + + ``apply_action`` coordinates the cache and output lifecycle: + + - **Tracing pass** (first ``apply_action`` after ``process_action``): + The cache still holds TracedTensors populated by ``compute_group``. + Action terms that read state (e.g. ``RelativeJointPositionAction`` + reading ``joint_pos``) get those TracedTensors from the cache, + keeping the LEAPP graph connected. After ``output_tensors()`` the + cache is cleared so subsequent decimation sub-steps read fresh values. + + - **Non-tracing passes** (remaining decimation sub-steps and all + subsequent iterations): The cache is cleared **before** running + action terms so every ``.data`` read returns the current simulator + value, preserving simulation correctness. + + Args: + action_manager: Action manager whose instance methods should be + wrapped. + """ + original_process = action_manager.process_action + original_apply = action_manager.apply_action + task_name = self.task_name + cache = self._annotated_tensor_cache + + def patched_process_action(action: torch.Tensor): + """Register raw_action buffers, call real process_action, preserve action clone.""" + original_process(action) + action_manager._action = action.clone() + self._pending_action_output_export = True + + def patched_apply_action(): + """Coordinate cache lifecycle and LEAPP output annotation.""" + if not self._pending_action_output_export: + cache.clear() + return original_apply() + + # Tracing pass: cache still holds TracedTensors from compute_group. + self._action_output_cache.clear() + self._captured_write_term_names.clear() + original_apply() + + self._action_output_cache.extend(self._collect_action_outputs(action_manager)) + self._action_output_cache.extend(self._collect_processed_action_fallbacks(action_manager)) + if self._uses_last_action_state: + annotate.update_state(task_name, {"last_action": action_manager._action}) + fallback_terms = self._fallback_term_names + static_values = self._collect_action_static_outputs(action_manager, fallback_terms) + annotate.output_tensors( + task_name, + self._action_output_cache, + static_outputs=static_values or None, + export_with=self.export_method, + ) + self._pending_action_output_export = False + self._action_output_cache.clear() + cache.clear() + return None + + action_manager.process_action = patched_process_action + action_manager.apply_action = patched_apply_action + + # ── Observation term wrappers ───────────────────────────────── + + @staticmethod + def _wrap_with_proxy(original_func, proxy_env): + """Wrap a term function so it receives the proxy env. + + Args: + original_func: Original observation term function or manager term. + proxy_env: Proxy environment routed into the wrapped callable. + + Returns: + Wrapped callable that substitutes ``proxy_env`` for the real env. + """ + + if isinstance(original_func, ManagerTermBase): + return _ManagerTermProxy(original_func, proxy_env) + + def wrapped(*args, **kwargs): + """Invoke the original function with the proxy environment. + + Args: + *args: Original positional arguments. + **kwargs: Original keyword arguments. + + Returns: + Result of the wrapped observation term. + """ + if args: + args = (proxy_env, *args[1:]) + else: + args = (proxy_env,) + return original_func(*args, **kwargs) + + wrapped.__name__ = getattr(original_func, "__name__", "unknown") + return wrapped + + def _wrap_last_action(self, original_func): + """Wrap ``last_action`` as a LEAPP state tensor. + + ``last_action`` is feedback state, not a regular dangling input. We + therefore register it through ``annotate.state_tensors(...)`` on the + observation side and update it through ``annotate.update_state(...)`` + after the traced action pass. + + Args: + original_func: Original ``last_action`` observation term. + + Returns: + Wrapped callable that exports ``last_action`` as LEAPP state. + """ + task_name = self.task_name + + def wrapped(env, action_name=None, **kwargs): + """Run the wrapped ``last_action`` term and annotate its output. + + Args: + env: Environment passed by the observation manager. + action_name: Optional action term name. + **kwargs: Additional keyword arguments for the term. + + Returns: + Annotated last-action tensor. + """ + result = original_func(env, action_name, **kwargs) + return annotate.state_tensors(task_name, {"last_action": result}) + + wrapped.__name__ = original_func.__name__ + return wrapped + + def _wrap_generated_commands(self, original_func, term_cfg): + """Wrap the ``generated_commands`` observation term to annotate its output as a LEAPP input. + + Resolves command semantics (kind, element_names) from the command manager + configuration when available. + + Args: + original_func: Original ``generated_commands`` observation term. + term_cfg: Observation term config used to resolve the command name. + + Returns: + Wrapped callable that exports generated commands as LEAPP inputs. + """ + task_name = self.task_name + command_name_from_cfg = term_cfg.params.get("command_name") + + def wrapped(env, command_name=None, **kwargs): + """Run the wrapped command term and annotate its output. + + Args: + env: Environment passed by the observation manager. + command_name: Optional command term name override. + **kwargs: Additional keyword arguments for the term. + + Returns: + Annotated command tensor. + """ + result = original_func(env, command_name, **kwargs) + leapp_input_name = command_name or command_name_from_cfg or "commands" + command_cfg = None + with suppress(AttributeError, KeyError): + command_cfg = env.command_manager.get_term(leapp_input_name).cfg + sem = TensorSemantics( + name=leapp_input_name, + ref=result, + kind=getattr(command_cfg, "cmd_kind", None), + element_names=getattr(command_cfg, "element_names", None), + extra=build_command_connection(leapp_input_name), + ) + return annotate.input_tensors(task_name, sem) + + wrapped.__name__ = original_func.__name__ + return wrapped + + # ── Output collection ───────────────────────────────────────── + + def _collect_action_outputs(self, action_manager) -> list[TensorSemantics]: + """Collect non-writer action tensors that should be exported. + + Args: + action_manager: Action manager whose terms should be inspected. + + Returns: + Exportable tensor semantics for dynamic action outputs such as OSC + gains. + """ + tensors: list[TensorSemantics] = [] + for term_name, term in action_manager._terms.items(): + osc = getattr(term, "_osc", None) + if osc and hasattr(osc, "cfg") and osc.cfg.impedance_mode in VARIABLE_IMPEDANCE_MODES: + asset = getattr(term, "_asset", None) + real_asset = getattr(asset, "_real_asset", asset) + joint_ids = getattr(term, "_joint_ids", None) + joint_names = getattr(real_asset, "joint_names", None) if real_asset else None + scene_key = self._action_term_scene_keys.get(term_name, "ego") + tensors.append( + TensorSemantics( + name=f"{term_name}_kp_gains", + ref=torch.diagonal(osc._motion_p_gains_task, dim1=-2, dim2=-1), + kind="kp", + element_names=select_element_names(joint_names, joint_ids), + extra=build_write_connection(scene_key, "write_joint_stiffness_to_sim_index"), + ) + ) + tensors.append( + TensorSemantics( + name=f"{term_name}_kd_gains", + ref=torch.diagonal(osc._motion_d_gains_task, dim1=-2, dim2=-1), + kind="kd", + element_names=select_element_names(joint_names, joint_ids), + extra=build_write_connection(scene_key, "write_joint_damping_to_sim_index"), + ) + ) + return tensors + + def _collect_processed_action_fallbacks(self, action_manager) -> list[TensorSemantics]: + """Fallback: use ``term.processed_actions`` for terms that produced no write outputs. + + When an action term does not call any ``_leapp_semantics``-decorated write method + (e.g. ``PreTrainedPolicyAction`` which delegates writes to a nested sub-policy), + we fall back to capturing ``term.processed_actions`` as the output tensor. + + Args: + action_manager: Action manager whose terms should be inspected. + + Returns: + Fallback tensor semantics built from ``processed_actions``. + """ + logger = logging.getLogger(__name__) + fallback_terms: set[str] = set() + tensors: list[TensorSemantics] = [] + for term_name, term in action_manager._terms.items(): + if term_name in self._captured_write_term_names: + continue + processed = getattr(term, "processed_actions", None) + if processed is None: + continue + if isinstance(processed, torch.Tensor): + logger.warning( + "Action term '%s' did not write to any asset directly. Falling back to processed_actions as the" + " export output.\nIf you wish to add semantic data to this policy, you need to manually annotate it" + " with output_tensors.", + term_name, + ) + tensors.append( + TensorSemantics( + name=term_name, + ref=processed.clone(), + kind=None, + element_names=None, + ) + ) + fallback_terms.add(term_name) + self._fallback_term_names = fallback_terms + return tensors + + def _collect_action_static_outputs( + self, action_manager, skip_terms: set[str] | None = None + ) -> list[TensorSemantics]: + """Collect static kp/kd gain values from action terms for export metadata. + + Terms in ``skip_terms`` are excluded — these are terms that fell back + to ``processed_actions`` and whose static gains (kp/kd) belong to a + lower abstraction level that is not part of the exported policy. + + Args: + action_manager: Action manager whose terms should be inspected. + skip_terms: Action term names whose static outputs should be + skipped. + + Returns: + Static tensor semantics for action gains exported as metadata. + """ + static_values: list[TensorSemantics] = [] + for term_name, term in action_manager._terms.items(): + if skip_terms and term_name in skip_terms: + continue + osc = getattr(term, "_osc", None) + if osc and hasattr(osc, "cfg") and osc.cfg.impedance_mode in VARIABLE_IMPEDANCE_MODES: + continue + asset = getattr(term, "_asset", None) + real_asset = getattr(asset, "_real_asset", asset) + if real_asset and hasattr(real_asset, "data"): + data = real_asset.data + joint_ids = getattr(term, "_joint_ids", None) + joint_names = getattr(real_asset, "joint_names", None) + scene_key = self._action_term_scene_keys.get(term_name, "ego") + if hasattr(data, "default_joint_stiffness") and data.default_joint_stiffness is not None: + gains = data.default_joint_stiffness.torch + static_values.append( + TensorSemantics( + name=f"{term_name}_kp_gains", + ref=gains[:, joint_ids] if joint_ids else gains, + kind="kp", + element_names=select_element_names(joint_names, joint_ids), + extra=build_write_connection(scene_key, "write_joint_stiffness_to_sim_index"), + ) + ) + if hasattr(data, "default_joint_damping") and data.default_joint_damping is not None: + gains = data.default_joint_damping.torch + static_values.append( + TensorSemantics( + name=f"{term_name}_kd_gains", + ref=gains[:, joint_ids] if joint_ids else gains, + kind="kd", + element_names=select_element_names(joint_names, joint_ids), + extra=build_write_connection(scene_key, "write_joint_damping_to_sim_index"), + ) + ) + return static_values + + +# ══════════════════════════════════════════════════════════════════ +# Public entry point +# ══════════════════════════════════════════════════════════════════ + + +def patch_env_for_export( + env: ManagerBasedEnv, + export_method: str, + required_obs_groups: set[str] | None = None, +) -> None: + """Patch the env's observation and action managers for LEAPP export. + + This is a thin public entry point around ``ExportPatcher``. It mutates + the provided env instance in-place so that: + + - Observation terms route through proxy objects that annotate tensor + reads from **any** scene entity data class (articulations, rigid + objects, sensors, etc.). + - Action terms route through proxy objects that annotate both data + reads **and** ``Articulation`` write methods. + + Data properties are resolved lazily through proxies — no hardcoded + class list is required. To produce LEAPP input annotations, the + accessed data property getter must carry ``_leapp_semantics``. + Likewise, action-side write methods must be annotated to produce + semantic LEAPP outputs. Undecorated reads and writes are forwarded + as normal runtime access, but they do not gain semantic annotation + metadata through this patching path. + + State reads are deduplicated across observation and action paths via a + shared cache, so a property like ``joint_pos`` that is read by both an + observation term and a relative-position action term appears as a single + LEAPP input edge. + + The underlying env, scene, assets, and tensors remain shared with the rest + of the pipeline; only the manager call paths are redirected. + + Args: + env: Manager-based environment to patch in place. + export_method: LEAPP export backend passed to + :func:`annotate.output_tensors`. + required_obs_groups: Observation groups that should be patched, or + ``None`` to patch all groups. + """ + patcher = ExportPatcher(export_method, required_obs_groups=required_obs_groups) + patcher.setup(env) diff --git a/source/isaaclab/isaaclab/utils/leapp/leapp_semantics.py b/source/isaaclab/isaaclab/utils/leapp/leapp_semantics.py new file mode 100644 index 000000000000..340291de16ad --- /dev/null +++ b/source/isaaclab/isaaclab/utils/leapp/leapp_semantics.py @@ -0,0 +1,145 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""LEAPP semantic metadata helpers for raw tensor-producing functions.""" + +from __future__ import annotations + +from collections.abc import Callable +from contextlib import suppress +from dataclasses import dataclass +from typing import Any + +try: + from leapp import InputKindEnum, OutputKindEnum +except ImportError: + + class _LeappEnumSentinel: + """Stand-in when leapp is not installed. + + Any attribute access returns ``None`` so that + ``@leapp_tensor_semantics(kind=InputKindEnum.BODY_POSE)`` + silently stores ``kind=None`` instead of crashing at import time. + The real enum values are only needed at export time, when leapp + *is* guaranteed to be available. + """ + + def __getattr__(self, name: str): + return None + + InputKindEnum = _LeappEnumSentinel() # type: ignore[assignment,misc] + OutputKindEnum = _LeappEnumSentinel() # type: ignore[assignment,misc] + + +@dataclass(frozen=True) +class LeappTensorSemantics: + """Semantic metadata attached directly to a raw tensor-producing function.""" + + kind: Any = None + element_names: list[str] | list[list[str]] | None = None + element_names_resolver: Callable | None = None + const: bool = False + + +XYZ_ELEMENT_NAMES: list[str] = ["x", "y", "z"] +QUAT_XYZW_ELEMENT_NAMES: list[str] = ["qx", "qy", "qz", "qw"] +POSE7_ELEMENT_NAMES: list[str] = ["x", "y", "z", "qx", "qy", "qz", "qw"] +POSE6_ELEMENT_NAMES: list[str] = ["x", "y", "z", "angular_x", "angular_y", "angular_z"] +WRENCH6_ELEMENT_NAMES: list[str] = ["fx", "fy", "fz", "tx", "ty", "tz"] + + +def select_element_names(names: list[str] | None, indices: Any = None) -> list[str] | None: + """Select element names using optional runtime indices.""" + if names is None: + return None + if indices is None or indices == slice(None): + return list(names) + if isinstance(indices, slice): + return list(names[indices]) + with suppress(AttributeError): + indices = indices.tolist() + if isinstance(indices, (list, tuple)): + return [names[int(index)] for index in indices] + if isinstance(indices, int): + return [names[indices]] + return None + + +def leapp_tensor_semantics( + *, + kind: Any = None, + element_names: list[str] | list[list[str]] | None = None, + element_names_resolver: Callable | None = None, + const: bool = False, +) -> Callable: + """Attach LEAPP semantic metadata to a raw tensor-producing function.""" + + semantics = LeappTensorSemantics( + kind=kind, + element_names=element_names, + element_names_resolver=element_names_resolver, + const=const, + ) + + def _apply(func: Callable) -> Callable: + func._leapp_semantics = semantics + return func + + return _apply + + +def resolve_leapp_element_names(semantics: LeappTensorSemantics | None, data_self) -> list | None: + """Resolve element names from attached semantics and a tensor-producing object.""" + if semantics is None: + return None + if semantics.element_names is not None: + return semantics.element_names + if semantics.element_names_resolver is not None: + return semantics.element_names_resolver(data_self) + return None + + +# ── Predefined element-name resolvers ───────────────────────────── + + +def joint_names_resolver(data_self) -> list[str] | None: + """Resolve joint element names from the data object at trace time.""" + return select_element_names( + getattr(data_self, "joint_names", getattr(data_self, "_joint_names", None)), + getattr(data_self, "_joint_ids", None), + ) + + +def body_names_resolver(data_self) -> list[str] | None: + """Resolve body element names from the data object at trace time.""" + return select_element_names( + getattr(data_self, "body_names", getattr(data_self, "_body_names", None)), + getattr(data_self, "_body_ids", None), + ) + + +def _compound_resolver(outer_fn: Callable, inner_names: list[str]) -> Callable: + """Build a 2D resolver: ``[outer_names, inner_constant_names]``.""" + + def resolver(data_self) -> list | None: + outer = outer_fn(data_self) + return [outer, inner_names] if outer else None + + return resolver + + +def _target_frame_names(data_self) -> list[str] | None: + names = getattr(data_self, "target_frame_names", None) + return list(names) if names is not None else None + + +body_xyz_resolver = _compound_resolver(body_names_resolver, XYZ_ELEMENT_NAMES) +body_pose_resolver = _compound_resolver(body_names_resolver, POSE7_ELEMENT_NAMES) +body_pose6_resolver = _compound_resolver(body_names_resolver, POSE6_ELEMENT_NAMES) +body_quat_resolver = _compound_resolver(body_names_resolver, QUAT_XYZW_ELEMENT_NAMES) +body_wrench_resolver = _compound_resolver(body_names_resolver, WRENCH6_ELEMENT_NAMES) +target_frame_xyz_resolver = _compound_resolver(_target_frame_names, XYZ_ELEMENT_NAMES) +target_frame_quat_resolver = _compound_resolver(_target_frame_names, QUAT_XYZW_ELEMENT_NAMES) +target_frame_pose_resolver = _compound_resolver(_target_frame_names, POSE7_ELEMENT_NAMES) diff --git a/source/isaaclab/isaaclab/utils/leapp/proxy.py b/source/isaaclab/isaaclab/utils/leapp/proxy.py new file mode 100644 index 000000000000..49ef86e7265f --- /dev/null +++ b/source/isaaclab/isaaclab/utils/leapp/proxy.py @@ -0,0 +1,521 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from __future__ import annotations + +import inspect +from collections.abc import Callable +from typing import Any, cast + +import torch +from leapp.utils.tensor_description import TensorSemantics + +from isaaclab.managers import ManagerTermBase +from isaaclab.utils.warp.proxy_array import ProxyArray + +from .leapp_semantics import resolve_leapp_element_names +from .utils import TracedProxyArray, build_write_connection + + +def _resolve_annotated_property( + property_resolution_cache: dict[tuple[type, str], tuple[Callable, Any] | None], + real_data: Any, + name: str, +) -> tuple[Callable, Any] | None: + """Resolve a concrete property getter and inherited semantics metadata. + + The execution getter always comes from the concrete runtime class. Semantic + metadata is resolved independently by walking the MRO until a property + definition with ``_leapp_semantics`` is found. This mirrors the output-side + export path, where semantics are authored on the base API while concrete + backends provide the runtime implementation. + """ + cache_key = (type(real_data), name) + if cache_key in property_resolution_cache: + return property_resolution_cache[cache_key] + + execution_prop = getattr(type(real_data), name, None) + if not isinstance(execution_prop, property) or execution_prop.fget is None: + property_resolution_cache[cache_key] = None + return None + + semantics_meta = None + for data_cls in type(real_data).__mro__: + prop = data_cls.__dict__.get(name) + if not isinstance(prop, property) or prop.fget is None: + continue + candidate = getattr(prop.fget, "_leapp_semantics", None) + if candidate is None: + continue + if getattr(candidate, "const", False): + property_resolution_cache[cache_key] = None + return None + semantics_meta = candidate + break + + if semantics_meta is None: + property_resolution_cache[cache_key] = None + return None + + resolution = (execution_prop.fget, semantics_meta) + property_resolution_cache[cache_key] = resolution + return resolution + + +def _resolve_annotated_method( + method_resolution_cache: dict[tuple[type, str], tuple[Callable, Any, inspect.Signature] | None], + real_asset: Any, + name: str, +) -> tuple[Callable, Any, inspect.Signature] | None: + """Resolve a concrete bound method and inherited semantics metadata.""" + cache_key = (type(real_asset), name) + if cache_key in method_resolution_cache: + return method_resolution_cache[cache_key] + + original_method = getattr(real_asset, name, None) + if not callable(original_method): + method_resolution_cache[cache_key] = None + return None + + for asset_cls in type(real_asset).__mro__: + candidate = asset_cls.__dict__.get(name) + if not callable(candidate): + continue + semantics_meta = getattr(candidate, "_leapp_semantics", None) + if semantics_meta is None: + continue + resolution = (original_method, semantics_meta, inspect.signature(candidate)) + method_resolution_cache[cache_key] = resolution + return resolution + + method_resolution_cache[cache_key] = None + return None + + +class _WriteJointNameContext: + """Resolve runtime joint-name subsets for lazy write interception.""" + + __slots__ = ("joint_names", "_joint_ids") + + def __init__(self, joint_names: list[str], joint_ids): + self.joint_names = joint_names + self._joint_ids = joint_ids + + +def _unique_output_name(term_name: str, method_name: str, output_cache: list[TensorSemantics]) -> str: + """Return a stable, unique output name for an action write entry.""" + existing = {t.name for t in output_cache} + candidate = term_name + if candidate in existing: + candidate = f"{term_name}_{method_name}" + suffix = 2 + while candidate in existing: + candidate = f"{term_name}_{method_name}_{suffix}" + suffix += 1 + return candidate + + +class _DataProxy: + """Proxy around a real data object that intercepts tensor-returning property reads. + + The real data object may be any scene entity data class (``ArticulationData``, + ``RigidObjectData``, sensor data classes, etc.). The proxy resolves property + semantics lazily on first access by walking the runtime class MRO. This lets + concrete backend overrides reuse semantic metadata authored on abstract base + properties without copying decorators onto every implementation. + + When a semantic property returns a :class:`~isaaclab.utils.warp.ProxyArray`, + the result is wrapped in a ``TracedProxyArray`` and cached for + deduplication. Non-proxy results and ordinary attributes are forwarded + transparently. + + All other attribute access is forwarded transparently to the real object. + """ + + def __init__( + self, + real_data: Any, + entity_name: str, + task_name: str, + property_resolution_cache: dict[tuple[type, str], tuple[Callable, Any] | None], + cache: dict, + input_name_resolver: Callable, + ): + object.__setattr__(self, "_real_data", real_data) + object.__setattr__(self, "_entity_name", entity_name) + object.__setattr__(self, "_task_name", task_name) + object.__setattr__(self, "_property_resolution_cache", property_resolution_cache) + object.__setattr__(self, "_cache", cache) + object.__setattr__(self, "_input_name_resolver", input_name_resolver) + + def __getattr__(self, name): + """Intercept semantic property reads; forward everything else.""" + real_data = object.__getattribute__(self, "_real_data") + resolution = _resolve_annotated_property( + object.__getattribute__(self, "_property_resolution_cache"), real_data, name + ) + if resolution is None: + return getattr(real_data, name) + + cache = object.__getattribute__(self, "_cache") + cache_key = (id(real_data), name) + if cache_key in cache: + return cache[cache_key] + + execution_fget, semantics_meta = resolution + result = execution_fget(real_data) + if not isinstance(result, ProxyArray): + return result + + input_name = object.__getattribute__(self, "_input_name_resolver")(name) + traced = TracedProxyArray( + result, + input_name=input_name, + semantics_meta=semantics_meta, + real_data=real_data, + entity_name=object.__getattribute__(self, "_entity_name"), + property_name=name, + task_name=object.__getattribute__(self, "_task_name"), + ) + cache[cache_key] = traced + return traced + + +class _EntityProxy: + """Proxy around a real scene entity that returns a ``_DataProxy`` for ``.data``. + + All other attribute access is forwarded transparently to the real asset. + """ + + def __init__(self, real_entity: Any, data_proxy: _DataProxy): + object.__setattr__(self, "_real_entity", real_entity) + object.__setattr__(self, "_data_proxy", data_proxy) + + @property + def data(self): + """Return the annotating data proxy instead of the real data object.""" + return object.__getattribute__(self, "_data_proxy") + + def __getattr__(self, name): + """Forward all non-data attribute access to the real scene entity.""" + return getattr(object.__getattribute__(self, "_real_entity"), name) + + +class _EntityMappingProxy: + """Proxy around a mapping of scene entities that lazily wraps data-producing entries.""" + + def __init__( + self, + real_mapping, + task_name: str, + property_resolution_cache: dict[tuple[type, str], tuple[Callable, Any] | None], + cache: dict, + ): + object.__setattr__(self, "_real_mapping", real_mapping) + object.__setattr__(self, "_task_name", task_name) + object.__setattr__(self, "_property_resolution_cache", property_resolution_cache) + object.__setattr__(self, "_cache", cache) + object.__setattr__(self, "_proxied", {}) + + def __getitem__(self, key): + """Return a proxied entity when it has a ``.data`` attribute.""" + proxied = object.__getattribute__(self, "_proxied") + if key in proxied: + return proxied[key] + real_mapping = object.__getattribute__(self, "_real_mapping") + entity = real_mapping[key] + data = getattr(entity, "data", None) + if data is None: + return entity + data_proxy = _DataProxy( + data, + key, + object.__getattribute__(self, "_task_name"), + object.__getattribute__(self, "_property_resolution_cache"), + object.__getattribute__(self, "_cache"), + input_name_resolver=lambda prop_name: f"{key}_{prop_name}", + ) + proxy = _EntityProxy(entity, data_proxy) + proxied[key] = proxy + return proxy + + def get(self, key, default=None): + """Return a proxied entity when present, default otherwise.""" + real_mapping = object.__getattribute__(self, "_real_mapping") + if key not in real_mapping: + return default + return self[key] + + def __iter__(self): + return iter(object.__getattribute__(self, "_real_mapping")) + + def __len__(self): + return len(object.__getattribute__(self, "_real_mapping")) + + def __getattr__(self, name): + """Forward all other mapping access to the real mapping.""" + return getattr(object.__getattribute__(self, "_real_mapping"), name) + + +class _SceneProxy: + """Proxy around the real InteractiveScene. + + When an observation term looks up a scene entity by name, this proxy lazily + wraps any entity that has a ``.data`` attribute. All tensor-returning + properties on the data object are intercepted for LEAPP annotation. This + covers articulations, rigid objects, and sensors through both + ``scene["name"]`` and ``scene.sensors["name"]`` access paths. + """ + + def __init__( + self, + real_scene, + task_name: str, + property_resolution_cache: dict[tuple[type, str], tuple[Callable, Any] | None], + cache: dict, + ): + object.__setattr__(self, "_real_scene", real_scene) + object.__setattr__(self, "_task_name", task_name) + object.__setattr__(self, "_property_resolution_cache", property_resolution_cache) + object.__setattr__(self, "_cache", cache) + object.__setattr__(self, "_proxied", {}) + object.__setattr__(self, "_sensor_mapping_proxy", None) + + def _maybe_proxy_entity(self, key: str, entity: Any): + """Return a proxy for any entity that has a ``.data`` attribute.""" + proxied = object.__getattribute__(self, "_proxied") + if key in proxied: + return proxied[key] + + data = getattr(entity, "data", None) + if data is None: + return entity + + cache = object.__getattribute__(self, "_cache") + data_proxy = _DataProxy( + data, + key, + object.__getattribute__(self, "_task_name"), + object.__getattribute__(self, "_property_resolution_cache"), + cache, + input_name_resolver=lambda prop_name, k=key: f"{k}_{prop_name}", + ) + proxy = _EntityProxy(entity, data_proxy) + proxied[key] = proxy + return proxy + + def __getitem__(self, key): + """Return a proxied entity when it exposes annotated data getters.""" + real_scene = object.__getattribute__(self, "_real_scene") + entity = real_scene[key] + return self._maybe_proxy_entity(key, entity) + + @property + def sensors(self): + """Return a mapping proxy for scene sensors.""" + sensor_mapping_proxy = object.__getattribute__(self, "_sensor_mapping_proxy") + if sensor_mapping_proxy is None: + real_scene = object.__getattribute__(self, "_real_scene") + sensor_mapping_proxy = _EntityMappingProxy( + real_scene.sensors, + object.__getattribute__(self, "_task_name"), + object.__getattribute__(self, "_property_resolution_cache"), + object.__getattribute__(self, "_cache"), + ) + object.__setattr__(self, "_sensor_mapping_proxy", sensor_mapping_proxy) + return sensor_mapping_proxy + + def __getattr__(self, name): + """Forward all other scene access to the real scene.""" + return getattr(object.__getattribute__(self, "_real_scene"), name) + + +class _EnvProxy: + """Proxy around the real env that returns a _SceneProxy for ``.scene``. + + All other attribute access (``num_envs``, ``command_manager``, etc.) + is forwarded transparently to the real env. + """ + + def __init__( + self, + real_env, + task_name: str, + property_resolution_cache: dict[tuple[type, str], tuple[Callable, Any] | None], + cache: dict, + ): + object.__setattr__(self, "_real_env", real_env) + object.__setattr__( + self, + "_scene_proxy", + _SceneProxy(real_env.scene, task_name, property_resolution_cache, cache), + ) + + @property + def scene(self): + """Return the scene proxy instead of the real scene.""" + return object.__getattribute__(self, "_scene_proxy") + + def __getattr__(self, name): + """Forward all non-scene attribute access to the real env.""" + return getattr(object.__getattribute__(self, "_real_env"), name) + + +def _build_scene_entity_lookup(real_scene) -> dict[int, tuple[str, str]]: + """Map real scene entity object ids to their lookup path.""" + lookup: dict[int, tuple[str, str]] = {} + for attr_name, attr_value in vars(real_scene).items(): + if not isinstance(attr_value, dict): + continue + container_kind = "sensors" if attr_name == "sensors" else "scene" + for key, entity in attr_value.items(): + lookup[id(entity)] = (container_kind, key) + return lookup + + +class _ManagerTermProxy(ManagerTermBase): + """Proxy a class-based manager term while preserving its lifecycle methods. + + Observation manager terms can be stateful ``ManagerTermBase`` instances that + expose ``reset()`` and ``serialize()`` in addition to being callable. This + proxy preserves that interface while swapping the env argument passed into + ``__call__`` for the observation-side proxy env. + """ + + def __init__(self, target: ManagerTermBase, proxy_env: _EnvProxy): + super().__init__(target.cfg, target._env) + self._target = target + self._proxy_env = proxy_env + self._entity_lookup = _build_scene_entity_lookup(target._env.scene) + + @property + def __name__(self) -> str: + """Expose the wrapped term name for compatibility and debugging.""" + return getattr(self._target, "__name__", self._target.__class__.__name__) + + def reset(self, env_ids=None) -> None: + """Forward resets to the wrapped term instance.""" + self._target.reset(env_ids=env_ids) + + def serialize(self) -> dict: + """Forward serialization to the wrapped term instance.""" + return self._target.serialize() + + def __call__(self, *args, **kwargs): + """Call the wrapped term with the proxy env in place of the real env.""" + if args: + args = (self._proxy_env, *args[1:]) + else: + args = (self._proxy_env,) + swapped_attrs: list[tuple[str, Any]] = [] + for attr_name, attr_value in vars(self._target).items(): + lookup = self._entity_lookup.get(id(attr_value)) + if lookup is None: + continue + + container_kind, key = lookup + proxy_entity = ( + self._proxy_env.scene.sensors[key] if container_kind == "sensors" else self._proxy_env.scene[key] + ) + swapped_attrs.append((attr_name, attr_value)) + setattr(self._target, attr_name, proxy_entity) + + try: + return self._target(*args, **kwargs) + finally: + for attr_name, attr_value in swapped_attrs: + setattr(self._target, attr_name, attr_value) + + def __getattr__(self, name): + """Forward all other attribute access to the wrapped term instance.""" + return getattr(self._target, name) + + +# ══════════════════════════════════════════════════════════════════ +# Action-side proxy +# ══════════════════════════════════════════════════════════════════ + + +class _ArticulationWriteProxy: + """Proxy around a real articulation implementation for action terms. + + Intercepts ``_leapp_semantics``-decorated write methods **and** routes + ``.data`` reads through a shared ``_DataProxy`` so that + action-side state reads (e.g. ``self._asset.data.joint_pos`` inside + ``RelativeJointPositionAction``) participate in LEAPP annotation and + share the dedup cache with observation-side reads. + + All other attribute access is forwarded transparently to the real asset. + """ + + def __init__( + self, + real_asset: Any, + entity_name: str, + term_name: str, + output_cache: list[TensorSemantics], + method_resolution_cache: dict[tuple[type, str], tuple[Callable, Any, inspect.Signature] | None], + captured_write_term_names: set[str], + data_proxy: _DataProxy, + ): + object.__setattr__(self, "_real_asset", real_asset) + object.__setattr__(self, "_entity_name", entity_name) + object.__setattr__(self, "_term_name", term_name) + object.__setattr__(self, "_output_cache", output_cache) + object.__setattr__(self, "_method_resolution_cache", method_resolution_cache) + object.__setattr__(self, "_captured_write_term_names", captured_write_term_names) + object.__setattr__(self, "_data_proxy", data_proxy) + + @property + def data(self): + """Return the shared annotating data proxy.""" + return object.__getattribute__(self, "_data_proxy") + + def __getattr__(self, name): + """Return an annotating wrapper for semantic write methods; forward everything else.""" + real_asset = object.__getattribute__(self, "_real_asset") + resolution = _resolve_annotated_method( + object.__getattribute__(self, "_method_resolution_cache"), + real_asset, + name, + ) + if resolution is None: + return getattr(real_asset, name) + + original_method, semantics_meta, signature = resolution + term_name = object.__getattribute__(self, "_term_name") + output_cache = object.__getattribute__(self, "_output_cache") + captured_write_term_names = object.__getattribute__(self, "_captured_write_term_names") + + def interceptor(*args, **kwargs): + result = original_method(*args, **kwargs) + bound_args = signature.bind_partial(real_asset, *args, **kwargs) + target = bound_args.arguments.get("target") + + if not isinstance(target, torch.Tensor): + return result + + target_tensor = cast(torch.Tensor, target) + joint_ids = bound_args.arguments.get("joint_ids") + output_cache.append( + TensorSemantics( + name=_unique_output_name(term_name, name, output_cache), + ref=target_tensor.clone(), + kind=semantics_meta.kind, + element_names=resolve_leapp_element_names( + semantics_meta, + _WriteJointNameContext(real_asset.joint_names, joint_ids), + ), + extra=build_write_connection( + object.__getattribute__(self, "_entity_name"), + name, + ), + ) + ) + captured_write_term_names.add(term_name) + + return result + + return interceptor diff --git a/source/isaaclab/isaaclab/utils/leapp/utils.py b/source/isaaclab/isaaclab/utils/leapp/utils.py new file mode 100644 index 000000000000..2308f662ab80 --- /dev/null +++ b/source/isaaclab/isaaclab/utils/leapp/utils.py @@ -0,0 +1,87 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from __future__ import annotations + +from types import SimpleNamespace +from typing import Any + +import torch +from leapp import annotate +from leapp.utils.tensor_description import TensorSemantics + +from isaaclab.utils.warp.proxy_array import ProxyArray + +from .leapp_semantics import LeappTensorSemantics, resolve_leapp_element_names + + +class TracedProxyArray(ProxyArray): + _traced_array: torch.Tensor + + def __init__( + self, + proxy_array: ProxyArray, + *, + input_name: str, + semantics_meta: LeappTensorSemantics, + real_data: Any, + entity_name: str, + property_name: str, + task_name: str, + ) -> None: + super().__init__(proxy_array.warp) + astorch = super().torch + sem = TensorSemantics( + name=input_name, + ref=astorch, + kind=semantics_meta.kind, + element_names=resolve_leapp_element_names(semantics_meta, real_data), + extra=build_state_connection(entity_name, property_name), + ) + annotated = annotate.input_tensors(task_name, sem) + object.__setattr__(self, "_traced_array", annotated) + + @property + def torch(self) -> torch.Tensor: + return self._traced_array + + @property + def warp(self) -> Any: + raise AttributeError("warp arrays are not supported for leapp export") + + +def ensure_env_spec_id(env, fallback_task_name: str = "policy") -> str: + """Return ``env.unwrapped.spec.id``, creating a fallback spec when needed.""" + spec = getattr(env.unwrapped, "spec", None) + if spec is None: + env.unwrapped.spec = SimpleNamespace(id=fallback_task_name) + return fallback_task_name + + task_name = getattr(spec, "id", None) + if task_name is None: + spec.id = fallback_task_name + return fallback_task_name + + return task_name + + +# ══════════════════════════════════════════════════════════════════ +# Connection Builders +# ══════════════════════════════════════════════════════════════════ + + +def build_state_connection(entity_name: str, property_name: str) -> dict[str, str]: + """Return a compact deployment connection string for a state property.""" + return {"isaaclab_connection": f"state:{entity_name}:{property_name}"} + + +def build_command_connection(command_name: str) -> dict[str, str]: + """Return a compact deployment connection string for a command term.""" + return {"isaaclab_connection": f"command:{command_name}"} + + +def build_write_connection(entity_name: str, method_name: str) -> dict[str, str]: + """Return a compact deployment connection string for an articulation write target.""" + return {"isaaclab_connection": f"write:{entity_name}:{method_name}"} diff --git a/source/isaaclab/isaaclab/utils/string.py b/source/isaaclab/isaaclab/utils/string.py index 21c5cd58e77f..4e7790006ade 100644 --- a/source/isaaclab/isaaclab/utils/string.py +++ b/source/isaaclab/isaaclab/utils/string.py @@ -6,6 +6,7 @@ """Sub-module containing utilities for transforming strings and regular expressions.""" import ast +import functools import importlib import inspect import re @@ -247,44 +248,19 @@ def __deepcopy__(self, memo): """ -def resolve_matching_names( - keys: str | Sequence[str], list_of_strings: Sequence[str], preserve_order: bool = False -) -> tuple[list[int], list[str]]: - """Match a list of query regular expressions against a list of strings and return the matched indices and names. - - When a list of query regular expressions is provided, the function checks each target string against each - query regular expression and returns the indices of the matched strings and the matched strings. - - If the :attr:`preserve_order` is True, the ordering of the matched indices and names is the same as the order - of the provided list of strings. This means that the ordering is dictated by the order of the target strings - and not the order of the query regular expressions. - - If the :attr:`preserve_order` is False, the ordering of the matched indices and names is the same as the order - of the provided list of query regular expressions. - - For example, consider the list of strings is ['a', 'b', 'c', 'd', 'e'] and the regular expressions are ['a|c', 'b']. - If :attr:`preserve_order` is False, then the function will return the indices of the matched strings and the - strings as: ([0, 1, 2], ['a', 'b', 'c']). When :attr:`preserve_order` is True, it will return them as: - ([0, 2, 1], ['a', 'c', 'b']). - - Note: - The function does not sort the indices. It returns the indices in the order they are found. - - Args: - keys: A regular expression or a list of regular expressions to match the strings in the list. - list_of_strings: A list of strings to match. - preserve_order: Whether to preserve the order of the query keys in the returned values. Defaults to False. - - Returns: - A tuple of lists containing the matched indices and names. +@functools.cache +def _resolve_matching_names_impl( + keys: tuple[str, ...], + list_of_strings: tuple[str, ...], + preserve_order: bool, + raise_when_no_match: bool, +) -> tuple[tuple[int, ...], tuple[str, ...]]: + """Cached implementation of :func:`resolve_matching_names`. - Raises: - ValueError: When multiple matches are found for a string in the list. - ValueError: When not all regular expressions are matched. + All arguments are hashable so that ``functools.cache`` can store results. + Returns tuples (immutable) to protect the cached data from mutation; + the public wrapper converts these back to fresh lists for each caller. """ - # resolve name keys - if isinstance(keys, str): - keys = [keys] # find matching patterns index_list = [] names_list = [] @@ -330,6 +306,8 @@ def resolve_matching_names( names_list = names_list_reorder # check that all regular expressions are matched if not all(keys_match_found): + if not raise_when_no_match: + return (), () # make this print nicely aligned for debugging msg = "\n" for key, value in zip(keys, keys_match_found): @@ -339,8 +317,66 @@ def resolve_matching_names( raise ValueError( f"Not all regular expressions are matched! Please check that the regular expressions are correct: {msg}" ) - # return - return index_list, names_list + # return immutable tuples for safe caching + return tuple(index_list), tuple(names_list) + + +def resolve_matching_names( + keys: str | Sequence[str], + list_of_strings: Sequence[str], + preserve_order: bool = False, + *, + raise_when_no_match: bool = True, +) -> tuple[list[int], list[str]]: + """Match a list of query regular expressions against a list of strings and return the matched indices and names. + + When a list of query regular expressions is provided, the function checks each target string against each + query regular expression and returns the indices of the matched strings and the matched strings. + + If the :attr:`preserve_order` is True, the ordering of the matched indices and names is the same as the order + of the provided list of strings. This means that the ordering is dictated by the order of the target strings + and not the order of the query regular expressions. + + If the :attr:`preserve_order` is False, the ordering of the matched indices and names is the same as the order + of the provided list of query regular expressions. + + For example, consider the list of strings is ['a', 'b', 'c', 'd', 'e'] and the regular expressions are ['a|c', 'b']. + If :attr:`preserve_order` is False, then the function will return the indices of the matched strings and the + strings as: ([0, 1, 2], ['a', 'b', 'c']). When :attr:`preserve_order` is True, it will return them as: + ([0, 2, 1], ['a', 'c', 'b']). + + Results are cached internally — repeated calls with the same arguments avoid redundant regex matching. + + Note: + The function does not sort the indices. It returns the indices in the order they are found. + + Args: + keys: A regular expression or a list of regular expressions to match the strings in the list. + list_of_strings: A list of strings to match. + preserve_order: Whether to preserve the order of the query keys in the returned values. Defaults to False. + raise_when_no_match: Whether to raise a ``ValueError`` when not all regular expressions are matched. + Defaults to True. When False, returns empty lists instead of raising. + + Returns: + A tuple of lists containing the matched indices and names. + + Raises: + ValueError: When multiple matches are found for a string in the list. + ValueError: When not all regular expressions are matched and :attr:`raise_when_no_match` is True. + """ + _keys = (keys,) if isinstance(keys, str) else tuple(keys) + idx, names = _resolve_matching_names_impl(_keys, tuple(list_of_strings), preserve_order, raise_when_no_match) + return list(idx), list(names) + + +def clear_resolve_matching_names_cache() -> None: + """Discard all cached results from :func:`resolve_matching_names`. + + Call this when the simulation scene is torn down so that cached + name-resolution entries from destroyed assets do not accumulate + across scene rebuilds in long-lived processes. + """ + _resolve_matching_names_impl.cache_clear() def resolve_matching_names_values( @@ -352,6 +388,11 @@ def resolve_matching_names_values( """Match a list of regular expressions in a dictionary against a list of strings and return the matched indices, names, and values. + Note: + Unlike :func:`resolve_matching_names`, this function is not cached. Current callers + use it during initialization only (e.g. action/actuator config resolution), so caching + would add complexity without a measurable benefit. + If the :attr:`preserve_order` is True, the ordering of the matched indices and names is the same as the order of the provided list of strings. This means that the ordering is dictated by the order of the target strings and not the order of the query regular expressions. diff --git a/source/isaaclab/isaaclab/utils/warp/__init__.py b/source/isaaclab/isaaclab/utils/warp/__init__.py index e5a4264c81c7..569b80c9b089 100644 --- a/source/isaaclab/isaaclab/utils/warp/__init__.py +++ b/source/isaaclab/isaaclab/utils/warp/__init__.py @@ -5,6 +5,8 @@ """Sub-module containing operations based on warp.""" +import warnings + import warp as wp wp.config.quiet = True @@ -13,3 +15,47 @@ from isaaclab.utils.module import lazy_export lazy_export() + +# Avoid a circular import at module load: `.proxy_array` imports warp, which is +# already loaded above. Importing it here ensures the class is available inside +# the shim. +from .proxy_array import ProxyArray # noqa: E402 + +_WP_TO_TORCH_ORIGINAL = wp.to_torch +_WP_TO_TORCH_WARNED = False + + +def _wp_to_torch_with_proxyarray(a, requires_grad=None): + """Shim for :func:`warp.to_torch` that gracefully handles :class:`ProxyArray`. + + Without this shim, ``wp.to_torch(proxy)`` would fail with + ``AttributeError: 'ProxyArray' object has no attribute 'requires_grad'`` + because :class:`ProxyArray` intentionally doesn't replicate the full + ``wp.array`` attribute surface. Users and third-party code that still use + ``wp.to_torch(asset.data.)`` from before the ProxyArray migration + would break hard. + + The shim routes :class:`ProxyArray` arguments to their cached ``.torch`` + view (a zero-copy :class:`torch.Tensor` of the same underlying memory) and + emits a one-shot :class:`DeprecationWarning`. For any other input type, + the original :func:`warp.to_torch` handles the call as before. + """ + global _WP_TO_TORCH_WARNED + if isinstance(a, ProxyArray): + if not _WP_TO_TORCH_WARNED: + _WP_TO_TORCH_WARNED = True + warnings.warn( + "wp.to_torch() is deprecated; use the `.torch` accessor on" + " the ProxyArray directly (e.g. `asset.data.joint_pos.torch`).", + DeprecationWarning, + stacklevel=2, + ) + return a.torch + return _WP_TO_TORCH_ORIGINAL(a, requires_grad=requires_grad) + + +# Patch at both the top-level ``warp`` namespace and the underlying module so +# callers using ``import warp as wp`` and rare ``from warp._src.torch import +# to_torch`` patterns both pick up the shim. +wp.to_torch = _wp_to_torch_with_proxyarray +wp._src.torch.to_torch = _wp_to_torch_with_proxyarray # noqa: SLF001 diff --git a/source/isaaclab/isaaclab/utils/warp/__init__.pyi b/source/isaaclab/isaaclab/utils/warp/__init__.pyi index ea25f04435d3..ab1de52f39f7 100644 --- a/source/isaaclab/isaaclab/utils/warp/__init__.pyi +++ b/source/isaaclab/isaaclab/utils/warp/__init__.pyi @@ -4,6 +4,7 @@ # SPDX-License-Identifier: BSD-3-Clause __all__ = [ + "ProxyArray", "convert_to_warp_mesh", "raycast_dynamic_meshes", "raycast_mesh", @@ -11,3 +12,4 @@ __all__ = [ ] from .ops import convert_to_warp_mesh, raycast_dynamic_meshes, raycast_mesh, raycast_single_mesh +from .proxy_array import ProxyArray diff --git a/source/isaaclab/isaaclab/utils/warp/kernels.py b/source/isaaclab/isaaclab/utils/warp/kernels.py index da2d9123db47..efcdbfe63f1e 100644 --- a/source/isaaclab/isaaclab/utils/warp/kernels.py +++ b/source/isaaclab/isaaclab/utils/warp/kernels.py @@ -53,7 +53,7 @@ def raycast_mesh_kernel( this array is not used. max_dist: The maximum ray-cast distance. Defaults to 1e6. return_distance: Whether to return the ray hit distances. Defaults to False. - return_normal: Whether to return the ray hit normals. Defaults to False`. + return_normal: Whether to return the ray hit normals. Defaults to False. return_face_id: Whether to return the ray hit face ids. Defaults to False. """ # get the thread id @@ -79,6 +79,63 @@ def raycast_mesh_kernel( ray_face_id[tid] = f +@wp.kernel(enable_backward=False) +def raycast_mesh_masked_kernel( + # input + mesh: wp.uint64, + env_mask: wp.array(dtype=wp.bool), + ray_starts: wp.array2d(dtype=wp.vec3f), + ray_directions: wp.array2d(dtype=wp.vec3f), + max_dist: wp.float32, + return_distance: int, + return_normal: int, + # output + ray_hits: wp.array2d(dtype=wp.vec3f), + ray_distance: wp.array2d(dtype=wp.float32), + ray_normal: wp.array2d(dtype=wp.vec3f), +): + """Ray-cast against a single static mesh for masked environments. + + Extends :func:`raycast_mesh_kernel` with environment masking and optional distance/normal output, + for use in multi-environment sensor pipelines. + + Launch with ``dim=(num_envs, num_rays)``. + + Args: + mesh: Warp mesh id to ray-cast against. + env_mask: Boolean mask for which environments to update. Shape is (num_envs,). + ray_starts: World-frame ray start positions [m]. Shape is (num_envs, num_rays). + ray_directions: World-frame unit ray directions. Shape is (num_envs, num_rays). + max_dist: Maximum ray-cast distance [m]. + return_distance: Whether to write hit distances to ``ray_distance`` (1) or skip (0). + return_normal: Whether to write surface normals to ``ray_normal`` (1) or skip (0). + ray_hits: Output ray hit positions [m]. Shape is (num_envs, num_rays). + Pre-filled with inf for missed hits; unchanged on miss. + ray_distance: Output hit distances [m]. Shape is (num_envs, num_rays). + Written only when ``return_distance`` is 1; pre-filled with inf for missed hits. + ray_normal: Output surface normals at hit positions. Shape is (num_envs, num_rays). + Written only when ``return_normal`` is 1; pre-filled with inf for missed hits. + """ + env, ray = wp.tid() + if not env_mask[env]: + return + + t = float(0.0) + u = float(0.0) + v = float(0.0) + sign = float(0.0) + n = wp.vec3f() + f = int(0) + + hit = wp.mesh_query_ray(mesh, ray_starts[env, ray], ray_directions[env, ray], max_dist, t, u, v, sign, n, f) + if hit: + ray_hits[env, ray] = ray_starts[env, ray] + t * ray_directions[env, ray] + if return_distance == 1: + ray_distance[env, ray] = t + if return_normal == 1: + ray_normal[env, ray] = n + + @wp.kernel(enable_backward=False) def raycast_static_meshes_kernel( mesh: wp.array2d(dtype=wp.uint64), @@ -110,14 +167,24 @@ def raycast_static_meshes_kernel( account the mesh's position and rotation. This kernel is useful for ray-casting against static meshes that are not expected to move. + .. warning:: + **Known race condition:** When two meshes are equidistant to the same ray, the + ``atomic_min`` + equality-check pattern used for closest-hit resolution is not fully + thread-safe. Two threads may both pass the equality check and write different output + fields (e.g., ``ray_hits`` from mesh A, ``ray_normal`` from mesh B). In practice this + is rare (requires exact floating-point tie) and the position output is still correct, + but normals, face IDs, and mesh IDs may be inconsistent for the affected ray. + See `warp#1058 `_ for progress on a + thread-safe fix. + Args: mesh: The input mesh. The ray-casting is performed against this mesh on the device specified by the `mesh`'s `device` attribute. ray_starts: The input ray start positions. Shape is (B, N, 3). ray_directions: The input ray directions. Shape is (B, N, 3). ray_hits: The output ray hit positions. Shape is (B, N, 3). - ray_distance: The output ray hit distances. Shape is (B, N,), if ``return_distance`` is True. Otherwise, - this array is not used. + ray_distance: The closest hit distance buffer. Shape is (B, N). Updated via ``atomic_min`` for every + thread that records a hit; used to resolve closest-hit among multiple meshes. ray_normal: The output ray hit normals. Shape is (B, N, 3), if ``return_normal`` is True. Otherwise, this array is not used. ray_face_id: The output ray hit face ids. Shape is (B, N,), if ``return_face_id`` is True. Otherwise, @@ -125,7 +192,7 @@ def raycast_static_meshes_kernel( ray_mesh_id: The output ray hit mesh ids. Shape is (B, N,), if ``return_mesh_id`` is True. Otherwise, this array is not used. max_dist: The maximum ray-cast distance. Defaults to 1e6. - return_normal: Whether to return the ray hit normals. Defaults to False`. + return_normal: Whether to return the ray hit normals. Defaults to False. return_face_id: Whether to return the ray hit face ids. Defaults to False. return_mesh_id: Whether to return the mesh id. Defaults to False. """ @@ -141,10 +208,11 @@ def raycast_static_meshes_kernel( # if the ray hit, store the hit data if mesh_query_ray_t.result: wp.atomic_min(ray_distance, tid_env, tid_ray, mesh_query_ray_t.t) - # check if hit distance is less than the current hit distance, only then update the memory - # TODO, in theory we could use the output of atomic_min to avoid the non-thread safe next comparison - # however, warp atomic_min is returning the wrong values on gpu currently. - # FIXME https://github.com/NVIDIA/warp/issues/1058 + # TODO(warp#1058): Use the return value of atomic_min to avoid the non-thread-safe + # equality check below. Currently warp atomic_min returns wrong values on GPU, so we + # fall back to a racy read-back. When two meshes tie on distance, normals/face-ids/ + # mesh-ids may be written by different threads. The hit *position* is still correct + # because all tying threads compute the same world-space point. if mesh_query_ray_t.t == ray_distance[tid_env, tid_ray]: # convert back to world space and update the hit data ray_hits[tid_env, tid_ray] = start_pos + mesh_query_ray_t.t * direction @@ -160,6 +228,7 @@ def raycast_static_meshes_kernel( @wp.kernel(enable_backward=False) def raycast_dynamic_meshes_kernel( + env_mask: wp.array(dtype=wp.bool), mesh: wp.array2d(dtype=wp.uint64), ray_starts: wp.array2d(dtype=wp.vec3), ray_directions: wp.array2d(dtype=wp.vec3), @@ -175,7 +244,7 @@ def raycast_dynamic_meshes_kernel( return_face_id: int = False, return_mesh_id: int = False, ): - """Performs ray-casting against multiple meshes. + """Performs ray-casting against multiple dynamic meshes. This function performs ray-casting against the given meshes using the provided ray start positions and directions. The resulting ray hit positions are stored in the :obj:`ray_hits` array. @@ -183,7 +252,6 @@ def raycast_dynamic_meshes_kernel( The function utilizes the ``mesh_query_ray`` method from the ``wp`` module to perform the actual ray-casting operation. The maximum ray-cast distance is set to ``1e6`` units. - Note: That the ``ray_starts``, ``ray_directions``, and ``ray_hits`` arrays should have compatible shapes and data types to ensure proper execution. Additionally, they all must be in the same frame. @@ -191,29 +259,42 @@ def raycast_dynamic_meshes_kernel( All arguments are expected to be batched with the first dimension (B, batch) being the number of envs and the second dimension (N, num_rays) being the number of rays. For Meshes, W is the number of meshes. + .. warning:: + **Known race condition:** When two meshes are equidistant to the same ray, the + ``atomic_min`` + equality-check pattern used for closest-hit resolution is not fully + thread-safe. Two threads may both pass the equality check and write different output + fields (e.g., ``ray_hits`` from mesh A, ``ray_normal`` from mesh B). In practice this + is rare (requires exact floating-point tie) and the position output is still correct, + but normals, face IDs, and mesh IDs may be inconsistent for the affected ray. + See `warp#1058 `_ for progress on a + thread-safe fix. + Args: + env_mask: Boolean mask selecting which environments to process. Shape is (B,). mesh: The input mesh. The ray-casting is performed against this mesh on the device specified by the `mesh`'s `device` attribute. ray_starts: The input ray start positions. Shape is (B, N, 3). ray_directions: The input ray directions. Shape is (B, N, 3). ray_hits: The output ray hit positions. Shape is (B, N, 3). - ray_distance: The output ray hit distances. Shape is (B, N,), if ``return_distance`` is True. Otherwise, - this array is not used. + ray_distance: The closest hit distance buffer. Shape is (B, N). Updated via ``atomic_min`` for every + thread that records a hit; used to resolve closest-hit among multiple meshes. ray_normal: The output ray hit normals. Shape is (B, N, 3), if ``return_normal`` is True. Otherwise, this array is not used. ray_face_id: The output ray hit face ids. Shape is (B, N,), if ``return_face_id`` is True. Otherwise, this array is not used. ray_mesh_id: The output ray hit mesh ids. Shape is (B, N,), if ``return_mesh_id`` is True. Otherwise, this array is not used. - mesh_positions: The input mesh positions in world frame. Shape is (W, 3). - mesh_rotations: The input mesh rotations in world frame. Shape is (W, 4). + mesh_positions: The input mesh positions in world frame. Shape is (B, W, 3). + mesh_rotations: The input mesh rotations in world frame. Shape is (B, W, 4). max_dist: The maximum ray-cast distance. Defaults to 1e6. - return_normal: Whether to return the ray hit normals. Defaults to False`. + return_normal: Whether to return the ray hit normals. Defaults to False. return_face_id: Whether to return the ray hit face ids. Defaults to False. return_mesh_id: Whether to return the mesh id. Defaults to False. """ # get the thread id tid_mesh_id, tid_env, tid_ray = wp.tid() + if not env_mask[tid_env]: + return mesh_pose = wp.transform(mesh_positions[tid_env, tid_mesh_id], mesh_rotations[tid_env, tid_mesh_id]) mesh_pose_inv = wp.transform_inverse(mesh_pose) @@ -225,10 +306,11 @@ def raycast_dynamic_meshes_kernel( # if the ray hit, store the hit data if mesh_query_ray_t.result: wp.atomic_min(ray_distance, tid_env, tid_ray, mesh_query_ray_t.t) - # check if hit distance is less than the current hit distance, only then update the memory - # TODO, in theory we could use the output of atomic_min to avoid the non-thread safe next comparison - # however, warp atomic_min is returning the wrong values on gpu currently. - # FIXME https://github.com/NVIDIA/warp/issues/1058 + # TODO(warp#1058): Use the return value of atomic_min to avoid the non-thread-safe + # equality check below. Currently warp atomic_min returns wrong values on GPU, so we + # fall back to a racy read-back. When two meshes tie on distance, normals/face-ids/ + # mesh-ids may be written by different threads. The hit *position* is still correct + # because all tying threads compute the same world-space point. if mesh_query_ray_t.t == ray_distance[tid_env, tid_ray]: # convert back to world space and update the hit data hit_pos = start_pos + mesh_query_ray_t.t * direction @@ -302,379 +384,324 @@ def reshape_tiled_image( ) ## -# Wrench Composer +# Wrench Composer — Dual-Buffer Architecture ## -@wp.func -def cast_to_link_frame(position: wp.vec3f, link_position: wp.vec3f, is_global: bool) -> wp.vec3f: - """Casts a position to the link frame of the body. - - Args: - position: The position to cast. - link_position: The link frame position. - is_global: Whether the position is in the global frame. - - Returns: - The position in the link frame of the body. - """ - if is_global: - return position - link_position - else: - return position - - -@wp.func -def cast_force_to_link_frame(force: wp.vec3f, link_quat: wp.quatf, is_global: bool) -> wp.vec3f: - """Casts a force to the link frame of the body. - - Args: - force: The force to cast. - link_quat: The link frame quaternion. - is_global: Whether the force is applied in the global frame. - Returns: - The force in the link frame of the body. - """ - if is_global: - return wp.quat_rotate_inv(link_quat, force) - else: - return force - - -@wp.func -def cast_torque_to_link_frame(torque: wp.vec3f, link_quat: wp.quatf, is_global: bool) -> wp.vec3f: - """Casts a torque to the link frame of the body. - - Args: - torque: The torque to cast. - link_quat: The link frame quaternion. - is_global: Whether the torque is applied in the global frame. - - Returns: - The torque in the link frame of the body. - """ - if is_global: - return wp.quat_rotate_inv(link_quat, torque) - else: - return torque - - @wp.kernel -def add_forces_and_torques_at_position_index( +def set_forces_to_dual_buffers_index( env_ids: wp.array(dtype=wp.int32), body_ids: wp.array(dtype=wp.int32), forces: wp.array2d(dtype=wp.vec3f), torques: wp.array2d(dtype=wp.vec3f), positions: wp.array2d(dtype=wp.vec3f), - link_poses: wp.array2d(dtype=wp.transformf), + global_force_w: wp.array2d(dtype=wp.vec3f), + global_torque_w: wp.array2d(dtype=wp.vec3f), + global_force_at_com_w: wp.array2d(dtype=wp.vec3f), + local_force_b: wp.array2d(dtype=wp.vec3f), + local_torque_b: wp.array2d(dtype=wp.vec3f), is_global: bool, - composed_forces_b: wp.array2d(dtype=wp.vec3f), - composed_torques_b: wp.array2d(dtype=wp.vec3f), ): - """Add forces and torques to the composed wrench at user-provided positions using index selection. + """Set forces/torques into dual buffers using index selection (overwrites). - When is_global is False, the user-provided positions offset the force application relative to - the link frame. When is_global is True, positions are in the global frame. Results are - accumulated (added) into the composed buffers. + Dispatched with ``dim=(len(env_ids), len(body_ids))``. - .. note:: - Expects partial data from the user (indexed by env_ids/body_ids). + When ``is_global`` is True, forces/torques are written to the world-frame buffers. + Forces with ``positions`` go to ``global_force_w`` with torque ``cross(P, F)`` accumulated + into ``global_torque_w``; forces without positions go to ``global_force_at_com_w``. + When ``is_global`` is False, values go to ``local_force_b`` / ``local_torque_b``. - Args: - env_ids: Input array of environment indices. Shape is (num_selected_envs,). - body_ids: Input array of body indices. Shape is (num_selected_bodies,). - forces: Input array of forces to apply. Shape is (num_selected_envs, num_selected_bodies). - Can be None if not provided. - torques: Input array of torques to apply. Shape is (num_selected_envs, num_selected_bodies). - Can be None if not provided. - positions: Input array of position offsets for force application. - Shape is (num_selected_envs, num_selected_bodies). Can be None if not provided. - link_poses: Input array of link frame poses in world frame. - Shape is (num_envs, num_bodies). - is_global: Input flag indicating whether forces/torques/positions are in the global frame. - composed_forces_b: Output array where forces in the link frame are accumulated. - Shape is (num_envs, num_bodies). - composed_torques_b: Output array where torques in the link frame are accumulated. - Shape is (num_envs, num_bodies). + Any of ``forces``, ``torques``, or ``positions`` may be ``None`` (null array). """ - # get the thread id tid_env, tid_body = wp.tid() + ei = env_ids[tid_env] + bi = body_ids[tid_body] - # add the forces to the composed force, if the positions are provided, also adds a torque to the composed torque. - if forces: - # add the forces to the composed force - composed_forces_b[env_ids[tid_env], body_ids[tid_body]] += cast_force_to_link_frame( - forces[tid_env, tid_body], - wp.transform_get_rotation(link_poses[env_ids[tid_env], body_ids[tid_body]]), - is_global, - ) - # if there is a position offset, add a torque to the composed torque. - if positions: - composed_torques_b[env_ids[tid_env], body_ids[tid_body]] += wp.skew( - cast_to_link_frame( - positions[tid_env, tid_body], - wp.transform_get_translation(link_poses[env_ids[tid_env], body_ids[tid_body]]), - is_global, - ) - ) @ cast_force_to_link_frame( - forces[tid_env, tid_body], - wp.transform_get_rotation(link_poses[env_ids[tid_env], body_ids[tid_body]]), - is_global, - ) - if torques: - composed_torques_b[env_ids[tid_env], body_ids[tid_body]] += cast_torque_to_link_frame( - torques[tid_env, tid_body], - wp.transform_get_rotation(link_poses[env_ids[tid_env], body_ids[tid_body]]), - is_global, - ) + if is_global: + if torques: + global_torque_w[ei, bi] = torques[tid_env, tid_body] + if forces: + if positions: + global_force_w[ei, bi] = forces[tid_env, tid_body] + if torques: + global_torque_w[ei, bi] = global_torque_w[ei, bi] + wp.cross( + positions[tid_env, tid_body], forces[tid_env, tid_body] + ) + else: + global_torque_w[ei, bi] = wp.cross(positions[tid_env, tid_body], forces[tid_env, tid_body]) + else: + global_force_at_com_w[ei, bi] = forces[tid_env, tid_body] + else: + if torques: + local_torque_b[ei, bi] = torques[tid_env, tid_body] + if forces: + local_force_b[ei, bi] = forces[tid_env, tid_body] + if positions: + if torques: + local_torque_b[ei, bi] = local_torque_b[ei, bi] + wp.cross( + positions[tid_env, tid_body], forces[tid_env, tid_body] + ) + else: + local_torque_b[ei, bi] = wp.cross(positions[tid_env, tid_body], forces[tid_env, tid_body]) @wp.kernel -def set_forces_and_torques_at_position_index( +def add_forces_to_dual_buffers_index( env_ids: wp.array(dtype=wp.int32), body_ids: wp.array(dtype=wp.int32), forces: wp.array2d(dtype=wp.vec3f), torques: wp.array2d(dtype=wp.vec3f), positions: wp.array2d(dtype=wp.vec3f), - link_poses: wp.array2d(dtype=wp.transformf), + global_force_w: wp.array2d(dtype=wp.vec3f), + global_torque_w: wp.array2d(dtype=wp.vec3f), + global_force_at_com_w: wp.array2d(dtype=wp.vec3f), + local_force_b: wp.array2d(dtype=wp.vec3f), + local_torque_b: wp.array2d(dtype=wp.vec3f), is_global: bool, - composed_forces_b: wp.array2d(dtype=wp.vec3f), - composed_torques_b: wp.array2d(dtype=wp.vec3f), ): - """Set forces and torques to the composed wrench at user-provided positions using index selection. - - When is_global is False, the user-provided positions offset the force application relative to - the link frame. When is_global is True, positions are in the global frame. Results are - overwritten (set) in the composed buffers. + """Add forces/torques into dual buffers using index selection (accumulates). - .. note:: - Expects partial data from the user (indexed by env_ids/body_ids). - - Args: - env_ids: Input array of environment indices. Shape is (num_selected_envs,). - body_ids: Input array of body indices. Shape is (num_selected_bodies,). - forces: Input array of forces to apply. Shape is (num_selected_envs, num_selected_bodies). - Can be None if not provided. - torques: Input array of torques to apply. Shape is (num_selected_envs, num_selected_bodies). - Can be None if not provided. - positions: Input array of position offsets for force application. - Shape is (num_selected_envs, num_selected_bodies). Can be None if not provided. - link_poses: Input array of link frame poses in world frame. - Shape is (num_envs, num_bodies). - is_global: Input flag indicating whether forces/torques/positions are in the global frame. - composed_forces_b: Output array where forces in the link frame are written. - Shape is (num_envs, num_bodies). - composed_torques_b: Output array where torques in the link frame are written. - Shape is (num_envs, num_bodies). + Same routing logic as :func:`set_forces_to_dual_buffers_index` but uses ``+=`` instead of ``=``. + Dispatched with ``dim=(len(env_ids), len(body_ids))``. """ - # get the thread id tid_env, tid_body = wp.tid() + ei = env_ids[tid_env] + bi = body_ids[tid_body] - # set the torques to the composed torque - if torques: - composed_torques_b[env_ids[tid_env], body_ids[tid_body]] = cast_torque_to_link_frame( - torques[tid_env, tid_body], - wp.transform_get_rotation(link_poses[env_ids[tid_env], body_ids[tid_body]]), - is_global, - ) - # set the forces to the composed force, if the positions are provided, adds a torque to the composed torque - # from the force at that position. - if forces: - # set the forces to the composed force - composed_forces_b[env_ids[tid_env], body_ids[tid_body]] = cast_force_to_link_frame( - forces[tid_env, tid_body], - wp.transform_get_rotation(link_poses[env_ids[tid_env], body_ids[tid_body]]), - is_global, - ) - # if there is a position offset, set the torque from the force at that position. - if positions: - composed_torques_b[env_ids[tid_env], body_ids[tid_body]] = wp.skew( - cast_to_link_frame( - positions[tid_env, tid_body], - wp.transform_get_translation(link_poses[env_ids[tid_env], body_ids[tid_body]]), - is_global, + if is_global: + if forces: + if positions: + global_force_w[ei, bi] = global_force_w[ei, bi] + forces[tid_env, tid_body] + global_torque_w[ei, bi] = global_torque_w[ei, bi] + wp.cross( + positions[tid_env, tid_body], forces[tid_env, tid_body] ) - ) @ cast_force_to_link_frame( - forces[tid_env, tid_body], - wp.transform_get_rotation(link_poses[env_ids[tid_env], body_ids[tid_body]]), - is_global, - ) + else: + global_force_at_com_w[ei, bi] = global_force_at_com_w[ei, bi] + forces[tid_env, tid_body] + if torques: + global_torque_w[ei, bi] = global_torque_w[ei, bi] + torques[tid_env, tid_body] + else: + if forces: + local_force_b[ei, bi] = local_force_b[ei, bi] + forces[tid_env, tid_body] + if positions: + local_torque_b[ei, bi] = local_torque_b[ei, bi] + wp.cross( + positions[tid_env, tid_body], forces[tid_env, tid_body] + ) + if torques: + local_torque_b[ei, bi] = local_torque_b[ei, bi] + torques[tid_env, tid_body] @wp.kernel -def add_forces_and_torques_at_position_mask( +def set_forces_to_dual_buffers_mask( env_mask: wp.array(dtype=wp.bool), body_mask: wp.array(dtype=wp.bool), forces: wp.array2d(dtype=wp.vec3f), torques: wp.array2d(dtype=wp.vec3f), positions: wp.array2d(dtype=wp.vec3f), - link_poses: wp.array2d(dtype=wp.transformf), + global_force_w: wp.array2d(dtype=wp.vec3f), + global_torque_w: wp.array2d(dtype=wp.vec3f), + global_force_at_com_w: wp.array2d(dtype=wp.vec3f), + local_force_b: wp.array2d(dtype=wp.vec3f), + local_torque_b: wp.array2d(dtype=wp.vec3f), is_global: bool, - composed_forces_b: wp.array2d(dtype=wp.vec3f), - composed_torques_b: wp.array2d(dtype=wp.vec3f), ): - """Add forces and torques to the composed wrench at user-provided positions using mask selection. - - When is_global is False, the user-provided positions offset the force application relative to - the link frame. When is_global is True, positions are in the global frame. Results are - accumulated (added) into the composed buffers. Only entries where both env_mask and body_mask - are True are processed. - - .. note:: - Expects full data from the user (num_envs x num_bodies). + """Set forces/torques into dual buffers using mask selection (overwrites). - Args: - env_mask: Input boolean mask for environments. Shape is (num_envs,). - body_mask: Input boolean mask for bodies. Shape is (num_bodies,). - forces: Input array of forces to apply. Shape is (num_envs, num_bodies). - Can be None if not provided. - torques: Input array of torques to apply. Shape is (num_envs, num_bodies). - Can be None if not provided. - positions: Input array of position offsets for force application. - Shape is (num_envs, num_bodies). Can be None if not provided. - link_poses: Input array of link frame poses in world frame. - Shape is (num_envs, num_bodies). - is_global: Input flag indicating whether forces/torques/positions are in the global frame. - composed_forces_b: Output array where forces in the link frame are accumulated. - Shape is (num_envs, num_bodies). - composed_torques_b: Output array where torques in the link frame are accumulated. - Shape is (num_envs, num_bodies). + Same routing logic as :func:`set_forces_to_dual_buffers_index` but threads are gated by + ``env_mask[tid_env] and body_mask[tid_body]``, and indices are direct (no indirection array). + Dispatched with ``dim=(num_envs, num_bodies)``. """ - # get the thread id tid_env, tid_body = wp.tid() if env_mask[tid_env] and body_mask[tid_body]: - # add the forces to the composed force, if the positions are provided, also adds a torque to the composed - # torque. - if forces: - # add the forces to the composed force - composed_forces_b[tid_env, tid_body] += cast_force_to_link_frame( - forces[tid_env, tid_body], wp.transform_get_rotation(link_poses[tid_env, tid_body]), is_global - ) - # if there is a position offset, add a torque to the composed torque. - if positions: - composed_torques_b[tid_env, tid_body] += wp.skew( - cast_to_link_frame( - positions[tid_env, tid_body], - wp.transform_get_translation(link_poses[tid_env, tid_body]), - is_global, - ) - ) @ cast_force_to_link_frame( - forces[tid_env, tid_body], wp.transform_get_rotation(link_poses[tid_env, tid_body]), is_global - ) - if torques: - composed_torques_b[tid_env, tid_body] += cast_torque_to_link_frame( - torques[tid_env, tid_body], wp.transform_get_rotation(link_poses[tid_env, tid_body]), is_global - ) + if is_global: + if torques: + global_torque_w[tid_env, tid_body] = torques[tid_env, tid_body] + if forces: + if positions: + global_force_w[tid_env, tid_body] = forces[tid_env, tid_body] + if torques: + global_torque_w[tid_env, tid_body] = global_torque_w[tid_env, tid_body] + wp.cross( + positions[tid_env, tid_body], forces[tid_env, tid_body] + ) + else: + global_torque_w[tid_env, tid_body] = wp.cross( + positions[tid_env, tid_body], forces[tid_env, tid_body] + ) + else: + global_force_at_com_w[tid_env, tid_body] = forces[tid_env, tid_body] + else: + if torques: + local_torque_b[tid_env, tid_body] = torques[tid_env, tid_body] + if forces: + local_force_b[tid_env, tid_body] = forces[tid_env, tid_body] + if positions: + if torques: + local_torque_b[tid_env, tid_body] = local_torque_b[tid_env, tid_body] + wp.cross( + positions[tid_env, tid_body], forces[tid_env, tid_body] + ) + else: + local_torque_b[tid_env, tid_body] = wp.cross( + positions[tid_env, tid_body], forces[tid_env, tid_body] + ) @wp.kernel -def set_forces_and_torques_at_position_mask( +def add_forces_to_dual_buffers_mask( env_mask: wp.array(dtype=wp.bool), body_mask: wp.array(dtype=wp.bool), forces: wp.array2d(dtype=wp.vec3f), torques: wp.array2d(dtype=wp.vec3f), positions: wp.array2d(dtype=wp.vec3f), - link_poses: wp.array2d(dtype=wp.transformf), + global_force_w: wp.array2d(dtype=wp.vec3f), + global_torque_w: wp.array2d(dtype=wp.vec3f), + global_force_at_com_w: wp.array2d(dtype=wp.vec3f), + local_force_b: wp.array2d(dtype=wp.vec3f), + local_torque_b: wp.array2d(dtype=wp.vec3f), is_global: bool, - composed_forces_b: wp.array2d(dtype=wp.vec3f), - composed_torques_b: wp.array2d(dtype=wp.vec3f), ): - """Set forces and torques to the composed wrench at user-provided positions using mask selection. + """Add forces/torques into dual buffers using mask selection (accumulates). - When is_global is False, the user-provided positions offset the force application relative to - the link frame. When is_global is True, positions are in the global frame. Results are - overwritten (set) in the composed buffers. Only entries where both env_mask and body_mask - are True are processed. - - .. note:: - Expects full data from the user (num_envs x num_bodies). - - Args: - env_mask: Input boolean mask for environments. Shape is (num_envs,). - body_mask: Input boolean mask for bodies. Shape is (num_bodies,). - forces: Input array of forces to apply. Shape is (num_envs, num_bodies). - Can be None if not provided. - torques: Input array of torques to apply. Shape is (num_envs, num_bodies). - Can be None if not provided. - positions: Input array of position offsets for force application. - Shape is (num_envs, num_bodies). Can be None if not provided. - link_poses: Input array of link frame poses in world frame. - Shape is (num_envs, num_bodies). - is_global: Input flag indicating whether forces/torques/positions are in the global frame. - composed_forces_b: Output array where forces in the link frame are written. - Shape is (num_envs, num_bodies). - composed_torques_b: Output array where torques in the link frame are written. - Shape is (num_envs, num_bodies). + Same routing logic as :func:`add_forces_to_dual_buffers_index` but threads are gated by + ``env_mask[tid_env] and body_mask[tid_body]``. + Dispatched with ``dim=(num_envs, num_bodies)``. """ - # get the thread id tid_env, tid_body = wp.tid() - # set the torques to the composed torque if env_mask[tid_env] and body_mask[tid_body]: - if torques: - composed_torques_b[tid_env, tid_body] = cast_torque_to_link_frame( - torques[tid_env, tid_body], wp.transform_get_rotation(link_poses[tid_env, tid_body]), is_global - ) - # set the forces to the composed force, if the positions are provided, adds a torque to the composed torque - # from the force at that position. - if forces: - # set the forces to the composed force - composed_forces_b[tid_env, tid_body] = cast_force_to_link_frame( - forces[tid_env, tid_body], wp.transform_get_rotation(link_poses[tid_env, tid_body]), is_global - ) - # if there is a position offset, set the torque from the force at that position. - if positions: - composed_torques_b[tid_env, tid_body] = wp.skew( - cast_to_link_frame( - positions[tid_env, tid_body], - wp.transform_get_translation(link_poses[tid_env, tid_body]), - is_global, + if is_global: + if forces: + if positions: + global_force_w[tid_env, tid_body] = global_force_w[tid_env, tid_body] + forces[tid_env, tid_body] + global_torque_w[tid_env, tid_body] = global_torque_w[tid_env, tid_body] + wp.cross( + positions[tid_env, tid_body], forces[tid_env, tid_body] ) - ) @ cast_force_to_link_frame( - forces[tid_env, tid_body], wp.transform_get_rotation(link_poses[tid_env, tid_body]), is_global - ) + else: + global_force_at_com_w[tid_env, tid_body] = ( + global_force_at_com_w[tid_env, tid_body] + forces[tid_env, tid_body] + ) + if torques: + global_torque_w[tid_env, tid_body] = global_torque_w[tid_env, tid_body] + torques[tid_env, tid_body] + else: + if forces: + local_force_b[tid_env, tid_body] = local_force_b[tid_env, tid_body] + forces[tid_env, tid_body] + if positions: + local_torque_b[tid_env, tid_body] = local_torque_b[tid_env, tid_body] + wp.cross( + positions[tid_env, tid_body], forces[tid_env, tid_body] + ) + if torques: + local_torque_b[tid_env, tid_body] = local_torque_b[tid_env, tid_body] + torques[tid_env, tid_body] @wp.kernel -def reset_wrench_composer_index( - env_ids: wp.array(dtype=wp.int32), - composed_forces_b: wp.array2d(dtype=wp.vec3f), - composed_torques_b: wp.array2d(dtype=wp.vec3f), +def add_raw_wrench_buffers( + src_gf: wp.array2d(dtype=wp.vec3f), + src_gt: wp.array2d(dtype=wp.vec3f), + src_gfc: wp.array2d(dtype=wp.vec3f), + src_lf: wp.array2d(dtype=wp.vec3f), + src_lt: wp.array2d(dtype=wp.vec3f), + dst_gf: wp.array2d(dtype=wp.vec3f), + dst_gt: wp.array2d(dtype=wp.vec3f), + dst_gfc: wp.array2d(dtype=wp.vec3f), + dst_lf: wp.array2d(dtype=wp.vec3f), + dst_lt: wp.array2d(dtype=wp.vec3f), ): - """Reset the composed force and torque to zero at the specified environment indices. + """Element-wise add all five source wrench buffers into destination buffers. - Args: - env_ids: Input array of environment indices to reset. Shape is (num_selected_envs,). - composed_forces_b: Output array where forces are zeroed. Shape is (num_envs, num_bodies). - composed_torques_b: Output array where torques are zeroed. Shape is (num_envs, num_bodies). + Dispatched with ``dim=(num_envs, num_bodies)``. Each ``src_*`` / ``dst_*`` pair corresponds + to one of the five input buffers (global_force_w, global_torque_w, global_force_at_com_w, + local_force_b, local_torque_b). """ + tid_env, tid_body = wp.tid() + dst_gf[tid_env, tid_body] = dst_gf[tid_env, tid_body] + src_gf[tid_env, tid_body] + dst_gt[tid_env, tid_body] = dst_gt[tid_env, tid_body] + src_gt[tid_env, tid_body] + dst_gfc[tid_env, tid_body] = dst_gfc[tid_env, tid_body] + src_gfc[tid_env, tid_body] + dst_lf[tid_env, tid_body] = dst_lf[tid_env, tid_body] + src_lf[tid_env, tid_body] + dst_lt[tid_env, tid_body] = dst_lt[tid_env, tid_body] + src_lt[tid_env, tid_body] - # get the thread id + +@wp.kernel +def compose_wrench_to_body_frame( + global_force_w: wp.array2d(dtype=wp.vec3f), + global_torque_w: wp.array2d(dtype=wp.vec3f), + global_force_at_com_w: wp.array2d(dtype=wp.vec3f), + local_force_b: wp.array2d(dtype=wp.vec3f), + local_torque_b: wp.array2d(dtype=wp.vec3f), + com_pos_w: wp.array2d(dtype=wp.vec3f), + link_quat_w: wp.array2d(dtype=wp.quatf), + out_force_b: wp.array2d(dtype=wp.vec3f), + out_torque_b: wp.array2d(dtype=wp.vec3f), +): + """Compose global and local wrench buffers into a single body-frame output. + + Global torques store the moment of positional forces about the world origin: ``cross(P, F)``. + This kernel corrects to be about the body's CoM via ``cross(P, F) - cross(com_pos_w, F) = + cross(P - com_pos_w, F)``, then rotates both force and torque into the body frame using + ``quat_rotate_inv(link_quat_w, ...)``, and adds local-frame values. + + Dispatched with ``dim=(num_envs, num_bodies)``. + """ tid_env, tid_body = wp.tid() + total_force_w = global_force_w[tid_env, tid_body] + global_force_at_com_w[tid_env, tid_body] + corrected_torque_w = global_torque_w[tid_env, tid_body] - wp.cross( + com_pos_w[tid_env, tid_body], global_force_w[tid_env, tid_body] + ) + out_force_b[tid_env, tid_body] = ( + wp.quat_rotate_inv(link_quat_w[tid_env, tid_body], total_force_w) + local_force_b[tid_env, tid_body] + ) + out_torque_b[tid_env, tid_body] = ( + wp.quat_rotate_inv(link_quat_w[tid_env, tid_body], corrected_torque_w) + local_torque_b[tid_env, tid_body] + ) + + +@wp.kernel +def reset_wrench_composer_index( + env_ids: wp.array(dtype=wp.int32), + global_force_w: wp.array2d(dtype=wp.vec3f), + global_torque_w: wp.array2d(dtype=wp.vec3f), + global_force_at_com_w: wp.array2d(dtype=wp.vec3f), + local_force_b: wp.array2d(dtype=wp.vec3f), + local_torque_b: wp.array2d(dtype=wp.vec3f), + out_force_b: wp.array2d(dtype=wp.vec3f), + out_torque_b: wp.array2d(dtype=wp.vec3f), +): + """Zero all 7 wrench composer buffers at the specified environment indices. - # reset the composed force and torque - composed_forces_b[env_ids[tid_env], tid_body] = wp.vec3f(0.0) - composed_torques_b[env_ids[tid_env], tid_body] = wp.vec3f(0.0) + Dispatched with ``dim=(len(env_ids), num_bodies)``. + """ + tid_env, tid_body = wp.tid() + ei = env_ids[tid_env] + z = wp.vec3f(0.0) + global_force_w[ei, tid_body] = z + global_torque_w[ei, tid_body] = z + global_force_at_com_w[ei, tid_body] = z + local_force_b[ei, tid_body] = z + local_torque_b[ei, tid_body] = z + out_force_b[ei, tid_body] = z + out_torque_b[ei, tid_body] = z @wp.kernel def reset_wrench_composer_mask( env_mask: wp.array(dtype=wp.bool), - composed_forces_b: wp.array2d(dtype=wp.vec3f), - composed_torques_b: wp.array2d(dtype=wp.vec3f), + global_force_w: wp.array2d(dtype=wp.vec3f), + global_torque_w: wp.array2d(dtype=wp.vec3f), + global_force_at_com_w: wp.array2d(dtype=wp.vec3f), + local_force_b: wp.array2d(dtype=wp.vec3f), + local_torque_b: wp.array2d(dtype=wp.vec3f), + out_force_b: wp.array2d(dtype=wp.vec3f), + out_torque_b: wp.array2d(dtype=wp.vec3f), ): - """Reset the composed force and torque to zero for environments matching the mask. + """Zero all 7 wrench composer buffers for environments matching the mask. - Args: - env_mask: Input boolean mask for environments. Shape is (num_envs,). - composed_forces_b: Output array where forces are zeroed. Shape is (num_envs, num_bodies). - composed_torques_b: Output array where torques are zeroed. Shape is (num_envs, num_bodies). + Dispatched with ``dim=(num_envs, num_bodies)``. """ - # get the thread id tid_env, tid_body = wp.tid() - - # reset the composed force and torque if env_mask[tid_env]: - composed_forces_b[tid_env, tid_body] = wp.vec3f(0.0) - composed_torques_b[tid_env, tid_body] = wp.vec3f(0.0) + z = wp.vec3f(0.0) + global_force_w[tid_env, tid_body] = z + global_torque_w[tid_env, tid_body] = z + global_force_at_com_w[tid_env, tid_body] = z + local_force_b[tid_env, tid_body] = z + local_torque_b[tid_env, tid_body] = z + out_force_b[tid_env, tid_body] = z + out_torque_b[tid_env, tid_body] = z diff --git a/source/isaaclab/isaaclab/utils/warp/math_ops.py b/source/isaaclab/isaaclab/utils/warp/math_ops.py new file mode 100644 index 000000000000..36a0f960a8b7 --- /dev/null +++ b/source/isaaclab/isaaclab/utils/warp/math_ops.py @@ -0,0 +1,34 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +import warp as wp + + +def transform_to_vec_quat( + t: wp.array, +) -> tuple[wp.array, wp.array]: + """Split a wp.transformf array into position (vec3f) and quaternion (quatf) arrays. + + Zero-copy: returns views into the same underlying memory. + + Args: + t: Array of transforms (dtype=wp.transformf). Shape ``(N,)``, ``(N, M)``, or ``(N, M, K)``. + + Returns: + Tuple of (positions, quaternions) as warp array views with matching dimensionality. + + Raises: + TypeError: If *t* does not have dtype ``wp.transformf``. + """ + if t.dtype != wp.transformf: + raise TypeError(f"Expected wp.transformf array, got dtype={t.dtype}") + floats = t.view(wp.float32) + if t.ndim == 1: + return floats[:, :3].view(wp.vec3f), floats[:, 3:].view(wp.quatf) + if t.ndim == 2: + return floats[:, :, :3].view(wp.vec3f), floats[:, :, 3:].view(wp.quatf) + if t.ndim == 3: + return floats[:, :, :, :3].view(wp.vec3f), floats[:, :, :, 3:].view(wp.quatf) + raise ValueError(f"Expected 1D, 2D, or 3D transform array, got ndim={t.ndim}") diff --git a/source/isaaclab/isaaclab/utils/warp/ops.py b/source/isaaclab/isaaclab/utils/warp/ops.py index 313a7fd43afb..a3ee273b627c 100644 --- a/source/isaaclab/isaaclab/utils/warp/ops.py +++ b/source/isaaclab/isaaclab/utils/warp/ops.py @@ -19,6 +19,10 @@ from . import kernels +# Cache of all-True env masks keyed by (n_envs, device) to avoid per-call allocations in +# raycast_dynamic_meshes. Populated lazily on first call with a given (n_envs, device) pair. +_all_env_mask_cache: dict[tuple[int, str], wp.array] = {} + def raycast_mesh( ray_starts: torch.Tensor, @@ -335,11 +339,19 @@ def raycast_dynamic_meshes( mesh_orientations_w = mesh_orientations_w.to(dtype=torch.float32, device=torch_device).contiguous() mesh_quat_wp_w = wp.from_torch(mesh_orientations_w, dtype=wp.quat) + # All environments active when called through this public API. + # Cache the mask by (n_envs, device) to avoid a per-call allocation. + cache_key = (n_envs, str(torch_device)) + if cache_key not in _all_env_mask_cache: + _all_env_mask_cache[cache_key] = wp.from_torch(torch.ones(n_envs, dtype=torch.bool, device=torch_device)) + all_env_mask = _all_env_mask_cache[cache_key] + # launch the warp kernel wp.launch( kernel=kernels.raycast_dynamic_meshes_kernel, dim=[n_meshes, n_envs, n_rays_per_env], inputs=[ + all_env_mask, mesh_ids_wp, ray_starts_wp, ray_directions_wp, diff --git a/source/isaaclab/isaaclab/utils/warp/proxy_array.py b/source/isaaclab/isaaclab/utils/warp/proxy_array.py new file mode 100644 index 000000000000..912e44798877 --- /dev/null +++ b/source/isaaclab/isaaclab/utils/warp/proxy_array.py @@ -0,0 +1,338 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Warp-first dual-access array wrapper with explicit ``.torch`` and ``.warp`` accessors. + +Inspired by ProxyArray from mujocolab/mjlab (BSD-3-Clause). +""" + +from __future__ import annotations + +import os +import warnings +from typing import ClassVar + +import torch +import warp as wp + +_QUATF_ACCESS_WARN_ENV = "WARN_ON_TORCH_QUATF_ACCESS" +"""Environment variable that, when set to ``"1"``, makes :attr:`ProxyArray.torch` +emit a :class:`UserWarning` on every read of a ``wp.quatf``-typed array. Used as a +runtime aid for tracking down call sites that may still assume Isaac Lab 2.x's +``(w, x, y, z)`` quaternion convention after the migration to Isaac Lab 3.x's +``(x, y, z, w)`` convention. See the Isaac Lab 3.0 migration guide for details.""" + + +class ProxyArray: + """Warp-first array wrapper providing cached zero-copy ``.torch`` and ``.warp`` accessors. + + This class wraps a :class:`warp.array` and provides: + + * A ``.warp`` property that returns the original warp array (for kernel interop). + * A ``.torch`` property that returns a cached, zero-copy :class:`torch.Tensor` view + (via :func:`warp.to_torch`). + * Convenience properties (``shape``, ``dtype``, ``device``) delegated to the warp array. + * A deprecation bridge for common torch functions, indexing, and arithmetic/comparison + operators while emitting a one-time :class:`DeprecationWarning`. Tensor instance methods + such as ``clone()`` are not forwarded; use explicit ``.torch`` access for those. + + Example: + + .. code-block:: python + + import warp as wp + from isaaclab.utils.warp.proxy_array import ProxyArray + + arr = wp.zeros(100, dtype=wp.vec3f, device="cuda:0") + ta = ProxyArray(arr) + + # Explicit access (preferred) + ta.warp # -> wp.array, shape (100,), dtype vec3f + ta.torch # -> torch.Tensor, shape (100, 3) + + # Deprecation bridge (warns once, then silent) + result = ta + 1.0 # works, emits DeprecationWarning + """ + + _deprecation_warned: ClassVar[bool] = False + """Class-level flag ensuring the deprecation warning is emitted at most once.""" + + def __init__(self, wp_array: wp.array) -> None: + """Initialize the ProxyArray wrapper. + + The instance is immutable after construction: the wrapped ``wp.array`` cannot + be reassigned. If the underlying simulation memory is re-allocated, construct + a new :class:`ProxyArray` instead of mutating an existing one. + + Args: + wp_array: The warp array to wrap. + + Raises: + TypeError: If ``wp_array`` is not a :class:`warp.array`. + """ + if not isinstance(wp_array, wp.array): + raise TypeError( + f"ProxyArray expects a warp.array, got {type(wp_array).__name__}." + " If you have a ProxyArray, use it directly instead of wrapping it again." + ) + # Bypass __setattr__ for the two internal fields — everything else raises. + object.__setattr__(self, "_warp", wp_array) + object.__setattr__(self, "_torch_cache", None) + # Cached once at construction so the .torch read path stays a constant-time + # check; only used when the WARN_ON_TORCH_QUATF_ACCESS env var is set. + object.__setattr__(self, "_is_quatf", wp_array.dtype is wp.quatf) + + def __setattr__(self, name: str, value) -> None: + """Forbid mutation of ProxyArray instances except for the internal torch cache. + + The torch view is populated lazily on first ``.torch`` access; that is the + only allowed post-init state change. Every other write raises + :class:`AttributeError` so callers don't accidentally re-point the wrapper. + """ + if name == "_torch_cache": + object.__setattr__(self, name, value) + return + raise AttributeError( + f"ProxyArray is immutable; cannot set attribute {name!r}." + " Construct a new ProxyArray instead of mutating an existing one." + ) + + @staticmethod + def _quatf_access_warning_enabled() -> bool: + """Return ``True`` when the ``WARN_ON_TORCH_QUATF_ACCESS`` env var is set to ``"1"``. + + Read on every :attr:`torch` access to keep the flag dynamic — a single + ``os.environ`` lookup is cheap relative to the warp/torch interop work + that follows. + """ + return os.environ.get(_QUATF_ACCESS_WARN_ENV, "0") == "1" + + # ------------------------------------------------------------------ + # Core accessors + # ------------------------------------------------------------------ + + @property + def warp(self) -> wp.array: + """The underlying warp array.""" + return self._warp + + @property + def torch(self) -> torch.Tensor: + """A cached, zero-copy :class:`torch.Tensor` view of the warp array. + + The tensor is created on first access via :func:`warp.to_torch` and cached + for subsequent calls. Since this is a zero-copy view, modifications to the + tensor are visible through the warp array and vice versa. + + When the underlying warp array has dtype ``wp.quatf`` and the + ``WARN_ON_TORCH_QUATF_ACCESS`` environment variable is set to ``"1"``, + each read emits a :class:`UserWarning` pointing at the call site. This + is a runtime aid for migrating Isaac Lab 2.x code (which used the + ``(w, x, y, z)`` quaternion convention) to Isaac Lab 3.x's + ``(x, y, z, w)`` convention. + """ + if self._is_quatf and self._quatf_access_warning_enabled(): + warnings.warn( + "Reading .torch on a wp.quatf-typed ProxyArray. The Isaac Lab" + " quaternion convention changed from (w, x, y, z) in 2.x to" + " (x, y, z, w) in 3.x. If your code assumes the old order," + " this is likely the source of incorrect rotations." + f" Unset {_QUATF_ACCESS_WARN_ENV} to silence this warning.", + UserWarning, + stacklevel=2, + ) + if self._torch_cache is None: + self._torch_cache = wp.to_torch(self._warp) + return self._torch_cache + + # ------------------------------------------------------------------ + # Convenience properties + # ------------------------------------------------------------------ + + @property + def shape(self) -> tuple[int, ...]: + """Shape of the underlying warp array.""" + return self._warp.shape + + @property + def dtype(self): + """Warp dtype of the underlying array.""" + return self._warp.dtype + + @property + def device(self) -> str: + """Device string of the underlying warp array.""" + return self._warp.device + + def __len__(self) -> int: + """Return the size of the first dimension.""" + return self._warp.shape[0] + + def __repr__(self) -> str: + """Return a string representation of the ProxyArray.""" + return f"ProxyArray(shape={self.shape}, dtype={self.dtype}, device={self.device})" + + # ------------------------------------------------------------------ + # Warp kernel interop + # ------------------------------------------------------------------ + + @property + def __cuda_array_interface__(self): + """Delegate the CUDA array interface to the underlying warp array. + + This allows a ``ProxyArray`` to be passed directly as an argument to + :func:`warp.launch` without explicitly accessing ``.warp``. + + Raises: + AttributeError: If the underlying warp array is not on a CUDA device. + """ + return self._warp.__cuda_array_interface__ + + @property + def __array_interface__(self): + """Delegate the NumPy array interface to the underlying warp array. + + This allows a ``ProxyArray`` to be passed directly as an argument to + :func:`warp.launch` on CPU without explicitly accessing ``.warp``. + + Raises: + AttributeError: If the underlying warp array is not on a CPU device. + """ + return self._warp.__array_interface__ + + # ------------------------------------------------------------------ + # Indexing (deprecation bridge — delegates to .torch) + # ------------------------------------------------------------------ + + def __getitem__(self, key): + """Index into the torch view of this array. + + Supports all torch indexing: ``int``, ``slice``, ``tuple``, + boolean masks, and fancy indexing (multi-dimensional). + """ + self._warn_implicit() + return self.torch[key] + + def __setitem__(self, key, value): + """Write through the torch view into the shared warp memory. + + Supports all torch indexing: ``int``, ``slice``, ``tuple``, + boolean masks, and fancy indexing (multi-dimensional). + """ + self._warn_implicit() + self.torch[key] = value + + # ------------------------------------------------------------------ + # Deprecation bridge + # ------------------------------------------------------------------ + + @classmethod + def _warn_implicit(cls) -> None: + """Emit a one-time deprecation warning for implicit torch usage.""" + if not cls._deprecation_warned: + cls._deprecation_warned = True + warnings.warn( + "Implicit use of ProxyArray as a torch.Tensor is deprecated. " + "Use the explicit .torch property instead (e.g., array.torch).", + DeprecationWarning, + stacklevel=3, + ) + + @classmethod + def __torch_function__(cls, func, types, args=(), kwargs=None): + """Enable torch operations on ProxyArray by unwrapping to ``.torch``. + + This method is called by PyTorch when a torch function receives a + ``ProxyArray`` as an argument. It unwraps all ``ProxyArray`` instances + to their ``.torch`` tensors and delegates to the original function. + """ + if kwargs is None: + kwargs = {} + cls._warn_implicit() + + def unwrap(x): + if isinstance(x, ProxyArray): + return x.torch + if isinstance(x, (list, tuple)): + return type(x)(unwrap(i) for i in x) + return x + + args = unwrap(args) + kwargs = {k: unwrap(v) for k, v in kwargs.items()} + return func(*args, **kwargs) + + # ------------------------------------------------------------------ + # Arithmetic operators + # ------------------------------------------------------------------ + + def _binop(self, other, op: str) -> torch.Tensor: + """Helper for binary and reflected binary operations.""" + self._warn_implicit() + other_val = other.torch if isinstance(other, ProxyArray) else other + return getattr(self.torch, op)(other_val) + + def __add__(self, other) -> torch.Tensor: + return self._binop(other, "__add__") + + def __radd__(self, other) -> torch.Tensor: + return self._binop(other, "__radd__") + + def __sub__(self, other) -> torch.Tensor: + return self._binop(other, "__sub__") + + def __rsub__(self, other) -> torch.Tensor: + return self._binop(other, "__rsub__") + + def __mul__(self, other) -> torch.Tensor: + return self._binop(other, "__mul__") + + def __rmul__(self, other) -> torch.Tensor: + return self._binop(other, "__rmul__") + + def __truediv__(self, other) -> torch.Tensor: + return self._binop(other, "__truediv__") + + def __rtruediv__(self, other) -> torch.Tensor: + return self._binop(other, "__rtruediv__") + + def __pow__(self, other) -> torch.Tensor: + return self._binop(other, "__pow__") + + def __rpow__(self, other) -> torch.Tensor: + return self._binop(other, "__rpow__") + + def __neg__(self) -> torch.Tensor: + self._warn_implicit() + return -self.torch + + def __pos__(self) -> torch.Tensor: + self._warn_implicit() + return +self.torch + + def __abs__(self) -> torch.Tensor: + self._warn_implicit() + return abs(self.torch) + + # ------------------------------------------------------------------ + # Comparison operators + # ------------------------------------------------------------------ + + def __eq__(self, other) -> torch.Tensor: + return self._binop(other, "__eq__") + + def __ne__(self, other) -> torch.Tensor: + return self._binop(other, "__ne__") + + def __lt__(self, other) -> torch.Tensor: + return self._binop(other, "__lt__") + + def __le__(self, other) -> torch.Tensor: + return self._binop(other, "__le__") + + def __gt__(self, other) -> torch.Tensor: + return self._binop(other, "__gt__") + + def __ge__(self, other) -> torch.Tensor: + return self._binop(other, "__ge__") diff --git a/source/isaaclab/isaaclab/utils/warp/utils.py b/source/isaaclab/isaaclab/utils/warp/utils.py new file mode 100644 index 000000000000..2df288dfba2c --- /dev/null +++ b/source/isaaclab/isaaclab/utils/warp/utils.py @@ -0,0 +1,151 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from __future__ import annotations + +import functools +from collections.abc import Sequence + +import torch +import warp as wp + +## +# Mask resolution - ids/mask to warp boolean mask. +## + + +@wp.kernel +def _populate_mask_from_ids( + mask: wp.array(dtype=wp.bool), + ids: wp.array(dtype=wp.int32), +): + i = wp.tid() + mask[ids[i]] = True + + +def resolve_1d_mask( + *, + ids: Sequence[int] | slice | torch.Tensor | wp.array | None = None, + mask: wp.array | torch.Tensor | None = None, + all_mask: wp.array, + scratch_mask: wp.array, + device: str, +) -> wp.array: + """Resolve ids/mask into a warp boolean mask. + + Callers provide pre-allocated ``all_mask`` (all-True) and ``scratch_mask`` (reusable + work buffer) so this function never allocates. + + Args: + ids: Index ids. Accepts ``Sequence[int]``, ``slice``, ``torch.Tensor``, + ``wp.array(dtype=wp.int32)``, or ``None`` (all elements). + mask: Direct boolean mask. ``wp.array`` is returned as-is; + ``torch.Tensor`` is converted. + all_mask: Pre-allocated all-True mask returned when both *ids* and *mask* + are ``None``. + scratch_mask: Pre-allocated scratch buffer populated in-place when *ids* + are provided. Not re-entrant (shared buffer). + device: Warp device string (e.g. ``"cuda:0"``). + + Returns: + A ``wp.array(dtype=wp.bool)`` mask. + """ + # Normalize slice(None) to None so the capture guard treats it identically to ids=None. + if isinstance(ids, slice) and ids == slice(None): + ids = None + + if wp.get_device().is_capturing: + if ids is not None or (mask is not None and not isinstance(mask, wp.array)): + raise RuntimeError( + "resolve_1d_mask is only capturable when mask is a wp.array or both ids and mask are None." + ) + + # --- Direct mask input --- + if mask is not None: + if isinstance(mask, wp.array): + return mask + if isinstance(mask, torch.Tensor): + if mask.dtype != torch.bool: + mask = mask.to(dtype=torch.bool) + if str(mask.device) != device: + mask = mask.to(device) + return wp.from_torch(mask, dtype=wp.bool) + raise TypeError(f"Unsupported mask type: {type(mask)}") + + # --- Fast path: all elements --- + if ids is None: + return all_mask + + # --- Normalize slice to list --- + if isinstance(ids, slice): + start, stop, step = ids.indices(scratch_mask.shape[0]) + ids = list(range(start, stop, step)) + + # --- Normalize to concrete type --- + if not isinstance(ids, (torch.Tensor, wp.array)): + ids = list(ids) + + # --- Populate scratch mask --- + scratch_mask.fill_(False) + + if isinstance(ids, torch.Tensor): + if ids.numel() == 0: + return scratch_mask + if str(ids.device) != device: + ids = ids.to(device) + if ids.dtype != torch.int32: + ids = ids.to(dtype=torch.int32) + if not ids.is_contiguous(): + ids = ids.contiguous() + ids_wp = wp.from_torch(ids, dtype=wp.int32) + elif isinstance(ids, wp.array): + if ids.shape[0] == 0: + return scratch_mask + if ids.dtype != wp.int32: + raise TypeError(f"Unsupported wp.array dtype for ids: {ids.dtype}. Expected wp.int32 index array.") + ids_wp = ids + else: + if len(ids) == 0: + return scratch_mask + ids_wp = wp.array(ids, dtype=wp.int32, device=device) + + wp.launch(_populate_mask_from_ids, dim=ids_wp.shape[0], inputs=[scratch_mask, ids_wp], device=device) + return scratch_mask + + +## +# Capture safety — property guard. +## + + +def capture_unsafe(reason: str | None = None): + """Mark a callable as not CUDA-graph-capture-safe. + + Raises ``RuntimeError`` if the decorated callable is invoked while + ``wp.get_device().is_capturing`` is ``True``. + + Args: + reason: Optional explanation appended to the error message. + + Usage:: + + @property + @capture_unsafe("Relies on a Python timestamp guard.") + def projected_gravity_b(self) -> wp.array: ... + """ + + def decorator(func): + @functools.wraps(func) + def wrapper(*args, **kwargs): + if wp.get_device().is_capturing: + msg = f"'{func.__qualname__}' cannot be called during CUDA graph capture." + if reason: + msg = f"{msg} {reason}" + raise RuntimeError(msg) + return func(*args, **kwargs) + + return wrapper + + return decorator diff --git a/source/isaaclab/isaaclab/utils/wrench_composer.py b/source/isaaclab/isaaclab/utils/wrench_composer.py index 5ad966a6e4e9..6c9390e97d7b 100644 --- a/source/isaaclab/isaaclab/utils/wrench_composer.py +++ b/source/isaaclab/isaaclab/utils/wrench_composer.py @@ -6,19 +6,23 @@ from __future__ import annotations import warnings +from collections.abc import Sequence from typing import TYPE_CHECKING import numpy as np import torch import warp as wp +from isaaclab.utils.warp import ProxyArray from isaaclab.utils.warp.kernels import ( - add_forces_and_torques_at_position_index, - add_forces_and_torques_at_position_mask, + add_forces_to_dual_buffers_index, + add_forces_to_dual_buffers_mask, + add_raw_wrench_buffers, + compose_wrench_to_body_frame, reset_wrench_composer_index, reset_wrench_composer_mask, - set_forces_and_torques_at_position_index, - set_forces_and_torques_at_position_mask, + set_forces_to_dual_buffers_index, + set_forces_to_dual_buffers_mask, ) if TYPE_CHECKING: @@ -27,16 +31,33 @@ class WrenchComposer: def __init__(self, asset: BaseArticulation | BaseRigidObject | BaseRigidObjectCollection) -> None: - """Wrench composer. + """Wrench composer with dual-buffer architecture. - This class is used to compose forces and torques at the body's link frame. - It can compose global wrenches and local wrenches. The result is always in the link frame of the body. + This class composes forces and torques applied to rigid bodies. Forces and torques can be + specified in either the global (world) frame or the local (body) frame. Internally, they are + stored in separate global and local input buffers. When the final composed wrench is needed, + the global contributions are rotated into the body frame and combined with the local + contributions to produce the output force and torque expressed in the body frame. + + The dual-buffer architecture uses five input buffers: + + - ``global_force_w``: Global forces [N] (world frame). + - ``global_torque_w``: Global torques [N·m] (world frame), including moment contributions + from positional forces (``cross(P, F)``). + - ``global_force_at_com_w``: Global forces [N] applied at the body's CoM (world frame, no positional torque). + - ``local_force_b``: Local forces [N] (body frame). + - ``local_torque_b``: Local torques [N·m] (body frame). + + And two output buffers: + + - ``out_force_b``: Composed force [N] in body frame. + - ``out_torque_b``: Composed torque [N·m] in body frame. Args: - asset: Asset to use. Defaults to None. + asset: Asset to use. """ self.num_envs = asset.num_instances - # Avoid isinstance to prevent circular import issues, use attribute presence instead. + # Avoid isinstance to prevent circular import issues; check by attribute presence instead. if hasattr(asset, "num_bodies"): self.num_bodies = asset.num_bodies else: @@ -44,16 +65,32 @@ def __init__(self, asset: BaseArticulation | BaseRigidObject | BaseRigidObjectCo self.device = asset.device self._asset = asset self._active = False - - # Avoid isinstance here due to potential circular import issues; check by attribute presence instead. - if hasattr(self._asset.data, "body_link_pose_w"): - self._get_link_pose_fn = lambda a=self._asset: a.data.body_link_pose_w + self._dirty = False + if hasattr(self._asset.data, "body_com_pos_w"): + self._get_com_pos_fn = lambda a=self._asset: a.data.body_com_pos_w.warp else: raise ValueError(f"Unsupported asset type: {self._asset.__class__.__name__}") + if hasattr(self._asset.data, "body_link_quat_w"): + self._get_link_quat_fn = lambda a=self._asset: a.data.body_link_quat_w.warp + else: + raise ValueError(f"Unsupported asset type: {self._asset.__class__.__name__}") + + # -- Input buffers (5 total) -- + self._global_force_w = wp.zeros((self.num_envs, self.num_bodies), dtype=wp.vec3f, device=self.device) + self._global_torque_w = wp.zeros((self.num_envs, self.num_bodies), dtype=wp.vec3f, device=self.device) + self._global_force_at_com_w = wp.zeros((self.num_envs, self.num_bodies), dtype=wp.vec3f, device=self.device) + self._local_force_b = wp.zeros((self.num_envs, self.num_bodies), dtype=wp.vec3f, device=self.device) + self._local_torque_b = wp.zeros((self.num_envs, self.num_bodies), dtype=wp.vec3f, device=self.device) + + # -- Output buffers (2 total) -- + self._out_force_b = wp.zeros((self.num_envs, self.num_bodies), dtype=wp.vec3f, device=self.device) + self._out_torque_b = wp.zeros((self.num_envs, self.num_bodies), dtype=wp.vec3f, device=self.device) - # Create buffers - self._composed_force_b = wp.zeros((self.num_envs, self.num_bodies), dtype=wp.vec3f, device=self.device) - self._composed_torque_b = wp.zeros((self.num_envs, self.num_bodies), dtype=wp.vec3f, device=self.device) + # ProxyArray caches for the output buffers, exposed via the public properties. + self._out_force_b_ta = ProxyArray(self._out_force_b) + self._out_torque_b_ta = ProxyArray(self._out_torque_b) + + # -- Index / mask helper arrays -- self._ALL_ENV_INDICES = wp.array(np.arange(self.num_envs, dtype=np.int32), dtype=wp.int32, device=self.device) self._ALL_BODY_INDICES = wp.array( np.arange(self.num_bodies, dtype=np.int32), dtype=wp.int32, device=self.device @@ -61,44 +98,133 @@ def __init__(self, asset: BaseArticulation | BaseRigidObject | BaseRigidObjectCo self._ALL_ENV_MASK = wp.ones((self.num_envs), dtype=wp.bool, device=self.device) self._ALL_BODY_MASK = wp.ones((self.num_bodies), dtype=wp.bool, device=self.device) - # Temporary buffers for the masks, positions, and forces/torques (reused to avoid allocations) - self._temp_env_mask_wp = wp.zeros((self.num_envs,), dtype=wp.bool, device=self.device) - self._temp_body_mask_wp = wp.zeros((self.num_bodies,), dtype=wp.bool, device=self.device) - self._temp_positions_wp = wp.zeros((self.num_envs, self.num_bodies), dtype=wp.vec3f, device=self.device) - self._temp_forces_wp = wp.zeros((self.num_envs, self.num_bodies), dtype=wp.vec3f, device=self.device) - self._temp_torques_wp = wp.zeros((self.num_envs, self.num_bodies), dtype=wp.vec3f, device=self.device) - - # Flag to check if the link poses have been updated. - self._link_poses_updated = False + # ------------------------------------------------------------------ + # Properties + # ------------------------------------------------------------------ @property def active(self) -> bool: - """Whether the wrench composer is active.""" + """Whether the wrench composer is active (has pending forces/torques). + + Set to ``True`` when any ``add_*`` or ``set_*`` method writes data. Cleared only by a + full :meth:`reset` call (no arguments). Partial resets (with ``env_ids`` or ``env_mask``) + do **not** clear this flag because checking whether all environments are zero would + require scanning the buffers, defeating the purpose of a cheap guard. + + This means the flag may remain ``True`` even if all buffers are zero after partial resets. + This is by design: the cost of an unnecessary compose + apply on zero data is negligible + compared to scanning the buffers every frame. + """ return self._active @property - def composed_force(self) -> wp.array: - """Composed force at the body's link frame. + def global_force_w(self) -> wp.array: + """Global force buffer [N] (world frame), dtype ``wp.vec3f``. Shape: ``(num_envs, num_bodies)``. - .. note:: If some of the forces are applied in the global frame, the composed force will be in the link frame - of the body. + .. note:: + This returns the underlying buffer reference for read-only inspection. Writing to it + directly bypasses the dirty flag and may produce stale output buffers. Use the + ``add_*`` or ``set_*`` methods to modify forces. + """ + return self._global_force_w - Returns: - wp.array: Composed force at the body's link frame. (num_envs, num_bodies, 3) + @property + def global_torque_w(self) -> wp.array: + """Global torque buffer [N·m] (world frame), dtype ``wp.vec3f``. Shape: ``(num_envs, num_bodies)``. + + Stores user-supplied torques plus moment contributions from positional forces (``cross(P, F)``). + + .. note:: + Read-only reference. See :attr:`global_force_w` for caveats on direct writes. """ - return self._composed_force_b + return self._global_torque_w @property - def composed_torque(self) -> wp.array: - """Composed torque at the body's link frame. + def global_force_at_com_w(self) -> wp.array: + """Global force at body's CoM buffer [N] (world frame, no positional torque). - .. note:: If some of the torques are applied in the global frame, the composed torque will be in the link frame - of the body. + dtype ``wp.vec3f``. Shape: ``(num_envs, num_bodies)``. - Returns: - wp.array: Composed torque at the body's link frame. (num_envs, num_bodies, 3) + .. note:: + Read-only reference. See :attr:`global_force_w` for caveats on direct writes. """ - return self._composed_torque_b + return self._global_force_at_com_w + + @property + def local_force_b(self) -> wp.array: + """Local force buffer [N] (body frame), dtype ``wp.vec3f``. Shape: ``(num_envs, num_bodies)``. + + .. note:: + Read-only reference. See :attr:`global_force_w` for caveats on direct writes. + """ + return self._local_force_b + + @property + def local_torque_b(self) -> wp.array: + """Local torque buffer [N·m] (body frame), dtype ``wp.vec3f``. Shape: ``(num_envs, num_bodies)``. + + .. note:: + Read-only reference. See :attr:`global_force_w` for caveats on direct writes. + """ + return self._local_torque_b + + @property + def out_force_b(self) -> ProxyArray: + """Composed output force [N] in the body frame. + + Shape is ``(num_envs, num_bodies)``, dtype = ``wp.vec3f``. In torch this resolves to + ``(num_envs, num_bodies, 3)``. Use ``.warp`` for the underlying :class:`wp.array` or + ``.torch`` for a cached zero-copy :class:`torch.Tensor` view. + + Triggers composition from input buffers if dirty. + """ + self._ensure_composed() + return self._out_force_b_ta + + @property + def out_torque_b(self) -> ProxyArray: + """Composed output torque [N·m] in the body frame. + + Shape is ``(num_envs, num_bodies)``, dtype = ``wp.vec3f``. In torch this resolves to + ``(num_envs, num_bodies, 3)``. Use ``.warp`` for the underlying :class:`wp.array` or + ``.torch`` for a cached zero-copy :class:`torch.Tensor` view. + + Triggers composition from input buffers if dirty. + """ + self._ensure_composed() + return self._out_torque_b_ta + + @property + def composed_force(self) -> ProxyArray: + """Composed force in the body frame. + + .. deprecated:: 4.5.33 + Use :attr:`out_force_b` instead. + """ + warnings.warn( + "The property 'composed_force' is deprecated. Use 'out_force_b' instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.out_force_b + + @property + def composed_torque(self) -> ProxyArray: + """Composed torque in the body frame. + + .. deprecated:: 4.5.33 + Use :attr:`out_torque_b` instead. + """ + warnings.warn( + "The property 'composed_torque' is deprecated. Use 'out_torque_b' instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.out_torque_b + + # ------------------------------------------------------------------ + # Public methods + # ------------------------------------------------------------------ def add_forces_and_torques_index( self, @@ -109,38 +235,26 @@ def add_forces_and_torques_index( env_ids: torch.Tensor | None = None, is_global: bool = False, ): - """Add forces and torques to the composed force and torque. - - Composed force and torque are the sum of all the forces and torques applied to the body. - It can compose global wrenches and local wrenches. The result is always in the link frame of the body. - - The user can provide any combination of forces, torques, and positions. + """Add forces and torques into the input buffers using index-based selection. - .. note:: Users may want to call `reset` function after every simulation step to ensure no force is carried - over to the next step. However, this may not necessary if the user calls `set_forces_and_torques` function - instead of `add_forces_and_torques`. + Accumulates onto whatever is already in the buffers. The result is always composed into the + body frame when the output properties are accessed. Args: - forces: Forces. (len(env_ids), len(body_ids), 3). Defaults to None. - torques: Torques. (len(env_ids), len(body_ids), 3). Defaults to None. - positions: Positions. (len(env_ids), len(body_ids), 3). Defaults to None. - body_ids: Body ids. Defaults to None (all bodies). - env_ids: Environment ids. Defaults to None (all environments). - is_global: Whether the forces and torques are applied in the global frame. Defaults to False. - - Raises: - ValueError: If the type of the input is not supported. - ValueError: If the input is a slice and it is not None. + forces: Forces [N]. Shape: (len(env_ids), len(body_ids), 3). Defaults to None. + torques: Torques [N·m]. Shape: (len(env_ids), len(body_ids), 3). Defaults to None. + positions: The positions [m] at which forces act. If `is_global` is True, these are global + positions expressed in the world frame. If `is_global` is False, these are offsets from the + body's CoM expressed in the body frame. If None, forces are assumed to act at the body's + CoM, independent of the `is_global` flag. + Shape: (len(env_ids), len(body_ids), 3). Defaults to None. + body_ids: Body indices. Defaults to None (all bodies). + env_ids: Environment indices. Defaults to None (all environments). + is_global: Whether the forces and torques are expressed in the global world frame or the local body frame. + Defaults to False. """ - # Resolve all indices - if (env_ids is None) or (env_ids == slice(None)): - env_ids = self._ALL_ENV_INDICES - if isinstance(env_ids, list): - env_ids = wp.array(env_ids, dtype=wp.int32, device=self.device) - if (body_ids is None) or (body_ids == slice(None)): - body_ids = self._ALL_BODY_INDICES - if isinstance(body_ids, list): - body_ids = wp.array(body_ids, dtype=wp.int32, device=self.device) + env_ids = self._resolve_env_ids(env_ids) + body_ids = self._resolve_body_ids(body_ids) if forces is None and torques is None: warnings.warn( "No forces or torques provided. No force will be added.", @@ -148,16 +262,12 @@ def add_forces_and_torques_index( stacklevel=2, ) return - # Get the link poses - if not self._link_poses_updated: - self._link_poses = self._get_link_pose_fn() - self._link_poses_updated = True - # Set the active flag to true self._active = True + self._dirty = True wp.launch( - add_forces_and_torques_at_position_index, + add_forces_to_dual_buffers_index, dim=(env_ids.shape[0], body_ids.shape[0]), inputs=[ env_ids, @@ -165,13 +275,13 @@ def add_forces_and_torques_index( forces, torques, positions, - self._link_poses, + self._global_force_w, + self._global_torque_w, + self._global_force_at_com_w, + self._local_force_b, + self._local_torque_b, is_global, ], - outputs=[ - self._composed_force_b, - self._composed_torque_b, - ], device=self.device, ) @@ -184,51 +294,43 @@ def set_forces_and_torques_index( env_ids: wp.array | torch.Tensor | None = None, is_global: bool = False, ): - """Set forces and torques to the composed force and torque. + """Set forces and torques into the input buffers using index-based selection. - Composed force and torque are the sum of all the forces and torques applied to the body. - It can compose global wrenches and local wrenches. The result is always in the link frame of the body. - - The user can provide any combination of forces, torques, and positions. + Resets the specified environments first, then writes the new values. This replaces any + previously accumulated forces/torques for the targeted environments while leaving other + environments untouched. Args: - forces: Forces. (num_envs, num_bodies, 3). Defaults to None. - torques: Torques. (num_envs, num_bodies, 3). Defaults to None. - positions: Positions. (num_envs, num_bodies, 3). Defaults to None. - body_ids: Body ids. (num_envs, num_bodies). Defaults to None (all bodies). - env_ids: Environment ids. (num_envs). Defaults to None (all environments). - is_global: Whether the forces and torques are applied in the global frame. Defaults to False. - - Raises: - ValueError: If the type of the input is not supported. - ValueError: If the input is a slice and it is not None. + forces: Forces [N]. Shape: (len(env_ids), len(body_ids), 3). Defaults to None. + torques: Torques [N·m]. Shape: (len(env_ids), len(body_ids), 3). Defaults to None. + positions: The positions [m] at which forces act. If `is_global` is True, these are global + positions expressed in the world frame. If `is_global` is False, these are offsets from the + body's CoM expressed in the body frame. If None, forces are assumed to act at the body's + CoM, independent of the `is_global` flag. + Shape: (len(env_ids), len(body_ids), 3). Defaults to None. + body_ids: Body indices. Defaults to None (all bodies). + env_ids: Environment indices. Defaults to None (all environments). + is_global: Whether the forces and torques are expressed in the global world frame or the local body frame. + Defaults to False. """ - # Resolve all indices - if (env_ids is None) or (env_ids == slice(None)): - env_ids = self._ALL_ENV_INDICES - if isinstance(env_ids, list): - env_ids = wp.array(env_ids, dtype=wp.int32, device=self.device) - if (body_ids is None) or (body_ids == slice(None)): - body_ids = self._ALL_BODY_INDICES - if isinstance(body_ids, list): - body_ids = wp.array(body_ids, dtype=wp.int32, device=self.device) + env_ids = self._resolve_env_ids(env_ids) + body_ids = self._resolve_body_ids(body_ids) if forces is None and torques is None: warnings.warn( - "No forces or torques provided. No force will be added.", + "No forces or torques provided. No force will be set.", UserWarning, stacklevel=2, ) return - # Get the link poses - if not self._link_poses_updated: - self._link_poses = self._get_link_pose_fn() - self._link_poses_updated = True - # Set the active flag to true + # Clear input buffers for the targeted environments before writing + self.reset(env_ids=env_ids) + self._active = True + self._dirty = True wp.launch( - set_forces_and_torques_at_position_index, + set_forces_to_dual_buffers_index, dim=(env_ids.shape[0], body_ids.shape[0]), inputs=[ env_ids, @@ -236,13 +338,13 @@ def set_forces_and_torques_index( forces, torques, positions, - self._link_poses, + self._global_force_w, + self._global_torque_w, + self._global_force_at_com_w, + self._local_force_b, + self._local_torque_b, is_global, ], - outputs=[ - self._composed_force_b, - self._composed_torque_b, - ], device=self.device, ) @@ -255,30 +357,23 @@ def add_forces_and_torques_mask( env_mask: wp.array | torch.Tensor | None = None, is_global: bool = False, ): - """Add forces and torques to the composed force and torque. - - Composed force and torque are the sum of all the forces and torques applied to the body. - It can compose global wrenches and local wrenches. The result is always in the link frame of the body. - - The user can provide any combination of forces, torques, and positions. + """Add forces and torques into the input buffers using mask-based selection. - .. note:: Users may want to call `reset` function after every simulation step to ensure no force is carried - over to the next step. However, this may not necessary if the user calls `set_forces_and_torques` function - instead of `add_forces_and_torques`. + Accumulates onto whatever is already in the buffers. Args: - forces: Forces. (num_envs, num_bodies, 3). Defaults to None. - torques: Torques. (num_envs, num_bodies, 3). Defaults to None. - positions: Positions. (num_envs, num_bodies, 3). Defaults to None. - body_mask: Body mask. (num_bodies). Defaults to None (all bodies). - env_mask: Environment mask. (num_envs). Defaults to None (all environments). - is_global: Whether the forces and torques are applied in the global frame. Defaults to False. - - Raises: - ValueError: If the type of the input is not supported. - ValueError: If the input is a slice and it is not None. + forces: Forces [N]. Shape: (num_envs, num_bodies, 3). Defaults to None. + torques: Torques [N·m]. Shape: (num_envs, num_bodies, 3). Defaults to None. + positions: The positions [m] at which forces act. If `is_global` is True, these are global + positions expressed in the world frame. If `is_global` is False, these are offsets from the + body's CoM expressed in the body frame. If None, forces are assumed to act at the body's + CoM, independent of the `is_global` flag. + Shape: (num_envs, num_bodies, 3). Defaults to None. + body_mask: Body mask. Shape: (num_bodies,). Defaults to None (all bodies). + env_mask: Environment mask. Shape: (num_envs,). Defaults to None (all environments). + is_global: Whether the forces and torques are expressed in the global world frame or the local body frame. + Defaults to False. """ - # Resolve all indices if env_mask is None: env_mask = self._ALL_ENV_MASK if body_mask is None: @@ -290,16 +385,12 @@ def add_forces_and_torques_mask( stacklevel=2, ) return - # Get the link poses - if not self._link_poses_updated: - self._link_poses = self._get_link_pose_fn() - self._link_poses_updated = True - # Set the active flag to true self._active = True + self._dirty = True wp.launch( - add_forces_and_torques_at_position_mask, + add_forces_to_dual_buffers_mask, dim=(self.num_envs, self.num_bodies), inputs=[ env_mask, @@ -307,13 +398,13 @@ def add_forces_and_torques_mask( forces, torques, positions, - self._link_poses, + self._global_force_w, + self._global_torque_w, + self._global_force_at_com_w, + self._local_force_b, + self._local_torque_b, is_global, ], - outputs=[ - self._composed_force_b, - self._composed_torque_b, - ], device=self.device, ) @@ -326,47 +417,45 @@ def set_forces_and_torques_mask( env_mask: wp.array | torch.Tensor | None = None, is_global: bool = False, ): - """Set forces and torques to the composed force and torque. - - Composed force and torque are the sum of all the forces and torques applied to the body. - It can compose global wrenches and local wrenches. The result is always in the link frame of the body. + """Set forces and torques into the input buffers using mask-based selection. - The user can provide any combination of forces, torques, and positions. + Resets the masked environments first, then writes the new values. This replaces any + previously accumulated forces/torques for the masked environments while leaving other + environments untouched. Args: - forces: Forces. (num_envs, num_bodies, 3). Defaults to None. - torques: Torques. (num_envs, num_bodies, 3). Defaults to None. - positions: Positions. (num_envs, num_bodies, 3). Defaults to None. - body_mask: Body mask. (num_bodies). Defaults to None (all bodies). - env_mask: Environment mask. (num_envs). Defaults to None (all environments). - is_global: Whether the forces and torques are applied in the global frame. Defaults to False. - - Raises: - ValueError: If the type of the input is not supported. - ValueError: If the input is a slice and it is not None. + forces: Forces [N]. Shape: (num_envs, num_bodies, 3). Defaults to None. + torques: Torques [N·m]. Shape: (num_envs, num_bodies, 3). Defaults to None. + positions: The positions [m] at which forces act. If `is_global` is True, these are global + positions expressed in the world frame. If `is_global` is False, these are offsets from the + body's CoM expressed in the body frame. If None, forces are assumed to act at the body's + CoM, independent of the `is_global` flag. + Shape: (num_envs, num_bodies, 3). Defaults to None. + body_mask: Body mask. Shape: (num_bodies,). Defaults to None (all bodies). + env_mask: Environment mask. Shape: (num_envs,). Defaults to None (all environments). + is_global: Whether the forces and torques are expressed in the global world frame or the local body frame. + Defaults to False. """ - # Resolve all indices if env_mask is None: env_mask = self._ALL_ENV_MASK if body_mask is None: body_mask = self._ALL_BODY_MASK if forces is None and torques is None: warnings.warn( - "No forces or torques provided. No force will be added.", + "No forces or torques provided. No force will be set.", UserWarning, stacklevel=2, ) return - # Get the link poses - if not self._link_poses_updated: - self._link_poses = self._get_link_pose_fn() - self._link_poses_updated = True - # Set the active flag to true + # Clear input buffers for the masked environments before writing + self.reset(env_mask=env_mask) + self._active = True + self._dirty = True wp.launch( - set_forces_and_torques_at_position_mask, + set_forces_to_dual_buffers_mask, dim=(self.num_envs, self.num_bodies), inputs=[ env_mask, @@ -374,74 +463,159 @@ def set_forces_and_torques_mask( forces, torques, positions, - self._link_poses, + self._global_force_w, + self._global_torque_w, + self._global_force_at_com_w, + self._local_force_b, + self._local_torque_b, is_global, ], - outputs=[ - self._composed_force_b, - self._composed_torque_b, + device=self.device, + ) + + def add_raw_buffers_from(self, other: WrenchComposer): + """Add another composer's raw input buffers into this composer's input buffers. + + This performs element-wise addition of all five input buffers from ``other`` into ``self``. + Useful for combining wrenches from multiple sources before composition. + + Args: + other: Another WrenchComposer whose input buffers will be added into this one. + """ + if not other._active: + return + if __debug__: + if other.num_envs != self.num_envs or other.num_bodies != self.num_bodies: + raise ValueError( + f"Cannot add buffers from composer with shape ({other.num_envs}, {other.num_bodies}) " + f"into composer with shape ({self.num_envs}, {self.num_bodies})." + ) + + self._active = True + self._dirty = True + + wp.launch( + add_raw_wrench_buffers, + dim=(self.num_envs, self.num_bodies), + inputs=[ + other._global_force_w, + other._global_torque_w, + other._global_force_at_com_w, + other._local_force_b, + other._local_torque_b, + self._global_force_w, + self._global_torque_w, + self._global_force_at_com_w, + self._local_force_b, + self._local_torque_b, ], device=self.device, ) - def reset(self, env_ids: wp.array | torch.Tensor | None = None, env_mask: wp.array | None = None): - """Reset the composed force and torque. + def compose_to_body_frame(self): + """Compose the five input buffers into the two output buffers in body frame. + + This corrects world-frame torques for the body's CoM position, rotates global forces and torques into the + body frame, then adds local-frame contributions. After this call, ``out_force_b`` and ``out_torque_b`` + contain the final composed wrench. + + The dirty flag is cleared after composition. + """ + com_pos_w = self._get_com_pos_fn() + link_quat_w = self._get_link_quat_fn() + + wp.launch( + compose_wrench_to_body_frame, + dim=(self.num_envs, self.num_bodies), + inputs=[ + self._global_force_w, + self._global_torque_w, + self._global_force_at_com_w, + self._local_force_b, + self._local_torque_b, + com_pos_w, + link_quat_w, + self._out_force_b, + self._out_torque_b, + ], + device=self.device, + ) + self._dirty = False - This function will reset the composed force and torque to zero. - It will also make sure the link positions and quaternions are updated in the next call of the - `add_forces_and_torques` or `set_forces_and_torques` functions. + def reset( + self, + env_ids: wp.array | torch.Tensor | Sequence[int] | slice | None = None, + env_mask: wp.array | None = None, + ): + """Reset the wrench composer buffers. - .. note:: This function should be called after every simulation step / reset to ensure no force is carried - over to the next step. + With no arguments, zeros all seven buffers (5 input + 2 output) and clears all flags. + With ``env_ids`` or ``env_mask``, performs a partial reset on the specified environments + using the reset kernels. - .. caution:: If both :attr:`env_ids` and :attr:`env_mask` are provided, then :attr:`env_mask` takes precedence - over :attr:`env_ids`. + .. caution:: If both ``env_ids`` and ``env_mask`` are provided, ``env_mask`` takes precedence. Args: env_ids: Environment indices. Defaults to None (all environments). env_mask: Environment mask. Defaults to None (all environments). """ if env_ids is None and env_mask is None: - self._composed_force_b.zero_() - self._composed_torque_b.zero_() + # Full reset: zero all 7 buffers + self._global_force_w.zero_() + self._global_torque_w.zero_() + self._global_force_at_com_w.zero_() + self._local_force_b.zero_() + self._local_torque_b.zero_() + self._out_force_b.zero_() + self._out_torque_b.zero_() self._active = False + self._dirty = False elif env_mask is not None: wp.launch( reset_wrench_composer_mask, dim=(self.num_envs, self.num_bodies), inputs=[ env_mask, - ], - outputs=[ - self._composed_force_b, - self._composed_torque_b, + self._global_force_w, + self._global_torque_w, + self._global_force_at_com_w, + self._local_force_b, + self._local_torque_b, + self._out_force_b, + self._out_torque_b, ], device=self.device, ) + self._dirty = True else: + # Partial reset via index if env_ids is None or env_ids == slice(None): env_ids = self._ALL_ENV_INDICES elif isinstance(env_ids, list): env_ids = wp.array(env_ids, dtype=wp.int32, device=self.device) elif isinstance(env_ids, torch.Tensor): env_ids = wp.from_torch(env_ids.to(torch.int32), dtype=wp.int32) + wp.launch( reset_wrench_composer_index, dim=(env_ids.shape[0], self.num_bodies), inputs=[ env_ids, - ], - outputs=[ - self._composed_force_b, - self._composed_torque_b, + self._global_force_w, + self._global_torque_w, + self._global_force_at_com_w, + self._local_force_b, + self._local_torque_b, + self._out_force_b, + self._out_torque_b, ], device=self.device, ) - self._link_poses_updated = False + self._dirty = True - """ - Deprecated functions. - """ + # ------------------------------------------------------------------ + # Deprecated methods + # ------------------------------------------------------------------ def add_forces_and_torques( self, @@ -452,10 +626,13 @@ def add_forces_and_torques( env_ids: torch.Tensor | None = None, is_global: bool = False, ): - """Deprecated, same as :meth:`add_forces_and_torques_index`.""" + """Deprecated, same as :meth:`add_forces_and_torques_index`. + + .. deprecated:: 4.5.33 + Use :meth:`add_forces_and_torques_index` instead. + """ warnings.warn( - "The function 'add_forces_and_torques' will be deprecated in a future release. Please" - " use 'add_forces_and_torques_index' instead.", + "The function 'add_forces_and_torques' is deprecated. Please use 'add_forces_and_torques_index' instead.", DeprecationWarning, stacklevel=2, ) @@ -470,11 +647,80 @@ def set_forces_and_torques( env_ids: wp.array | torch.Tensor | None = None, is_global: bool = False, ): - """Deprecated, same as :meth:`set_forces_and_torques_index`.""" + """Deprecated, same as :meth:`set_forces_and_torques_index`. + + .. deprecated:: 4.5.33 + Use :meth:`set_forces_and_torques_index` instead. + """ warnings.warn( - "The function 'set_forces_and_torques' will be deprecated in a future release. Please" - " use 'set_forces_and_torques_index' instead.", + "The function 'set_forces_and_torques' is deprecated. Please use 'set_forces_and_torques_index' instead.", DeprecationWarning, stacklevel=2, ) self.set_forces_and_torques_index(forces, torques, positions, body_ids, env_ids, is_global) + + # ------------------------------------------------------------------ + # Internal helpers + # ------------------------------------------------------------------ + + def _resolve_env_ids(self, env_ids: wp.array | torch.Tensor | list | slice | None) -> wp.array: + """Resolve environment IDs to a warp int32 array. + + Args: + env_ids: Environment indices as any supported type, or None for all environments. + + Returns: + Warp array of int32 environment indices. + + Raises: + TypeError: If ``env_ids`` is an unsupported type. + """ + if env_ids is None: + return self._ALL_ENV_INDICES + # Check tensor types before slice comparison (tensor == slice crashes) + if isinstance(env_ids, torch.Tensor): + if env_ids.dtype == torch.int64: + env_ids = env_ids.to(torch.int32) + return wp.from_torch(env_ids.contiguous(), dtype=wp.int32) + if isinstance(env_ids, wp.array): + return env_ids + if env_ids == slice(None): + return self._ALL_ENV_INDICES + if isinstance(env_ids, list): + return wp.array(env_ids, dtype=wp.int32, device=self.device) + raise TypeError( + f"env_ids must be None, slice(None), list, torch.Tensor, or wp.array, got {type(env_ids).__name__}" + ) + + def _resolve_body_ids(self, body_ids: wp.array | torch.Tensor | list | slice | None) -> wp.array: + """Resolve body IDs to a warp int32 array. + + Args: + body_ids: Body indices as any supported type, or None for all bodies. + + Returns: + Warp array of int32 body indices. + + Raises: + TypeError: If ``body_ids`` is an unsupported type. + """ + if body_ids is None: + return self._ALL_BODY_INDICES + if isinstance(body_ids, torch.Tensor): + if body_ids.dtype == torch.int64: + body_ids = body_ids.to(torch.int32) + return wp.from_torch(body_ids.contiguous(), dtype=wp.int32) + if isinstance(body_ids, wp.array): + return body_ids + if body_ids == slice(None): + return self._ALL_BODY_INDICES + if isinstance(body_ids, list): + return wp.array(body_ids, dtype=wp.int32, device=self.device) + raise TypeError( + f"body_ids must be None, slice(None), list, torch.Tensor, or wp.array, got {type(body_ids).__name__}" + ) + + def _ensure_composed(self): + """Compose input buffers into output buffers if dirty.""" + if self._dirty: + self.compose_to_body_frame() diff --git a/source/isaaclab/isaaclab/visualizers/base_visualizer.py b/source/isaaclab/isaaclab/visualizers/base_visualizer.py index 2480bc89bbaa..b0fc5a81088f 100644 --- a/source/isaaclab/isaaclab/visualizers/base_visualizer.py +++ b/source/isaaclab/isaaclab/visualizers/base_visualizer.py @@ -136,7 +136,7 @@ def get_visualized_env_ids(self) -> list[int] | None: Returns: Visualized environment ids, or ``None`` for all environments. """ - return getattr(self, "_env_ids", None) + return self._env_ids def _compute_visualized_env_ids(self) -> list[int] | None: """Compute which environment indices to visualize from config. @@ -146,28 +146,21 @@ def _compute_visualized_env_ids(self) -> list[int] | None: """ if self._scene_data_provider is None: return None - filter_mode = getattr(self.cfg, "env_filter_mode", "none") - if filter_mode == "none": - return None - + cfg = self.cfg num_envs = self._scene_data_provider.get_metadata().get("num_envs", 0) if num_envs <= 0: - logger.debug("[Visualizer] num_envs is 0 or missing from provider metadata; env filtering disabled.") + logger.debug("[Visualizer] num_envs is 0 or missing from provider metadata; env selection disabled.") return None - if filter_mode == "env_ids": - env_ids_cfg = getattr(self.cfg, "env_filter_ids", None) - if env_ids_cfg is not None and len(env_ids_cfg) > 0: - return [i for i in env_ids_cfg if 0 <= i < num_envs] - return None - if filter_mode == "random_n": - count = int(getattr(self.cfg, "env_filter_random_n", 0)) - if count <= 0: - return None - count = min(count, num_envs) - seed = int(getattr(self.cfg, "env_filter_seed", 0)) - rng = random.Random(seed) - return sorted(rng.sample(range(num_envs), count)) - logger.warning("[Visualizer] Unknown env_filter_mode='%s'; defaulting to all envs.", filter_mode) + # Explicit list wins; never combine with random cap-only mode. + if cfg.visible_env_indices is not None: + return [i for i in cfg.visible_env_indices if 0 <= i < num_envs] + + max_visible = getattr(cfg, "max_visible_envs", None) + # Random subset only for cap-only mode: needs a cap and no explicit indices (see VisualizerCfg). + if max_visible is not None and getattr(cfg, "randomly_sample_visible_envs", True) and int(max_visible) >= 0: + k = min(int(max_visible), num_envs) + # k == 0: sample(range(n), 0) is []; contiguous resolver used the same convention. + return sorted(random.sample(range(num_envs), k)) return None def get_rendering_dt(self) -> float | None: @@ -187,6 +180,14 @@ def set_camera_view(self, eye: tuple, target: tuple) -> None: """ pass + def _resolve_cfg_camera_pose( + self, _visualizer_name: str + ) -> tuple[tuple[float, float, float], tuple[float, float, float]]: + """Resolve camera pose from cfg eye/lookat fields.""" + eye = tuple(float(v) for v in self.cfg.eye) + lookat = tuple(float(v) for v in self.cfg.lookat) + return eye, lookat + def _resolve_camera_pose_from_usd_path( self, usd_path: str ) -> tuple[tuple[float, float, float], tuple[float, float, float]] | None: diff --git a/source/isaaclab/isaaclab/visualizers/visualizer_cfg.py b/source/isaaclab/isaaclab/visualizers/visualizer_cfg.py index a96e3c04d2b5..1ee4cde038b5 100644 --- a/source/isaaclab/isaaclab/visualizers/visualizer_cfg.py +++ b/source/isaaclab/isaaclab/visualizers/visualizer_cfg.py @@ -34,32 +34,33 @@ class VisualizerCfg: enable_live_plots: bool = True """Enable live plotting of data.""" - camera_position: tuple[float, float, float] = (8.0, 8.0, 3.0) - """Initial camera position (x, y, z) in world coordinates.""" + eye: tuple[float, float, float] = (7.5, 7.5, 7.5) + """Initial camera eye position (x, y, z) in world coordinates.""" - camera_target: tuple[float, float, float] = (0.0, 0.0, 0.0) - """Initial camera target/look-at point (x, y, z) in world coordinates.""" + lookat: tuple[float, float, float] = (0.0, 0.0, 0.0) + """Initial camera look-at point (x, y, z) in world coordinates.""" - camera_source: Literal["cfg", "usd_path"] = "cfg" - """Camera source mode: 'cfg' uses camera_position/target, 'usd_path' follows a USD camera prim.""" + cam_source: Literal["cfg", "prim_path"] = "cfg" + """Camera source mode: 'cfg' uses eye/lookat, 'prim_path' follows a camera prim.""" - camera_usd_path: str = "/World/envs/env_0/Camera" - """Absolute USD path to a camera prim when camera_source='usd_path'.""" + cam_prim_path: str = "/World/envs/env_0/Camera" + """Absolute USD path to a camera prim when cam_source='prim_path'.""" - env_filter_mode: Literal["none", "env_ids", "random_n"] = "none" - """Env filter mode: 'none', 'env_ids', or 'random_n'.""" + max_visible_envs: int | None = None + """Upper bound on how many envs are shown. - env_filter_random_n: int = 64 - """If env_filter_mode='random_n', number of envs to sample.""" + * If visible_env_indices is not None, then this field will apply also + to the explicit env indices set to the visible_env_indices. + """ - env_filter_seed: int = 0 - """Seed for deterministic env sampling.""" + visible_env_indices: list[int] | None = None + """env indices to visualize in order (out-of-range indices are dropped).""" - env_filter_ids: list[int] = [i for i in range(0, 64, 4)] - """If env_filter_mode='env_ids', only these env indices are shown. + randomly_sample_visible_envs: bool = True + """If ``max_visible_envs`` is provided, when enabled, selected visible envs are randomly sampled. + If disabled, the first ``max_visible_envs`` envs are selected. - This improves performance, particularly for large-scale training, by reducing scene updates sent to visualizers. - Note, OV visualizer only applies a cosmetic visibility toggle (no performance gain). + * Note: ``visible_env_indices`` overrides this field. """ def get_visualizer_type(self) -> str | None: diff --git a/source/isaaclab/setup.py b/source/isaaclab/setup.py index 2bbdcac07f4d..67c18c4c62d1 100644 --- a/source/isaaclab/setup.py +++ b/source/isaaclab/setup.py @@ -29,9 +29,9 @@ "gymnasium==1.2.1", # procedural-generation "trimesh", - "pyglet>=2.1.6", - "mujoco>=3.5", - "mujoco-warp>=3.5", + "pyglet>=2.1.6,<3", + "mujoco==3.6.0", + "mujoco-warp==3.6.0", # image processing "transformers==4.57.6", "einops", # needed for transformers, doesn't always auto-install @@ -43,14 +43,14 @@ "botocore", # livestream "starlette==0.49.1", - "omniverseclient", + "omniverseclient==2.71.1.7015", # testing "pytest", "pytest-mock", "junitparser", "coverage==7.6.1", "debugpy>=1.8.20", - "flatdict==4.0.0", + "flatdict>=4.1.0", "flaky", "packaging", "psutil", @@ -64,10 +64,9 @@ SUPPORTED_ARCHS = "platform_machine in 'x86_64,AMD64'" INSTALL_REQUIRES += [ # required by isaaclab.isaaclab.controllers.pink_ik + f"pin ; platform_system == 'Linux' and ({SUPPORTED_ARCHS_ARM})", f"pin-pink==3.1.0 ; platform_system == 'Linux' and ({SUPPORTED_ARCHS_ARM})", f"daqp==0.7.2 ; platform_system == 'Linux' and ({SUPPORTED_ARCHS_ARM})", - # required by isaaclab.devices.openxr.retargeters.humanoid.fourier.gr1_t2_dex_retargeting_utils - f"dex-retargeting==0.5.0 ; platform_system == 'Linux' and ({SUPPORTED_ARCHS})", ] # Adds OpenUSD dependencies based on architecture for Kit less mode. INSTALL_REQUIRES += [ @@ -130,16 +129,13 @@ license="BSD-3-Clause", include_package_data=True, package_data={"": ["*.pyi"]}, - python_requires=">=3.10", + python_requires=">=3.12", install_requires=INSTALL_REQUIRES, extras_require=EXTRAS_REQUIRE, dependency_links=PYTORCH_INDEX_URL, packages=["isaaclab"], classifiers=[ - "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", - "Isaac Sim :: 5.0.0", - "Isaac Sim :: 5.1.0", "Isaac Sim :: 6.0.0", ], zip_safe=False, diff --git a/source/isaaclab/test/app/test_kwarg_launch.py b/source/isaaclab/test/app/test_kwarg_launch.py index 0dffa89764a0..3cc22b157ef7 100644 --- a/source/isaaclab/test/app/test_kwarg_launch.py +++ b/source/isaaclab/test/app/test_kwarg_launch.py @@ -43,25 +43,27 @@ def test_set_visualizer_settings_stores_values(monkeypatch: pytest.MonkeyPatch): monkeypatch.setattr(app_launcher_module, "get_settings_manager", lambda: settings) launcher = AppLauncher.__new__(AppLauncher) - launcher._set_visualizer_settings({"visualizer": ["viser", "rerun"], "visualizer_max_worlds": 0}) + launcher._set_visualizer_settings({"visualizer": ["viser", "rerun"], "max_visible_envs": 0}) assert settings.values == { "/isaaclab/visualizer/types": "viser rerun", "/isaaclab/visualizer/explicit": False, "/isaaclab/visualizer/disable_all": False, - "/isaaclab/visualizer/max_worlds": 0, + "/isaaclab/visualizer/max_visible_envs": 0, } -def test_set_visualizer_settings_rejects_negative_max_worlds(monkeypatch: pytest.MonkeyPatch): +def test_set_visualizer_settings_rejects_negative_max_visible_envs( + monkeypatch: pytest.MonkeyPatch, +): def _unexpected_settings_manager(): raise AssertionError("settings manager should not be queried for invalid values") monkeypatch.setattr(app_launcher_module, "get_settings_manager", _unexpected_settings_manager) launcher = AppLauncher.__new__(AppLauncher) - with pytest.raises(ValueError, match="Invalid value for --visualizer_max_worlds: -5"): - launcher._set_visualizer_settings({"visualizer": ["viser"], "visualizer_max_worlds": -5}) + with pytest.raises(ValueError, match="Invalid value for --max_visible_envs: -5"): + launcher._set_visualizer_settings({"visualizer": ["viser"], "max_visible_envs": -5}) def test_set_visualizer_settings_suppresses_settings_manager_errors(monkeypatch: pytest.MonkeyPatch): @@ -71,17 +73,17 @@ def _raise_settings_error(): monkeypatch.setattr(app_launcher_module, "get_settings_manager", _raise_settings_error) launcher = AppLauncher.__new__(AppLauncher) - launcher._set_visualizer_settings({"visualizer": ["viser"], "visualizer_max_worlds": 3}) + launcher._set_visualizer_settings({"visualizer": ["viser"], "max_visible_envs": 3}) def test_parse_visualizer_csv_accepts_comma_delimited_values(): - parsed = app_launcher_module._parse_visualizer_csv("kit,newton,rerun,viser") + parsed = app_launcher_module.AppLauncher._parse_visualizer_csv("kit,newton,rerun,viser") assert parsed == ["kit", "newton", "rerun", "viser"] def test_parse_visualizer_csv_rejects_spaces_between_entries(): with pytest.raises(argparse.ArgumentTypeError, match="spaces are not allowed"): - app_launcher_module._parse_visualizer_csv("kit, newton") + app_launcher_module.AppLauncher._parse_visualizer_csv("kit, newton") def test_resolve_visualizer_settings_rejects_none_with_others(): @@ -97,11 +99,11 @@ def test_visualizer_csv_does_not_swallow_hydra_overrides(): app_launcher_module.AppLauncher.add_app_launcher_args(parser) args, hydra_args = parser.parse_known_args( - ["--visualizer", "kit,newton,rerun", "presets=newton", "env.episode_length=10"] + ["--visualizer", "kit,newton,rerun", "presets=newton_mjwarp", "env.episode_length=10"] ) assert args.visualizer == ["kit", "newton", "rerun"] - assert hydra_args == ["presets=newton", "env.episode_length=10"] + assert hydra_args == ["presets=newton_mjwarp", "env.episode_length=10"] def _resolve_headless_for_case(monkeypatch: pytest.MonkeyPatch, launcher_args: dict) -> tuple[bool, AppLauncher]: diff --git a/source/isaaclab/test/assets/check_external_force.py b/source/isaaclab/test/assets/check_external_force.py index f038b907a1f0..f4b0da603812 100644 --- a/source/isaaclab/test/assets/check_external_force.py +++ b/source/isaaclab/test/assets/check_external_force.py @@ -96,13 +96,13 @@ def main(): sim_time = 0.0 count = 0 # reset root state - root_state = robot.data.default_root_state.clone() + root_state = robot.data.default_root_state.torch.clone() root_state[0, :2] = torch.tensor([0.0, -0.5], device=sim.device) root_state[1, :2] = torch.tensor([0.0, 0.5], device=sim.device) robot.write_root_pose_to_sim(root_state[:, :7]) robot.write_root_velocity_to_sim(root_state[:, 7:]) # reset dof state - joint_pos, joint_vel = robot.data.default_joint_pos, robot.data.default_joint_vel + joint_pos, joint_vel = robot.data.default_joint_pos.torch, robot.data.default_joint_vel.torch robot.write_joint_state_to_sim(joint_pos, joint_vel) robot.reset() # apply force @@ -112,7 +112,7 @@ def main(): # reset command print(">>>>>>>> Reset!") # apply action to the robot - robot.set_joint_position_target(robot.data.default_joint_pos.clone()) + robot.set_joint_position_target(robot.data.default_joint_pos.torch.clone()) robot.write_data_to_sim() # perform step sim.step() diff --git a/source/isaaclab/test/assets/check_fixed_base_assets.py b/source/isaaclab/test/assets/check_fixed_base_assets.py index c62c5a3334da..11f9010a7d88 100644 --- a/source/isaaclab/test/assets/check_fixed_base_assets.py +++ b/source/isaaclab/test/assets/check_fixed_base_assets.py @@ -108,13 +108,16 @@ def run_simulator(sim: sim_utils.SimulationContext, entities: dict[str, Articula # reset robots for index, robot in enumerate(entities.values()): # root state - root_state = robot.data.default_root_state.clone() + root_state = robot.data.default_root_state.torch.clone() root_state[:, :3] += origins[index] root_state[:, :2] += torch.randn_like(root_state[:, :2]) * 0.25 robot.write_root_pose_to_sim(root_state[:, :7]) robot.write_root_velocity_to_sim(root_state[:, 7:]) # joint state - joint_pos, joint_vel = robot.data.default_joint_pos.clone(), robot.data.default_joint_vel.clone() + joint_pos, joint_vel = ( + robot.data.default_joint_pos.torch.clone(), + robot.data.default_joint_vel.torch.clone(), + ) robot.write_joint_state_to_sim(joint_pos, joint_vel) # reset the internal state robot.reset() @@ -124,7 +127,7 @@ def run_simulator(sim: sim_utils.SimulationContext, entities: dict[str, Articula if count % 200 == 0: print("Name: ", name, "is_fixed_base: ", robot.is_fixed_base) # generate random joint positions - joint_pos_target = robot.data.default_joint_pos + torch.randn_like(robot.data.joint_pos) * 0.1 + joint_pos_target = robot.data.default_joint_pos.torch + torch.randn_like(robot.data.joint_pos.torch) * 0.1 # apply action to the robot robot.set_joint_position_target(joint_pos_target) # write data to sim diff --git a/source/isaaclab/test/assets/check_ridgeback_franka.py b/source/isaaclab/test/assets/check_ridgeback_franka.py index 724cd8b2a080..69ca6a7d8761 100644 --- a/source/isaaclab/test/assets/check_ridgeback_franka.py +++ b/source/isaaclab/test/assets/check_ridgeback_franka.py @@ -72,7 +72,7 @@ def add_robots() -> Articulation: def run_simulator(sim: sim_utils.SimulationContext, robot: Articulation): """Runs the simulator by applying actions to the robot at every time-step""" # dummy action - actions = robot.data.default_joint_pos.clone() + actions = robot.data.default_joint_pos.torch.clone() # Define simulation stepping sim_dt = sim.get_physics_dt() @@ -87,12 +87,15 @@ def run_simulator(sim: sim_utils.SimulationContext, robot: Articulation): sim_time = 0.0 ep_step_count = 0 # reset dof state - joint_pos, joint_vel = robot.data.default_joint_pos.clone(), robot.data.default_joint_vel.clone() + joint_pos, joint_vel = ( + robot.data.default_joint_pos.torch.clone(), + robot.data.default_joint_vel.torch.clone(), + ) robot.write_joint_state_to_sim(joint_pos, joint_vel) # reset internals robot.reset() # reset command - actions = torch.rand_like(robot.data.default_joint_pos) + robot.data.default_joint_pos + actions = torch.rand_like(robot.data.default_joint_pos.torch) + robot.data.default_joint_pos.torch # -- base actions[:, 0:3] = 0.0 # -- gripper diff --git a/source/isaaclab/test/assets/test_articulation_iface.py b/source/isaaclab/test/assets/test_articulation_iface.py index 64842ed7273f..3e471026a9dc 100644 --- a/source/isaaclab/test/assets/test_articulation_iface.py +++ b/source/isaaclab/test/assets/test_articulation_iface.py @@ -13,16 +13,25 @@ The setup is a bit convoluted so that we can run these tests without requiring Isaac Sim or GPU simulation. """ -"""Launch Isaac Sim Simulator first.""" +"""Launch Isaac Sim Simulator first (when available).""" -from isaaclab.app import AppLauncher +import os +import sys +from unittest.mock import MagicMock -HEADLESS = True +# When running kitless (e.g., ovphysx backend via run_ovphysx.sh), AppLauncher +# will try to boot Kit and hang. Skip it entirely when LD_PRELOAD is cleared +# (the signature of run_ovphysx.sh) or when EXP_PATH is not set. +_kitless = os.environ.get("LD_PRELOAD", "") == "" and "EXP_PATH" not in os.environ -# launch omniverse app -simulation_app = AppLauncher(headless=True).app +if not _kitless: + from isaaclab.app import AppLauncher -from unittest.mock import MagicMock + simulation_app = AppLauncher(headless=True).app +else: + simulation_app = None + for _mod in ("isaacsim.core", "isaacsim.core.simulation_manager"): + sys.modules.setdefault(_mod, MagicMock()) import numpy as np import pytest @@ -32,13 +41,14 @@ from isaaclab.assets.articulation.articulation_cfg import ArticulationCfg from isaaclab.test.mock_interfaces.utils import MockWrenchComposer -# Mock SimulationManager.get_physics_sim_view() to return a mock object with gravity -# This is needed because the Data classes call SimulationManager.get_physics_sim_view().get_gravity() -# but there's no actual physics scene when running unit tests +# Mock SimulationManager.get_physics_sim_view() to return a mock object with gravity. +# This is needed because the PhysX Data classes call +# SimulationManager.get_physics_sim_view().get_gravity() but there's no actual +# physics scene when running unit tests. _mock_physics_sim_view = MagicMock() _mock_physics_sim_view.get_gravity.return_value = (0.0, 0.0, -9.81) -from isaacsim.core.simulation_manager import SimulationManager +from isaaclab_physx.physics import PhysxManager as SimulationManager SimulationManager.get_physics_sim_view = MagicMock(return_value=_mock_physics_sim_view) @@ -66,6 +76,15 @@ except ImportError: pass +try: + from isaaclab_ovphysx.assets.articulation.articulation import Articulation as OvPhysxArticulation + from isaaclab_ovphysx.assets.articulation.articulation_data import ArticulationData as OvPhysxArticulationData + from isaaclab_ovphysx.test.mock_interfaces.views import MockOvPhysxBindingSet + + BACKENDS.append("ovphysx") +except ImportError: + pass + def create_physx_articulation( num_instances: int = 2, @@ -141,34 +160,147 @@ def create_physx_articulation( # Set up other required attributes object.__setattr__(articulation, "actuators", {}) object.__setattr__(articulation, "_has_implicit_actuators", False) - object.__setattr__(articulation, "_ALL_INDICES", torch.arange(num_instances, dtype=torch.int32, device=device)) - object.__setattr__(articulation, "_ALL_BODY_INDICES", torch.arange(num_bodies, dtype=torch.int32, device=device)) - object.__setattr__(articulation, "_ALL_JOINT_INDICES", torch.arange(num_joints, dtype=torch.int32, device=device)) + object.__setattr__(articulation, "_ALL_INDICES", wp.array(np.arange(num_instances, dtype=np.int32), device=device)) + object.__setattr__( + articulation, "_ALL_BODY_INDICES", wp.array(np.arange(num_bodies, dtype=np.int32), device=device) + ) + object.__setattr__( + articulation, "_ALL_JOINT_INDICES", wp.array(np.arange(num_joints, dtype=np.int32), device=device) + ) # Tendon index arrays - all_fixed_tendon_indices = wp.from_torch( - torch.arange(num_fixed_tendons, dtype=torch.int32, device=device), dtype=wp.int32 + object.__setattr__( + articulation, + "_ALL_FIXED_TENDON_INDICES", + wp.array(np.arange(num_fixed_tendons, dtype=np.int32), device=device), ) - all_spatial_tendon_indices = wp.from_torch( - torch.arange(num_spatial_tendons, dtype=torch.int32, device=device), dtype=wp.int32 + object.__setattr__( + articulation, + "_ALL_SPATIAL_TENDON_INDICES", + wp.array(np.arange(num_spatial_tendons, dtype=np.int32), device=device), ) - object.__setattr__(articulation, "_ALL_FIXED_TENDON_INDICES", all_fixed_tendon_indices) - object.__setattr__(articulation, "_ALL_SPATIAL_TENDON_INDICES", all_spatial_tendon_indices) # Warp arrays for set_external_force_and_torque - all_indices = torch.arange(num_instances, dtype=torch.int32, device=device) - all_body_indices = torch.arange(num_bodies, dtype=torch.int32, device=device) - object.__setattr__(articulation, "_ALL_INDICES_WP", wp.from_torch(all_indices, dtype=wp.int32)) - object.__setattr__(articulation, "_ALL_BODY_INDICES_WP", wp.from_torch(all_body_indices, dtype=wp.int32)) + object.__setattr__( + articulation, "_ALL_INDICES_WP", wp.array(np.arange(num_instances, dtype=np.int32), device=device) + ) + object.__setattr__( + articulation, "_ALL_BODY_INDICES_WP", wp.array(np.arange(num_bodies, dtype=np.int32), device=device) + ) # Initialize joint targets object.__setattr__(articulation, "_joint_pos_target_sim", torch.zeros(num_instances, num_joints, device=device)) object.__setattr__(articulation, "_joint_vel_target_sim", torch.zeros(num_instances, num_joints, device=device)) object.__setattr__(articulation, "_joint_effort_target_sim", torch.zeros(num_instances, num_joints, device=device)) + # Cached .view(wp.float32) wrappers + object.__setattr__(articulation, "_root_link_pose_w_f32", None) + object.__setattr__(articulation, "_root_com_vel_w_f32", None) + object.__setattr__(articulation, "_root_link_vel_w_f32", None) + object.__setattr__(articulation, "_inst_wrench_force_f32", None) + object.__setattr__(articulation, "_inst_wrench_torque_f32", None) + object.__setattr__(articulation, "_perm_wrench_force_f32", None) + object.__setattr__(articulation, "_perm_wrench_torque_f32", None) + + # Pre-allocated pinned CPU buffers for PhysX TensorAPI writes + N, J, B = num_instances, num_joints, num_bodies + cpu_env_ids = wp.array(np.arange(N, dtype=np.int32), device="cpu") + object.__setattr__(articulation, "_cpu_env_ids_all", cpu_env_ids) + object.__setattr__(articulation, "_cpu_joint_stiffness", wp.zeros((N, J), dtype=wp.float32, device="cpu")) + object.__setattr__(articulation, "_cpu_joint_damping", wp.zeros((N, J), dtype=wp.float32, device="cpu")) + object.__setattr__(articulation, "_cpu_joint_pos_limits", wp.zeros((N, J, 2), dtype=wp.float32, device="cpu")) + object.__setattr__(articulation, "_cpu_joint_vel_limits", wp.zeros((N, J), dtype=wp.float32, device="cpu")) + object.__setattr__(articulation, "_cpu_joint_effort_limits", wp.zeros((N, J), dtype=wp.float32, device="cpu")) + object.__setattr__(articulation, "_cpu_joint_armature", wp.zeros((N, J), dtype=wp.float32, device="cpu")) + object.__setattr__(articulation, "_cpu_joint_friction_props", wp.zeros((N, J, 3), dtype=wp.float32, device="cpu")) + object.__setattr__(articulation, "_cpu_body_mass", wp.zeros((N, B), dtype=wp.float32, device="cpu")) + object.__setattr__(articulation, "_cpu_body_coms", wp.zeros((N, B, 7), dtype=wp.float32, device="cpu")) + object.__setattr__(articulation, "_cpu_body_inertia", wp.zeros((N, B, 9), dtype=wp.float32, device="cpu")) + return articulation, mock_view +def create_ovphysx_articulation( + num_instances: int = 2, + num_joints: int = 6, + num_bodies: int = 7, + num_fixed_tendons: int = 0, + num_spatial_tendons: int = 0, + device: str = "cuda:0", +): + """Create a test OvPhysX Articulation instance with mocked tensor bindings.""" + joint_names = [f"joint_{i}" for i in range(num_joints)] + body_names = [f"body_{i}" for i in range(num_bodies)] + + articulation = object.__new__(OvPhysxArticulation) + + articulation.cfg = ArticulationCfg( + prim_path="/World/Robot", + soft_joint_pos_limit_factor=1.0, + actuators={}, + ) + + # Create mock binding set + mock_bindings = MockOvPhysxBindingSet( + num_instances=num_instances, + num_joints=num_joints, + num_bodies=num_bodies, + is_fixed_base=False, + joint_names=joint_names, + body_names=body_names, + num_fixed_tendons=num_fixed_tendons, + num_spatial_tendons=num_spatial_tendons, + ) + mock_bindings.set_random_data() + + fixed_tendon_names = [f"fixed_tendon_{i}" for i in range(num_fixed_tendons)] + spatial_tendon_names = [f"spatial_tendon_{i}" for i in range(num_spatial_tendons)] + + object.__setattr__(articulation, "_device", device) + object.__setattr__(articulation, "_ovphysx", MagicMock()) + object.__setattr__(articulation, "_bindings", mock_bindings.bindings) + object.__setattr__(articulation, "_num_instances", num_instances) + object.__setattr__(articulation, "_num_joints", num_joints) + object.__setattr__(articulation, "_num_bodies", num_bodies) + object.__setattr__(articulation, "_is_fixed_base", False) + object.__setattr__(articulation, "_joint_names", joint_names) + object.__setattr__(articulation, "_body_names", body_names) + object.__setattr__(articulation, "_fixed_tendon_names", fixed_tendon_names) + object.__setattr__(articulation, "_spatial_tendon_names", spatial_tendon_names) + object.__setattr__(articulation, "_num_fixed_tendons", num_fixed_tendons) + object.__setattr__(articulation, "_num_spatial_tendons", num_spatial_tendons) + + # Create ArticulationData + data = OvPhysxArticulationData(mock_bindings.bindings, device) + data._num_instances = num_instances + data._num_joints = num_joints + data._num_bodies = num_bodies + data._num_fixed_tendons = num_fixed_tendons + data._num_spatial_tendons = num_spatial_tendons + data._is_fixed_base = False + data.body_names = body_names + data.joint_names = joint_names + data.fixed_tendon_names = fixed_tendon_names + data.spatial_tendon_names = spatial_tendon_names + data._create_buffers() + object.__setattr__(articulation, "_data", data) + + # Wrench composers + mock_inst_wrench = MockWrenchComposer(articulation) + mock_perm_wrench = MockWrenchComposer(articulation) + object.__setattr__(articulation, "_instantaneous_wrench_composer", mock_inst_wrench) + object.__setattr__(articulation, "_permanent_wrench_composer", mock_perm_wrench) + + # Prevent __del__ / _clear_callbacks from raising + object.__setattr__(articulation, "_initialize_handle", None) + object.__setattr__(articulation, "_invalidate_initialize_handle", None) + object.__setattr__(articulation, "_prim_deletion_handle", None) + object.__setattr__(articulation, "_debug_vis_handle", None) + object.__setattr__(articulation, "actuators", {}) + + return articulation, mock_bindings + + def create_newton_articulation( num_instances: int = 2, num_joints: int = 6, @@ -326,6 +458,10 @@ def get_articulation( return create_physx_articulation( num_instances, num_joints, num_bodies, num_fixed_tendons, num_spatial_tendons, device ) + elif backend == "ovphysx": + return create_ovphysx_articulation( + num_instances, num_joints, num_bodies, num_fixed_tendons, num_spatial_tendons, device + ) elif backend == "newton": return create_newton_articulation(num_instances, num_joints, num_bodies, device) elif backend.lower() == "mock": @@ -361,9 +497,11 @@ def articulation_iface(request): # --------------------------------------------------------------------------- -def _check_wp_array(arr, *, expected_shape: tuple, expected_dtype: type, name: str): - """Assert that `arr` is a wp.array with the expected shape and dtype.""" - assert isinstance(arr, wp.array), f"{name}: expected wp.array, got {type(arr)}" +def _check_proxy_array(arr, *, expected_shape: tuple, expected_dtype: type, name: str): + """Assert that `arr` is a ProxyArray with the expected shape and dtype.""" + from isaaclab.utils.warp import ProxyArray + + assert isinstance(arr, ProxyArray), f"{name}: expected ProxyArray, got {type(arr)}" assert arr.shape == expected_shape, f"{name}: expected shape {expected_shape}, got {arr.shape}" assert arr.dtype == expected_dtype, f"{name}: expected dtype {expected_dtype}, got {arr.dtype}" @@ -378,6 +516,52 @@ def _check_wp_array(arr, *, expected_shape: tuple, expected_dtype: type, name: s ) _default_devices = pytest.mark.parametrize("device", ["cuda:0", "cpu"]) +_index_resolution_backends = pytest.mark.parametrize( + "backend", [backend for backend in ("physx", "newton") if backend in BACKENDS], indirect=False +) + + +# --------------------------------------------------------------------------- +# Tests: Index resolution helpers +# --------------------------------------------------------------------------- + + +class TestArticulationIndexResolution: + """Test backend-specific index resolution helpers.""" + + @_index_resolution_backends + def test_resolve_env_ids_handles_tensor_view_shape(self, backend): + art, _ = get_articulation(backend, num_instances=4, device="cpu") + + env_ids = torch.arange(4, dtype=torch.int32, device="cpu") + resolved_full = art._resolve_env_ids(env_ids) + resolved_view = art._resolve_env_ids(env_ids[:2]) + + assert resolved_full.shape[0] == 4 + assert resolved_view.shape[0] == 2 + + @_index_resolution_backends + def test_resolve_joint_ids_handles_tensor_view_shape(self, backend): + art, _ = get_articulation(backend, num_joints=4, device="cpu") + + joint_ids = torch.arange(4, dtype=torch.int32, device="cpu") + resolved_full = art._resolve_joint_ids(joint_ids) + resolved_view = art._resolve_joint_ids(joint_ids[:2]) + + assert resolved_full.shape[0] == 4 + assert resolved_view.shape[0] == 2 + + @_index_resolution_backends + def test_resolve_body_ids_handles_tensor_view_shape(self, backend): + art, _ = get_articulation(backend, num_bodies=4, device="cpu") + + body_ids = torch.arange(4, dtype=torch.int32, device="cpu") + resolved_full = art._resolve_body_ids(body_ids) + resolved_view = art._resolve_body_ids(body_ids[:2]) + + assert resolved_full.shape[0] == 4 + assert resolved_view.shape[0] == 2 + # --------------------------------------------------------------------------- # Tests: Articulation properties @@ -498,6 +682,72 @@ def test_find_joints_single(self, backend, num_instances, num_joints, num_bodies assert names == [first_joint] +# --------------------------------------------------------------------------- +# Tests: resolve_matching_names caching behavior +# --------------------------------------------------------------------------- + + +_non_mock_backends = pytest.mark.parametrize("backend", [b for b in BACKENDS if b != "mock"], indirect=False) + + +class TestResolveMatchingNamesCache: + """Test that resolve_matching_names caching returns correct, isolated results.""" + + @_non_mock_backends + @pytest.mark.parametrize("num_instances, num_joints, num_bodies", [(2, 6, 7)]) + @_default_devices + def test_unmatched_regex_raises(self, backend, num_instances, num_joints, num_bodies, device): + """ValueError from resolve_matching_names propagates correctly.""" + art, _ = get_articulation(backend, num_instances, num_joints, num_bodies, device=device) + with pytest.raises(ValueError): + art.find_bodies("nonexistent_body_xyz") + with pytest.raises(ValueError): + art.find_joints("nonexistent_joint_xyz") + + @_backends + @pytest.mark.parametrize("num_instances, num_joints, num_bodies", [(2, 6, 7)]) + @_default_devices + def test_mutating_result_does_not_corrupt_cache( + self, backend, num_instances, num_joints, num_bodies, device, articulation_iface + ): + """Mutating returned lists must not affect future cached results.""" + art, _ = articulation_iface + + for finder, expected_len in [("find_bodies", num_bodies), ("find_joints", num_joints)]: + idx1, names1 = getattr(art, finder)(".*") + assert len(idx1) == expected_len + + idx1.clear() + names1.append("corrupted") + + idx2, names2 = getattr(art, finder)(".*") + assert len(idx2) == expected_len + assert "corrupted" not in names2 + + @_non_mock_backends + @pytest.mark.parametrize("num_instances, num_joints, num_bodies", [(2, 6, 7)]) + @_default_devices + def test_find_with_multiple_patterns(self, backend, num_instances, num_joints, num_bodies, device): + """Passing a list of regex patterns works correctly.""" + art, _ = get_articulation(backend, num_instances, num_joints, num_bodies, device=device) + idx, names = art.find_joints(["joint_0", "joint_1"]) + assert "joint_0" in names + assert "joint_1" in names + assert len(names) == 2 + + @_non_mock_backends + @pytest.mark.parametrize("num_instances, num_joints, num_bodies", [(2, 6, 7)]) + @_default_devices + def test_find_with_preserve_order(self, backend, num_instances, num_joints, num_bodies, device): + """preserve_order=True returns names in the order of the input patterns.""" + art, _ = get_articulation(backend, num_instances, num_joints, num_bodies, device=device) + idx_fwd, names_fwd = art.find_joints(["joint_1", "joint_0"], preserve_order=True) + assert names_fwd == ["joint_1", "joint_0"] + + idx_rev, names_rev = art.find_joints(["joint_0", "joint_1"], preserve_order=True) + assert names_rev == ["joint_0", "joint_1"] + + # --------------------------------------------------------------------------- # Tests: ArticulationData root state properties # --------------------------------------------------------------------------- @@ -512,7 +762,7 @@ class TestArticulationDataRootState: def test_root_link_pose_w(self, backend, num_instances, num_joints, num_bodies, device, articulation_iface): art, _ = articulation_iface art.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( art.data.root_link_pose_w, expected_shape=(num_instances,), expected_dtype=wp.transformf, @@ -525,7 +775,7 @@ def test_root_link_pose_w(self, backend, num_instances, num_joints, num_bodies, def test_root_link_vel_w(self, backend, num_instances, num_joints, num_bodies, device, articulation_iface): art, _ = articulation_iface art.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( art.data.root_link_vel_w, expected_shape=(num_instances,), expected_dtype=wp.spatial_vectorf, @@ -538,7 +788,7 @@ def test_root_link_vel_w(self, backend, num_instances, num_joints, num_bodies, d def test_root_com_pose_w(self, backend, num_instances, num_joints, num_bodies, device, articulation_iface): art, _ = articulation_iface art.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( art.data.root_com_pose_w, expected_shape=(num_instances,), expected_dtype=wp.transformf, @@ -551,7 +801,7 @@ def test_root_com_pose_w(self, backend, num_instances, num_joints, num_bodies, d def test_root_com_vel_w(self, backend, num_instances, num_joints, num_bodies, device, articulation_iface): art, _ = articulation_iface art.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( art.data.root_com_vel_w, expected_shape=(num_instances,), expected_dtype=wp.spatial_vectorf, @@ -564,7 +814,7 @@ def test_root_com_vel_w(self, backend, num_instances, num_joints, num_bodies, de def test_root_link_pos_w(self, backend, num_instances, num_joints, num_bodies, device, articulation_iface): art, _ = articulation_iface art.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( art.data.root_link_pos_w, expected_shape=(num_instances,), expected_dtype=wp.vec3f, name="root_link_pos_w" ) @@ -574,7 +824,7 @@ def test_root_link_pos_w(self, backend, num_instances, num_joints, num_bodies, d def test_root_link_quat_w(self, backend, num_instances, num_joints, num_bodies, device, articulation_iface): art, _ = articulation_iface art.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( art.data.root_link_quat_w, expected_shape=(num_instances,), expected_dtype=wp.quatf, name="root_link_quat_w" ) @@ -584,7 +834,7 @@ def test_root_link_quat_w(self, backend, num_instances, num_joints, num_bodies, def test_root_link_lin_vel_w(self, backend, num_instances, num_joints, num_bodies, device, articulation_iface): art, _ = articulation_iface art.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( art.data.root_link_lin_vel_w, expected_shape=(num_instances,), expected_dtype=wp.vec3f, @@ -597,7 +847,7 @@ def test_root_link_lin_vel_w(self, backend, num_instances, num_joints, num_bodie def test_root_link_ang_vel_w(self, backend, num_instances, num_joints, num_bodies, device, articulation_iface): art, _ = articulation_iface art.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( art.data.root_link_ang_vel_w, expected_shape=(num_instances,), expected_dtype=wp.vec3f, @@ -610,7 +860,7 @@ def test_root_link_ang_vel_w(self, backend, num_instances, num_joints, num_bodie def test_root_com_pos_w(self, backend, num_instances, num_joints, num_bodies, device, articulation_iface): art, _ = articulation_iface art.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( art.data.root_com_pos_w, expected_shape=(num_instances,), expected_dtype=wp.vec3f, name="root_com_pos_w" ) @@ -620,7 +870,7 @@ def test_root_com_pos_w(self, backend, num_instances, num_joints, num_bodies, de def test_root_com_quat_w(self, backend, num_instances, num_joints, num_bodies, device, articulation_iface): art, _ = articulation_iface art.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( art.data.root_com_quat_w, expected_shape=(num_instances,), expected_dtype=wp.quatf, name="root_com_quat_w" ) @@ -630,7 +880,7 @@ def test_root_com_quat_w(self, backend, num_instances, num_joints, num_bodies, d def test_root_com_lin_vel_w(self, backend, num_instances, num_joints, num_bodies, device, articulation_iface): art, _ = articulation_iface art.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( art.data.root_com_lin_vel_w, expected_shape=(num_instances,), expected_dtype=wp.vec3f, @@ -643,7 +893,7 @@ def test_root_com_lin_vel_w(self, backend, num_instances, num_joints, num_bodies def test_root_com_ang_vel_w(self, backend, num_instances, num_joints, num_bodies, device, articulation_iface): art, _ = articulation_iface art.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( art.data.root_com_ang_vel_w, expected_shape=(num_instances,), expected_dtype=wp.vec3f, @@ -665,7 +915,7 @@ class TestArticulationDataDerivedProperties: def test_projected_gravity_b(self, backend, num_instances, num_joints, num_bodies, device, articulation_iface): art, _ = articulation_iface art.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( art.data.projected_gravity_b, expected_shape=(num_instances,), expected_dtype=wp.vec3f, @@ -678,7 +928,7 @@ def test_projected_gravity_b(self, backend, num_instances, num_joints, num_bodie def test_heading_w(self, backend, num_instances, num_joints, num_bodies, device, articulation_iface): art, _ = articulation_iface art.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( art.data.heading_w, expected_shape=(num_instances,), expected_dtype=wp.float32, name="heading_w" ) @@ -688,7 +938,7 @@ def test_heading_w(self, backend, num_instances, num_joints, num_bodies, device, def test_root_link_lin_vel_b(self, backend, num_instances, num_joints, num_bodies, device, articulation_iface): art, _ = articulation_iface art.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( art.data.root_link_lin_vel_b, expected_shape=(num_instances,), expected_dtype=wp.vec3f, @@ -701,7 +951,7 @@ def test_root_link_lin_vel_b(self, backend, num_instances, num_joints, num_bodie def test_root_link_ang_vel_b(self, backend, num_instances, num_joints, num_bodies, device, articulation_iface): art, _ = articulation_iface art.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( art.data.root_link_ang_vel_b, expected_shape=(num_instances,), expected_dtype=wp.vec3f, @@ -714,7 +964,7 @@ def test_root_link_ang_vel_b(self, backend, num_instances, num_joints, num_bodie def test_root_com_lin_vel_b(self, backend, num_instances, num_joints, num_bodies, device, articulation_iface): art, _ = articulation_iface art.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( art.data.root_com_lin_vel_b, expected_shape=(num_instances,), expected_dtype=wp.vec3f, @@ -727,7 +977,7 @@ def test_root_com_lin_vel_b(self, backend, num_instances, num_joints, num_bodies def test_root_com_ang_vel_b(self, backend, num_instances, num_joints, num_bodies, device, articulation_iface): art, _ = articulation_iface art.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( art.data.root_com_ang_vel_b, expected_shape=(num_instances,), expected_dtype=wp.vec3f, @@ -749,7 +999,7 @@ class TestArticulationDataBodyState: def test_body_link_pose_w(self, backend, num_instances, num_joints, num_bodies, device, articulation_iface): art, _ = articulation_iface art.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( art.data.body_link_pose_w, expected_shape=(num_instances, num_bodies), expected_dtype=wp.transformf, @@ -762,7 +1012,7 @@ def test_body_link_pose_w(self, backend, num_instances, num_joints, num_bodies, def test_body_link_vel_w(self, backend, num_instances, num_joints, num_bodies, device, articulation_iface): art, _ = articulation_iface art.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( art.data.body_link_vel_w, expected_shape=(num_instances, num_bodies), expected_dtype=wp.spatial_vectorf, @@ -775,7 +1025,7 @@ def test_body_link_vel_w(self, backend, num_instances, num_joints, num_bodies, d def test_body_com_pose_w(self, backend, num_instances, num_joints, num_bodies, device, articulation_iface): art, _ = articulation_iface art.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( art.data.body_com_pose_w, expected_shape=(num_instances, num_bodies), expected_dtype=wp.transformf, @@ -788,7 +1038,7 @@ def test_body_com_pose_w(self, backend, num_instances, num_joints, num_bodies, d def test_body_com_vel_w(self, backend, num_instances, num_joints, num_bodies, device, articulation_iface): art, _ = articulation_iface art.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( art.data.body_com_vel_w, expected_shape=(num_instances, num_bodies), expected_dtype=wp.spatial_vectorf, @@ -801,7 +1051,7 @@ def test_body_com_vel_w(self, backend, num_instances, num_joints, num_bodies, de def test_body_com_acc_w(self, backend, num_instances, num_joints, num_bodies, device, articulation_iface): art, _ = articulation_iface art.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( art.data.body_com_acc_w, expected_shape=(num_instances, num_bodies), expected_dtype=wp.spatial_vectorf, @@ -816,7 +1066,7 @@ def test_body_com_pose_b(self, backend, num_instances, num_joints, num_bodies, d pytest.xfail("Newton only stores CoM position, not orientation") art, _ = articulation_iface art.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( art.data.body_com_pose_b, expected_shape=(num_instances, num_bodies), expected_dtype=wp.transformf, @@ -829,7 +1079,7 @@ def test_body_com_pose_b(self, backend, num_instances, num_joints, num_bodies, d def test_body_mass(self, backend, num_instances, num_joints, num_bodies, device, articulation_iface): art, _ = articulation_iface art.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( art.data.body_mass, expected_shape=(num_instances, num_bodies), expected_dtype=wp.float32, name="body_mass" ) @@ -839,37 +1089,20 @@ def test_body_mass(self, backend, num_instances, num_joints, num_bodies, device, def test_body_inertia(self, backend, num_instances, num_joints, num_bodies, device, articulation_iface): art, _ = articulation_iface art.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( art.data.body_inertia, expected_shape=(num_instances, num_bodies, 9), expected_dtype=wp.float32, name="body_inertia", ) - @_backends - @_default_dims - @_default_devices - def test_body_incoming_joint_wrench_b( - self, backend, num_instances, num_joints, num_bodies, device, articulation_iface - ): - if backend == "newton": - pytest.xfail("Newton does not support joint wrench reporting") - art, _ = articulation_iface - art.data.update(dt=0.01) - _check_wp_array( - art.data.body_incoming_joint_wrench_b, - expected_shape=(num_instances, num_bodies), - expected_dtype=wp.spatial_vectorf, - name="body_incoming_joint_wrench_b", - ) - @_backends @_default_dims @_default_devices def test_body_link_pos_w(self, backend, num_instances, num_joints, num_bodies, device, articulation_iface): art, _ = articulation_iface art.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( art.data.body_link_pos_w, expected_shape=(num_instances, num_bodies), expected_dtype=wp.vec3f, @@ -882,7 +1115,7 @@ def test_body_link_pos_w(self, backend, num_instances, num_joints, num_bodies, d def test_body_link_quat_w(self, backend, num_instances, num_joints, num_bodies, device, articulation_iface): art, _ = articulation_iface art.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( art.data.body_link_quat_w, expected_shape=(num_instances, num_bodies), expected_dtype=wp.quatf, @@ -895,7 +1128,7 @@ def test_body_link_quat_w(self, backend, num_instances, num_joints, num_bodies, def test_body_link_lin_vel_w(self, backend, num_instances, num_joints, num_bodies, device, articulation_iface): art, _ = articulation_iface art.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( art.data.body_link_lin_vel_w, expected_shape=(num_instances, num_bodies), expected_dtype=wp.vec3f, @@ -908,7 +1141,7 @@ def test_body_link_lin_vel_w(self, backend, num_instances, num_joints, num_bodie def test_body_link_ang_vel_w(self, backend, num_instances, num_joints, num_bodies, device, articulation_iface): art, _ = articulation_iface art.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( art.data.body_link_ang_vel_w, expected_shape=(num_instances, num_bodies), expected_dtype=wp.vec3f, @@ -921,7 +1154,7 @@ def test_body_link_ang_vel_w(self, backend, num_instances, num_joints, num_bodie def test_body_com_pos_w(self, backend, num_instances, num_joints, num_bodies, device, articulation_iface): art, _ = articulation_iface art.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( art.data.body_com_pos_w, expected_shape=(num_instances, num_bodies), expected_dtype=wp.vec3f, @@ -934,7 +1167,7 @@ def test_body_com_pos_w(self, backend, num_instances, num_joints, num_bodies, de def test_body_com_quat_w(self, backend, num_instances, num_joints, num_bodies, device, articulation_iface): art, _ = articulation_iface art.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( art.data.body_com_quat_w, expected_shape=(num_instances, num_bodies), expected_dtype=wp.quatf, @@ -947,7 +1180,7 @@ def test_body_com_quat_w(self, backend, num_instances, num_joints, num_bodies, d def test_body_com_pos_b(self, backend, num_instances, num_joints, num_bodies, device, articulation_iface): art, _ = articulation_iface art.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( art.data.body_com_pos_b, expected_shape=(num_instances, num_bodies), expected_dtype=wp.vec3f, @@ -962,7 +1195,7 @@ def test_body_com_quat_b(self, backend, num_instances, num_joints, num_bodies, d pytest.xfail("Newton only stores CoM position, not orientation") art, _ = articulation_iface art.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( art.data.body_com_quat_b, expected_shape=(num_instances, num_bodies), expected_dtype=wp.quatf, @@ -984,7 +1217,7 @@ class TestArticulationDataJointState: def test_joint_pos(self, backend, num_instances, num_joints, num_bodies, device, articulation_iface): art, _ = articulation_iface art.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( art.data.joint_pos, expected_shape=(num_instances, num_joints), expected_dtype=wp.float32, name="joint_pos" ) @@ -994,7 +1227,7 @@ def test_joint_pos(self, backend, num_instances, num_joints, num_bodies, device, def test_joint_vel(self, backend, num_instances, num_joints, num_bodies, device, articulation_iface): art, _ = articulation_iface art.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( art.data.joint_vel, expected_shape=(num_instances, num_joints), expected_dtype=wp.float32, name="joint_vel" ) @@ -1004,7 +1237,7 @@ def test_joint_vel(self, backend, num_instances, num_joints, num_bodies, device, def test_joint_acc(self, backend, num_instances, num_joints, num_bodies, device, articulation_iface): art, _ = articulation_iface art.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( art.data.joint_acc, expected_shape=(num_instances, num_joints), expected_dtype=wp.float32, name="joint_acc" ) @@ -1014,7 +1247,7 @@ def test_joint_acc(self, backend, num_instances, num_joints, num_bodies, device, def test_joint_stiffness(self, backend, num_instances, num_joints, num_bodies, device, articulation_iface): art, _ = articulation_iface art.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( art.data.joint_stiffness, expected_shape=(num_instances, num_joints), expected_dtype=wp.float32, @@ -1027,7 +1260,7 @@ def test_joint_stiffness(self, backend, num_instances, num_joints, num_bodies, d def test_joint_damping(self, backend, num_instances, num_joints, num_bodies, device, articulation_iface): art, _ = articulation_iface art.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( art.data.joint_damping, expected_shape=(num_instances, num_joints), expected_dtype=wp.float32, @@ -1040,7 +1273,7 @@ def test_joint_damping(self, backend, num_instances, num_joints, num_bodies, dev def test_joint_armature(self, backend, num_instances, num_joints, num_bodies, device, articulation_iface): art, _ = articulation_iface art.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( art.data.joint_armature, expected_shape=(num_instances, num_joints), expected_dtype=wp.float32, @@ -1053,7 +1286,7 @@ def test_joint_armature(self, backend, num_instances, num_joints, num_bodies, de def test_joint_friction_coeff(self, backend, num_instances, num_joints, num_bodies, device, articulation_iface): art, _ = articulation_iface art.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( art.data.joint_friction_coeff, expected_shape=(num_instances, num_joints), expected_dtype=wp.float32, @@ -1066,7 +1299,7 @@ def test_joint_friction_coeff(self, backend, num_instances, num_joints, num_bodi def test_joint_pos_limits(self, backend, num_instances, num_joints, num_bodies, device, articulation_iface): art, _ = articulation_iface art.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( art.data.joint_pos_limits, expected_shape=(num_instances, num_joints), expected_dtype=wp.vec2f, @@ -1079,7 +1312,7 @@ def test_joint_pos_limits(self, backend, num_instances, num_joints, num_bodies, def test_joint_vel_limits(self, backend, num_instances, num_joints, num_bodies, device, articulation_iface): art, _ = articulation_iface art.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( art.data.joint_vel_limits, expected_shape=(num_instances, num_joints), expected_dtype=wp.float32, @@ -1092,7 +1325,7 @@ def test_joint_vel_limits(self, backend, num_instances, num_joints, num_bodies, def test_joint_effort_limits(self, backend, num_instances, num_joints, num_bodies, device, articulation_iface): art, _ = articulation_iface art.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( art.data.joint_effort_limits, expected_shape=(num_instances, num_joints), expected_dtype=wp.float32, @@ -1105,7 +1338,7 @@ def test_joint_effort_limits(self, backend, num_instances, num_joints, num_bodie def test_soft_joint_pos_limits(self, backend, num_instances, num_joints, num_bodies, device, articulation_iface): art, _ = articulation_iface art.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( art.data.soft_joint_pos_limits, expected_shape=(num_instances, num_joints), expected_dtype=wp.vec2f, @@ -1127,7 +1360,7 @@ class TestArticulationDataDefaults: def test_default_root_pose(self, backend, num_instances, num_joints, num_bodies, device, articulation_iface): art, _ = articulation_iface art.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( art.data.default_root_pose, expected_shape=(num_instances,), expected_dtype=wp.transformf, @@ -1140,7 +1373,7 @@ def test_default_root_pose(self, backend, num_instances, num_joints, num_bodies, def test_default_root_vel(self, backend, num_instances, num_joints, num_bodies, device, articulation_iface): art, _ = articulation_iface art.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( art.data.default_root_vel, expected_shape=(num_instances,), expected_dtype=wp.spatial_vectorf, @@ -1153,7 +1386,7 @@ def test_default_root_vel(self, backend, num_instances, num_joints, num_bodies, def test_default_joint_pos(self, backend, num_instances, num_joints, num_bodies, device, articulation_iface): art, _ = articulation_iface art.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( art.data.default_joint_pos, expected_shape=(num_instances, num_joints), expected_dtype=wp.float32, @@ -1166,7 +1399,7 @@ def test_default_joint_pos(self, backend, num_instances, num_joints, num_bodies, def test_default_joint_vel(self, backend, num_instances, num_joints, num_bodies, device, articulation_iface): art, _ = articulation_iface art.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( art.data.default_joint_vel, expected_shape=(num_instances, num_joints), expected_dtype=wp.float32, @@ -1179,7 +1412,7 @@ def test_default_joint_vel(self, backend, num_instances, num_joints, num_bodies, def test_joint_pos_target(self, backend, num_instances, num_joints, num_bodies, device, articulation_iface): art, _ = articulation_iface art.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( art.data.joint_pos_target, expected_shape=(num_instances, num_joints), expected_dtype=wp.float32, @@ -1192,7 +1425,7 @@ def test_joint_pos_target(self, backend, num_instances, num_joints, num_bodies, def test_joint_vel_target(self, backend, num_instances, num_joints, num_bodies, device, articulation_iface): art, _ = articulation_iface art.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( art.data.joint_vel_target, expected_shape=(num_instances, num_joints), expected_dtype=wp.float32, @@ -1205,7 +1438,7 @@ def test_joint_vel_target(self, backend, num_instances, num_joints, num_bodies, def test_joint_effort_target(self, backend, num_instances, num_joints, num_bodies, device, articulation_iface): art, _ = articulation_iface art.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( art.data.joint_effort_target, expected_shape=(num_instances, num_joints), expected_dtype=wp.float32, @@ -2016,7 +2249,7 @@ def test_fixed_tendon_stiffness( ): art, _ = articulation_iface art.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( art.data.fixed_tendon_stiffness, expected_shape=(num_instances, num_fixed_tendons), expected_dtype=wp.float32, @@ -2039,7 +2272,7 @@ def test_fixed_tendon_damping( ): art, _ = articulation_iface art.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( art.data.fixed_tendon_damping, expected_shape=(num_instances, num_fixed_tendons), expected_dtype=wp.float32, @@ -2062,7 +2295,7 @@ def test_fixed_tendon_limit_stiffness( ): art, _ = articulation_iface art.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( art.data.fixed_tendon_limit_stiffness, expected_shape=(num_instances, num_fixed_tendons), expected_dtype=wp.float32, @@ -2085,7 +2318,7 @@ def test_fixed_tendon_rest_length( ): art, _ = articulation_iface art.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( art.data.fixed_tendon_rest_length, expected_shape=(num_instances, num_fixed_tendons), expected_dtype=wp.float32, @@ -2108,7 +2341,7 @@ def test_fixed_tendon_offset( ): art, _ = articulation_iface art.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( art.data.fixed_tendon_offset, expected_shape=(num_instances, num_fixed_tendons), expected_dtype=wp.float32, @@ -2131,8 +2364,10 @@ def test_fixed_tendon_pos_limits( ): art, _ = articulation_iface art.data.update(dt=0.01) + from isaaclab.utils.warp import ProxyArray + arr = art.data.fixed_tendon_pos_limits - assert isinstance(arr, wp.array), f"fixed_tendon_pos_limits: expected wp.array, got {type(arr)}" + assert isinstance(arr, ProxyArray), f"fixed_tendon_pos_limits: expected ProxyArray, got {type(arr)}" if num_fixed_tendons == 0: # When no tendons, shape is (N, 0, 2) float32 assert arr.shape == (num_instances, 0, 2) @@ -2162,7 +2397,7 @@ def test_spatial_tendon_stiffness( if num_spatial_tendons == 0: pytest.skip("No spatial tendons configured") art.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( art.data.spatial_tendon_stiffness, expected_shape=(num_instances, num_spatial_tendons), expected_dtype=wp.float32, @@ -2187,7 +2422,7 @@ def test_spatial_tendon_damping( if num_spatial_tendons == 0: pytest.skip("No spatial tendons configured") art.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( art.data.spatial_tendon_damping, expected_shape=(num_instances, num_spatial_tendons), expected_dtype=wp.float32, @@ -2212,7 +2447,7 @@ def test_spatial_tendon_limit_stiffness( if num_spatial_tendons == 0: pytest.skip("No spatial tendons configured") art.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( art.data.spatial_tendon_limit_stiffness, expected_shape=(num_instances, num_spatial_tendons), expected_dtype=wp.float32, @@ -2237,7 +2472,7 @@ def test_spatial_tendon_offset( if num_spatial_tendons == 0: pytest.skip("No spatial tendons configured") art.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( art.data.spatial_tendon_offset, expected_shape=(num_instances, num_spatial_tendons), expected_dtype=wp.float32, diff --git a/source/isaaclab/test/assets/test_rigid_object_collection_iface.py b/source/isaaclab/test/assets/test_rigid_object_collection_iface.py index 143d32a7f3ba..42c2e8d731b5 100644 --- a/source/isaaclab/test/assets/test_rigid_object_collection_iface.py +++ b/source/isaaclab/test/assets/test_rigid_object_collection_iface.py @@ -38,7 +38,7 @@ _mock_physics_sim_view = MagicMock() _mock_physics_sim_view.get_gravity.return_value = (0.0, 0.0, -9.81) -from isaacsim.core.simulation_manager import SimulationManager +from isaaclab_physx.physics import PhysxManager as SimulationManager SimulationManager.get_physics_sim_view = MagicMock(return_value=_mock_physics_sim_view) @@ -254,9 +254,11 @@ def collection_iface(request): # --------------------------------------------------------------------------- -def _check_wp_array(arr, *, expected_shape: tuple, expected_dtype: type, name: str): - """Assert that `arr` is a wp.array with the expected shape and dtype.""" - assert isinstance(arr, wp.array), f"{name}: expected wp.array, got {type(arr)}" +def _check_proxy_array(arr, *, expected_shape: tuple, expected_dtype: type, name: str): + """Assert that `arr` is a ProxyArray with the expected shape and dtype.""" + from isaaclab.utils.warp import ProxyArray + + assert isinstance(arr, ProxyArray), f"{name}: expected ProxyArray, got {type(arr)}" assert arr.shape == expected_shape, f"{name}: expected shape {expected_shape}, got {arr.shape}" assert arr.dtype == expected_dtype, f"{name}: expected dtype {expected_dtype}, got {arr.dtype}" @@ -269,6 +271,9 @@ def _check_wp_array(arr, *, expected_shape: tuple, expected_dtype: type, name: s _default_bodies = pytest.mark.parametrize("num_bodies", [1, 3]) _default_devices = pytest.mark.parametrize("device", ["cuda:0", "cpu"]) +_index_resolution_backends = pytest.mark.parametrize( + "backend", [backend for backend in ("physx", "newton") if backend in BACKENDS], indirect=False +) # --------------------------------------------------------------------------- @@ -349,6 +354,37 @@ def _make_item_mask(total: int, selected: list[int], device: str) -> wp.array: return wp.array(mask_np, dtype=wp.bool, device=device) +# --------------------------------------------------------------------------- +# Tests: Index resolution helpers +# --------------------------------------------------------------------------- + + +class TestCollectionIndexResolution: + """Test backend-specific index resolution helpers.""" + + @_index_resolution_backends + def test_resolve_env_ids_handles_tensor_view_shape(self, backend): + obj, _ = get_rigid_object_collection(backend, num_instances=4, device="cpu") + + env_ids = torch.arange(4, dtype=torch.int32, device="cpu") + resolved_full = obj._resolve_env_ids(env_ids) + resolved_view = obj._resolve_env_ids(env_ids[:2]) + + assert resolved_full.shape[0] == 4 + assert resolved_view.shape[0] == 2 + + @_index_resolution_backends + def test_resolve_body_ids_handles_tensor_view_shape(self, backend): + obj, _ = get_rigid_object_collection(backend, num_bodies=4, device="cpu") + + body_ids = torch.arange(4, dtype=torch.int32, device="cpu") + resolved_full = obj._resolve_body_ids(body_ids) + resolved_view = obj._resolve_body_ids(body_ids[:2]) + + assert resolved_full.shape[0] == 4 + assert resolved_view.shape[0] == 2 + + # --------------------------------------------------------------------------- # Tests: Collection properties # --------------------------------------------------------------------------- @@ -443,7 +479,7 @@ class TestCollectionDataBodyState: def test_body_link_pose_w(self, backend, num_instances, num_bodies, device, collection_iface): obj, _ = collection_iface obj.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( obj.data.body_link_pose_w, expected_shape=(num_instances, num_bodies), expected_dtype=wp.transformf, @@ -457,7 +493,7 @@ def test_body_link_pose_w(self, backend, num_instances, num_bodies, device, coll def test_body_link_vel_w(self, backend, num_instances, num_bodies, device, collection_iface): obj, _ = collection_iface obj.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( obj.data.body_link_vel_w, expected_shape=(num_instances, num_bodies), expected_dtype=wp.spatial_vectorf, @@ -471,7 +507,7 @@ def test_body_link_vel_w(self, backend, num_instances, num_bodies, device, colle def test_body_com_pose_w(self, backend, num_instances, num_bodies, device, collection_iface): obj, _ = collection_iface obj.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( obj.data.body_com_pose_w, expected_shape=(num_instances, num_bodies), expected_dtype=wp.transformf, @@ -485,7 +521,7 @@ def test_body_com_pose_w(self, backend, num_instances, num_bodies, device, colle def test_body_com_vel_w(self, backend, num_instances, num_bodies, device, collection_iface): obj, _ = collection_iface obj.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( obj.data.body_com_vel_w, expected_shape=(num_instances, num_bodies), expected_dtype=wp.spatial_vectorf, @@ -499,7 +535,7 @@ def test_body_com_vel_w(self, backend, num_instances, num_bodies, device, collec def test_body_com_acc_w(self, backend, num_instances, num_bodies, device, collection_iface): obj, _ = collection_iface obj.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( obj.data.body_com_acc_w, expected_shape=(num_instances, num_bodies), expected_dtype=wp.spatial_vectorf, @@ -513,7 +549,7 @@ def test_body_com_acc_w(self, backend, num_instances, num_bodies, device, collec def test_body_com_pose_b(self, backend, num_instances, num_bodies, device, collection_iface): obj, _ = collection_iface obj.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( obj.data.body_com_pose_b, expected_shape=(num_instances, num_bodies), expected_dtype=wp.transformf, @@ -536,7 +572,7 @@ class TestCollectionDataSliced: def test_body_link_pos_w(self, backend, num_instances, num_bodies, device, collection_iface): obj, _ = collection_iface obj.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( obj.data.body_link_pos_w, expected_shape=(num_instances, num_bodies), expected_dtype=wp.vec3f, @@ -550,7 +586,7 @@ def test_body_link_pos_w(self, backend, num_instances, num_bodies, device, colle def test_body_link_quat_w(self, backend, num_instances, num_bodies, device, collection_iface): obj, _ = collection_iface obj.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( obj.data.body_link_quat_w, expected_shape=(num_instances, num_bodies), expected_dtype=wp.quatf, @@ -564,7 +600,7 @@ def test_body_link_quat_w(self, backend, num_instances, num_bodies, device, coll def test_body_link_lin_vel_w(self, backend, num_instances, num_bodies, device, collection_iface): obj, _ = collection_iface obj.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( obj.data.body_link_lin_vel_w, expected_shape=(num_instances, num_bodies), expected_dtype=wp.vec3f, @@ -578,7 +614,7 @@ def test_body_link_lin_vel_w(self, backend, num_instances, num_bodies, device, c def test_body_link_ang_vel_w(self, backend, num_instances, num_bodies, device, collection_iface): obj, _ = collection_iface obj.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( obj.data.body_link_ang_vel_w, expected_shape=(num_instances, num_bodies), expected_dtype=wp.vec3f, @@ -592,7 +628,7 @@ def test_body_link_ang_vel_w(self, backend, num_instances, num_bodies, device, c def test_body_com_pos_w(self, backend, num_instances, num_bodies, device, collection_iface): obj, _ = collection_iface obj.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( obj.data.body_com_pos_w, expected_shape=(num_instances, num_bodies), expected_dtype=wp.vec3f, @@ -606,7 +642,7 @@ def test_body_com_pos_w(self, backend, num_instances, num_bodies, device, collec def test_body_com_quat_w(self, backend, num_instances, num_bodies, device, collection_iface): obj, _ = collection_iface obj.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( obj.data.body_com_quat_w, expected_shape=(num_instances, num_bodies), expected_dtype=wp.quatf, @@ -620,7 +656,7 @@ def test_body_com_quat_w(self, backend, num_instances, num_bodies, device, colle def test_body_com_lin_vel_w(self, backend, num_instances, num_bodies, device, collection_iface): obj, _ = collection_iface obj.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( obj.data.body_com_lin_vel_w, expected_shape=(num_instances, num_bodies), expected_dtype=wp.vec3f, @@ -634,7 +670,7 @@ def test_body_com_lin_vel_w(self, backend, num_instances, num_bodies, device, co def test_body_com_ang_vel_w(self, backend, num_instances, num_bodies, device, collection_iface): obj, _ = collection_iface obj.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( obj.data.body_com_ang_vel_w, expected_shape=(num_instances, num_bodies), expected_dtype=wp.vec3f, @@ -648,7 +684,7 @@ def test_body_com_ang_vel_w(self, backend, num_instances, num_bodies, device, co def test_body_com_lin_acc_w(self, backend, num_instances, num_bodies, device, collection_iface): obj, _ = collection_iface obj.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( obj.data.body_com_lin_acc_w, expected_shape=(num_instances, num_bodies), expected_dtype=wp.vec3f, @@ -662,7 +698,7 @@ def test_body_com_lin_acc_w(self, backend, num_instances, num_bodies, device, co def test_body_com_ang_acc_w(self, backend, num_instances, num_bodies, device, collection_iface): obj, _ = collection_iface obj.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( obj.data.body_com_ang_acc_w, expected_shape=(num_instances, num_bodies), expected_dtype=wp.vec3f, @@ -676,7 +712,7 @@ def test_body_com_ang_acc_w(self, backend, num_instances, num_bodies, device, co def test_body_com_pos_b(self, backend, num_instances, num_bodies, device, collection_iface): obj, _ = collection_iface obj.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( obj.data.body_com_pos_b, expected_shape=(num_instances, num_bodies), expected_dtype=wp.vec3f, @@ -690,7 +726,7 @@ def test_body_com_pos_b(self, backend, num_instances, num_bodies, device, collec def test_body_com_quat_b(self, backend, num_instances, num_bodies, device, collection_iface): obj, _ = collection_iface obj.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( obj.data.body_com_quat_b, expected_shape=(num_instances, num_bodies), expected_dtype=wp.quatf, @@ -713,7 +749,7 @@ class TestCollectionDataDerived: def test_projected_gravity_b(self, backend, num_instances, num_bodies, device, collection_iface): obj, _ = collection_iface obj.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( obj.data.projected_gravity_b, expected_shape=(num_instances, num_bodies), expected_dtype=wp.vec3f, @@ -727,7 +763,7 @@ def test_projected_gravity_b(self, backend, num_instances, num_bodies, device, c def test_heading_w(self, backend, num_instances, num_bodies, device, collection_iface): obj, _ = collection_iface obj.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( obj.data.heading_w, expected_shape=(num_instances, num_bodies), expected_dtype=wp.float32, name="heading_w" ) @@ -738,7 +774,7 @@ def test_heading_w(self, backend, num_instances, num_bodies, device, collection_ def test_body_link_lin_vel_b(self, backend, num_instances, num_bodies, device, collection_iface): obj, _ = collection_iface obj.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( obj.data.body_link_lin_vel_b, expected_shape=(num_instances, num_bodies), expected_dtype=wp.vec3f, @@ -752,7 +788,7 @@ def test_body_link_lin_vel_b(self, backend, num_instances, num_bodies, device, c def test_body_link_ang_vel_b(self, backend, num_instances, num_bodies, device, collection_iface): obj, _ = collection_iface obj.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( obj.data.body_link_ang_vel_b, expected_shape=(num_instances, num_bodies), expected_dtype=wp.vec3f, @@ -766,7 +802,7 @@ def test_body_link_ang_vel_b(self, backend, num_instances, num_bodies, device, c def test_body_com_lin_vel_b(self, backend, num_instances, num_bodies, device, collection_iface): obj, _ = collection_iface obj.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( obj.data.body_com_lin_vel_b, expected_shape=(num_instances, num_bodies), expected_dtype=wp.vec3f, @@ -780,7 +816,7 @@ def test_body_com_lin_vel_b(self, backend, num_instances, num_bodies, device, co def test_body_com_ang_vel_b(self, backend, num_instances, num_bodies, device, collection_iface): obj, _ = collection_iface obj.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( obj.data.body_com_ang_vel_b, expected_shape=(num_instances, num_bodies), expected_dtype=wp.vec3f, @@ -803,7 +839,7 @@ class TestCollectionDataMass: def test_body_mass(self, backend, num_instances, num_bodies, device, collection_iface): obj, _ = collection_iface obj.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( obj.data.body_mass, expected_shape=(num_instances, num_bodies), expected_dtype=wp.float32, name="body_mass" ) @@ -814,7 +850,7 @@ def test_body_mass(self, backend, num_instances, num_bodies, device, collection_ def test_body_inertia(self, backend, num_instances, num_bodies, device, collection_iface): obj, _ = collection_iface obj.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( obj.data.body_inertia, expected_shape=(num_instances, num_bodies, 9), expected_dtype=wp.float32, @@ -837,7 +873,7 @@ class TestCollectionDataDefaults: def test_default_body_pose(self, backend, num_instances, num_bodies, device, collection_iface): obj, _ = collection_iface obj.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( obj.data.default_body_pose, expected_shape=(num_instances, num_bodies), expected_dtype=wp.transformf, @@ -851,7 +887,7 @@ def test_default_body_pose(self, backend, num_instances, num_bodies, device, col def test_default_body_vel(self, backend, num_instances, num_bodies, device, collection_iface): obj, _ = collection_iface obj.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( obj.data.default_body_vel, expected_shape=(num_instances, num_bodies), expected_dtype=wp.spatial_vectorf, diff --git a/source/isaaclab/test/assets/test_rigid_object_iface.py b/source/isaaclab/test/assets/test_rigid_object_iface.py index 1dc89d2c4c54..178feeddb603 100644 --- a/source/isaaclab/test/assets/test_rigid_object_iface.py +++ b/source/isaaclab/test/assets/test_rigid_object_iface.py @@ -38,7 +38,7 @@ _mock_physics_sim_view = MagicMock() _mock_physics_sim_view.get_gravity.return_value = (0.0, 0.0, -9.81) -from isaacsim.core.simulation_manager import SimulationManager +from isaaclab_physx.physics import PhysxManager as SimulationManager SimulationManager.get_physics_sim_view = MagicMock(return_value=_mock_physics_sim_view) @@ -112,6 +112,22 @@ def create_physx_rigid_object( object.__setattr__(rigid_object, "_ALL_INDICES", wp.array(np.arange(num_instances, dtype=np.int32), device=device)) object.__setattr__(rigid_object, "_ALL_BODY_INDICES", wp.array(np.array([0], dtype=np.int32), device=device)) + # Cached .view(wp.float32) wrappers + object.__setattr__(rigid_object, "_root_link_pose_w_f32", None) + object.__setattr__(rigid_object, "_root_com_vel_w_f32", None) + object.__setattr__(rigid_object, "_inst_wrench_force_f32", None) + object.__setattr__(rigid_object, "_inst_wrench_torque_f32", None) + object.__setattr__(rigid_object, "_perm_wrench_force_f32", None) + object.__setattr__(rigid_object, "_perm_wrench_torque_f32", None) + + # Pre-allocated pinned CPU buffers for PhysX TensorAPI writes + N, B = num_instances, 1 # rigid object has 1 body + cpu_env_ids = wp.array(np.arange(N, dtype=np.int32), device="cpu") + object.__setattr__(rigid_object, "_cpu_env_ids_all", cpu_env_ids) + object.__setattr__(rigid_object, "_cpu_body_mass", wp.zeros((N, B), dtype=wp.float32, device="cpu")) + object.__setattr__(rigid_object, "_cpu_body_coms", wp.zeros((N, B, 7), dtype=wp.float32, device="cpu")) + object.__setattr__(rigid_object, "_cpu_body_inertia", wp.zeros((N, B, 9), dtype=wp.float32, device="cpu")) + return rigid_object, mock_view @@ -231,9 +247,11 @@ def rigid_object_iface(request): # --------------------------------------------------------------------------- -def _check_wp_array(arr, *, expected_shape: tuple, expected_dtype: type, name: str): - """Assert that `arr` is a wp.array with the expected shape and dtype.""" - assert isinstance(arr, wp.array), f"{name}: expected wp.array, got {type(arr)}" +def _check_proxy_array(arr, *, expected_shape: tuple, expected_dtype: type, name: str): + """Assert that `arr` is a ProxyArray with the expected shape and dtype.""" + from isaaclab.utils.warp import ProxyArray + + assert isinstance(arr, ProxyArray), f"{name}: expected ProxyArray, got {type(arr)}" assert arr.shape == expected_shape, f"{name}: expected shape {expected_shape}, got {arr.shape}" assert arr.dtype == expected_dtype, f"{name}: expected dtype {expected_dtype}, got {arr.dtype}" @@ -244,6 +262,29 @@ def _check_wp_array(arr, *, expected_shape: tuple, expected_dtype: type, name: s _default_dims = pytest.mark.parametrize("num_instances", [1, 2, 100]) _default_devices = pytest.mark.parametrize("device", ["cuda:0", "cpu"]) +_index_resolution_backends = pytest.mark.parametrize( + "backend", [backend for backend in ("physx", "newton") if backend in BACKENDS], indirect=False +) + + +# --------------------------------------------------------------------------- +# Tests: Index resolution helpers +# --------------------------------------------------------------------------- + + +class TestRigidObjectIndexResolution: + """Test backend-specific index resolution helpers.""" + + @_index_resolution_backends + def test_resolve_env_ids_handles_tensor_view_shape(self, backend): + obj, _ = get_rigid_object(backend, num_instances=4, device="cpu") + + env_ids = torch.arange(4, dtype=torch.int32, device="cpu") + resolved_full = obj._resolve_env_ids(env_ids) + resolved_view = obj._resolve_env_ids(env_ids[:2]) + + assert resolved_full.shape[0] == 4 + assert resolved_view.shape[0] == 2 # --------------------------------------------------------------------------- @@ -333,7 +374,7 @@ class TestRigidObjectDataRootState: def test_root_link_pose_w(self, backend, num_instances, device, rigid_object_iface): obj, _ = rigid_object_iface obj.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( obj.data.root_link_pose_w, expected_shape=(num_instances,), expected_dtype=wp.transformf, @@ -346,7 +387,7 @@ def test_root_link_pose_w(self, backend, num_instances, device, rigid_object_ifa def test_root_link_vel_w(self, backend, num_instances, device, rigid_object_iface): obj, _ = rigid_object_iface obj.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( obj.data.root_link_vel_w, expected_shape=(num_instances,), expected_dtype=wp.spatial_vectorf, @@ -359,7 +400,7 @@ def test_root_link_vel_w(self, backend, num_instances, device, rigid_object_ifac def test_root_com_pose_w(self, backend, num_instances, device, rigid_object_iface): obj, _ = rigid_object_iface obj.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( obj.data.root_com_pose_w, expected_shape=(num_instances,), expected_dtype=wp.transformf, @@ -372,7 +413,7 @@ def test_root_com_pose_w(self, backend, num_instances, device, rigid_object_ifac def test_root_com_vel_w(self, backend, num_instances, device, rigid_object_iface): obj, _ = rigid_object_iface obj.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( obj.data.root_com_vel_w, expected_shape=(num_instances,), expected_dtype=wp.spatial_vectorf, @@ -385,7 +426,7 @@ def test_root_com_vel_w(self, backend, num_instances, device, rigid_object_iface def test_root_link_pos_w(self, backend, num_instances, device, rigid_object_iface): obj, _ = rigid_object_iface obj.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( obj.data.root_link_pos_w, expected_shape=(num_instances,), expected_dtype=wp.vec3f, name="root_link_pos_w" ) @@ -395,7 +436,7 @@ def test_root_link_pos_w(self, backend, num_instances, device, rigid_object_ifac def test_root_link_quat_w(self, backend, num_instances, device, rigid_object_iface): obj, _ = rigid_object_iface obj.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( obj.data.root_link_quat_w, expected_shape=(num_instances,), expected_dtype=wp.quatf, name="root_link_quat_w" ) @@ -405,7 +446,7 @@ def test_root_link_quat_w(self, backend, num_instances, device, rigid_object_ifa def test_root_link_lin_vel_w(self, backend, num_instances, device, rigid_object_iface): obj, _ = rigid_object_iface obj.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( obj.data.root_link_lin_vel_w, expected_shape=(num_instances,), expected_dtype=wp.vec3f, @@ -418,7 +459,7 @@ def test_root_link_lin_vel_w(self, backend, num_instances, device, rigid_object_ def test_root_link_ang_vel_w(self, backend, num_instances, device, rigid_object_iface): obj, _ = rigid_object_iface obj.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( obj.data.root_link_ang_vel_w, expected_shape=(num_instances,), expected_dtype=wp.vec3f, @@ -431,7 +472,7 @@ def test_root_link_ang_vel_w(self, backend, num_instances, device, rigid_object_ def test_root_com_pos_w(self, backend, num_instances, device, rigid_object_iface): obj, _ = rigid_object_iface obj.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( obj.data.root_com_pos_w, expected_shape=(num_instances,), expected_dtype=wp.vec3f, name="root_com_pos_w" ) @@ -441,7 +482,7 @@ def test_root_com_pos_w(self, backend, num_instances, device, rigid_object_iface def test_root_com_quat_w(self, backend, num_instances, device, rigid_object_iface): obj, _ = rigid_object_iface obj.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( obj.data.root_com_quat_w, expected_shape=(num_instances,), expected_dtype=wp.quatf, name="root_com_quat_w" ) @@ -451,7 +492,7 @@ def test_root_com_quat_w(self, backend, num_instances, device, rigid_object_ifac def test_root_com_lin_vel_w(self, backend, num_instances, device, rigid_object_iface): obj, _ = rigid_object_iface obj.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( obj.data.root_com_lin_vel_w, expected_shape=(num_instances,), expected_dtype=wp.vec3f, @@ -464,7 +505,7 @@ def test_root_com_lin_vel_w(self, backend, num_instances, device, rigid_object_i def test_root_com_ang_vel_w(self, backend, num_instances, device, rigid_object_iface): obj, _ = rigid_object_iface obj.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( obj.data.root_com_ang_vel_w, expected_shape=(num_instances,), expected_dtype=wp.vec3f, @@ -486,7 +527,7 @@ class TestRigidObjectDataDerivedProperties: def test_projected_gravity_b(self, backend, num_instances, device, rigid_object_iface): obj, _ = rigid_object_iface obj.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( obj.data.projected_gravity_b, expected_shape=(num_instances,), expected_dtype=wp.vec3f, @@ -499,7 +540,7 @@ def test_projected_gravity_b(self, backend, num_instances, device, rigid_object_ def test_heading_w(self, backend, num_instances, device, rigid_object_iface): obj, _ = rigid_object_iface obj.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( obj.data.heading_w, expected_shape=(num_instances,), expected_dtype=wp.float32, name="heading_w" ) @@ -509,7 +550,7 @@ def test_heading_w(self, backend, num_instances, device, rigid_object_iface): def test_root_link_lin_vel_b(self, backend, num_instances, device, rigid_object_iface): obj, _ = rigid_object_iface obj.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( obj.data.root_link_lin_vel_b, expected_shape=(num_instances,), expected_dtype=wp.vec3f, @@ -522,7 +563,7 @@ def test_root_link_lin_vel_b(self, backend, num_instances, device, rigid_object_ def test_root_link_ang_vel_b(self, backend, num_instances, device, rigid_object_iface): obj, _ = rigid_object_iface obj.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( obj.data.root_link_ang_vel_b, expected_shape=(num_instances,), expected_dtype=wp.vec3f, @@ -535,7 +576,7 @@ def test_root_link_ang_vel_b(self, backend, num_instances, device, rigid_object_ def test_root_com_lin_vel_b(self, backend, num_instances, device, rigid_object_iface): obj, _ = rigid_object_iface obj.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( obj.data.root_com_lin_vel_b, expected_shape=(num_instances,), expected_dtype=wp.vec3f, @@ -548,7 +589,7 @@ def test_root_com_lin_vel_b(self, backend, num_instances, device, rigid_object_i def test_root_com_ang_vel_b(self, backend, num_instances, device, rigid_object_iface): obj, _ = rigid_object_iface obj.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( obj.data.root_com_ang_vel_b, expected_shape=(num_instances,), expected_dtype=wp.vec3f, @@ -570,7 +611,7 @@ class TestRigidObjectDataBodyState: def test_body_link_pose_w(self, backend, num_instances, device, rigid_object_iface): obj, _ = rigid_object_iface obj.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( obj.data.body_link_pose_w, expected_shape=(num_instances, 1), expected_dtype=wp.transformf, @@ -583,7 +624,7 @@ def test_body_link_pose_w(self, backend, num_instances, device, rigid_object_ifa def test_body_link_vel_w(self, backend, num_instances, device, rigid_object_iface): obj, _ = rigid_object_iface obj.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( obj.data.body_link_vel_w, expected_shape=(num_instances, 1), expected_dtype=wp.spatial_vectorf, @@ -596,7 +637,7 @@ def test_body_link_vel_w(self, backend, num_instances, device, rigid_object_ifac def test_body_com_pose_w(self, backend, num_instances, device, rigid_object_iface): obj, _ = rigid_object_iface obj.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( obj.data.body_com_pose_w, expected_shape=(num_instances, 1), expected_dtype=wp.transformf, @@ -609,7 +650,7 @@ def test_body_com_pose_w(self, backend, num_instances, device, rigid_object_ifac def test_body_com_vel_w(self, backend, num_instances, device, rigid_object_iface): obj, _ = rigid_object_iface obj.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( obj.data.body_com_vel_w, expected_shape=(num_instances, 1), expected_dtype=wp.spatial_vectorf, @@ -622,7 +663,7 @@ def test_body_com_vel_w(self, backend, num_instances, device, rigid_object_iface def test_body_com_acc_w(self, backend, num_instances, device, rigid_object_iface): obj, _ = rigid_object_iface obj.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( obj.data.body_com_acc_w, expected_shape=(num_instances, 1), expected_dtype=wp.spatial_vectorf, @@ -635,7 +676,7 @@ def test_body_com_acc_w(self, backend, num_instances, device, rigid_object_iface def test_body_com_pose_b(self, backend, num_instances, device, rigid_object_iface): obj, _ = rigid_object_iface obj.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( obj.data.body_com_pose_b, expected_shape=(num_instances, 1), expected_dtype=wp.transformf, @@ -648,7 +689,7 @@ def test_body_com_pose_b(self, backend, num_instances, device, rigid_object_ifac def test_body_mass(self, backend, num_instances, device, rigid_object_iface): obj, _ = rigid_object_iface obj.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( obj.data.body_mass, expected_shape=(num_instances, 1), expected_dtype=wp.float32, name="body_mass" ) @@ -658,7 +699,7 @@ def test_body_mass(self, backend, num_instances, device, rigid_object_iface): def test_body_inertia(self, backend, num_instances, device, rigid_object_iface): obj, _ = rigid_object_iface obj.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( obj.data.body_inertia, expected_shape=(num_instances, 1, 9), expected_dtype=wp.float32, name="body_inertia" ) @@ -668,7 +709,7 @@ def test_body_inertia(self, backend, num_instances, device, rigid_object_iface): def test_body_link_pos_w(self, backend, num_instances, device, rigid_object_iface): obj, _ = rigid_object_iface obj.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( obj.data.body_link_pos_w, expected_shape=(num_instances, 1), expected_dtype=wp.vec3f, name="body_link_pos_w" ) @@ -678,7 +719,7 @@ def test_body_link_pos_w(self, backend, num_instances, device, rigid_object_ifac def test_body_link_quat_w(self, backend, num_instances, device, rigid_object_iface): obj, _ = rigid_object_iface obj.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( obj.data.body_link_quat_w, expected_shape=(num_instances, 1), expected_dtype=wp.quatf, @@ -691,7 +732,7 @@ def test_body_link_quat_w(self, backend, num_instances, device, rigid_object_ifa def test_body_link_lin_vel_w(self, backend, num_instances, device, rigid_object_iface): obj, _ = rigid_object_iface obj.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( obj.data.body_link_lin_vel_w, expected_shape=(num_instances, 1), expected_dtype=wp.vec3f, @@ -704,7 +745,7 @@ def test_body_link_lin_vel_w(self, backend, num_instances, device, rigid_object_ def test_body_link_ang_vel_w(self, backend, num_instances, device, rigid_object_iface): obj, _ = rigid_object_iface obj.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( obj.data.body_link_ang_vel_w, expected_shape=(num_instances, 1), expected_dtype=wp.vec3f, @@ -717,7 +758,7 @@ def test_body_link_ang_vel_w(self, backend, num_instances, device, rigid_object_ def test_body_com_pos_w(self, backend, num_instances, device, rigid_object_iface): obj, _ = rigid_object_iface obj.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( obj.data.body_com_pos_w, expected_shape=(num_instances, 1), expected_dtype=wp.vec3f, name="body_com_pos_w" ) @@ -727,7 +768,7 @@ def test_body_com_pos_w(self, backend, num_instances, device, rigid_object_iface def test_body_com_quat_w(self, backend, num_instances, device, rigid_object_iface): obj, _ = rigid_object_iface obj.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( obj.data.body_com_quat_w, expected_shape=(num_instances, 1), expected_dtype=wp.quatf, name="body_com_quat_w" ) @@ -737,7 +778,7 @@ def test_body_com_quat_w(self, backend, num_instances, device, rigid_object_ifac def test_body_com_pos_b(self, backend, num_instances, device, rigid_object_iface): obj, _ = rigid_object_iface obj.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( obj.data.body_com_pos_b, expected_shape=(num_instances, 1), expected_dtype=wp.vec3f, name="body_com_pos_b" ) @@ -747,7 +788,7 @@ def test_body_com_pos_b(self, backend, num_instances, device, rigid_object_iface def test_body_com_quat_b(self, backend, num_instances, device, rigid_object_iface): obj, _ = rigid_object_iface obj.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( obj.data.body_com_quat_b, expected_shape=(num_instances, 1), expected_dtype=wp.quatf, name="body_com_quat_b" ) @@ -766,7 +807,7 @@ class TestRigidObjectDataDefaults: def test_default_root_pose(self, backend, num_instances, device, rigid_object_iface): obj, _ = rigid_object_iface obj.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( obj.data.default_root_pose, expected_shape=(num_instances,), expected_dtype=wp.transformf, @@ -779,7 +820,7 @@ def test_default_root_pose(self, backend, num_instances, device, rigid_object_if def test_default_root_vel(self, backend, num_instances, device, rigid_object_iface): obj, _ = rigid_object_iface obj.data.update(dt=0.01) - _check_wp_array( + _check_proxy_array( obj.data.default_root_vel, expected_shape=(num_instances,), expected_dtype=wp.spatial_vectorf, diff --git a/source/isaaclab/test/cli/test_install_commands.py b/source/isaaclab/test/cli/test_install_commands.py new file mode 100644 index 000000000000..a7c89ccd9d53 --- /dev/null +++ b/source/isaaclab/test/cli/test_install_commands.py @@ -0,0 +1,786 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Tests for install command functions. + +Covers all combinations of: +- Python environment types: uv venv, pip venv, conda, Isaac Sim kit Python, system Python +- Isaac Sim installation methods: local _isaac_sim symlink, pip-installed isaacsim, none +""" + +import subprocess +from contextlib import contextmanager +from pathlib import Path +from unittest import mock + +import pytest + +from isaaclab.cli.commands.install import ( + _PREBUNDLE_REPOINT_PACKAGES, + _ensure_cuda_torch, + _maybe_uninstall_prebundled_torch, + _repoint_prebundle_packages, + _torch_first_on_sys_path_is_prebundle, +) + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + + +def _cp(returncode: int = 0, stdout: str = "") -> mock.MagicMock: + """Return a mock CompletedProcess with the given returncode and stdout.""" + r = mock.MagicMock(spec=subprocess.CompletedProcess) + r.returncode = returncode + r.stdout = stdout + return r + + +def _make_prebundle(base: Path, packages: list[str]) -> Path: + """Create a fake pip_prebundle directory populated with the given package dirs.""" + prebundle = base / "pip_prebundle" + prebundle.mkdir(parents=True) + for pkg in packages: + (prebundle / pkg).mkdir() + return prebundle + + +def _make_site_packages( + base: Path, + packages: list[str], + subdirs: dict[str, list[str]] | None = None, +) -> Path: + """Create a fake site-packages directory. + + Args: + packages: Top-level package directory names to create. + subdirs: Optional mapping of package name → list of subdirectory names to create inside it. + """ + site_pkgs = base / "site-packages" + site_pkgs.mkdir(parents=True, exist_ok=True) + for pkg in packages: + (site_pkgs / pkg).mkdir(exist_ok=True) + for pkg, subs in (subdirs or {}).items(): + for sub in subs: + (site_pkgs / pkg / sub).mkdir(parents=True, exist_ok=True) + return site_pkgs + + +# --------------------------------------------------------------------------- +# _torch_first_on_sys_path_is_prebundle +# --------------------------------------------------------------------------- + + +class TestTorchProbe: + """Tests for :func:`_torch_first_on_sys_path_is_prebundle`. + + The function shells out to ``python_exe -c `` and interprets the + subprocess exit code: 1 → prebundle is first; 0 → it is not. + """ + + def test_returns_true_when_prebundle_first(self, tmp_path): + """Probe exits 1 → the first torch on sys.path is under a pip_prebundle directory.""" + with mock.patch("isaaclab.cli.commands.install.run_command", return_value=_cp(returncode=1)): + result = _torch_first_on_sys_path_is_prebundle( + str(tmp_path / "python"), + env={"PYTHONPATH": "/fake/extsDeprecated/pip_prebundle"}, + ) + assert result is True + + def test_returns_false_when_site_packages_first(self, tmp_path): + """Probe exits 0 → the first torch on sys.path is in regular site-packages.""" + with mock.patch("isaaclab.cli.commands.install.run_command", return_value=_cp(returncode=0)): + result = _torch_first_on_sys_path_is_prebundle( + str(tmp_path / "python"), + env={"PYTHONPATH": "/conda/lib/python3.12/site-packages"}, + ) + assert result is False + + def test_returns_false_when_torch_not_found_anywhere(self, tmp_path): + """Probe exits 0 (no torch on sys.path at all) → returns False.""" + with mock.patch("isaaclab.cli.commands.install.run_command", return_value=_cp(returncode=0)): + result = _torch_first_on_sys_path_is_prebundle( + str(tmp_path / "python"), + env={}, + ) + assert result is False + + def test_passes_env_to_subprocess(self, tmp_path): + """The custom env dict is forwarded to run_command.""" + env_sent = {"PYTHONPATH": "/some/path"} + with mock.patch("isaaclab.cli.commands.install.run_command", return_value=_cp(0)) as mock_run: + _torch_first_on_sys_path_is_prebundle(str(tmp_path / "python"), env=env_sent) + call_kwargs = mock_run.call_args + assert call_kwargs.kwargs.get("env") == env_sent or ( + len(call_kwargs.args) > 1 and call_kwargs.args[1] == env_sent + ) + + +# --------------------------------------------------------------------------- +# _maybe_uninstall_prebundled_torch +# --------------------------------------------------------------------------- + + +class TestMaybeUninstallTorch: + """Tests for :func:`_maybe_uninstall_prebundled_torch`.""" + + def test_does_not_uninstall_when_probe_false(self, tmp_path): + """When the probe returns False, no pip uninstall command is issued.""" + py = str(tmp_path / "python") + with ( + mock.patch( + "isaaclab.cli.commands.install._torch_first_on_sys_path_is_prebundle", + return_value=False, + ), + mock.patch("isaaclab.cli.commands.install.run_command") as mock_run, + ): + _maybe_uninstall_prebundled_torch(py, [py, "-m", "pip"], using_uv=False, probe_env={}) + mock_run.assert_not_called() + + def test_uninstalls_torch_stack_with_minus_y_for_pip(self, tmp_path): + """When probe returns True and pip is in use, uninstall includes -y flag.""" + py = str(tmp_path / "python") + with ( + mock.patch( + "isaaclab.cli.commands.install._torch_first_on_sys_path_is_prebundle", + return_value=True, + ), + mock.patch("isaaclab.cli.commands.install.run_command") as mock_run, + ): + _maybe_uninstall_prebundled_torch(py, [py, "-m", "pip"], using_uv=False, probe_env={}) + mock_run.assert_called_once() + issued = mock_run.call_args[0][0] + assert "uninstall" in issued + assert "-y" in issued + assert "torch" in issued + assert "torchvision" in issued + assert "torchaudio" in issued + + def test_uninstalls_torch_stack_without_minus_y_for_uv(self, tmp_path): + """When probe returns True and uv pip is in use, uninstall omits -y (uv doesn't accept it).""" + with ( + mock.patch( + "isaaclab.cli.commands.install._torch_first_on_sys_path_is_prebundle", + return_value=True, + ), + mock.patch("isaaclab.cli.commands.install.run_command") as mock_run, + ): + _maybe_uninstall_prebundled_torch("/fake/python", ["uv", "pip"], using_uv=True, probe_env={}) + issued = mock_run.call_args[0][0] + assert "uninstall" in issued + assert "-y" not in issued + + def test_probe_receives_original_pythonpath(self, tmp_path): + """The probe_env dict is forwarded unchanged to the torch-probe function.""" + py = str(tmp_path / "python") + probe_env = {"PYTHONPATH": "/a/extsDeprecated/pip_prebundle:/b/site-packages"} + with mock.patch( + "isaaclab.cli.commands.install._torch_first_on_sys_path_is_prebundle", + return_value=False, + ) as mock_probe: + _maybe_uninstall_prebundled_torch(py, [py, "-m", "pip"], using_uv=False, probe_env=probe_env) + mock_probe.assert_called_once_with(py, env=probe_env) + + +# --------------------------------------------------------------------------- +# _ensure_cuda_torch — architecture × environment combinations +# --------------------------------------------------------------------------- + + +class TestEnsureCudaTorch: + """Tests for :func:`_ensure_cuda_torch` across architectures and environment types. + + Combinations tested: + - Architecture: x86 (cu128) vs ARM (cu130) + - Pip command: ``python -m pip`` (venv/conda/kit) vs ``uv pip`` (uv venv) + - Torch state: already installed at correct version; wrong CUDA tag; not installed + """ + + # ---- x86 scenarios ------------------------------------------------------- + + def test_x86_skips_install_when_correct_version_present(self, tmp_path): + """x86: torch 2.10.0+cu128 already installed → pip install is not called.""" + py = str(tmp_path / "python") + pip_cmd = [py, "-m", "pip"] + pip_show_out = "Name: torch\nVersion: 2.10.0+cu128\n" + + with ( + mock.patch("isaaclab.cli.commands.install.extract_python_exe", return_value=py), + mock.patch("isaaclab.cli.commands.install.get_pip_command", return_value=pip_cmd), + mock.patch("isaaclab.cli.commands.install.is_arm", return_value=False), + mock.patch("isaaclab.cli.commands.install.run_command", return_value=_cp(0, pip_show_out)) as mock_run, + ): + _ensure_cuda_torch() + + # Only the initial ``pip show torch`` call; no install. + assert mock_run.call_count == 1 + assert "show" in mock_run.call_args[0][0] + + def test_x86_installs_cu128_when_torch_missing(self, tmp_path): + """x86: no torch installed → installs torch+cu128 from pytorch.org/whl/cu128.""" + py = str(tmp_path / "python") + pip_cmd = [py, "-m", "pip"] + calls: list[list[str]] = [] + + def _run(cmd, **kwargs): + calls.append(list(cmd)) + return _cp(0, "") # pip show returns nothing → torch absent + + with ( + mock.patch("isaaclab.cli.commands.install.extract_python_exe", return_value=py), + mock.patch("isaaclab.cli.commands.install.get_pip_command", return_value=pip_cmd), + mock.patch("isaaclab.cli.commands.install.is_arm", return_value=False), + mock.patch("isaaclab.cli.commands.install.run_command", side_effect=_run), + ): + _ensure_cuda_torch() + + install_cmds = [c for c in calls if "install" in c] + combined = " ".join(str(t) for c in install_cmds for t in c) + assert "cu128" in combined + assert "torch" in combined + + def test_x86_reinstalls_when_wrong_cuda_tag(self, tmp_path): + """x86: torch+cu130 installed (ARM build) → uninstalls and reinstalls as cu128.""" + py = str(tmp_path / "python") + pip_cmd = [py, "-m", "pip"] + calls: list[list[str]] = [] + + def _run(cmd, **kwargs): + calls.append(list(cmd)) + stdout = "Name: torch\nVersion: 2.10.0+cu130\n" if "show" in cmd else "" + return _cp(0, stdout) + + with ( + mock.patch("isaaclab.cli.commands.install.extract_python_exe", return_value=py), + mock.patch("isaaclab.cli.commands.install.get_pip_command", return_value=pip_cmd), + mock.patch("isaaclab.cli.commands.install.is_arm", return_value=False), + mock.patch("isaaclab.cli.commands.install.run_command", side_effect=_run), + ): + _ensure_cuda_torch() + + assert any("uninstall" in c for c in calls), "Expected an uninstall call" + install_cmds = [c for c in calls if "install" in c] + combined = " ".join(str(t) for c in install_cmds for t in c) + assert "cu128" in combined + + # ---- ARM scenarios ------------------------------------------------------- + + def test_arm_installs_cu130_when_torch_missing(self, tmp_path): + """ARM: no torch installed → installs torch+cu130 from pytorch.org/whl/cu130.""" + py = str(tmp_path / "python") + pip_cmd = [py, "-m", "pip"] + calls: list[list[str]] = [] + + def _run(cmd, **kwargs): + calls.append(list(cmd)) + return _cp(0, "") + + with ( + mock.patch("isaaclab.cli.commands.install.extract_python_exe", return_value=py), + mock.patch("isaaclab.cli.commands.install.get_pip_command", return_value=pip_cmd), + mock.patch("isaaclab.cli.commands.install.is_arm", return_value=True), + mock.patch("isaaclab.cli.commands.install.run_command", side_effect=_run), + ): + _ensure_cuda_torch() + + install_cmds = [c for c in calls if "install" in c] + combined = " ".join(str(t) for c in install_cmds for t in c) + assert "cu130" in combined + + def test_arm_skips_install_when_correct_version_present(self, tmp_path): + """ARM: torch 2.10.0+cu130 already installed → pip install is not called.""" + py = str(tmp_path / "python") + pip_cmd = [py, "-m", "pip"] + pip_show_out = "Name: torch\nVersion: 2.10.0+cu130\n" + + with ( + mock.patch("isaaclab.cli.commands.install.extract_python_exe", return_value=py), + mock.patch("isaaclab.cli.commands.install.get_pip_command", return_value=pip_cmd), + mock.patch("isaaclab.cli.commands.install.is_arm", return_value=True), + mock.patch("isaaclab.cli.commands.install.run_command", return_value=_cp(0, pip_show_out)) as mock_run, + ): + _ensure_cuda_torch() + + assert mock_run.call_count == 1 + + def test_arm_reinstalls_when_wrong_cuda_tag(self, tmp_path): + """ARM: torch+cu128 installed (x86 build) → uninstalls and reinstalls as cu130.""" + py = str(tmp_path / "python") + pip_cmd = [py, "-m", "pip"] + calls: list[list[str]] = [] + + def _run(cmd, **kwargs): + calls.append(list(cmd)) + stdout = "Name: torch\nVersion: 2.10.0+cu128\n" if "show" in cmd else "" + return _cp(0, stdout) + + with ( + mock.patch("isaaclab.cli.commands.install.extract_python_exe", return_value=py), + mock.patch("isaaclab.cli.commands.install.get_pip_command", return_value=pip_cmd), + mock.patch("isaaclab.cli.commands.install.is_arm", return_value=True), + mock.patch("isaaclab.cli.commands.install.run_command", side_effect=_run), + ): + _ensure_cuda_torch() + + assert any("uninstall" in c for c in calls) + install_cmds = [c for c in calls if "install" in c] + combined = " ".join(str(t) for c in install_cmds for t in c) + assert "cu130" in combined + + # ---- uv venv environment ------------------------------------------------ + + def test_uv_venv_uses_uv_pip_command(self, tmp_path): + """In a uv venv get_pip_command returns ['uv', 'pip'] and uninstall omits -y.""" + py = str(tmp_path / "python") + calls: list[list[str]] = [] + + def _run(cmd, **kwargs): + calls.append(list(cmd)) + return _cp(0, "") # no current torch → triggers install + + with ( + mock.patch("isaaclab.cli.commands.install.extract_python_exe", return_value=py), + mock.patch("isaaclab.cli.commands.install.get_pip_command", return_value=["uv", "pip"]), + mock.patch("isaaclab.cli.commands.install.is_arm", return_value=False), + mock.patch("isaaclab.cli.commands.install.run_command", side_effect=_run), + ): + _ensure_cuda_torch() + + assert calls[0][0] == "uv", "Expected uv as the pip command prefix" + uninstall_calls = [c for c in calls if "uninstall" in c] + assert uninstall_calls, "Expected an uninstall call before reinstall" + assert "-y" not in uninstall_calls[0], "uv pip uninstall must not include -y" + + # ---- conda / pip venv / kit Python environments ------------------------- + + def test_conda_uses_python_m_pip_with_minus_y(self, tmp_path): + """In a conda env (no uv), get_pip_command returns python -m pip; uninstall uses -y.""" + py = str(tmp_path / "conda" / "bin" / "python") + pip_cmd = [py, "-m", "pip"] + calls: list[list[str]] = [] + + def _run(cmd, **kwargs): + calls.append(list(cmd)) + return _cp(0, "") + + with ( + mock.patch("isaaclab.cli.commands.install.extract_python_exe", return_value=py), + mock.patch("isaaclab.cli.commands.install.get_pip_command", return_value=pip_cmd), + mock.patch("isaaclab.cli.commands.install.is_arm", return_value=False), + mock.patch("isaaclab.cli.commands.install.run_command", side_effect=_run), + ): + _ensure_cuda_torch() + + uninstall_calls = [c for c in calls if "uninstall" in c] + assert uninstall_calls + assert "-y" in uninstall_calls[0], "pip uninstall must include -y" + assert py in uninstall_calls[0], "Expected python exe in pip command" + + def test_kit_python_uses_python_sh_as_pip_prefix(self, tmp_path): + """With Isaac Sim's kit Python, python.sh is the executable prefix in the pip command.""" + python_sh = str(tmp_path / "_isaac_sim" / "python.sh") + pip_cmd = [python_sh, "-m", "pip"] + calls: list[list[str]] = [] + + def _run(cmd, **kwargs): + calls.append(list(cmd)) + return _cp(0, "") + + with ( + mock.patch("isaaclab.cli.commands.install.extract_python_exe", return_value=python_sh), + mock.patch("isaaclab.cli.commands.install.get_pip_command", return_value=pip_cmd), + mock.patch("isaaclab.cli.commands.install.is_arm", return_value=False), + mock.patch("isaaclab.cli.commands.install.run_command", side_effect=_run), + ): + _ensure_cuda_torch() + + assert calls[0][0] == python_sh + + +# --------------------------------------------------------------------------- +# _repoint_prebundle_packages — Isaac Sim install method × venv type +# --------------------------------------------------------------------------- + + +class TestRePointPrebundlePackages: + """Tests for :func:`_repoint_prebundle_packages`. + + Covers all combinations of: + - Isaac Sim installation method: local _isaac_sim symlink, pip-installed isaacsim, none + - Python environment / site-packages source: uv venv, pip venv, conda, kit Python + - nvidia namespace package special handling: cudnn present vs absent + """ + + # ---- shared fixtures / helpers ------------------------------------------ + + def _sim_with_prebundle(self, base: Path, packages: list[str]) -> tuple[Path, Path]: + """Create a minimal fake Isaac Sim tree containing a pip_prebundle dir. + + Returns ``(isaacsim_path, prebundle_dir)``. + """ + isaacsim_path = base / "isaac_sim" + isaacsim_path.mkdir(parents=True) + prebundle = isaacsim_path / "exts" / "some.ext" / "pip_prebundle" + prebundle.mkdir(parents=True) + for pkg in packages: + (prebundle / pkg).mkdir() + return isaacsim_path, prebundle + + @contextmanager + def _patch(self, isaacsim_path: Path | None, site_packages: Path, python_exe: str): + """Context manager that mocks all external calls in _repoint_prebundle_packages.""" + with ( + mock.patch("isaaclab.cli.commands.install.extract_isaacsim_path", return_value=isaacsim_path), + mock.patch("isaaclab.cli.commands.install.extract_python_exe", return_value=python_exe), + mock.patch("isaaclab.cli.commands.install.is_windows", return_value=False), + mock.patch( + "isaaclab.cli.commands.install.run_command", + return_value=_cp(0, str(site_packages)), + ), + ): + yield + + # ---- no Isaac Sim -------------------------------------------------------- + + def test_no_op_when_isaac_sim_absent(self, tmp_path): + """When Isaac Sim is not found, _repoint_prebundle_packages returns immediately without touching anything.""" + with ( + mock.patch("isaaclab.cli.commands.install.extract_isaacsim_path", return_value=None), + mock.patch("isaaclab.cli.commands.install.run_command") as mock_run, + ): + _repoint_prebundle_packages() + mock_run.assert_not_called() + + # ---- no pip_prebundle directories ---------------------------------------- + + def test_no_op_when_no_pip_prebundle_dirs(self, tmp_path): + """When Isaac Sim has no pip_prebundle directories, nothing is repointed.""" + isaacsim_path = tmp_path / "isaac_sim" + isaacsim_path.mkdir() + site_pkgs = _make_site_packages(tmp_path / "env", ["torch"]) + py = str(tmp_path / "python") + + with self._patch(isaacsim_path, site_pkgs, py): + _repoint_prebundle_packages() + + assert not (site_pkgs.parent / "pip_prebundle" / "torch").exists() + + # ---- local _isaac_sim symlink (local build) ------------------------------ + + def test_local_build_symlinks_torch_to_venv_site_packages(self, tmp_path): + """Local _isaac_sim symlink + uv/pip venv: prebundle torch → venv site-packages/torch.""" + isaacsim_path, prebundle = self._sim_with_prebundle(tmp_path / "sim", ["torch"]) + site_pkgs = _make_site_packages(tmp_path / "env", ["torch"]) + py = str(tmp_path / "env" / "bin" / "python") + + with self._patch(isaacsim_path, site_pkgs, py): + _repoint_prebundle_packages() + + symlink = prebundle / "torch" + assert symlink.is_symlink(), "torch should be a symlink after repoint" + assert symlink.resolve() == (site_pkgs / "torch").resolve() + assert (prebundle / "torch.bak").is_dir(), "Original torch should be backed up" + + def test_local_build_skips_nvidia_when_cudnn_absent_kit_python(self, tmp_path): + """Local build + kit Python: site-packages/nvidia has only 'srl' (no cudnn) → nvidia NOT repointed. + + This is the real-world failure mode that caused the libcudnn.so.9 import error: + kit Python's site-packages/nvidia has only the 'srl' namespace sub-package, so + replacing the prebundle's nvidia/ (which contains the CUDA shared libraries) with + a symlink to that stripped-down directory would make libcudnn.so.9 unreachable. + """ + isaacsim_path, prebundle = self._sim_with_prebundle(tmp_path / "sim", ["nvidia"]) + # Simulate kit Python's site-packages: nvidia/ exists but contains only 'srl' + site_pkgs = _make_site_packages(tmp_path / "kit" / "python" / "site-packages", ["nvidia"]) + (site_pkgs / "nvidia" / "srl").mkdir() + py = str(tmp_path / "isaac_sim" / "python.sh") + + with self._patch(isaacsim_path, site_pkgs, py): + _repoint_prebundle_packages() + + assert not (prebundle / "nvidia").is_symlink(), "nvidia must NOT be repointed when cudnn is missing" + assert (prebundle / "nvidia").is_dir(), "Original nvidia directory must be preserved" + + def test_local_build_repoints_nvidia_when_cudnn_present_venv(self, tmp_path): + """Local build + CUDA-capable venv: site-packages/nvidia has cudnn → nvidia IS repointed. + + This covers the conda or pip venv case where the user installed torch+cu128/cu130 + with its nvidia-cudnn-cu12 dependency, giving site-packages/nvidia/cudnn/. + """ + isaacsim_path, prebundle = self._sim_with_prebundle(tmp_path / "sim", ["nvidia"]) + # Full CUDA venv: nvidia/ has cudnn and cublas + site_pkgs = _make_site_packages( + tmp_path / "env", + ["nvidia"], + subdirs={"nvidia": ["cudnn", "cublas"]}, + ) + py = str(tmp_path / "env" / "bin" / "python") + + with self._patch(isaacsim_path, site_pkgs, py): + _repoint_prebundle_packages() + + symlink = prebundle / "nvidia" + assert symlink.is_symlink(), "nvidia should be repointed when cudnn is present" + assert symlink.resolve() == (site_pkgs / "nvidia").resolve() + + def test_idempotent_when_symlink_already_correct(self, tmp_path): + """Calling _repoint_prebundle_packages twice does not break the symlinks.""" + isaacsim_path, prebundle = self._sim_with_prebundle(tmp_path / "sim", []) + site_pkgs = _make_site_packages(tmp_path / "env", ["torch"]) + py = str(tmp_path / "env" / "bin" / "python") + + # Pre-create the correct symlink (as if a previous install already ran). + (prebundle / "torch").symlink_to(site_pkgs / "torch") + original_target = (prebundle / "torch").resolve() + + with self._patch(isaacsim_path, site_pkgs, py): + _repoint_prebundle_packages() + + assert (prebundle / "torch").resolve() == original_target, "Correct symlink must not be changed" + + def test_updates_stale_symlink_pointing_to_old_env(self, tmp_path): + """A symlink from a previous venv that no longer matches current site-packages is updated.""" + isaacsim_path, prebundle = self._sim_with_prebundle(tmp_path / "sim", []) + site_pkgs = _make_site_packages(tmp_path / "env_new", ["torch"]) + old_env = _make_site_packages(tmp_path / "env_old", ["torch"]) + py = str(tmp_path / "env_new" / "bin" / "python") + + # Pre-create a stale symlink pointing at the old env. + (prebundle / "torch").symlink_to(old_env / "torch") + + with self._patch(isaacsim_path, site_pkgs, py): + _repoint_prebundle_packages() + + assert (prebundle / "torch").resolve() == (site_pkgs / "torch").resolve(), "Stale symlink must be updated" + + def test_removes_old_backup_before_renaming(self, tmp_path): + """A pre-existing .bak directory is removed before the current package is backed up.""" + isaacsim_path, prebundle = self._sim_with_prebundle(tmp_path / "sim", ["torch"]) + site_pkgs = _make_site_packages(tmp_path / "env", ["torch"]) + py = str(tmp_path / "env" / "bin" / "python") + + # Simulate leftover backup from a previous partial install. + old_backup = prebundle / "torch.bak" + old_backup.mkdir() + (old_backup / "stale_file.py").touch() + + with self._patch(isaacsim_path, site_pkgs, py): + _repoint_prebundle_packages() + + assert (prebundle / "torch").is_symlink(), "torch must be repointed" + # The old backup was replaced by the fresh backup. + assert (prebundle / "torch.bak").is_dir() + + # ---- pip-installed isaacsim (path found via import probe) ---------------- + + def test_pip_isaacsim_symlinks_torch(self, tmp_path): + """pip-installed isaacsim: extract_isaacsim_path() returns its directory and torch is repointed.""" + # With pip-installed isaacsim the path may be inside site-packages rather than a symlink + # at the repo root, but _repoint_prebundle_packages treats it identically. + isaacsim_path, prebundle = self._sim_with_prebundle(tmp_path / "pip_isaacsim", ["torch"]) + site_pkgs = _make_site_packages(tmp_path / "env", ["torch"]) + py = str(tmp_path / "env" / "bin" / "python") + + with self._patch(isaacsim_path, site_pkgs, py): + _repoint_prebundle_packages() + + assert (prebundle / "torch").is_symlink() + assert (prebundle / "torch").resolve() == (site_pkgs / "torch").resolve() + + def test_pip_isaacsim_skips_nvidia_without_cudnn(self, tmp_path): + """pip-installed isaacsim + no cudnn in site-packages → nvidia prebundle preserved.""" + isaacsim_path, prebundle = self._sim_with_prebundle(tmp_path / "pip_isaacsim", ["nvidia"]) + # site-packages has nvidia/ but without a cudnn sub-package + site_pkgs = _make_site_packages(tmp_path / "env", ["nvidia"]) + py = str(tmp_path / "env" / "bin" / "python") + + with self._patch(isaacsim_path, site_pkgs, py): + _repoint_prebundle_packages() + + assert not (prebundle / "nvidia").is_symlink(), "nvidia must not be repointed without cudnn" + + # ---- different venv types ------------------------------------------------ + + def test_uv_venv_repoints_torch_using_venv_site_packages(self, tmp_path): + """uv venv: site-packages inside VIRTUAL_ENV is used as the symlink target.""" + venv_site = tmp_path / "env_uv" / "lib" / "python3.12" / "site-packages" + venv_site.mkdir(parents=True) + (venv_site / "torch").mkdir() + isaacsim_path, prebundle = self._sim_with_prebundle(tmp_path / "sim", ["torch"]) + py = str(tmp_path / "env_uv" / "bin" / "python") + + with ( + mock.patch("isaaclab.cli.commands.install.extract_isaacsim_path", return_value=isaacsim_path), + mock.patch("isaaclab.cli.commands.install.extract_python_exe", return_value=py), + mock.patch("isaaclab.cli.commands.install.is_windows", return_value=False), + mock.patch("isaaclab.cli.commands.install.run_command", return_value=_cp(0, str(venv_site))), + ): + _repoint_prebundle_packages() + + assert (prebundle / "torch").is_symlink() + assert (prebundle / "torch").resolve() == (venv_site / "torch").resolve() + + def test_conda_repoints_torch_using_conda_site_packages(self, tmp_path): + """conda env: site-packages inside CONDA_PREFIX is used as the symlink target.""" + conda_site = tmp_path / "conda" / "lib" / "python3.12" / "site-packages" + conda_site.mkdir(parents=True) + (conda_site / "torch").mkdir() + isaacsim_path, prebundle = self._sim_with_prebundle(tmp_path / "sim", ["torch"]) + py = str(tmp_path / "conda" / "bin" / "python") + + with ( + mock.patch("isaaclab.cli.commands.install.extract_isaacsim_path", return_value=isaacsim_path), + mock.patch("isaaclab.cli.commands.install.extract_python_exe", return_value=py), + mock.patch("isaaclab.cli.commands.install.is_windows", return_value=False), + mock.patch("isaaclab.cli.commands.install.run_command", return_value=_cp(0, str(conda_site))), + ): + _repoint_prebundle_packages() + + assert (prebundle / "torch").is_symlink() + assert (prebundle / "torch").resolve() == (conda_site / "torch").resolve() + + def test_conda_repoints_nvidia_when_full_cuda_torch_installed(self, tmp_path): + """conda env with nvidia-cudnn-cu12 installed: nvidia/ is repointed because cudnn subdir exists.""" + conda_site = tmp_path / "conda" / "lib" / "python3.12" / "site-packages" + conda_site.mkdir(parents=True) + (conda_site / "nvidia").mkdir() + (conda_site / "nvidia" / "cudnn").mkdir() + (conda_site / "nvidia" / "cublas").mkdir() + isaacsim_path, prebundle = self._sim_with_prebundle(tmp_path / "sim", ["nvidia"]) + py = str(tmp_path / "conda" / "bin" / "python") + + with ( + mock.patch("isaaclab.cli.commands.install.extract_isaacsim_path", return_value=isaacsim_path), + mock.patch("isaaclab.cli.commands.install.extract_python_exe", return_value=py), + mock.patch("isaaclab.cli.commands.install.is_windows", return_value=False), + mock.patch("isaaclab.cli.commands.install.run_command", return_value=_cp(0, str(conda_site))), + ): + _repoint_prebundle_packages() + + assert (prebundle / "nvidia").is_symlink() + + def test_conda_skips_nvidia_when_no_cudnn(self, tmp_path): + """conda env without CUDA torch: site-packages/nvidia lacks cudnn → nvidia not repointed.""" + conda_site = tmp_path / "conda" / "lib" / "python3.12" / "site-packages" + conda_site.mkdir(parents=True) + (conda_site / "nvidia").mkdir() # exists but no cudnn inside + isaacsim_path, prebundle = self._sim_with_prebundle(tmp_path / "sim", ["nvidia"]) + py = str(tmp_path / "conda" / "bin" / "python") + + with ( + mock.patch("isaaclab.cli.commands.install.extract_isaacsim_path", return_value=isaacsim_path), + mock.patch("isaaclab.cli.commands.install.extract_python_exe", return_value=py), + mock.patch("isaaclab.cli.commands.install.is_windows", return_value=False), + mock.patch("isaaclab.cli.commands.install.run_command", return_value=_cp(0, str(conda_site))), + ): + _repoint_prebundle_packages() + + assert not (prebundle / "nvidia").is_symlink() + + # ---- multiple prebundle directories ------------------------------------- + + def test_repoints_across_multiple_prebundle_dirs(self, tmp_path): + """When Isaac Sim has multiple pip_prebundle directories, each is processed.""" + isaacsim_path = tmp_path / "isaac_sim" + isaacsim_path.mkdir() + + # Two separate extension pip_prebundle dirs, each with torch. + pb1 = isaacsim_path / "exts" / "ext_a" / "pip_prebundle" + pb2 = isaacsim_path / "exts" / "ext_b" / "pip_prebundle" + for pb in (pb1, pb2): + pb.mkdir(parents=True) + (pb / "torch").mkdir() + + site_pkgs = _make_site_packages(tmp_path / "env", ["torch"]) + py = str(tmp_path / "env" / "bin" / "python") + + with self._patch(isaacsim_path, site_pkgs, py): + _repoint_prebundle_packages() + + for pb in (pb1, pb2): + assert (pb / "torch").is_symlink(), f"torch in {pb} should be repointed" + + # ---- Windows: copy instead of symlink ----------------------------------- + + def test_copies_package_on_windows_instead_of_symlinking(self, tmp_path): + """On Windows, packages are copied rather than symlinked (Windows doesn't support posix symlinks).""" + isaacsim_path, prebundle = self._sim_with_prebundle(tmp_path / "sim", ["torch"]) + site_pkgs = _make_site_packages(tmp_path / "env", ["torch"]) + (site_pkgs / "torch" / "version.py").write_text("__version__ = '2.10.0'") + py = str(tmp_path / "env" / "bin" / "python") + + with ( + mock.patch("isaaclab.cli.commands.install.extract_isaacsim_path", return_value=isaacsim_path), + mock.patch("isaaclab.cli.commands.install.extract_python_exe", return_value=py), + mock.patch("isaaclab.cli.commands.install.is_windows", return_value=True), + mock.patch("isaaclab.cli.commands.install.run_command", return_value=_cp(0, str(site_pkgs))), + ): + _repoint_prebundle_packages() + + torch_in_prebundle = prebundle / "torch" + assert torch_in_prebundle.is_dir(), "torch should be a directory (copy) on Windows" + assert not torch_in_prebundle.is_symlink(), "torch must not be a symlink on Windows" + assert (torch_in_prebundle / "version.py").exists(), "Copied file should be present" + + # ---- error handling ----------------------------------------------------- + + def test_oserror_on_one_package_does_not_abort_others(self, tmp_path): + """An OSError while repointing one package is logged and processing continues for others.""" + isaacsim_path, prebundle = self._sim_with_prebundle(tmp_path / "sim", ["torch", "torchvision"]) + site_pkgs = _make_site_packages(tmp_path / "env", ["torch", "torchvision"]) + py = str(tmp_path / "env" / "bin" / "python") + + original_symlink_to = Path.symlink_to + call_count: list[int] = [0] + + def _selective_symlink(self_path: Path, target: Path, **kwargs) -> None: + call_count[0] += 1 + # Fail on the first symlink_to call (torch) but succeed for others. + if call_count[0] == 1: + raise OSError("Permission denied") + return original_symlink_to(self_path, target, **kwargs) + + with ( + mock.patch("isaaclab.cli.commands.install.extract_isaacsim_path", return_value=isaacsim_path), + mock.patch("isaaclab.cli.commands.install.extract_python_exe", return_value=py), + mock.patch("isaaclab.cli.commands.install.is_windows", return_value=False), + mock.patch("isaaclab.cli.commands.install.run_command", return_value=_cp(0, str(site_pkgs))), + mock.patch.object(Path, "symlink_to", _selective_symlink), + ): + _repoint_prebundle_packages() # must not raise + + # torchvision (second package) must still be repointed despite torch failure. + assert (prebundle / "torchvision").is_symlink(), "torchvision must succeed after torch OSError" + + def test_skips_gracefully_when_site_packages_probe_fails(self, tmp_path): + """When the site-packages probe subprocess fails, _repoint_prebundle_packages is a no-op.""" + isaacsim_path, prebundle = self._sim_with_prebundle(tmp_path / "sim", ["torch"]) + py = str(tmp_path / "python") + + with ( + mock.patch("isaaclab.cli.commands.install.extract_isaacsim_path", return_value=isaacsim_path), + mock.patch("isaaclab.cli.commands.install.extract_python_exe", return_value=py), + mock.patch("isaaclab.cli.commands.install.is_windows", return_value=False), + # Probe subprocess exits non-zero + mock.patch("isaaclab.cli.commands.install.run_command", return_value=_cp(returncode=1, stdout="")), + ): + _repoint_prebundle_packages() + + assert not (prebundle / "torch").is_symlink(), "No symlink should be created when probe fails" + + # ---- all packages in the repoint list are covered ----------------------- + + @pytest.mark.parametrize("pkg_name", [p for p in _PREBUNDLE_REPOINT_PACKAGES if p != "nvidia"]) + def test_all_non_nvidia_packages_are_repointed(self, tmp_path, pkg_name): + """Every non-nvidia entry in _PREBUNDLE_REPOINT_PACKAGES is repointed when it exists.""" + isaacsim_path, prebundle = self._sim_with_prebundle(tmp_path / "sim", [pkg_name]) + site_pkgs = _make_site_packages(tmp_path / "env", [pkg_name]) + py = str(tmp_path / "env" / "bin" / "python") + + with self._patch(isaacsim_path, site_pkgs, py): + _repoint_prebundle_packages() + + assert (prebundle / pkg_name).is_symlink(), f"{pkg_name} should be repointed" + assert (prebundle / pkg_name).resolve() == (site_pkgs / pkg_name).resolve() diff --git a/source/isaaclab/test/cli/test_install_prebundle.py b/source/isaaclab/test/cli/test_install_prebundle.py new file mode 100644 index 000000000000..ef08d0a1a726 --- /dev/null +++ b/source/isaaclab/test/cli/test_install_prebundle.py @@ -0,0 +1,81 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Tests for prebundle probe and _split_install_items. + +Supplements test_install_commands.py with tests that verify the probe +script text and the comma-separated install item parser. +""" + +from unittest import mock + +from isaaclab.cli.commands.install import ( + _split_install_items, + _torch_first_on_sys_path_is_prebundle, +) + +# --------------------------------------------------------------------------- +# _split_install_items +# --------------------------------------------------------------------------- + + +class TestSplitInstallItems: + """Tests for :func:`_split_install_items`.""" + + def test_single_item(self): + assert _split_install_items("assets") == ["assets"] + + def test_comma_separated(self): + assert _split_install_items("assets,tasks,rl") == ["assets", "tasks", "rl"] + + def test_with_spaces(self): + assert _split_install_items(" assets , tasks , rl ") == ["assets", "tasks", "rl"] + + def test_brackets_preserved(self): + """Commas inside brackets should not split.""" + assert _split_install_items("visualizers[rerun,newton],tasks") == [ + "visualizers[rerun,newton]", + "tasks", + ] + + def test_nested_brackets(self): + assert _split_install_items("a[b[c,d],e],f") == ["a[b[c,d],e]", "f"] + + def test_empty_string(self): + assert _split_install_items("") == [] + + def test_trailing_comma(self): + assert _split_install_items("assets,tasks,") == ["assets", "tasks"] + + def test_single_with_extra(self): + assert _split_install_items("visualizers[all]") == ["visualizers[all]"] + + +# --------------------------------------------------------------------------- +# _torch_first_on_sys_path_is_prebundle — probe script verification +# --------------------------------------------------------------------------- + + +class TestTorchProbeScriptContent: + """Verify that the probe script checks for 'pip_prebundle' not 'extsDeprecated'.""" + + def test_probe_script_checks_pip_prebundle(self): + """The inline Python probe must use 'pip_prebundle' as its path indicator.""" + import subprocess + + captured_cmd = None + + def fake_run(cmd, *, env=None, check=False, capture_output=False, text=False): + nonlocal captured_cmd + captured_cmd = cmd + return subprocess.CompletedProcess(args=cmd, returncode=0) + + with mock.patch("isaaclab.cli.commands.install.run_command", side_effect=fake_run): + _torch_first_on_sys_path_is_prebundle("/fake/python", env={}) + + assert captured_cmd is not None + probe_script = captured_cmd[2] # [python_exe, "-c", probe] + assert "pip_prebundle" in probe_script, "Probe must check for 'pip_prebundle'" + assert "extsDeprecated" not in probe_script, "Probe must NOT check only for 'extsDeprecated'" diff --git a/source/isaaclab/test/controllers/test_differential_ik.py b/source/isaaclab/test/controllers/test_differential_ik.py index 34ae911ac911..47abc78e0de6 100644 --- a/source/isaaclab/test/controllers/test_differential_ik.py +++ b/source/isaaclab/test/controllers/test_differential_ik.py @@ -16,9 +16,8 @@ import torch import warp as wp -from isaacsim.core.cloner import GridCloner - import isaaclab.sim as sim_utils +from isaaclab import cloner from isaaclab.assets import Articulation from isaaclab.controllers import DifferentialIKController, DifferentialIKControllerCfg @@ -53,18 +52,15 @@ def sim(): cfg = sim_utils.GroundPlaneCfg() cfg.func("/World/GroundPlane", cfg) - # Create interface to clone the scene - cloner = GridCloner(spacing=2.0, stage=stage) - cloner.define_base_env("/World/envs") - env_prim_paths = cloner.generate_paths("/World/envs/env", num_envs) + # Create environment clones using Isaac Lab's cloner utilities + env_prim_paths = [f"/World/envs/env_{i}" for i in range(num_envs)] + env_fmt = "/World/envs/env_{}" + env_ids = torch.arange(num_envs, dtype=torch.long, device=sim.device) + env_origins, _ = cloner.grid_transforms(num_envs, spacing=2.0, device=sim.device) # create source prim stage.DefinePrim(env_prim_paths[0], "Xform") # clone the env xform - cloner.clone( - source_prim_path=env_prim_paths[0], - prim_paths=env_prim_paths, - replicate_physics=True, - ) + cloner.usd_replicate(stage, [env_fmt.format(0)], [env_fmt], env_ids, positions=env_origins) # Define goals for the arm (x, y, z, qx, qy, qz, qw) ee_goals_set = [ @@ -156,8 +152,8 @@ def _run_ik_controller( ee_pose_b_des = torch.zeros(num_envs, diff_ik_controller.action_dim, device=sim.device) ee_pose_b_des[:] = ee_pose_b_des_set[current_goal_idx] # Compute current pose of the end-effector - ee_pose_w = wp.to_torch(robot.data.body_pose_w)[:, ee_frame_idx] - root_pose_w = wp.to_torch(robot.data.root_pose_w) + ee_pose_w = robot.data.body_pose_w.torch[:, ee_frame_idx] + root_pose_w = robot.data.root_pose_w.torch ee_pos_b, ee_quat_b = subtract_frame_transforms( root_pose_w[:, 0:3], root_pose_w[:, 3:7], ee_pose_w[:, 0:3], ee_pose_w[:, 3:7] ) @@ -179,14 +175,14 @@ def _run_ik_controller( torch.testing.assert_close(pos_error_norm, des_error, rtol=0.0, atol=1e-3) torch.testing.assert_close(rot_error_norm, des_error, rtol=0.0, atol=1e-3) # reset joint state - joint_pos = wp.to_torch(robot.data.default_joint_pos).clone() - joint_vel = wp.to_torch(robot.data.default_joint_vel).clone() + joint_pos = robot.data.default_joint_pos.torch.clone() + joint_vel = robot.data.default_joint_vel.torch.clone() # joint_pos *= sample_uniform(0.9, 1.1, joint_pos.shape, joint_pos.device) robot.write_joint_state_to_sim(joint_pos, joint_vel) robot.set_joint_position_target(joint_pos) robot.write_data_to_sim() # randomize root state yaw, ik should work regardless base rotation - root_state = wp.to_torch(robot.data.root_state_w).clone() + root_state = robot.data.root_state_w.torch.clone() root_state[:, 3:7] = random_yaw_orientation(num_envs, sim.device) robot.write_root_pose_to_sim(root_state[:, :7]) robot.write_root_velocity_to_sim(root_state[:, 7:]) @@ -204,13 +200,13 @@ def _run_ik_controller( # so we MUST skip the first step # obtain quantities from simulation jacobian = wp.to_torch(robot.root_view.get_jacobians())[:, ee_jacobi_idx, :, arm_joint_ids] - ee_pose_w = wp.to_torch(robot.data.body_pose_w)[:, ee_frame_idx] - root_pose_w = wp.to_torch(robot.data.root_pose_w) + ee_pose_w = robot.data.body_pose_w.torch[:, ee_frame_idx] + root_pose_w = robot.data.root_pose_w.torch base_rot = root_pose_w[:, 3:7] base_rot_matrix = matrix_from_quat(quat_inv(base_rot)) jacobian[:, :3, :] = torch.bmm(base_rot_matrix, jacobian[:, :3, :]) jacobian[:, 3:, :] = torch.bmm(base_rot_matrix, jacobian[:, 3:, :]) - joint_pos = wp.to_torch(robot.data.joint_pos)[:, arm_joint_ids] + joint_pos = robot.data.joint_pos.torch[:, arm_joint_ids] # compute frame in root frame ee_pos_b, ee_quat_b = subtract_frame_transforms( root_pose_w[:, 0:3], root_pose_w[:, 3:7], ee_pose_w[:, 0:3], ee_pose_w[:, 3:7] diff --git a/source/isaaclab/test/controllers/test_operational_space.py b/source/isaaclab/test/controllers/test_operational_space.py index 3b9eb1a2c5a0..63c1633c5f7c 100644 --- a/source/isaaclab/test/controllers/test_operational_space.py +++ b/source/isaaclab/test/controllers/test_operational_space.py @@ -17,10 +17,9 @@ import warp as wp from flaky import flaky -from isaacsim.core.cloner import GridCloner - import isaaclab.envs.mdp as mdp import isaaclab.sim as sim_utils +from isaaclab import cloner from isaaclab.assets import Articulation from isaaclab.assets.articulation import ArticulationCfg from isaaclab.controllers import OperationalSpaceController, OperationalSpaceControllerCfg @@ -82,18 +81,15 @@ def sim(): translation=[0, 0, 1], ) - # Create interface to clone the scene - cloner = GridCloner(spacing=2.0, stage=stage) - cloner.define_base_env("/World/envs") - env_prim_paths = cloner.generate_paths("/World/envs/env", num_envs) + # Create environment clones using Isaac Lab's cloner utilities + env_prim_paths = [f"/World/envs/env_{i}" for i in range(num_envs)] + env_fmt = "/World/envs/env_{}" + env_ids = torch.arange(num_envs, dtype=torch.long, device=sim.device) + env_origins, _ = cloner.grid_transforms(num_envs, spacing=2.0, device=sim.device) # create source prim stage.DefinePrim(env_prim_paths[0], "Xform") # clone the env xform - cloner.clone( - source_prim_path=env_prim_paths[0], - prim_paths=env_prim_paths, - replicate_physics=True, - ) + cloner.usd_replicate(stage, [env_fmt.format(0)], [env_fmt], env_ids, positions=env_origins) robot_cfg = FRANKA_PANDA_CFG.replace(prim_path="/World/envs/env_.*/Robot") robot_cfg.actuators["panda_shoulder"].stiffness = 0.0 @@ -1460,7 +1456,7 @@ def _run_op_space_controller( robot.update(dt=sim_dt) # Get the center of the robot soft joint limits - joint_centers = torch.mean(wp.to_torch(robot.data.soft_joint_pos_limits)[:, arm_joint_ids, :], dim=-1) + joint_centers = torch.mean(robot.data.soft_joint_pos_limits.torch[:, arm_joint_ids, :], dim=-1) # get the updated states ( @@ -1500,8 +1496,8 @@ def _run_op_space_controller( osc, ee_pose_b, ee_target_pose_b, ee_force_b, command, pos_mask, rot_mask, force_mask, frame ) # reset joint state to default - default_joint_pos = wp.to_torch(robot.data.default_joint_pos).clone() - default_joint_vel = wp.to_torch(robot.data.default_joint_vel).clone() + default_joint_pos = robot.data.default_joint_pos.torch.clone() + default_joint_vel = robot.data.default_joint_vel.torch.clone() robot.write_joint_state_to_sim(default_joint_pos, default_joint_vel) robot.set_joint_effort_target(zero_joint_efforts) # Set zero torques in the initial step robot.write_data_to_sim() @@ -1599,28 +1595,24 @@ def _update_states( gravity = wp.to_torch(robot.root_view.get_gravity_compensation_forces())[:, arm_joint_ids] # Convert the Jacobian from world to root frame jacobian_b = jacobian_w.clone() - root_rot_matrix = matrix_from_quat(quat_inv(wp.to_torch(robot.data.root_quat_w))) + root_rot_matrix = matrix_from_quat(quat_inv(robot.data.root_quat_w.torch)) jacobian_b[:, :3, :] = torch.bmm(root_rot_matrix, jacobian_b[:, :3, :]) jacobian_b[:, 3:, :] = torch.bmm(root_rot_matrix, jacobian_b[:, 3:, :]) # Compute current pose of the end-effector - root_pose_w = wp.to_torch(robot.data.root_pose_w) - ee_pose_w = wp.to_torch(robot.data.body_pose_w)[:, ee_frame_idx] + root_pose_w = robot.data.root_pose_w.torch + ee_pose_w = robot.data.body_pose_w.torch[:, ee_frame_idx] ee_pos_b, ee_quat_b = subtract_frame_transforms( root_pose_w[:, 0:3], root_pose_w[:, 3:7], ee_pose_w[:, 0:3], ee_pose_w[:, 3:7] ) ee_pose_b = torch.cat([ee_pos_b, ee_quat_b], dim=-1) # Compute the current velocity of the end-effector - ee_vel_w = wp.to_torch(robot.data.body_vel_w)[ - :, ee_frame_idx, : - ] # Extract end-effector velocity in the world frame - root_vel_w = wp.to_torch(robot.data.root_vel_w) # Extract root velocity in the world frame + ee_vel_w = robot.data.body_vel_w.torch[:, ee_frame_idx, :] # Extract end-effector velocity in the world frame + root_vel_w = robot.data.root_vel_w.torch # Extract root velocity in the world frame relative_vel_w = ee_vel_w - root_vel_w # Compute the relative velocity in the world frame - ee_lin_vel_b = quat_apply_inverse( - wp.to_torch(robot.data.root_quat_w), relative_vel_w[:, 0:3] - ) # From world to root frame - ee_ang_vel_b = quat_apply_inverse(wp.to_torch(robot.data.root_quat_w), relative_vel_w[:, 3:6]) + ee_lin_vel_b = quat_apply_inverse(robot.data.root_quat_w.torch, relative_vel_w[:, 0:3]) # From world to root frame + ee_ang_vel_b = quat_apply_inverse(robot.data.root_quat_w.torch, relative_vel_w[:, 3:6]) ee_vel_b = torch.cat([ee_lin_vel_b, ee_ang_vel_b], dim=-1) # Calculate the contact force @@ -1630,14 +1622,14 @@ def _update_states( contact_forces.update(sim_dt) # update contact sensor # Calculate the contact force by averaging over last four time steps (i.e., to smoothen) and # taking the max of three surfaces as only one should be the contact of interest - ee_force_w, _ = torch.max(torch.mean(wp.to_torch(contact_forces.data.net_forces_w_history), dim=1), dim=1) + ee_force_w, _ = torch.max(torch.mean(contact_forces.data.net_forces_w_history.torch, dim=1), dim=1) # This is a simplification, only for the sake of testing. ee_force_b = ee_force_w # Get joint positions and velocities - joint_pos = wp.to_torch(robot.data.joint_pos)[:, arm_joint_ids] - joint_vel = wp.to_torch(robot.data.joint_vel)[:, arm_joint_ids] + joint_pos = robot.data.joint_pos.torch[:, arm_joint_ids] + joint_vel = robot.data.joint_vel.torch[:, arm_joint_ids] return ( jacobian_b, diff --git a/source/isaaclab/test/controllers/test_pink_ik.py b/source/isaaclab/test/controllers/test_pink_ik.py index 9913c76f7dcf..4c7669b1c72e 100644 --- a/source/isaaclab/test/controllers/test_pink_ik.py +++ b/source/isaaclab/test/controllers/test_pink_ik.py @@ -21,7 +21,6 @@ import numpy as np import pytest import torch -import warp as wp from pink.configuration import Configuration from pink.tasks import FrameTask @@ -31,6 +30,8 @@ import isaaclab_tasks # noqa: F401 from isaaclab_tasks.utils.parse_cfg import parse_env_cfg +pytestmark = pytest.mark.isaacsim_ci + def load_test_config(env_name): """Load test configuration based on environment type.""" @@ -288,7 +289,7 @@ def run_movement_test(test_setup, test_config, test_cfg, aux_function=None): def get_link_pose(env, link_name): """Get the position and orientation of a link.""" link_index = env.scene["robot"].data.body_names.index(link_name) - link_states = wp.to_torch(env.scene._articulations["robot"].data.body_link_state_w) + link_states = env.scene._articulations["robot"].data.body_link_state_w.torch link_pose = link_states[:, link_index, :7] return link_pose[:, :3], link_pose[:, 3:7] @@ -341,7 +342,7 @@ def compute_errors( isaaclab_controlled_joint_ids = action_term._isaaclab_controlled_joint_ids # Get current and target positions for controlled joints only - curr_joints = wp.to_torch(articulation.data.joint_pos)[:, isaaclab_controlled_joint_ids].cpu().numpy()[0] + curr_joints = articulation.data.joint_pos.torch[:, isaaclab_controlled_joint_ids].cpu().numpy()[0] target_joints = action_term.processed_actions[:, : len(isaaclab_controlled_joint_ids)].cpu().numpy()[0] # Reorder joints for Pink IK (using controlled joint ordering) diff --git a/source/isaaclab/test/controllers/test_pink_ik_components.py b/source/isaaclab/test/controllers/test_pink_ik_components.py index 84dfd716a0b4..2533e78e0123 100644 --- a/source/isaaclab/test/controllers/test_pink_ik_components.py +++ b/source/isaaclab/test/controllers/test_pink_ik_components.py @@ -19,6 +19,8 @@ from isaaclab.controllers.pink_ik.pink_kinematics_configuration import PinkKinematicsConfiguration +pytestmark = pytest.mark.isaacsim_ci + class TestPinkKinematicsConfiguration: """Test suite for PinkKinematicsConfiguration class.""" diff --git a/source/isaaclab/test/deps/isaacsim/check_camera.py b/source/isaaclab/test/deps/isaacsim/check_camera.py index 27a0dfdfca99..ee2c9d5adf28 100644 --- a/source/isaaclab/test/deps/isaacsim/check_camera.py +++ b/source/isaaclab/test/deps/isaacsim/check_camera.py @@ -3,241 +3,17 @@ # # SPDX-License-Identifier: BSD-3-Clause -""" -This script shows the issue with renderer in Isaac Sim that affects episodic resets. +"""Historic camera episodic-reset reproducer (retired). -The first few images of every new episode are not updated. They take multiple steps to update -and have the same image as the previous episode for the first few steps. +This script previously depended on Isaac Sim core extensions that Isaac Sim now carries under +``source/deprecated`` in the Isaac Sim repository. It has been retired from Isaac Lab to avoid +depending on those extension IDs and import paths. -``` -# run with cube -_isaac_sim/python.sh source/isaaclab/test/deps/isaacsim/check_camera.py --scenario cube -# run with anymal -_isaac_sim/python.sh source/isaaclab/test/deps/isaacsim/check_camera.py --scenario anymal -``` +Use :class:`~isaaclab.sim.SimulationContext`, Isaac Lab sensors, and ``isaacsim.core.experimental.*`` +APIs when debugging rendering and camera pipelines. """ -"""Launch Isaac Sim Simulator first.""" - -import argparse - -# isaaclab -from isaaclab.app import AppLauncher - -# add argparse arguments -parser = argparse.ArgumentParser( - description="This script shows the issue with renderer in Isaac Sim that affects episodic resets." +raise RuntimeError( + "This standalone reproducer was retired; it depended on deprecated Isaac Sim core extensions. " + "Use Isaac Lab :mod:`isaaclab.sim` and ``isaacsim.core.experimental.*`` instead." ) -parser.add_argument("--gpu", action="store_true", default=False, help="Use GPU device for camera rendering output.") -parser.add_argument("--scenario", type=str, default="anymal", help="Scenario to load.", choices=["anymal", "cube"]) -# 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 os -import random - -import numpy as np -from PIL import Image, ImageChops - -import isaacsim.core.utils.nucleus as nucleus_utils -import isaacsim.core.utils.prims as prim_utils -import omni.replicator.core as rep -from isaacsim.core.api.world import World -from isaacsim.core.prims import Articulation, RigidPrim, SingleGeometryPrim, SingleRigidPrim -from isaacsim.core.utils.viewports import set_camera_view -from pxr import Gf, UsdGeom - -# check nucleus connection -if nucleus_utils.get_assets_root_path() is None: - msg = ( - "Unable to perform Nucleus login on Omniverse. Assets root path is not set.\n" - "\tPlease check: https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/overview.html#omniverse-nucleus" - ) - raise RuntimeError(msg) - -ISAAC_NUCLEUS_DIR = f"{nucleus_utils.get_assets_root_path()}/Isaac" -"""Path to the `Isaac` directory on the NVIDIA Nucleus Server.""" - - -def main(): - """Runs a camera sensor from isaaclab.""" - - # Load kit helper - world = World(physics_dt=0.005, rendering_dt=0.005, backend="torch", device="cpu") - # Set main camera - set_camera_view([2.5, 2.5, 2.5], [0.0, 0.0, 0.0]) - - # Enable flatcache which avoids passing data over to USD structure - # this speeds up the read-write operation of GPU buffers - if world.get_physics_context().use_gpu_pipeline: - world.get_physics_context().enable_flatcache(True) - # Enable hydra scene-graph instancing - # this is needed to visualize the scene when flatcache is enabled - world._settings.set_bool("/persistent/omnihydra/useSceneGraphInstancing", True) - - # Populate scene - # Ground - world.scene.add_default_ground_plane() - # Lights-1 - prim_utils.create_prim("/World/Light/GreySphere", "SphereLight", translation=(4.5, 3.5, 10.0)) - # Lights-2 - prim_utils.create_prim("/World/Light/WhiteSphere", "SphereLight", translation=(-4.5, 3.5, 10.0)) - # Xform to hold objects - if args_cli.scenario == "cube": - prim_utils.create_prim("/World/Objects", "Xform") - # Random objects - for i in range(8): - # sample random position - position = np.random.rand(3) - np.asarray([0.05, 0.05, -1.0]) - position *= np.asarray([1.5, 1.5, 0.5]) - # create prim - prim_type = random.choice(["Cube", "Sphere", "Cylinder"]) - _ = prim_utils.create_prim( - f"/World/Objects/Obj_{i:02d}", - prim_type, - translation=position, - scale=(0.25, 0.25, 0.25), - semantic_label=prim_type, - ) - # add rigid properties - SingleGeometryPrim(f"/World/Objects/Obj_{i:02d}", collision=True) - rigid_obj = SingleRigidPrim(f"/World/Objects/Obj_{i:02d}", mass=5.0) - # cast to geom prim - geom_prim = getattr(UsdGeom, prim_type)(rigid_obj.prim) - # set random color - color = Gf.Vec3f(random.random(), random.random(), random.random()) - geom_prim.CreateDisplayColorAttr() - geom_prim.GetDisplayColorAttr().Set([color]) - # Setup camera sensor on the world - cam_prim_path = "/World/CameraSensor" - else: - # Robot - prim_utils.create_prim( - "/World/Robot", - usd_path=f"{ISAAC_NUCLEUS_DIR}/Robots/ANYbotics/anymal_c/anymal_c.usd", - translation=(0.0, 0.0, 0.6), - ) - # Setup camera sensor on the robot - cam_prim_path = "/World/CameraSensor" - - # Create camera - cam_prim = prim_utils.create_prim( - cam_prim_path, - prim_type="Camera", - translation=(5.0, 5.0, 5.0), - orientation=(0.17591988, 0.42470818, 0.82047324, 0.33985113), - ) - _ = UsdGeom.Camera(cam_prim) - # Get render product - render_prod_path = rep.create.render_product(cam_prim_path, resolution=(640, 480)) - # create annotator node - rep_registry = {} - for name in ["rgb", "distance_to_image_plane"]: - # create annotator - rep_annotator = rep.AnnotatorRegistry.get_annotator(name, device="cpu") - rep_annotator.attach(render_prod_path) - # add to registry - rep_registry[name] = rep_annotator - - # Create replicator writer - output_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "output", "camera", args_cli.scenario) - os.makedirs(output_dir, exist_ok=True) - - # Create a view of the stuff we want to see - if args_cli.scenario == "cube": - view: RigidPrim = world.scene.add(RigidPrim("/World/Objects/.*", name="my_object")) - else: - view: Articulation = world.scene.add(Articulation("/World/Robot", name="my_object")) - # Play simulator - world.reset() - # Get initial state - if args_cli.scenario == "cube": - initial_pos, initial_quat = view.get_world_poses() - initial_joint_pos = None - initial_joint_vel = None - else: - initial_pos, initial_quat = view.get_world_poses() - initial_joint_pos = view.get_joint_positions() - initial_joint_vel = view.get_joint_velocities() - - # Counter - count = 0 - prev_im = None - # make episode directory - episode_count = 0 - episode_dir = os.path.join(output_dir, f"episode_{episode_count:06d}") - os.makedirs(episode_dir, exist_ok=True) - # Simulate physics - while simulation_app.is_running(): - # If simulation is stopped, then exit. - if world.is_stopped(): - break - # If simulation is paused, then skip. - if not world.is_playing(): - world.step(render=False) - continue - # Reset on intervals - if count % 25 == 0: - # reset all the state - view.set_world_poses(initial_pos, initial_quat) - if initial_joint_pos is not None: - view.set_joint_positions(initial_joint_pos) - if initial_joint_vel is not None: - view.set_joint_velocities(initial_joint_vel) - # make a new episode directory - episode_dir = os.path.join(output_dir, f"episode_{episode_count:06d}") - os.makedirs(episode_dir, exist_ok=True) - # reset counters - count = 0 - episode_count += 1 - # Step simulation - for _ in range(15): - world.step(render=False) - world.render() - # Update camera data - rgb_data = rep_registry["rgb"].get_data() - depth_data = rep_registry["distance_to_image_plane"].get_data() - - # Show current image number - print(f"[Epi {episode_count:03d}] Current image number: {count:06d}") - # Save data - curr_im = Image.fromarray(rgb_data) - curr_im.save(os.path.join(episode_dir, f"{count:06d}_rgb.png")) - # Save diff - if prev_im is not None: - diff_im = ImageChops.difference(curr_im, prev_im) - # convert to grayscale and threshold - diff_im = diff_im.convert("L") - threshold = 30 - diff_im = diff_im.point(lambda p: p > threshold and 255) - # Save all of them together - dst_im = Image.new("RGB", (curr_im.width + prev_im.width + diff_im.width, diff_im.height)) - dst_im.paste(prev_im, (0, 0)) - dst_im.paste(curr_im, (prev_im.width, 0)) - dst_im.paste(diff_im, (2 * prev_im.width, 0)) - dst_im.save(os.path.join(episode_dir, f"{count:06d}_diff.png")) - - # Save to previous - prev_im = curr_im.copy() - # Update counter - count += 1 - - # Print camera info - print("Received shape of rgb image: ", rgb_data.shape) - print("Received shape of depth image: ", depth_data.shape) - print("-------------------------------") - - -if __name__ == "__main__": - # run the main function - main() - # close sim app - simulation_app.close() diff --git a/source/isaaclab/test/deps/isaacsim/check_floating_base_made_fixed.py b/source/isaaclab/test/deps/isaacsim/check_floating_base_made_fixed.py index 8798fba361e8..f03012610e97 100644 --- a/source/isaaclab/test/deps/isaacsim/check_floating_base_made_fixed.py +++ b/source/isaaclab/test/deps/isaacsim/check_floating_base_made_fixed.py @@ -3,205 +3,17 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""This script demonstrates how to make a floating robot fixed in Isaac Sim.""" - -"""Launch Isaac Sim Simulator first.""" - - -import argparse -import contextlib - -with contextlib.suppress(ModuleNotFoundError): - import isaacsim # noqa: F401 - -from isaacsim import SimulationApp - -# add argparse arguments -parser = argparse.ArgumentParser( - description="This script shows the issue in Isaac Sim with making a floating robot fixed." -) -parser.add_argument("--headless", action="store_true", help="Run in headless mode.") -parser.add_argument("--fix-base", action="store_true", help="Whether to fix the base of the robot.") -# parse the arguments -args_cli = parser.parse_args() - -# launch omniverse app -simulation_app = SimulationApp({"headless": args_cli.headless}) - -"""Rest everything follows.""" - -import logging - -import torch - -import omni.kit.commands -import omni.physx -from isaacsim.core.api.world import World -from isaacsim.core.prims import Articulation -from isaacsim.core.utils.viewports import set_camera_view -from pxr import UsdPhysics - -import isaaclab.sim.utils.nucleus as nucleus_utils -import isaaclab.sim.utils.prims as prim_utils -import isaaclab.sim.utils.stage as stage_utils - -# import logger -logger = logging.getLogger(__name__) - -# check nucleus connection -if nucleus_utils.get_assets_root_path() is None: - msg = ( - "Unable to perform Nucleus login on Omniverse. Assets root path is not set.\n" - "\tPlease check: https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/overview.html#omniverse-nucleus" - ) - logger.error(msg) - raise RuntimeError(msg) - - -ISAAC_NUCLEUS_DIR = f"{nucleus_utils.get_assets_root_path()}/Isaac" -"""Path to the `Isaac` directory on the NVIDIA Nucleus Server.""" - -ISAACLAB_NUCLEUS_DIR = f"{ISAAC_NUCLEUS_DIR}/IsaacLab" -"""Path to the `Isaac/IsaacLab` directory on the NVIDIA Nucleus Server.""" +"""Historic floating-base / fixed-base reproducer (retired). +This script previously depended on Isaac Sim core extensions that Isaac Sim now carries under +``source/deprecated`` in the Isaac Sim repository. It has been retired from Isaac Lab to avoid +depending on those extension IDs and import paths. +Use :class:`~isaaclab.sim.SimulationContext` and ``isaacsim.core.experimental.prims.Articulation`` +for articulation-level debugging. """ -Main -""" - - -def main(): - """Spawns the ANYmal robot and makes it fixed.""" - # Load kit helper - world = World(physics_dt=0.005, rendering_dt=0.005, backend="torch", device="cpu") - # Set main camera - set_camera_view([2.5, 2.5, 2.5], [0.0, 0.0, 0.0]) - - # Enable hydra scene-graph instancing - # this is needed to visualize the scene when flatcache is enabled - world._settings.set_bool("/persistent/omnihydra/useSceneGraphInstancing", True) - - # Spawn things into stage - # Ground-plane - world.scene.add_default_ground_plane(prim_path="/World/defaultGroundPlane", z_position=0.0) - # Lights-1 - prim_utils.create_prim("/World/Light/GreySphere", "SphereLight", translation=(4.5, 3.5, 10.0)) - # Lights-2 - prim_utils.create_prim("/World/Light/WhiteSphere", "SphereLight", translation=(-4.5, 3.5, 10.0)) - # -- Robot - # resolve asset - usd_path = f"{ISAACLAB_NUCLEUS_DIR}/Robots/ANYbotics/ANYmal-C/anymal_c.usd" - root_prim_path = "/World/Robot/base" - # add asset - print("Loading robot from: ", usd_path) - prim_utils.create_prim( - "/World/Robot", - usd_path=usd_path, - translation=(0.0, 0.0, 0.6), - ) - # create fixed joint - if args_cli.fix_base: - # get all necessary information - stage = stage_utils.get_current_stage() - root_prim = stage.GetPrimAtPath(root_prim_path) - parent_prim = root_prim.GetParent() - - # here we assume that the root prim is a rigid body - # there is no clear way to deal with situation where the root prim is not a rigid body but has articulation api - # in that case, it is unclear how to get the link to the first link in the tree - if not root_prim.HasAPI(UsdPhysics.RigidBodyAPI): - raise RuntimeError("The root prim does not have the RigidBodyAPI applied.") - - # create fixed joint - omni.kit.commands.execute( - "CreateJointCommand", - stage=stage, - joint_type="Fixed", - from_prim=None, - to_prim=root_prim, - ) - - # move the root to the parent if this is a rigid body - # having a fixed joint on a rigid body makes physx treat it as a part of the maximal coordinate tree - # if we put to joint on the parent, physx parser treats it as a fixed base articulation - # get parent prim - parent_prim = root_prim.GetParent() - # apply api to parent - UsdPhysics.ArticulationRootAPI.Apply(parent_prim) - parent_prim.AddAppliedSchema("PhysxArticulationAPI") - - # copy the attributes - # -- usd attributes - root_usd_articulation_api = UsdPhysics.ArticulationRootAPI(root_prim) - for attr_name in root_usd_articulation_api.GetSchemaAttributeNames(): - attr = root_prim.GetAttribute(attr_name) - parent_prim.GetAttribute(attr_name).Set(attr.Get()) - # -- physx attributes (by name: physxArticulation:*) - for attr in root_prim.GetAttributes(): - name = attr.GetName() - if name.startswith("physxArticulation:"): - parent_prim.GetAttribute(name).Set(attr.Get()) - # remove api from root - root_prim.RemoveAPI(UsdPhysics.ArticulationRootAPI) - root_prim.RemoveAppliedSchema("PhysxArticulationAPI") - - # rename root path to parent path - root_prim_path = parent_prim.GetPath().pathString - - # Setup robot - robot_view = Articulation(root_prim_path, name="ANYMAL") - world.scene.add(robot_view) - # Play the simulator - world.reset() - - # Now we are ready! - print("[INFO]: Setup complete...") - - # dummy actions - # actions = torch.zeros(robot.count, robot.num_actions, device=robot.device) - - init_root_pos_w, init_root_quat_w = robot_view.get_world_poses() - # Define simulation stepping - sim_dt = world.get_physics_dt() - # episode counter - sim_time = 0.0 - count = 0 - # Simulate physics - while simulation_app.is_running(): - # If simulation is stopped, then exit. - if world.is_stopped(): - break - # If simulation is paused, then skip. - if not world.is_playing(): - world.step(render=False) - continue - # do reset - if count % 20 == 0: - # reset - sim_time = 0.0 - count = 0 - # reset root state - root_pos_w = init_root_pos_w.clone() - root_pos_w[:, :2] += torch.rand_like(root_pos_w[:, :2]) * 0.5 - robot_view.set_world_poses(root_pos_w, init_root_quat_w) - # print if it is fixed base - print("Fixed base: ", robot_view._physics_view.shared_metatype.fixed_base) - print("Moving base to: ", root_pos_w[0].cpu().numpy()) - print("-" * 50) - - # apply random joint actions - actions = torch.rand_like(robot_view.get_joint_positions()) * 0.001 - robot_view.set_joint_efforts(actions) - # perform step - world.step() - # update sim-time - sim_time += sim_dt - count += 1 - - -if __name__ == "__main__": - # run the main function - main() - # close sim app - simulation_app.close() +raise RuntimeError( + "This standalone reproducer was retired; it depended on deprecated Isaac Sim core extensions. " + "Use Isaac Lab :mod:`isaaclab.sim` and ``isaacsim.core.experimental.*`` instead." +) diff --git a/source/isaaclab/test/deps/isaacsim/check_legged_robot_clone.py b/source/isaaclab/test/deps/isaacsim/check_legged_robot_clone.py index 3e56a441f001..54b13a2f0c1c 100644 --- a/source/isaaclab/test/deps/isaacsim/check_legged_robot_clone.py +++ b/source/isaaclab/test/deps/isaacsim/check_legged_robot_clone.py @@ -3,184 +3,17 @@ # # SPDX-License-Identifier: BSD-3-Clause -""" -This script demonstrates how to use the cloner API from Isaac Sim. - -Reference: https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/tutorial_gym_cloner.html -""" - -"""Launch Isaac Sim Simulator first.""" - - -import argparse -import contextlib - -with contextlib.suppress(ModuleNotFoundError): - import isaacsim # noqa: F401 - -from isaacsim import SimulationApp - -# add argparse arguments -parser = argparse.ArgumentParser( - description="This script shows the issue in Isaac Sim with GPU simulation of floating robots." -) -parser.add_argument("--num_robots", type=int, default=128, help="Number of robots to spawn.") -parser.add_argument( - "--asset", - type=str, - default="isaaclab", - help="The asset source location for the robot. Can be: isaaclab, oige, custom asset path.", -) -parser.add_argument("--headless", action="store_true", help="Run in headless mode.") -# parse the arguments -args_cli = parser.parse_args() - -# launch omniverse app -simulation_app = SimulationApp({"headless": args_cli.headless}) - -"""Rest everything follows.""" - -import logging -import os - -import torch - -from isaacsim.core.api.world import World -from isaacsim.core.cloner import GridCloner -from isaacsim.core.prims import Articulation -from isaacsim.core.utils.viewports import set_camera_view - -import isaaclab.sim.utils.nucleus as nucleus_utils -import isaaclab.sim.utils.prims as prim_utils - -# import logger -logger = logging.getLogger(__name__) +"""Historic legged-robot cloning reproducer (retired). -# check nucleus connection -if nucleus_utils.get_assets_root_path() is None: - msg = ( - "Unable to perform Nucleus login on Omniverse. Assets root path is not set.\n" - "\tPlease check: https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/overview.html#omniverse-nucleus" - ) - logger.error(msg) - raise RuntimeError(msg) +This script previously depended on Isaac Sim core extensions that Isaac Sim now carries under +``source/deprecated`` in the Isaac Sim repository. It has been retired from Isaac Lab to avoid +depending on those extension IDs and import paths. - -ISAAC_NUCLEUS_DIR = f"{nucleus_utils.get_assets_root_path()}/Isaac" -"""Path to the `Isaac` directory on the NVIDIA Nucleus Server.""" - -ISAACLAB_NUCLEUS_DIR = f"{ISAAC_NUCLEUS_DIR}/IsaacLab" -"""Path to the `Isaac/IsaacLab` directory on the NVIDIA Nucleus Server.""" - - -""" -Main +Use :class:`~isaaclab.sim.SimulationContext`, :class:`isaacsim.core.cloner.GridCloner`, and +``isaacsim.core.experimental.prims.Articulation`` for cloning workflows. """ - -def main(): - """Spawns the ANYmal robot and clones it using Isaac Sim Cloner API.""" - - # Load kit helper - world = World(physics_dt=0.005, rendering_dt=0.005, backend="torch", device="cuda:0") - # Set main camera - set_camera_view([2.5, 2.5, 2.5], [0.0, 0.0, 0.0]) - - # Enable hydra scene-graph instancing - # this is needed to visualize the scene when flatcache is enabled - world._settings.set_bool("/persistent/omnihydra/useSceneGraphInstancing", True) - - # Create interface to clone the scene - cloner = GridCloner(spacing=2.0, stage=world.stage) - cloner.define_base_env("/World/envs") - # Everything under the namespace "/World/envs/env_0" will be cloned - prim_utils.define_prim("/World/envs/env_0") - - # Spawn things into stage - # Ground-plane - world.scene.add_default_ground_plane(prim_path="/World/defaultGroundPlane", z_position=0.0) - # Lights-1 - prim_utils.create_prim("/World/Light/GreySphere", "SphereLight", translation=(4.5, 3.5, 10.0)) - # Lights-2 - prim_utils.create_prim("/World/Light/WhiteSphere", "SphereLight", translation=(-4.5, 3.5, 10.0)) - # -- Robot - # resolve asset - if args_cli.asset == "isaaclab": - usd_path = f"{ISAACLAB_NUCLEUS_DIR}/Robots/ANYbotics/ANYmal-C/anymal_c.usd" - root_prim_path = "/World/envs/env_.*/Robot/base" - elif args_cli.asset == "oige": - usd_path = f"{ISAAC_NUCLEUS_DIR}/Robots/ANYbotics/anymal_c/anymal_c.usd" - root_prim_path = "/World/envs/env_.*/Robot" - elif os.path.exists(args_cli.asset): - usd_path = args_cli.asset - else: - raise ValueError(f"Invalid asset: {args_cli.asset}. Must be one of: isaaclab, oige.") - # add asset - print("Loading robot from: ", usd_path) - prim_utils.create_prim( - "/World/envs/env_0/Robot", - usd_path=usd_path, - translation=(0.0, 0.0, 0.6), - ) - - # Clone the scene - num_envs = args_cli.num_robots - cloner.define_base_env("/World/envs") - envs_prim_paths = cloner.generate_paths("/World/envs/env", num_paths=num_envs) - envs_positions = cloner.clone( - source_prim_path="/World/envs/env_0", prim_paths=envs_prim_paths, replicate_physics=True - ) - # convert environment positions to torch tensor - envs_positions = torch.tensor(envs_positions, dtype=torch.float, device=world.device) - # filter collisions within each environment instance - physics_scene_path = world.get_physics_context().prim_path - cloner.filter_collisions( - physics_scene_path, "/World/collisions", envs_prim_paths, global_paths=["/World/defaultGroundPlane"] - ) - - # Resolve robot prim paths - if args_cli.asset == "isaaclab": - root_prim_path = "/World/envs/env_.*/Robot/base" - elif args_cli.asset == "oige": - root_prim_path = "/World/envs/env_.*/Robot" - elif os.path.exists(args_cli.asset): - usd_path = args_cli.asset - root_prim_path = "/World/envs/env_.*/Robot" - else: - raise ValueError(f"Invalid asset: {args_cli.asset}. Must be one of: isaaclab, oige.") - # Setup robot - robot_view = Articulation(root_prim_path, name="ANYMAL") - world.scene.add(robot_view) - # Play the simulator - world.reset() - - # Now we are ready! - print("[INFO]: Setup complete...") - - # dummy actions - # actions = torch.zeros(robot.count, robot.num_actions, device=robot.device) - - # Define simulation stepping - sim_dt = world.get_physics_dt() - # episode counter - sim_time = 0.0 - # Simulate physics - while simulation_app.is_running(): - # If simulation is stopped, then exit. - if world.is_stopped(): - break - # If simulation is paused, then skip. - if not world.is_playing(): - world.step(render=False) - continue - # perform step - world.step() - # update sim-time - sim_time += sim_dt - - -if __name__ == "__main__": - # run the main function - main() - # close sim app - simulation_app.close() +raise RuntimeError( + "This standalone reproducer was retired; it depended on deprecated Isaac Sim core extensions. " + "Use Isaac Lab :mod:`isaaclab.sim` and ``isaacsim.core.experimental.*`` instead." +) diff --git a/source/isaaclab/test/deps/isaacsim/check_ref_count.py b/source/isaaclab/test/deps/isaacsim/check_ref_count.py index c0380183a28c..02465f722f3d 100644 --- a/source/isaaclab/test/deps/isaacsim/check_ref_count.py +++ b/source/isaaclab/test/deps/isaacsim/check_ref_count.py @@ -20,7 +20,6 @@ """Launch Isaac Sim Simulator first.""" - import contextlib with contextlib.suppress(ModuleNotFoundError): @@ -39,11 +38,12 @@ import torch # noqa: F401 -from isaacsim.core.api.simulation_context import SimulationContext -from isaacsim.core.prims import Articulation +import carb +from isaacsim.core.experimental.prims import Articulation import isaaclab.sim.utils.nucleus as nucleus_utils import isaaclab.sim.utils.prims as prim_utils +from isaaclab.sim import SimulationCfg, SimulationContext # import logger logger = logging.getLogger(__name__) @@ -85,17 +85,13 @@ def __init__(self): # Resolve robot prim paths root_prim_path = "/World/Robot/base" # Setup robot - self.view = Articulation(root_prim_path, name="ANYMAL") + self.view = Articulation(root_prim_path) def __del__(self): """Delete the Anymal articulation class.""" print("Deleting the Anymal view.") self.view = None - def initialize(self): - """Initialize the Anymal view.""" - self.view.initialize() - """ Main @@ -105,12 +101,10 @@ def initialize(self): def main(): """Spawns the ANYmal robot and clones it using Isaac Sim Cloner API.""" - # Load kit helper - sim = SimulationContext(physics_dt=0.005, rendering_dt=0.005, backend="torch", device="cuda:0") + carb.settings.get_settings().set_bool("/persistent/omnihydra/useSceneGraphInstancing", True) - # Enable hydra scene-graph instancing - # this is needed to visualize the scene when flatcache is enabled - sim._settings.set_bool("/persistent/omnihydra/useSceneGraphInstancing", True) + # Load kit helper + sim = SimulationContext(cfg=SimulationCfg(dt=0.005, device="cuda:0")) # Create a dummy tensor for testing # Uncommenting the following line will yield a reference count of 1 for the robot (as desired) @@ -130,8 +124,6 @@ def main(): print("Referrers of the robot view: ", gc.get_referrers(robot)) print("---" * 10) - robot.initialize() - print("Reference count of the robot view: ", ctypes.c_long.from_address(id(robot)).value) print("Referrers of the robot view: ", gc.get_referrers(robot)) print("---" * 10) @@ -144,7 +136,7 @@ def main(): print("---" * 10) # Clean up - sim.clear_instance() + SimulationContext.clear_instance() print("Reference count of the robot view: ", ctypes.c_long.from_address(id(robot)).value) print("Referrers of the robot view: ", gc.get_referrers(robot)) diff --git a/source/isaaclab/test/deps/isaacsim/check_rep_texture_randomizer.py b/source/isaaclab/test/deps/isaacsim/check_rep_texture_randomizer.py index 99d7d452ef79..dd3875994e38 100644 --- a/source/isaaclab/test/deps/isaacsim/check_rep_texture_randomizer.py +++ b/source/isaaclab/test/deps/isaacsim/check_rep_texture_randomizer.py @@ -3,163 +3,17 @@ # # SPDX-License-Identifier: BSD-3-Clause -""" -This script shows how to use replicator to randomly change the textures of a USD scene. - -Note: - Currently this script fails since cloner does not support changing textures of cloned - USD prims. This is because the prims are cloned using `Sdf.ChangeBlock` which does not - allow individual texture changes. - -Usage: - -.. code-block:: bash +"""Historic replicator texture randomization reproducer (retired). - ./isaaclab.sh -p source/isaaclab/test/deps/isaacsim/check_rep_texture_randomizer.py +This script previously depended on Isaac Sim core extensions that Isaac Sim now carries under +``source/deprecated`` in the Isaac Sim repository. It has been retired from Isaac Lab to avoid +depending on those extension IDs and import paths. +Use :class:`~isaaclab.sim.SimulationContext`, :class:`isaacsim.core.cloner.GridCloner`, and +``isaacsim.core.experimental.*`` when experimenting with Omniverse Replicator workflows. """ -"""Launch Isaac Sim Simulator first.""" - -import argparse - -# isaaclab -from isaaclab.app import AppLauncher - -# add argparse arguments -parser = argparse.ArgumentParser( - description="This script shows how to use replicator to randomly change the textures of a USD scene." +raise RuntimeError( + "This standalone reproducer was retired; it depended on deprecated Isaac Sim core extensions. " + "Use Isaac Lab :mod:`isaaclab.sim` and ``isaacsim.core.experimental.*`` instead." ) -# 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 numpy as np -import torch - -import omni.replicator.core as rep -from isaacsim.core.api.objects import DynamicSphere -from isaacsim.core.api.simulation_context import SimulationContext -from isaacsim.core.cloner import GridCloner -from isaacsim.core.prims import RigidPrim -from isaacsim.core.utils.viewports import set_camera_view - -import isaaclab.sim.utils.prims as prim_utils - - -def main(): - """Spawn a bunch of balls and randomly change their textures.""" - - # Load kit helper - sim_params = { - "use_gpu": True, - "use_gpu_pipeline": True, - "use_flatcache": True, # deprecated from Isaac Sim 2023.1 onwards - "use_fabric": True, # used from Isaac Sim 2023.1 onwards - "enable_scene_query_support": True, - } - sim = SimulationContext( - physics_dt=1.0 / 60.0, rendering_dt=1.0 / 60.0, sim_params=sim_params, backend="torch", device="cuda:0" - ) - # Set main camera - set_camera_view([0.0, 30.0, 25.0], [0.0, 0.0, -2.5]) - - # Parameters - num_balls = 128 - - # Create interface to clone the scene - cloner = GridCloner(spacing=2.0, stage=sim.stage) - cloner.define_base_env("/World/envs") - # Everything under the namespace "/World/envs/env_0" will be cloned - prim_utils.define_prim("/World/envs/env_0") - - # Define the scene - # -- Ball - DynamicSphere(prim_path="/World/envs/env_0/ball", translation=np.array([0.0, 0.0, 5.0]), mass=0.5, radius=0.25) - - # Clone the scene - cloner.define_base_env("/World/envs") - envs_prim_paths = cloner.generate_paths("/World/envs/env", num_paths=num_balls) - env_positions = cloner.clone( - source_prim_path="/World/envs/env_0", prim_paths=envs_prim_paths, replicate_physics=True, copy_from_source=True - ) - physics_scene_path = sim.get_physics_context().prim_path - cloner.filter_collisions( - physics_scene_path, "/World/collisions", prim_paths=envs_prim_paths, global_paths=["/World/ground"] - ) - - # Use replicator to randomize color on the spheres - with rep.new_layer(): - # Define a function to get all the shapes - def get_shapes(): - shapes = rep.get.prims(path_pattern="/World/envs/env_.*/ball") - with shapes: - rep.randomizer.color(colors=rep.distribution.uniform((0, 0, 0), (1, 1, 1))) - return shapes.node - - # Register the function - rep.randomizer.register(get_shapes) - # Specify the frequency of randomization - with rep.trigger.on_frame(): - rep.randomizer.get_shapes() - - # Set ball positions over terrain origins - # Create a view over all the balls - ball_view = RigidPrim("/World/envs/env_.*/ball", reset_xform_properties=False) - # cache initial state of the balls - ball_initial_positions = torch.tensor(env_positions, dtype=torch.float, device=sim.device) - ball_initial_positions[:, 2] += 5.0 - # set initial poses - # note: setting here writes to USD :) - ball_view.set_world_poses(positions=ball_initial_positions) - - # Play simulator - sim.reset() - # Step replicator to randomize colors - rep.orchestrator.step(pause_timeline=False) - # Stop replicator to prevent further randomization - rep.orchestrator.stop() - # Pause simulator at the beginning for inspection - sim.pause() - - # Initialize the ball views for physics simulation - ball_view.initialize() - ball_initial_velocities = ball_view.get_velocities() - - # Create a counter for resetting the scene - step_count = 0 - # Simulate physics - while simulation_app.is_running(): - # If simulation is stopped, then exit. - if sim.is_stopped(): - break - # If simulation is paused, then skip. - if not sim.is_playing(): - sim.step() - continue - # Reset the scene - if step_count % 500 == 0: - # reset the balls - ball_view.set_world_poses(positions=ball_initial_positions) - ball_view.set_velocities(ball_initial_velocities) - # reset the counter - step_count = 0 - # Step simulation - sim.step() - # Update counter - step_count += 1 - - -if __name__ == "__main__": - # run the main function - main() - # close sim app - simulation_app.close() diff --git a/source/isaaclab/test/envs/check_manager_based_env_floating_cube.py b/source/isaaclab/test/envs/check_manager_based_env_floating_cube.py index 06123ad07a63..4762cc855cc5 100644 --- a/source/isaaclab/test/envs/check_manager_based_env_floating_cube.py +++ b/source/isaaclab/test/envs/check_manager_based_env_floating_cube.py @@ -31,7 +31,6 @@ """Rest everything follows.""" import torch -import warp as wp import isaaclab.envs.mdp as mdp import isaaclab.sim as sim_utils @@ -129,8 +128,8 @@ def process_actions(self, actions: torch.Tensor): def apply_actions(self): # implement a PD controller to track the target position - pos_error = self._processed_actions - (wp.to_torch(self._asset.data.root_pos_w) - self._env.scene.env_origins) - vel_error = -wp.to_torch(self._asset.data.root_lin_vel_w) + pos_error = self._processed_actions - (self._asset.data.root_pos_w.torch - self._env.scene.env_origins) + vel_error = -self._asset.data.root_lin_vel_w.torch # set velocity targets self._vel_command[:, :3] = self.p_gain * pos_error + self.d_gain * vel_error self._asset.write_root_velocity_to_sim(self._vel_command) @@ -152,7 +151,7 @@ def base_position(env: ManagerBasedEnv, asset_cfg: SceneEntityCfg) -> torch.Tens """Root linear velocity in the asset's root frame.""" # extract the used quantities (to enable type-hinting) asset: RigidObject = env.scene[asset_cfg.name] - return wp.to_torch(asset.data.root_pos_w) - env.scene.env_origins + return asset.data.root_pos_w.torch - env.scene.env_origins ## diff --git a/source/isaaclab/test/envs/test_env_rendering_logic.py b/source/isaaclab/test/envs/test_env_rendering_logic.py index 0b04143f9537..59299e2e93ee 100644 --- a/source/isaaclab/test/envs/test_env_rendering_logic.py +++ b/source/isaaclab/test/envs/test_env_rendering_logic.py @@ -31,6 +31,8 @@ from isaaclab.sim import SimulationCfg, SimulationContext from isaaclab.utils import configclass +pytestmark = pytest.mark.isaacsim_ci + @configclass class EmptyManagerCfg: @@ -79,20 +81,29 @@ class EnvCfg(ManagerBasedRLEnvCfg): return ManagerBasedRLEnv(cfg=EnvCfg()) -def create_direct_rl_env(render_interval: int): - """Create a direct RL environment.""" +def create_direct_rl_env(render_interval: int, episode_length_steps: int | None = None): + """Create a direct RL environment. + + Args: + render_interval: Render interval in physics steps. + episode_length_steps: If provided, the episode terminates (via time-out) after this + many *env* steps. Useful for testing post-reset re-render paths. + """ + # Compute episode_length_s from step count when requested + _dt = 0.005 + _decimation = 4 + _step_dt = _dt * _decimation + _episode_length_s = (episode_length_steps * _step_dt) if episode_length_steps is not None else 100.0 @configclass class EnvCfg(DirectRLEnvCfg): """Configuration for the test environment.""" - decimation: int = 4 + decimation: int = _decimation action_space: int = 0 observation_space: int = 0 - episode_length_s: float = 100.0 - sim: SimulationCfg = SimulationCfg( - dt=0.005, render_interval=render_interval, visualizer_cfgs=KitVisualizerCfg() - ) + episode_length_s: float = _episode_length_s + sim: SimulationCfg = SimulationCfg(dt=_dt, render_interval=render_interval, visualizer_cfgs=KitVisualizerCfg()) scene: InteractiveSceneCfg = InteractiveSceneCfg(num_envs=1, env_spacing=1.0) class Env(DirectRLEnv): @@ -111,7 +122,8 @@ def _get_rewards(self): return {} def _get_dones(self): - return torch.zeros(1, dtype=torch.bool), torch.zeros(1, dtype=torch.bool) + time_out = self.episode_length_buf >= self.max_episode_length + return torch.zeros_like(time_out), time_out return Env(cfg=EnvCfg()) @@ -239,3 +251,235 @@ def wrapped_step(dt): else: # If env creation failed, still clear the singleton SimulationContext.clear_instance() + + +@pytest.mark.parametrize("env_type", ["manager_based_env", "manager_based_rl_env", "direct_rl_env"]) +def test_env_render_false_skips_rendering(env_type, physics_callback, render_callback): + """Test that setting render_enabled=False skips all rendering while physics continues.""" + physics_cb, get_physics_stats = physics_callback + render_cb, get_render_stats = render_callback + + env = None + physics_handle = None + original_step = None + viz = None + + try: + # create a new stage + sim_utils.create_new_stage() + + # create environment with render_interval=1 so rendering would happen every physics step + if env_type == "manager_based_env": + env = create_manager_based_env(render_interval=1) + elif env_type == "manager_based_rl_env": + env = create_manager_based_rl_env(render_interval=1) + else: + env = create_direct_rl_env(render_interval=1) + + # enable the flag to render the environment + env.sim.set_setting("/isaaclab/render/rtx_sensors", True) + + # disable the app from shutting down when the environment is closed + env.sim._app_control_on_stop_handle = None # type: ignore + + # Reset to initialize visualizers + env.reset() + + # Ensure the default Kit visualizer is active for rendering callbacks. + assert isinstance(env.sim.visualizers[0], KitVisualizer) + + # add physics callback + physics_handle = env.sim.physics_manager.register_callback( + physics_cb, IsaacEvents.POST_PHYSICS_STEP, name="physics_step" + ) + + # Wrap visualizer step to track render calls + viz = env.sim.visualizers[0] + original_step = viz.step + render_dt = env.cfg.sim.dt * env.cfg.sim.render_interval + + def wrapped_step(dt): + original_step(dt) + render_cb(render_dt) + + viz.step = wrapped_step + + # create a zero action tensor for stepping the environment + actions = torch.zeros((env.num_envs, 0), device=env.device) + + # Step with render_enabled=False for several steps + env.render_enabled = False + for i in range(10): + env.step(action=actions) + + # Physics should still advance normally + _, num_physics_steps = get_physics_stats() + assert num_physics_steps == (i + 1) * env.cfg.decimation, "Physics steps mismatch with render_enabled=False" + + # No rendering should have occurred + _, num_render_steps = get_render_stats() + assert num_render_steps == 0, f"Expected 0 render steps with render_enabled=False, got {num_render_steps}" + + finally: + if viz is not None and original_step is not None: + viz.step = original_step + if physics_handle is not None: + physics_handle.deregister() + if env is not None: + env.close() + else: + SimulationContext.clear_instance() + + +@pytest.mark.parametrize("env_type", ["manager_based_env", "manager_based_rl_env", "direct_rl_env"]) +def test_env_render_flag_mixed_steps(env_type, physics_callback, render_callback): + """Test that render_enabled can be toggled between steps and rendering counts are correct.""" + physics_cb, get_physics_stats = physics_callback + render_cb, get_render_stats = render_callback + + env = None + physics_handle = None + original_step = None + viz = None + + try: + # create a new stage + sim_utils.create_new_stage() + + # create environment with render_interval=1 so every decimation step renders + if env_type == "manager_based_env": + env = create_manager_based_env(render_interval=1) + elif env_type == "manager_based_rl_env": + env = create_manager_based_rl_env(render_interval=1) + else: + env = create_direct_rl_env(render_interval=1) + + # enable the flag to render the environment + env.sim.set_setting("/isaaclab/render/rtx_sensors", True) + + # disable the app from shutting down when the environment is closed + env.sim._app_control_on_stop_handle = None # type: ignore + + # Reset to initialize visualizers + env.reset() + + # Ensure the default Kit visualizer is active for rendering callbacks. + assert isinstance(env.sim.visualizers[0], KitVisualizer) + + # add physics callback + physics_handle = env.sim.physics_manager.register_callback( + physics_cb, IsaacEvents.POST_PHYSICS_STEP, name="physics_step" + ) + + # Wrap visualizer step to track render calls + viz = env.sim.visualizers[0] + original_step = viz.step + render_dt = env.cfg.sim.dt * env.cfg.sim.render_interval + + def wrapped_step(dt): + original_step(dt) + render_cb(render_dt) + + viz.step = wrapped_step + + # create a zero action tensor for stepping the environment + actions = torch.zeros((env.num_envs, 0), device=env.device) + + expected_render_steps = 0 + + # Step 5 times with render_enabled=True, then 5 with render_enabled=False + for i in range(10): + should_render = i < 5 + env.render_enabled = should_render + env.step(action=actions) + + # Physics always advances + _, num_physics_steps = get_physics_stats() + assert num_physics_steps == (i + 1) * env.cfg.decimation, "Physics steps mismatch in mixed test" + + # Rendering only happens in the first 5 steps + if should_render: + expected_render_steps += env.cfg.decimation # render_interval=1, so renders every decimation step + + _, num_render_steps = get_render_stats() + assert num_render_steps == expected_render_steps, ( + f"Render steps mismatch at step {i}: expected {expected_render_steps}, got {num_render_steps}" + ) + + finally: + if viz is not None and original_step is not None: + viz.step = original_step + if physics_handle is not None: + physics_handle.deregister() + if env is not None: + env.close() + else: + SimulationContext.clear_instance() + + +def test_env_render_false_with_resets(physics_callback, render_callback): + """Test that render_enabled=False skips post-reset re-renders during short episodes. + + Uses a direct RL env with a 3-step episode so that resets occur during the + test loop, exercising the post-reset re-render gate. + """ + physics_cb, get_physics_stats = physics_callback + render_cb, get_render_stats = render_callback + + env = None + physics_handle = None + original_step = None + viz = None + + try: + sim_utils.create_new_stage() + + # 3-step episode: resets will occur at steps 3, 6, 9, ... + env = create_direct_rl_env(render_interval=1, episode_length_steps=3) + + env.sim.set_setting("/isaaclab/render/rtx_sensors", True) + env.sim._app_control_on_stop_handle = None # type: ignore + + env.reset() + assert isinstance(env.sim.visualizers[0], KitVisualizer) + + physics_handle = env.sim.physics_manager.register_callback( + physics_cb, IsaacEvents.POST_PHYSICS_STEP, name="physics_step" + ) + + viz = env.sim.visualizers[0] + original_step = viz.step + render_dt = env.cfg.sim.dt * env.cfg.sim.render_interval + + def wrapped_step(dt): + original_step(dt) + render_cb(render_dt) + + viz.step = wrapped_step + + actions = torch.zeros((env.num_envs, 0), device=env.device) + + # Disable rendering and run past several episode boundaries + env.render_enabled = False + for i in range(10): + env.step(action=actions) + + # Physics always advances + _, num_physics_steps = get_physics_stats() + assert num_physics_steps == (i + 1) * env.cfg.decimation, f"Physics steps mismatch at step {i} with resets" + + # No Kit rendering should occur — including post-reset re-renders + _, num_render_steps = get_render_stats() + assert num_render_steps == 0, ( + f"Expected 0 render steps with render_enabled=False and resets, got {num_render_steps} at step {i}" + ) + + finally: + if viz is not None and original_step is not None: + viz.step = original_step + if physics_handle is not None: + physics_handle.deregister() + if env is not None: + env.close() + else: + SimulationContext.clear_instance() diff --git a/source/isaaclab/test/envs/test_manager_based_rl_env_obs_spaces.py b/source/isaaclab/test/envs/test_manager_based_rl_env_obs_spaces.py index 02cd337cf442..8eaeb88f0de5 100644 --- a/source/isaaclab/test/envs/test_manager_based_rl_env_obs_spaces.py +++ b/source/isaaclab/test/envs/test_manager_based_rl_env_obs_spaces.py @@ -120,9 +120,9 @@ def test_obs_space_follows_clip_contraint(env_cfg_cls, device): sim_utils.create_new_stage() # configure the env -- resolve Hydra presets so _Preset fields become plain values - from isaaclab_tasks.utils.hydra import resolve_preset_defaults + from isaaclab_tasks.utils.hydra import resolve_presets - env_cfg = resolve_preset_defaults(env_cfg_cls()) + env_cfg = resolve_presets(env_cfg_cls()) env_cfg.scene.num_envs = 2 # keep num_envs small for testing env_cfg.observations.policy.concatenate_terms = False env_cfg.sim.device = device diff --git a/source/isaaclab/test/envs/test_manager_based_rl_env_ui.py b/source/isaaclab/test/envs/test_manager_based_rl_env_ui.py index b2db866a575b..2a6157120848 100644 --- a/source/isaaclab/test/envs/test_manager_based_rl_env_ui.py +++ b/source/isaaclab/test/envs/test_manager_based_rl_env_ui.py @@ -16,7 +16,7 @@ """Rest everything follows.""" -from isaacsim.core.utils.extensions import enable_extension +from isaacsim.core.experimental.utils.app import enable_extension import isaaclab.sim as sim_utils from isaaclab.envs import ManagerBasedRLEnv, ManagerBasedRLEnvCfg diff --git a/source/isaaclab/test/envs/test_modify_env_param_curr_term.py b/source/isaaclab/test/envs/test_modify_env_param_curr_term.py index 9f58cbabc5bb..683b6eae02c7 100644 --- a/source/isaaclab/test/envs/test_modify_env_param_curr_term.py +++ b/source/isaaclab/test/envs/test_modify_env_param_curr_term.py @@ -12,7 +12,6 @@ import pytest import torch -import warp as wp import isaaclab.envs.mdp as mdp import isaaclab.sim as sim_utils @@ -89,14 +88,14 @@ def test_curriculum_modify_env_param(device): # test before curriculum kicks in, value agrees with default configuration joint_ids = env.event_manager.cfg.reset_cart_position.params["asset_cfg"].joint_ids assert env.observation_manager.cfg.policy.joint_pos_rel.func == mdp.joint_pos_rel - assert torch.any(wp.to_torch(robot.data.joint_pos)[:, joint_ids] != 0.0) + assert torch.any(robot.data.joint_pos.torch[:, joint_ids] != 0.0) assert env.max_episode_length_s == env_cfg.episode_length_s if count == 2: # test after curriculum makes effect, value agrees with new values assert env.observation_manager.cfg.policy.joint_pos_rel.func == mdp.joint_pos joint_ids = env.event_manager.cfg.reset_cart_position.params["asset_cfg"].joint_ids - assert torch.all(wp.to_torch(robot.data.joint_pos)[:, joint_ids] == 0.0) + assert torch.all(robot.data.joint_pos.torch[:, joint_ids] == 0.0) assert env.max_episode_length_s == 20 env.step(actions) diff --git a/source/isaaclab/test/envs/test_scale_randomization.py b/source/isaaclab/test/envs/test_scale_randomization.py index e3614e260a16..af5dc220e63f 100644 --- a/source/isaaclab/test/envs/test_scale_randomization.py +++ b/source/isaaclab/test/envs/test_scale_randomization.py @@ -22,7 +22,6 @@ import pytest import torch -import warp as wp from pxr import Sdf @@ -102,8 +101,8 @@ def process_actions(self, actions: torch.Tensor): def apply_actions(self): # implement a PD controller to track the target position - pos_error = self._processed_actions - (wp.to_torch(self._asset.data.root_pos_w) - self._env.scene.env_origins) - vel_error = -wp.to_torch(self._asset.data.root_lin_vel_w) + pos_error = self._processed_actions - (self._asset.data.root_pos_w.torch - self._env.scene.env_origins) + vel_error = -self._asset.data.root_lin_vel_w.torch # set velocity targets self._vel_command[:, :3] = self.p_gain * pos_error + self.d_gain * vel_error self._asset.write_root_velocity_to_sim(self._vel_command) @@ -131,7 +130,7 @@ def base_position(env: ManagerBasedEnv, asset_cfg: SceneEntityCfg) -> torch.Tens """Root linear velocity in the asset's root frame.""" # extract the used quantities (to enable type-hinting) asset: RigidObject = env.scene[asset_cfg.name] - return wp.to_torch(asset.data.root_pos_w) - env.scene.env_origins + return asset.data.root_pos_w.torch - env.scene.env_origins ## diff --git a/source/isaaclab/test/envs/test_video_recorder.py b/source/isaaclab/test/envs/test_video_recorder.py new file mode 100644 index 000000000000..91af56632d6b --- /dev/null +++ b/source/isaaclab/test/envs/test_video_recorder.py @@ -0,0 +1,433 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause +"""Unit tests for VideoRecorder.""" + +import math +import sys +from types import SimpleNamespace +from unittest.mock import MagicMock, patch + +import numpy as np +import pytest + +from isaaclab.envs.utils import video_recorder as _video_recorder_module +from isaaclab.envs.utils.video_recorder import VideoRecorder, _resolve_video_backend, _sync_camera_from_visualizer + +pytestmark = pytest.mark.isaacsim_ci +_BLANK_720p = np.zeros((720, 1280, 3), dtype=np.uint8) +_DEFAULT_CFG = dict( + env_render_mode="rgb_array", + eye=(7.5, 7.5, 7.5), + lookat=(0.0, 0.0, 0.0), + backend_source="visualizer", + window_width=1280, + window_height=720, +) + + +def _create_recorder(**kw): + """Return a VideoRecorder with ``__init__`` bypassed and all deps mocked out.""" + backend = kw.pop("_backend", None) + matched_visualizer = kw.pop("_matched_visualizer", None) + live_visualizer = kw.pop("_live_visualizer", None) + recorder = object.__new__(VideoRecorder) + recorder.cfg = SimpleNamespace(**{**_DEFAULT_CFG, **kw}) + recorder._scene = MagicMock() + recorder._scene.sensors = {} + recorder._scene._sensor_renderer_types = MagicMock(return_value=[]) + recorder._scene.sim.visualizers = [] + recorder._backend = backend + recorder._matched_visualizer = matched_visualizer + recorder._live_visualizer = live_visualizer + cap = MagicMock() + cap.render_rgb_array = MagicMock(return_value=_BLANK_720p) + recorder._capture = cap if backend else None + return recorder + + +def test_init_perspective_mode_creates_kit_capture(): + """With kit backend, __init__ builds Isaac Sim Kit perspective capture.""" + scene = MagicMock() + scene.sensors = {} + scene.num_envs = 1 + cfg = SimpleNamespace(**_DEFAULT_CFG) + fake_capture = MagicMock() + kit_mod = MagicMock() + kit_mod.create_isaacsim_kit_perspective_video = MagicMock(return_value=fake_capture) + with patch.object(_video_recorder_module, "_resolve_video_backend", return_value=("kit", None)): + with patch.object(_video_recorder_module, "_sync_camera_from_visualizer"): + with patch.dict( + sys.modules, + { + "isaaclab_physx.video_recording": MagicMock(), + "isaaclab_physx.video_recording.isaacsim_kit_perspective_video": kit_mod, + "isaaclab_physx.video_recording.isaacsim_kit_perspective_video_cfg": MagicMock(), + }, + ): + vr = VideoRecorder(cfg, scene) + kit_mod.create_isaacsim_kit_perspective_video.assert_called_once() + assert vr._capture is fake_capture + assert vr._matched_visualizer is None + + +def test_init_newton_backend_creates_newton_capture(): + """With newton_gl backend, __init__ builds Newton GL perspective capture.""" + scene = MagicMock() + cfg = SimpleNamespace(**_DEFAULT_CFG) + fake_capture = MagicMock() + newton_mod = MagicMock() + newton_mod.create_newton_gl_perspective_video = MagicMock(return_value=fake_capture) + with patch.object(_video_recorder_module, "_resolve_video_backend", return_value=("newton_gl", "newton")): + with patch.object(_video_recorder_module, "_sync_camera_from_visualizer"): + with patch.dict( + sys.modules, + { + "pyglet": MagicMock(), + "isaaclab_newton.video_recording": MagicMock(), + "isaaclab_newton.video_recording.newton_gl_perspective_video": newton_mod, + "isaaclab_newton.video_recording.newton_gl_perspective_video_cfg": MagicMock(), + }, + ): + vr = VideoRecorder(cfg, scene) + newton_mod.create_newton_gl_perspective_video.assert_called_once() + assert vr._capture is fake_capture + assert vr._matched_visualizer == "newton" + + +def test_init_kit_from_visualizer_syncs_camera(): + """When backend comes from a visualizer, _sync_camera_from_visualizer is called.""" + scene = MagicMock() + cfg = SimpleNamespace(**_DEFAULT_CFG) + with patch.object(_video_recorder_module, "_resolve_video_backend", return_value=("kit", "kit")): + with patch.object(_video_recorder_module, "_sync_camera_from_visualizer") as mock_sync: + with patch.dict( + sys.modules, + { + "isaaclab_physx.video_recording": MagicMock(), + "isaaclab_physx.video_recording.isaacsim_kit_perspective_video": MagicMock(), + "isaaclab_physx.video_recording.isaacsim_kit_perspective_video_cfg": MagicMock(), + }, + ): + VideoRecorder(cfg, scene) + mock_sync.assert_called_once_with(scene, "kit", cfg) + + +def test_init_no_visualizer_skips_camera_sync(): + """When backend comes from physics/renderer stack, camera sync is skipped.""" + scene = MagicMock() + cfg = SimpleNamespace(**_DEFAULT_CFG) + with patch.object(_video_recorder_module, "_resolve_video_backend", return_value=("kit", None)): + with patch.object(_video_recorder_module, "_sync_camera_from_visualizer") as mock_sync: + with patch.dict( + sys.modules, + { + "isaaclab_physx.video_recording": MagicMock(), + "isaaclab_physx.video_recording.isaacsim_kit_perspective_video": MagicMock(), + "isaaclab_physx.video_recording.isaacsim_kit_perspective_video_cfg": MagicMock(), + }, + ): + VideoRecorder(cfg, scene) + mock_sync.assert_not_called() + + +def _make_scene(visualizer_types, physics_name="PhysxPhysicsManager", renderer_types=None): + scene = MagicMock() + scene.sim.resolve_visualizer_types.return_value = visualizer_types + scene.sim.physics_manager.__name__ = physics_name + scene._sensor_renderer_types.return_value = renderer_types or [] + return scene + + +def test_resolve_backend_prefers_kit_visualizer(): + """When 'kit' visualizer is active, backend is 'kit' with matched type 'kit'.""" + scene = _make_scene(["kit"]) + backend, matched = _resolve_video_backend(scene) + assert backend == "kit" + assert matched == "kit" + + +def test_resolve_backend_prefers_newton_visualizer(): + """When 'newton' visualizer is active, backend is 'newton_gl' with matched type 'newton'.""" + scene = _make_scene(["newton"], physics_name="NewtonPhysicsManager") + backend, matched = _resolve_video_backend(scene) + assert backend == "newton_gl" + assert matched == "newton" + + +def test_resolve_backend_renderer_source_ignores_visualizer(): + """When backend_source is 'renderer', active visualizers do not drive backend selection.""" + scene = _make_scene(["newton"], physics_name="PhysxPhysicsManager") + backend, matched = _resolve_video_backend(scene, backend_source="renderer") + assert backend == "kit" + assert matched is None + + +def test_resolve_backend_kit_wins_over_newton_visualizer(): + """When both kit and newton visualizers are active, kit takes priority.""" + scene = _make_scene(["newton", "kit"]) + backend, matched = _resolve_video_backend(scene) + assert backend == "kit" + assert matched == "kit" + + +def test_resolve_backend_unsupported_visualizer_falls_through(): + """viser/rerun visualizers fall through to physics stack detection.""" + scene = _make_scene(["viser"], physics_name="PhysxPhysicsManager") + backend, matched = _resolve_video_backend(scene) + assert backend == "kit" + assert matched is None + + +def test_resolve_backend_fallback_physx_returns_none_matched(): + """Physics/renderer fallback returns None as matched visualizer.""" + scene = _make_scene([], physics_name="PhysxPhysicsManager") + backend, matched = _resolve_video_backend(scene) + assert backend == "kit" + assert matched is None + + +def test_resolve_backend_fallback_newton_physics_returns_none_matched(): + """Newton physics fallback returns None as matched visualizer.""" + scene = _make_scene([], physics_name="NewtonPhysicsManager") + backend, matched = _resolve_video_backend(scene) + assert backend == "newton_gl" + assert matched is None + + +def test_resolve_backend_raises_when_no_supported_backend(): + """RuntimeError when no supported backend can be detected.""" + scene = _make_scene([], physics_name="UnknownManager") + with pytest.raises(RuntimeError, match="No supported backend detected"): + _resolve_video_backend(scene) + + +def test_resolve_backend_raises_for_invalid_backend_source(): + """Only 'visualizer' and 'renderer' are valid backend source modes.""" + scene = _make_scene([]) + with pytest.raises(ValueError, match="backend_source"): + _resolve_video_backend(scene, backend_source="invalid") + + +def _make_visualizer_cfg(visualizer_type, eye=None, lookat=None): + return SimpleNamespace(visualizer_type=visualizer_type, eye=eye, lookat=lookat) + + +def test_sync_camera_overwrites_cfg_from_visualizer(): + """Visualizer cfg eye/lookat are written into VideoRecorderCfg.""" + scene = MagicMock() + scene.sim._resolve_visualizer_cfgs.return_value = [ + _make_visualizer_cfg("newton", eye=(1.0, 2.0, 3.0), lookat=(4.0, 5.0, 6.0)), + ] + cfg = SimpleNamespace(**_DEFAULT_CFG) + _sync_camera_from_visualizer(scene, "newton", cfg) + assert cfg.eye == (1.0, 2.0, 3.0) + assert cfg.lookat == (4.0, 5.0, 6.0) + + +def test_sync_camera_skips_wrong_visualizer_type(): + """Only the matching visualizer type updates the cfg.""" + scene = MagicMock() + scene.sim._resolve_visualizer_cfgs.return_value = [ + _make_visualizer_cfg("kit", eye=(9.0, 9.0, 9.0), lookat=(1.0, 1.0, 1.0)), + ] + cfg = SimpleNamespace(**_DEFAULT_CFG) + original_eye = cfg.eye + _sync_camera_from_visualizer(scene, "newton", cfg) + assert cfg.eye == original_eye # unchanged + + +def test_sync_camera_handles_missing_camera_fields(): + """If visualizer cfg has no camera fields, existing cfg values are kept.""" + scene = MagicMock() + vcfg = _make_visualizer_cfg("newton", eye=None, lookat=None) + scene.sim._resolve_visualizer_cfgs.return_value = [vcfg] + cfg = SimpleNamespace(**_DEFAULT_CFG) + original_eye = cfg.eye + _sync_camera_from_visualizer(scene, "newton", cfg) + assert cfg.eye == original_eye + + +def test_sync_camera_handles_resolve_exception(): + """If _resolve_visualizer_cfgs raises, no exception propagates and cfg is unchanged.""" + scene = MagicMock() + scene.sim._resolve_visualizer_cfgs.side_effect = RuntimeError("boom") + cfg = SimpleNamespace(**_DEFAULT_CFG) + original_eye = cfg.eye + _sync_camera_from_visualizer(scene, "newton", cfg) + assert cfg.eye == original_eye + + +def test_render_rgb_array_delegates_to_capture(): + """render_rgb_array returns capture.render_rgb_array().""" + recorder = _create_recorder(_backend="kit") + result = recorder.render_rgb_array() + recorder._capture.render_rgb_array.assert_called_once() + assert result.shape == (720, 1280, 3) + + +def test_render_rgb_array_none_when_no_backend(): + """Without rgb_array env_render_mode, _capture is None and render returns None.""" + recorder = _create_recorder(env_render_mode=None) + recorder._backend = None + recorder._capture = None + assert recorder.render_rgb_array() is None + + +def test_capture_exception_propagates(): + """Failures in backend capture propagate.""" + recorder = _create_recorder(_backend="newton_gl") + recorder._capture.render_rgb_array.side_effect = RuntimeError("fail") + with pytest.raises(RuntimeError, match="fail"): + recorder.render_rgb_array() + + +def test_render_rgb_array_calls_capture_each_step(): + """Each render_rgb_array call hits the backend capture.""" + recorder = _create_recorder(_backend="kit") + for _ in range(3): + recorder.render_rgb_array() + assert recorder._capture.render_rgb_array.call_count == 3 + + +def test_render_rgb_array_calls_sync_newton_camera_when_newton_visualizer(): + """render_rgb_array triggers _sync_newton_camera when matched_visualizer is 'newton'.""" + recorder = _create_recorder(_backend="newton_gl", _matched_visualizer="newton") + with patch.object(recorder, "_sync_newton_camera") as mock_sync: + recorder.render_rgb_array() + mock_sync.assert_called_once() + + +def test_render_rgb_array_skips_sync_for_kit_visualizer(): + """render_rgb_array does NOT call _sync_newton_camera for kit backend.""" + recorder = _create_recorder(_backend="kit", _matched_visualizer="kit") + with patch.object(recorder, "_sync_newton_camera") as mock_sync: + recorder.render_rgb_array() + mock_sync.assert_not_called() + + +def test_render_rgb_array_skips_sync_when_no_visualizer(): + """render_rgb_array does NOT call _sync_newton_camera when using physics/renderer stack.""" + recorder = _create_recorder(_backend="kit", _matched_visualizer=None) + with patch.object(recorder, "_sync_newton_camera") as mock_sync: + recorder.render_rgb_array() + mock_sync.assert_not_called() + + +def _make_newton_visualizer(pos=(1.0, 2.0, 3.0), yaw_deg=45.0, pitch_deg=30.0): + """Return a mock that quacks like a NewtonVisualizer with a live camera.""" + viz = MagicMock() + viz.cfg.visualizer_type = "newton" + cam = MagicMock() + cam.pos = pos + cam.yaw = yaw_deg + cam.pitch = pitch_deg + viz._viewer = MagicMock() + viz._viewer.camera = cam + return viz + + +def test_sync_newton_camera_lazy_lookup_finds_visualizer(): + """_sync_newton_camera resolves the Newton visualizer on the first call.""" + recorder = _create_recorder(_backend="newton_gl", _matched_visualizer="newton") + newton_viz = _make_newton_visualizer() + recorder._scene.sim.visualizers = [newton_viz] + + recorder._sync_newton_camera() + + assert recorder._live_visualizer is newton_viz + recorder._capture.update_camera.assert_called_once() + + +def test_sync_newton_camera_uses_cached_visualizer(): + """_sync_newton_camera uses the cached _live_visualizer and skips the list walk.""" + recorder = _create_recorder(_backend="newton_gl", _matched_visualizer="newton") + newton_viz = _make_newton_visualizer() + # pre-cache the visualizer + recorder._live_visualizer = newton_viz + + other_viz = _make_newton_visualizer(pos=(99.0, 99.0, 99.0)) + # replace sim.visualizers with a second Newton visualizer + # if the cache is bypassed the recorder would use this one instead. + recorder._scene.sim.visualizers = [other_viz] + recorder._sync_newton_camera() + position = recorder._capture.update_camera.call_args[0][0] + assert position != (99.0, 99.0, 99.0) + recorder._capture.update_camera.assert_called_once() + + +def test_sync_newton_camera_correct_position_forwarded(): + """_sync_newton_camera reads cam.pos and passes it as position to update_camera.""" + recorder = _create_recorder(_backend="newton_gl", _matched_visualizer="newton") + newton_viz = _make_newton_visualizer(pos=(10.0, 20.0, 30.0), yaw_deg=0.0, pitch_deg=0.0) + recorder._live_visualizer = newton_viz + + recorder._sync_newton_camera() + + args = recorder._capture.update_camera.call_args + position = args[0][0] + assert position == (10.0, 20.0, 30.0) + + +def test_sync_newton_camera_target_derived_from_pitch_yaw(): + """Target is reconstructed from pitch/yaw and is unit-distance from position.""" + recorder = _create_recorder(_backend="newton_gl", _matched_visualizer="newton") + pos = (0.0, 0.0, 0.0) + yaw_deg, pitch_deg = 0.0, 0.0 # looking along +X at horizon + newton_viz = _make_newton_visualizer(pos=pos, yaw_deg=yaw_deg, pitch_deg=pitch_deg) + recorder._live_visualizer = newton_viz + + recorder._sync_newton_camera() + + args = recorder._capture.update_camera.call_args[0] + position, target = args + dx = target[0] - position[0] + dy = target[1] - position[1] + dz = target[2] - position[2] + dist = math.sqrt(dx**2 + dy**2 + dz**2) + assert abs(dist - 1.0) < 1e-6 + assert abs(dx - 1.0) < 1e-6 + assert abs(dy) < 1e-6 + assert abs(dz) < 1e-6 + + +def test_sync_newton_camera_no_visualizer_does_not_raise(): + """_sync_newton_camera silently skips when no Newton visualizer is registered.""" + recorder = _create_recorder(_backend="newton_gl", _matched_visualizer="newton") + recorder._scene.sim.visualizers = [] + recorder._sync_newton_camera() # must not raise + recorder._capture.update_camera.assert_not_called() + + +def test_sync_newton_camera_skips_non_newton_visualizers(): + """_sync_newton_camera ignores visualizers whose type is not 'newton'.""" + recorder = _create_recorder(_backend="newton_gl", _matched_visualizer="newton") + kit_viz = MagicMock() + kit_viz.cfg.visualizer_type = "kit" + recorder._scene.sim.visualizers = [kit_viz] + recorder._sync_newton_camera() + recorder._capture.update_camera.assert_not_called() + + +def test_sync_newton_camera_skips_when_viewer_is_none(): + """_sync_newton_camera skips camera update when _viewer is None (headless fallback).""" + recorder = _create_recorder(_backend="newton_gl", _matched_visualizer="newton") + viz = MagicMock() + viz.cfg.visualizer_type = "newton" + viz._viewer = None + recorder._live_visualizer = viz + recorder._sync_newton_camera() + recorder._capture.update_camera.assert_not_called() + + +def test_sync_newton_camera_called_per_frame(): + """_sync_newton_camera (and thus update_camera) is called on every render step.""" + recorder = _create_recorder(_backend="newton_gl", _matched_visualizer="newton") + newton_viz = _make_newton_visualizer() + recorder._live_visualizer = newton_viz + + for _ in range(4): + recorder.render_rgb_array() + + assert recorder._capture.update_camera.call_count == 4 diff --git a/source/isaaclab/test/install_ci/conftest.py b/source/isaaclab/test/install_ci/conftest.py new file mode 100644 index 000000000000..c4bbc94ab200 --- /dev/null +++ b/source/isaaclab/test/install_ci/conftest.py @@ -0,0 +1,141 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Shared pytest fixtures and configuration for installation CI tests.""" + +from __future__ import annotations + +import os +import platform +import subprocess +import sys +from pathlib import Path + +import pytest +import utils as _utils +from utils import find_isaaclab_root, run_cmd # noqa: F401 – re-exported for tests + +_CYAN_BRIGHT = "\033[96m" +_RESET = "\033[0m" + +_EXECUTION_ENVIRONMENT_KEY = pytest.StashKey[_utils.ExecutionEnvironment]() + + +# Fixtures + + +@pytest.fixture(scope="session") +def isaaclab_root() -> Path: + """Resolved absolute path to the IsaacLab repository root.""" + return find_isaaclab_root() + + +@pytest.fixture +def tmp_venv(tmp_path: Path): + """Create a temporary Python virtual-environment and tear it down after the test. + + Yields a dict with: + ``path`` – Path to the venv directory + ``python`` – Path to the venv's python executable + ``pip`` – Path to the venv's pip executable + """ + venv_dir = tmp_path / "venv" + subprocess.check_call([sys.executable, "-m", "venv", str(venv_dir)]) + + if platform.system() == "Windows": + python_exe = venv_dir / "Scripts" / "python.exe" + pip_exe = venv_dir / "Scripts" / "pip.exe" + else: + python_exe = venv_dir / "bin" / "python" + pip_exe = venv_dir / "bin" / "pip" + + # Upgrade pip inside the venv to avoid old-pip issues + subprocess.check_call([str(pip_exe), "install", "--upgrade", "pip"], timeout=120) + + yield {"path": venv_dir, "python": python_exe, "pip": pip_exe} + + # Cleanup is handled by tmp_path (pytest removes it automatically) + + +@pytest.fixture(scope="session") +def wheel_path() -> Path | None: + """Path to a pre-built isaaclab wheel, or None. + + Set the ``ISAACLAB_WHEEL`` environment variable to the wheel file path + before running tests. + """ + value = os.environ.get("ISAACLAB_WHEEL") + if value: + p = Path(value).resolve() + if not p.exists(): + pytest.fail(f"ISAACLAB_WHEEL points to non-existent file: {p}") + return p + return None + + +# Markers + + +def pytest_configure(config: pytest.Config) -> None: + config.addinivalue_line("markers", "bug: bug-regression tests (use bug id as argument)") + config.addinivalue_line("markers", "gpu: tests that require a GPU") + config.addinivalue_line("markers", "docker: tests that only run inside Docker") + config.addinivalue_line("markers", "native: tests that only run natively (not in Docker)") + config.addinivalue_line("markers", "slow: tests that take a long time") + config.addinivalue_line("markers", "uv: tests that require the uv package manager") + + try: + config.stash[_EXECUTION_ENVIRONMENT_KEY] = _utils.detect_execution_environment() + except ValueError as exc: + raise pytest.UsageError(str(exc)) from exc + + # Enable real-time output when pytest capture is disabled (-s) + capture = config.getoption("capture", default="fd") + _utils.stream_output = capture == "no" + + +def pytest_report_header(config: pytest.Config) -> str: + """Show the detected install_ci execution environment in the test header.""" + return f"install_ci execution environment: {config.stash[_EXECUTION_ENVIRONMENT_KEY]}" + + +def pytest_runtest_logreport(report: pytest.TestReport) -> None: + """Print a newline after the PASSED/FAILED/SKIPPED result.""" + if report.when == "call" or (report.when == "setup" and report.skipped): + sys.stdout.write("\n") + + +@pytest.hookimpl(tryfirst=True) +def pytest_collection_modifyitems(config: pytest.Config, items: list[pytest.Item]) -> None: + """Map dynamic bug markers and skip items with mismatched env markers. + + This allows filtering by bug ID natively in pytest: `-m "nvbugs_5968136"` + instead of the (unsupported natively) `-m "bug('nvbugs_5968136')"`. + """ + execution_environment = config.stash[_EXECUTION_ENVIRONMENT_KEY] + known_bugs = set() + for item in items: + for mark in item.iter_markers(name="bug"): + for arg in mark.args: + if isinstance(arg, str): + known_bugs.add(arg) + + for bug in known_bugs: + config.addinivalue_line("markers", f"{bug}: dynamically generated bug marker") + + for item in items: + for mark in item.iter_markers(name="bug"): + for arg in mark.args: + if isinstance(arg, str): + item.add_marker(arg) + + marker_names = {mark.name for mark in item.iter_markers()} + try: + skip_reason = _utils.get_execution_environment_skip_reason(marker_names, execution_environment) + except ValueError as exc: + raise pytest.UsageError(f"{item.nodeid}: {exc}") from exc + + if skip_reason: + item.add_marker(pytest.mark.skip(reason=skip_reason)) diff --git a/source/isaaclab/test/install_ci/pytest.ini b/source/isaaclab/test/install_ci/pytest.ini new file mode 100644 index 000000000000..67eac9b17ca7 --- /dev/null +++ b/source/isaaclab/test/install_ci/pytest.ini @@ -0,0 +1,15 @@ +[pytest] +testpaths = . +python_files = + test_*.py + *.test.py + *_test.py + *_tests.py +markers = + bug: bug-regression tests (use bug id as argument) + gpu: tests that require a GPU + docker: tests that only run inside Docker + native: tests that only run natively (not in Docker) + slow: tests that take a long time + uv: tests that require the uv package manager +timeout = 1200 diff --git a/source/isaaclab/test/install_ci/test_environment_markers.py b/source/isaaclab/test/install_ci/test_environment_markers.py new file mode 100644 index 000000000000..c002353b5c3e --- /dev/null +++ b/source/isaaclab/test/install_ci/test_environment_markers.py @@ -0,0 +1,77 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Unit tests for install_ci execution-environment marker handling.""" + +from __future__ import annotations + +import pytest +from utils import ( + detect_execution_environment, + get_execution_environment_skip_reason, +) + + +class TestDetectExecutionEnvironment: + """Tests for detect_execution_environment().""" + + def test_uses_override(self, tmp_path): + environment = detect_execution_environment( + environ={"ISAACLAB_INSTALL_CI_ENV": "docker"}, + filesystem_root=tmp_path, + ) + + assert environment == "docker" + + def test_detects_marker_file(self, tmp_path): + (tmp_path / ".dockerenv").touch() + + environment = detect_execution_environment(environ={}, filesystem_root=tmp_path) + + assert environment == "docker" + + def test_detects_cgroup_hint(self, tmp_path): + cgroup_path = tmp_path / "proc" / "self" + cgroup_path.mkdir(parents=True) + (cgroup_path / "cgroup").write_text("0::/docker/container-id\n", encoding="utf-8") + + environment = detect_execution_environment(environ={}, filesystem_root=tmp_path) + + assert environment == "docker" + + def test_defaults_to_native(self, tmp_path): + environment = detect_execution_environment(environ={}, filesystem_root=tmp_path) + + assert environment == "native" + + def test_rejects_invalid_override(self, tmp_path): + with pytest.raises(ValueError, match="ISAACLAB_INSTALL_CI_ENV"): + detect_execution_environment( + environ={"ISAACLAB_INSTALL_CI_ENV": "virtual-machine"}, + filesystem_root=tmp_path, + ) + + +class TestGetExecutionEnvironmentSkipReason: + """Tests for get_execution_environment_skip_reason().""" + + @pytest.mark.parametrize( + ("marker_names", "execution_environment", "expected_reason"), + [ + ({"docker"}, "native", "requires Docker execution environment, detected native"), + ({"native"}, "docker", "requires native execution environment, detected docker"), + ({"docker"}, "docker", None), + ({"native"}, "native", None), + (set(), "native", None), + ], + ) + def test_skip_reason(self, marker_names, execution_environment, expected_reason): + skip_reason = get_execution_environment_skip_reason(marker_names, execution_environment) + + assert skip_reason == expected_reason + + def test_rejects_conflicting_markers(self): + with pytest.raises(ValueError, match="docker"): + get_execution_environment_skip_reason({"docker", "native"}, "native") diff --git a/source/isaaclab/test/install_ci/test_isaaclabx_i_newton.py b/source/isaaclab/test/install_ci/test_isaaclabx_i_newton.py new file mode 100644 index 000000000000..4f7740dfe6fd --- /dev/null +++ b/source/isaaclab/test/install_ci/test_isaaclabx_i_newton.py @@ -0,0 +1,61 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Test installing isaaclab_newton and running its test suite.""" + +from __future__ import annotations + +import shutil + +import pytest +from utils import UV_Mixin, find_isaaclab_root + + +class Test_Install_Newton(UV_Mixin): + """Install ./isaaclab.sh -i newton and run the isaaclab_newton test suite.""" + + @classmethod + def setup_class(cls): + # check if uv is available + if not shutil.which("uv"): + pytest.skip("uv is not available") + + # check if isaacsim is importable + # or "_isaac_sim" link is present + try: + import isaacsim # noqa: F401 + except ImportError: + print("[DEBUG] Module isaacsim is not importable") + isaac_sim_link = find_isaaclab_root() / "_isaac_sim" + if not isaac_sim_link.exists(): + print(f'[DEBUG] Link "{isaac_sim_link}" does not exist') + pytest.skip("isaacsim is not importable and _isaac_sim link not found, skipping") + + @pytest.mark.uv + @pytest.mark.gpu + @pytest.mark.slow + @pytest.mark.native + @pytest.mark.timeout(3600) + def test_install_newton_and_run_tests(self, isaaclab_root): + """Install newton extension and run the isaaclab_newton test suite.""" + + try: + self.create_uv_env(isaaclab_root) + + # ./isaaclab.sh -i newton + result = self.run_in_uv_env([str(self.cli_script), "-i", "newton"], cwd=isaaclab_root) + assert result.returncode == 0, f"isaaclab -i newton failed:\n{result.stdout}\n{result.stderr}" + + # Run isaaclab_newton test suite + test_dir = str(isaaclab_root / "source" / "isaaclab_newton" / "test") + result = self.run_in_uv_env( + ["python", "-m", "pytest", test_dir, "-sv", "--tb=short"], + cwd=isaaclab_root, + ) + output = result.stdout + result.stderr + assert result.returncode == 0, f"isaaclab_newton tests failed (rc={result.returncode}):\n{output}" + + finally: + self.destroy_uv_env() diff --git a/source/isaaclab/test/install_ci/test_isaaclabx_i_physx.py b/source/isaaclab/test/install_ci/test_isaaclabx_i_physx.py new file mode 100644 index 000000000000..04bf2b346b23 --- /dev/null +++ b/source/isaaclab/test/install_ci/test_isaaclabx_i_physx.py @@ -0,0 +1,61 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Test installing isaaclab_physx and running its test suite.""" + +from __future__ import annotations + +import shutil + +import pytest +from utils import UV_Mixin, find_isaaclab_root + + +class Test_Install_Physx(UV_Mixin): + """Install ./isaaclab.sh -i physx and run the isaaclab_physx test suite.""" + + @classmethod + def setup_class(cls): + # check if uv is available + if not shutil.which("uv"): + pytest.skip("uv is not available") + + # check if isaacsim is importable + # or "_isaac_sim" link is present + try: + import isaacsim # noqa: F401 + except ImportError: + print("[DEBUG] Module isaacsim is not importable") + isaac_sim_link = find_isaaclab_root() / "_isaac_sim" + if not isaac_sim_link.exists(): + print(f'[DEBUG] Link "{isaac_sim_link}" does not exist') + pytest.skip("isaacsim is not importable and _isaac_sim link not found, skipping") + + @pytest.mark.uv + @pytest.mark.gpu + @pytest.mark.slow + @pytest.mark.native + @pytest.mark.timeout(3600) + def test_install_physx_and_run_tests(self, isaaclab_root): + """Install physx extension and run the isaaclab_physx test suite.""" + + try: + self.create_uv_env(isaaclab_root) + + # ./isaaclab.sh -i physx + result = self.run_in_uv_env([str(self.cli_script), "-i", "physx"], cwd=isaaclab_root) + assert result.returncode == 0, f"isaaclab -i physx failed:\n{result.stdout}\n{result.stderr}" + + # Run isaaclab_physx test suite + test_dir = str(isaaclab_root / "source" / "isaaclab_physx" / "test") + result = self.run_in_uv_env( + ["python", "-m", "pytest", test_dir, "-sv", "--tb=short"], + cwd=isaaclab_root, + ) + output = result.stdout + result.stderr + assert result.returncode == 0, f"isaaclab_physx tests failed (rc={result.returncode}):\n{output}" + + finally: + self.destroy_uv_env() diff --git a/source/isaaclab/test/install_ci/test_isaaclabx_uv_smoke.py b/source/isaaclab/test/install_ci/test_isaaclabx_uv_smoke.py new file mode 100644 index 000000000000..8bff8426e1fe --- /dev/null +++ b/source/isaaclab/test/install_ci/test_isaaclabx_uv_smoke.py @@ -0,0 +1,73 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Test uv-based installation scenarios for isaaclab.""" + +from __future__ import annotations + +import shutil + +import pytest +from utils import UV_Mixin + + +class Test_UV_Env_Smoke(UV_Mixin): + """Test ./isaaclab.x -u, then validate with some quick checks.""" + + @classmethod + def setup_class(cls): + if not shutil.which("uv"): + pytest.skip("uv is not available") + + @pytest.mark.uv + @pytest.mark.timeout(10) + def test_isaaclab_sh_uv_creates_env_with_python_312(self, isaaclab_root): + """Run ./isaaclab.x -u and verify the created env has Python 3.12.""" + + try: + self.create_uv_env(isaaclab_root) + # python --version + version_output = self.run_in_uv_env(["python", "--version"]).stdout.strip() + assert "3.12" in version_output, f"Expected Python 3.12, got: {version_output}" + finally: + self.destroy_uv_env() + + @pytest.mark.uv + @pytest.mark.timeout(200) + def test_isaaclab_install_assets(self, isaaclab_root): + """Run ./isaaclab.x -i 'assets' and verify isaaclab_assets is importable.""" + + try: + self.create_uv_env(isaaclab_root) + + # ./isaaclab.x -i assets + result = self.run_in_uv_env([str(self.cli_script), "-i", "assets"], cwd=isaaclab_root) + assert result.returncode == 0, f"isaaclab -i assets failed:\n{result.stdout}\n{result.stderr}" + + # import isaaclab_assets + result = self.run_in_uv_env(["python", "-c", "import isaaclab_assets; print(isaaclab_assets.__version__)"]) + assert result.returncode == 0, f"import isaaclab_assets failed:\n{result.stdout}\n{result.stderr}" + + finally: + self.destroy_uv_env() + + @pytest.mark.uv + @pytest.mark.timeout(300) + def test_isaaclab_newton_installs_isaaclab_newton(self, isaaclab_root): + """Run ./isaaclab.x -i 'newton' and verify isaaclab_newton is importable.""" + + try: + self.create_uv_env(isaaclab_root) + + # ./isaaclab.x -i newton + result = self.run_in_uv_env([str(self.cli_script), "-i", "newton"], cwd=isaaclab_root) + assert result.returncode == 0, f"isaaclab -i newton failed:\n{result.stdout}\n{result.stderr}" + + # import isaaclab_newton + result = self.run_in_uv_env(["python", "-c", "import isaaclab_newton; print(isaaclab_newton.__version__)"]) + assert result.returncode == 0, f"import isaaclab_newton failed:\n{result.stdout}\n{result.stderr}" + + finally: + self.destroy_uv_env() diff --git a/source/isaaclab/test/install_ci/test_isaaclabx_uv_training.py b/source/isaaclab/test/install_ci/test_isaaclabx_uv_training.py new file mode 100644 index 000000000000..9bd2bfa40f32 --- /dev/null +++ b/source/isaaclab/test/install_ci/test_isaaclabx_uv_training.py @@ -0,0 +1,64 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Heavy uv-based installation and training tests for isaaclab.""" + +from __future__ import annotations + +import shutil + +import pytest +from utils import UV_Mixin + + +class Test_UV_Env_Heavy(UV_Mixin): + """Test ./isaaclab.x -u, then run heavy training.""" + + @classmethod + def setup_class(cls): + if not shutil.which("uv"): + pytest.skip("uv is not available") + + @pytest.mark.uv + @pytest.mark.slow + @pytest.mark.gpu + @pytest.mark.bug("nvbugs_5968136") + @pytest.mark.skip(reason="Cartpole training fails in MuJoCo stiffness conversion.") + @pytest.mark.timeout(1200) + def test_install_and_train_cartpole(self, isaaclab_root): + """`isaaclab.x -i assets,tasks,rl[all],physx,newton,contrib` then train Isaac-Cartpole-Direct-v0""" + + try: + self.create_uv_env(isaaclab_root) + + # Install assets, tasks, rl[all], physx, newton, contrib + result = self.run_in_uv_env( + [str(self.cli_script), "-i", "assets,tasks,rl[all],physx,newton,contrib"], cwd=isaaclab_root + ) + assert result.returncode == 0, f"isaaclab -i failed:\n{result.stdout}\n{result.stderr}" + + # Run a short training + result = self.run_in_uv_env( + [ + str(self.cli_script), + "-p", + "scripts/reinforcement_learning/rsl_rl/train.py", + "--task", + "Isaac-Cartpole-Direct-v0", + "--num_envs", + "4096", + "presets=newton_mjwarp", + "--max_iterations", + "5", + ], + cwd=isaaclab_root, + ) + output = result.stdout + result.stderr + assert result.returncode == 0, f"Training failed (rc={result.returncode}):\n{output}" + assert "Traceback (most recent call last):" not in output, ( + f"Training produced a Python traceback:\n{output}" + ) + finally: + self.destroy_uv_env() diff --git a/source/isaaclab/test/install_ci/test_wheel_builder.py b/source/isaaclab/test/install_ci/test_wheel_builder.py new file mode 100644 index 000000000000..51b93a6a4234 --- /dev/null +++ b/source/isaaclab/test/install_ci/test_wheel_builder.py @@ -0,0 +1,106 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Test wheel build and install scenarios for isaaclab.""" + +from __future__ import annotations + +import glob +import shutil + +import pytest +from utils import UV_Mixin, run_cmd + + +class Test_Wheel_Builder(UV_Mixin): + """Test building the isaaclab wheel and installing it in a uv environment.""" + + @classmethod + def setup_class(cls): + if not shutil.which("uv"): + pytest.skip("uv is not available") + + @pytest.fixture(autouse=True, scope="class") + def _build_and_install_wheel(self, isaaclab_root): + """Build the wheel and install it in a uv environment once for all tests.""" + + cls = self.__class__ + build_script = isaaclab_root / "tools" / "wheel_builder" / "build.sh" + dist_dir = isaaclab_root / "tools" / "wheel_builder" / "build" / "dist" + + # Build the wheel + result = run_cmd(["bash", str(build_script)], cwd=isaaclab_root) + assert result.returncode == 0, f"build.sh failed:\n{result.stdout}\n{result.stderr}" + + # Find the built wheel + wheels = glob.glob(str(dist_dir / "isaaclab-*.whl")) + assert len(wheels) == 1, f"Expected exactly 1 wheel in {dist_dir}, found: {wheels}" + cls.wheel_path = wheels[0] + + # Create uv environment and install the wheel + self.create_uv_env(isaaclab_root) + + # Share env state with all test instances via the class + cls.env_path = self.env_path + cls.python = self.python + cls.cli_script = self.cli_script + result = self.run_in_uv_env(["uv", "pip", "install", cls.wheel_path + "[all]"]) + assert result.returncode == 0, f"uv pip install wheel failed:\n{result.stdout}\n{result.stderr}" + + yield + + self.destroy_uv_env() + + # import isaaclab + def test_import_isaaclab(self): + """Verify 'isaaclab' is importable.""" + result = self.run_in_uv_env(["python", "-c", "import isaaclab;"]) + assert result.returncode == 0, f"import isaaclab failed:\n{result.stdout}\n{result.stderr}" + + # from isaaclab import __version__; print(__version__) + def test_version_matches_wheel(self): + """Verify isaaclab.__version__ matches the wheel version.""" + result = self.run_in_uv_env(["python", "-c", "from isaaclab import __version__; print(__version__)"]) + imported_version = result.stdout.strip() + expected_version = self.wheel_path.split("/")[-1].split("-")[1] + assert imported_version == expected_version, ( + f"isaaclab.__version__ mismatch: expected {expected_version}, got {imported_version}" + ) + + # from isaaclab.app import AppLauncher + def test_import_isaaclab_app(self): + """Verify isaaclab.app and AppLauncher are importable.""" + result = self.run_in_uv_env(["python", "-c", "from isaaclab.app import AppLauncher"]) + assert result.returncode == 0, f"import isaaclab.app failed:\n{result.stdout}\n{result.stderr}" + + # from isaaclab.envs import ViewerCfg + def test_import_isaaclab_envs(self): + """Verify isaaclab.envs is importable.""" + result = self.run_in_uv_env(["python", "-c", "from isaaclab.envs import ViewerCfg"]) + assert result.returncode == 0, f"import isaaclab.envs failed:\n{result.stdout}\n{result.stderr}" + + # from isaaclab_assets.robots.allegro import ALLEGRO_HAND_CFG + def test_import_isaaclab_assets(self): + """Verify isaaclab_assets is importable.""" + result = self.run_in_uv_env(["python", "-c", "from isaaclab_assets.robots.allegro import ALLEGRO_HAND_CFG"]) + assert result.returncode == 0, f"import isaaclab_assets failed:\n{result.stdout}\n{result.stderr}" + + # from isaaclab.scene import InteractiveSceneCfg + def test_import_isaaclab_scene(self): + """Verify isaaclab.scene and InteractiveSceneCfg are importable.""" + result = self.run_in_uv_env(["python", "-c", "from isaaclab.scene import InteractiveSceneCfg"]) + assert result.returncode == 0, f"import isaaclab.scene failed:\n{result.stdout}\n{result.stderr}" + + # python -m isaaclab --help + def test_cli_help(self): + """Verify the isaaclab CLI is functional.""" + result = self.run_in_uv_env(["python", "-m", "isaaclab", "--help"]) + assert result.returncode == 0, f"isaaclab CLI help failed:\n{result.stdout}\n{result.stderr}" + + # import pinocchio as pin; print(pin.__version__) + def test_pinocchio_import(self): + """Verify pinocchio is importable and has the expected version.""" + result = self.run_in_uv_env(["python", "-c", "import pinocchio as pin; print(pin.__version__)"]) + assert result.returncode == 0, f"import pinocchio failed:\n{result.stdout}\n{result.stderr}" diff --git a/source/isaaclab/test/install_ci/utils.py b/source/isaaclab/test/install_ci/utils.py new file mode 100644 index 000000000000..85055f26c0bc --- /dev/null +++ b/source/isaaclab/test/install_ci/utils.py @@ -0,0 +1,244 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Shared utilities for Isaac Lab installation CI tests.""" + +from __future__ import annotations + +import os +import platform +import shlex +import shutil +import subprocess +import sys +import time +from pathlib import Path +from typing import Literal + +_DIM = "\033[2m" +_MAGENTA = "\033[95m" +_RESET = "\033[0m" + +# Controls whether run_cmd() streams output by default. +# Set to True by conftest.py when pytest runs with -s / --capture=no. +stream_output: bool = False + +# ISAACLAB_INSTALL_CI_ENV can be set to override execution +# environment detection in install_ci tests +# (for testing the testing while testing). + +ExecutionEnvironment = Literal["docker", "native"] + + +def detect_execution_environment( + environ: dict[str, str] | None = None, + filesystem_root: Path | None = None, +) -> ExecutionEnvironment: + """Detect whether install_ci tests are running in Docker or natively.""" + env = environ if environ is not None else os.environ + root = filesystem_root if filesystem_root is not None else Path("/") + + override = env.get("ISAACLAB_INSTALL_CI_ENV") + if override: + cleaned = override.strip().lower() + if cleaned not in ("docker", "native"): + raise ValueError(f"ISAACLAB_INSTALL_CI_ENV must be 'docker' or 'native', got: {override!r}") + return cleaned # type: ignore[return-value] + + if (root / ".dockerenv").exists() or (root / "run" / ".containerenv").exists(): + return "docker" + + for cgroup_path in (root / "proc" / "1" / "cgroup", root / "proc" / "self" / "cgroup"): + try: + cgroup_text = cgroup_path.read_text(encoding="utf-8", errors="ignore") + except OSError: + continue + if any( + hint in cgroup_text + for hint in ( + "docker", + "containerd", + "kubepods", + "libpod", + "podman", + ) + ): + return "docker" + + if env.get("container"): + return "docker" + + return "native" + + +def get_execution_environment_skip_reason( + marker_names: set[str], + execution_environment: ExecutionEnvironment, +) -> str | None: + """Return a skip reason when environment markers do not match the runtime.""" + has_docker = "docker" in marker_names + has_native = "native" in marker_names + + if has_docker and has_native: + raise ValueError("tests cannot be marked with both 'docker' and 'native'") + + if has_docker and execution_environment != "docker": + return f"requires Docker execution environment, detected {execution_environment}" + + if has_native and execution_environment != "native": + return f"requires native execution environment, detected {execution_environment}" + + return None + + +def find_isaaclab_root() -> Path: + """Walk up from this file to find the repo root (contains isaaclab.sh).""" + here = Path(__file__).resolve() + for parent in [here] + list(here.parents): + if (parent / "isaaclab.sh").exists(): + return parent + raise FileNotFoundError("Could not locate IsaacLab repository root (no isaaclab.sh found)") + + +def run_cmd( + args: list[str], + *, + cwd: str | Path | None = None, + env: dict[str, str] | None = None, + timeout: int = 600, + err_on_err: bool = False, + stream: bool | None = None, +) -> subprocess.CompletedProcess: + """Run a command, merging *env* into the current environment. + + Args: + args: Command and arguments to run. + cwd: Working directory for the subprocess. + env: Extra environment variables merged into the current environment. + timeout: Timeout in seconds. + err_on_err: Raise CalledProcessError on non-zero exit. + stream: When True, stream stdout/stderr to the console in + real time instead of capturing them. Defaults to True when + pytest is invoked with ``-s`` (``--capture=no``). + + Returns: + The CompletedProcess; raises CalledProcessError when *check* is + True and return code != 0. + """ + if stream is None: + stream = stream_output + merged_env = {**os.environ, **(env or {})} + cmd_str = " ".join(str(a) for a in args) + if stream: + sys.stdout.write(f"{_MAGENTA}[COMMAND] {cmd_str}{_RESET}\n") + sys.stdout.flush() + # Stream output to console in real time. + t0 = time.monotonic() + proc = subprocess.Popen( + [str(a) for a in args], + cwd=str(cwd) if cwd else None, + env=merged_env, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + text=True, + ) + assert proc.stdout is not None + lines: list[str] = [] + try: + for line in proc.stdout: + lines.append(line) + sys.stdout.write(f"{_DIM}{line}{_RESET}") + sys.stdout.flush() + except Exception: + proc.kill() + raise + try: + proc.wait(timeout=timeout) + except subprocess.TimeoutExpired: + proc.kill() + proc.wait() + raise + elapsed = time.monotonic() - t0 + sys.stdout.write(f"{_MAGENTA}[{elapsed:.1f}s]{_RESET}\n") + sys.stdout.flush() + result = subprocess.CompletedProcess( + args=proc.args, + returncode=proc.returncode, + stdout="".join(lines), + stderr="", + ) + if err_on_err and result.returncode != 0: + raise subprocess.CalledProcessError(result.returncode, result.args, result.stdout, result.stderr) + return result + return subprocess.run( + [str(a) for a in args], + cwd=str(cwd) if cwd else None, + env=merged_env, + capture_output=True, + text=True, + timeout=timeout, + check=err_on_err, + ) + + +_IS_WINDOWS = platform.system() == "Windows" + + +class UV_Mixin: + """Mixin providing uv virtual-environment helpers for test classes.""" + + env_path: Path + python: Path + cli_script: Path + + def create_uv_env(self, isaaclab_root: Path, env_name: str = "") -> None: + """Create a uv environment and store info on self. + + Sets ``self.env_path``, ``self.python``, and ``self.cli_script``. + + Args: + isaaclab_root: Path to the IsaacLab repository root. + env_name: Name for the venv directory. A random name is + generated when empty. + """ + env_name = env_name if env_name else f"_isaaclab_install_ci_{os.urandom(4).hex()}" + + self.env_path = isaaclab_root / env_name + self.cli_script = isaaclab_root / ("isaaclab.bat" if _IS_WINDOWS else "isaaclab.sh") + + if self.env_path.exists(): + shutil.rmtree(self.env_path) + + result = run_cmd([str(self.cli_script), "-u", env_name], cwd=isaaclab_root, err_on_err=False) + assert result.returncode == 0, f"uv env creation failed:\n{result.stdout}\n{result.stderr}" + assert self.env_path.exists(), f"Expected env directory {self.env_path} was not created" + + # Prevent the venv from being tracked by git. + (self.env_path / ".gitignore").write_text("*\n") + + self.python = (self.env_path / "Scripts" / "python.exe") if _IS_WINDOWS else (self.env_path / "bin" / "python") + assert self.python.exists(), f"Python executable not found at {self.python}" + + def destroy_uv_env(self) -> None: + """Remove the uv environment directory if it exists.""" + if hasattr(self, "env_path") and self.env_path.exists(): + shutil.rmtree(self.env_path) + + def run_in_uv_env(self, cmd: list[str], **kwargs) -> subprocess.CompletedProcess: + """Run a command inside the activated venv by sourcing the activate script. + + Args: + cmd: Command and arguments to run inside the venv. + **kwargs: Extra keyword arguments forwarded to :func:`run_cmd`. + """ + escaped = " ".join(shlex.quote(str(a)) for a in cmd) + if _IS_WINDOWS: + activate = str(self.env_path / "Scripts" / "activate.bat") + shell_cmd = f'call "{activate}" && {escaped}' + return run_cmd(["cmd", "/c", shell_cmd], **kwargs) + else: + activate = shlex.quote(str(self.env_path / "bin" / "activate")) + shell_cmd = f"source {activate} && {escaped}" + return run_cmd(["bash", "-c", shell_cmd], **kwargs) diff --git a/source/isaaclab/test/managers/test_observation_manager.py b/source/isaaclab/test/managers/test_observation_manager.py index 4c44bfd00ba5..d738f179da71 100644 --- a/source/isaaclab/test/managers/test_observation_manager.py +++ b/source/isaaclab/test/managers/test_observation_manager.py @@ -194,8 +194,7 @@ class SampleGroupCfg(ObservationGroupCfg): obs_man_str_split = obs_man_str.split("|") term_1_str_index = obs_man_str_split.index(" term_1 ") term_1_str_shape = obs_man_str_split[term_1_str_index + 1].strip() - # Handle numpy 2.0 where shape may be represented as (np.int64(20),) instead of (20,) - assert term_1_str_shape in ("(20,)", "(np.int64(20),)") + assert term_1_str_shape == "(20,)" def test_config_equivalence(setup_env): diff --git a/source/isaaclab/test/markers/check_markers_visibility.py b/source/isaaclab/test/markers/check_markers_visibility.py index 98dbee8ddcd7..eadc8af82a53 100644 --- a/source/isaaclab/test/markers/check_markers_visibility.py +++ b/source/isaaclab/test/markers/check_markers_visibility.py @@ -96,14 +96,14 @@ def run_simulator( count = 0 # reset the scene entities # root state - root_state = scene["robot"].data.default_root_state.clone() + root_state = scene["robot"].data.default_root_state.torch.clone() root_state[:, :3] += scene.env_origins scene["robot"].write_root_pose_to_sim(root_state[:, :7]) scene["robot"].write_root_velocity_to_sim(root_state[:, 7:]) # set joint positions with some noise joint_pos, joint_vel = ( - scene["robot"].data.default_joint_pos.clone(), - scene["robot"].data.default_joint_vel.clone(), + scene["robot"].data.default_joint_pos.torch.clone(), + scene["robot"].data.default_joint_vel.torch.clone(), ) scene["robot"].write_joint_state_to_sim(joint_pos, joint_vel) # clear internal buffers diff --git a/source/isaaclab/test/markers/test_visualization_markers.py b/source/isaaclab/test/markers/test_visualization_markers.py index ebc183b804b8..906c14ccb7d5 100644 --- a/source/isaaclab/test/markers/test_visualization_markers.py +++ b/source/isaaclab/test/markers/test_visualization_markers.py @@ -126,6 +126,7 @@ def test_multiple_prototypes_marker(sim): sim.step() +@pytest.mark.flaky(max_runs=3, min_passes=1) def test_visualization_time_based_on_prototypes(sim): """Test with time taken when number of prototypes is increased.""" # create a marker diff --git a/source/isaaclab/test/performance/test_kit_startup_performance.py b/source/isaaclab/test/performance/test_kit_startup_performance.py index f4134d04ae14..0a39f23ea4aa 100644 --- a/source/isaaclab/test/performance/test_kit_startup_performance.py +++ b/source/isaaclab/test/performance/test_kit_startup_performance.py @@ -20,4 +20,4 @@ def test_kit_start_up_time(): end_time = time.time() elapsed_time = end_time - start_time # we are doing some more imports on the automate side - will investigate using warp instead of numba cuda - assert elapsed_time <= 12.0 + assert elapsed_time <= 15.0 diff --git a/source/isaaclab/test/performance/test_robot_load_performance.py b/source/isaaclab/test/performance/test_robot_load_performance.py index f76a109c35d2..a298c8b746e5 100644 --- a/source/isaaclab/test/performance/test_robot_load_performance.py +++ b/source/isaaclab/test/performance/test_robot_load_performance.py @@ -32,11 +32,12 @@ @pytest.mark.parametrize( "test_config,device", [ - ({"name": "Cartpole", "robot_cfg": CARTPOLE_CFG, "expected_load_time": 10.0}, "cuda:0"), - ({"name": "Cartpole", "robot_cfg": CARTPOLE_CFG, "expected_load_time": 10.0}, "cpu"), + # TODO: regression - this used to be 10 + ({"name": "Cartpole", "robot_cfg": CARTPOLE_CFG, "expected_load_time": 15.0}, "cuda:0"), + ({"name": "Cartpole", "robot_cfg": CARTPOLE_CFG, "expected_load_time": 15.0}, "cpu"), # TODO: regression - this used to be 40 - ({"name": "Anymal_D", "robot_cfg": ANYMAL_D_CFG, "expected_load_time": 50.0}, "cuda:0"), - ({"name": "Anymal_D", "robot_cfg": ANYMAL_D_CFG, "expected_load_time": 50.0}, "cpu"), + ({"name": "Anymal_D", "robot_cfg": ANYMAL_D_CFG, "expected_load_time": 60.0}, "cuda:0"), + ({"name": "Anymal_D", "robot_cfg": ANYMAL_D_CFG, "expected_load_time": 60.0}, "cpu"), ], ) def test_robot_load_performance(test_config, device): diff --git a/source/isaaclab/test/renderers/test_camera_output_contract.py b/source/isaaclab/test/renderers/test_camera_output_contract.py new file mode 100644 index 000000000000..2d6087d29708 --- /dev/null +++ b/source/isaaclab/test/renderers/test_camera_output_contract.py @@ -0,0 +1,228 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Tests for the renderer→camera output contract.""" + +import warnings + +import pytest +import torch + +pytest.importorskip("isaaclab_physx") + +from isaaclab.sensors.camera import CameraCfg, TiledCameraCfg +from isaaclab.sensors.camera.camera_data import CameraData, RenderBufferKind, RenderBufferSpec +from isaaclab.sim import PinholeCameraCfg + +_SPAWN = PinholeCameraCfg( + focal_length=24.0, + focus_distance=400.0, + horizontal_aperture=20.955, + clipping_range=(0.1, 1.0e5), +) + + +@pytest.mark.parametrize( + "field_name,deprecated_value", + [ + ("colorize_semantic_segmentation", False), + ("colorize_instance_segmentation", False), + ("colorize_instance_id_segmentation", False), + ("semantic_filter", ["class"]), + ("semantic_segmentation_mapping", {"class:cube": (1, 2, 3, 4)}), + ("depth_clipping_behavior", "max"), + ], +) +def test_camera_cfg_forwards_deprecated_fields_to_renderer_cfg(field_name, deprecated_value): + """Deprecated CameraCfg field is forwarded to renderer_cfg with a warning.""" + kwargs = { + "height": 64, + "width": 64, + "prim_path": "/World/Camera", + "spawn": _SPAWN, + "data_types": ["rgb"], + field_name: deprecated_value, + } + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + cfg = CameraCfg(**kwargs) + + deprecation_warnings = [w for w in caught if issubclass(w.category, DeprecationWarning)] + assert any(f"CameraCfg.{field_name}" in str(w.message) for w in deprecation_warnings) + assert getattr(cfg.renderer_cfg, field_name) == deprecated_value + + +def test_camera_cfg_default_does_not_warn_or_forward(): + """Default-valued deprecated fields stay silent.""" + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + cfg = CameraCfg( + height=64, + width=64, + prim_path="/World/Camera", + spawn=_SPAWN, + data_types=["rgb"], + ) + + deprecation_warnings = [ + w for w in caught if issubclass(w.category, DeprecationWarning) and "CameraCfg." in str(w.message) + ] + assert deprecation_warnings == [] + assert cfg.renderer_cfg.colorize_semantic_segmentation is True + + +def test_camera_cfg_post_construction_mutation_is_silent_no_op(): + """Mutating a deprecated field after construction does not propagate to renderer_cfg.""" + cfg = CameraCfg( + height=64, + width=64, + prim_path="/World/Camera", + spawn=_SPAWN, + data_types=["rgb"], + ) + assert cfg.renderer_cfg.colorize_semantic_segmentation is True + cfg.colorize_semantic_segmentation = False + assert cfg.renderer_cfg.colorize_semantic_segmentation is True + + +def test_tiled_camera_cfg_does_not_forward_deprecated_fields(): + """TiledCameraCfg skips CameraCfg's per-field forwarder.""" + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + cfg = TiledCameraCfg( + height=64, + width=64, + prim_path="/World/Camera", + spawn=_SPAWN, + data_types=["rgb"], + colorize_semantic_segmentation=False, + ) + + tiled_warnings = [ + w for w in caught if issubclass(w.category, DeprecationWarning) and "TiledCameraCfg" in str(w.message) + ] + assert tiled_warnings + + field_warnings = [ + w for w in caught if issubclass(w.category, DeprecationWarning) and "CameraCfg.colorize_" in str(w.message) + ] + assert field_warnings == [] + + assert cfg.renderer_cfg.colorize_semantic_segmentation is True + + +def test_newton_warp_supported_output_types_key_set(): + """NewtonWarpRenderer publishes the documented key set.""" + pytest.importorskip("isaaclab_newton") + pytest.importorskip("newton") + from isaaclab_newton.renderers.newton_warp_renderer import NewtonWarpRenderer + from isaaclab_newton.renderers.newton_warp_renderer_cfg import NewtonWarpRendererCfg + + renderer = NewtonWarpRenderer.__new__(NewtonWarpRenderer) + renderer.cfg = NewtonWarpRendererCfg() + specs = renderer.supported_output_types() + + assert set(specs.keys()) == { + RenderBufferKind.RGB, + RenderBufferKind.RGBA, + RenderBufferKind.ALBEDO, + RenderBufferKind.DEPTH, + RenderBufferKind.NORMALS, + RenderBufferKind.INSTANCE_SEGMENTATION_FAST, + } + + +def _make_camera_cfg(data_types: list[str]) -> CameraCfg: + return CameraCfg( + height=8, + width=16, + prim_path="/World/Camera", + spawn=_SPAWN, + data_types=data_types, + ) + + +def test_camera_data_allocates_supported_subset_and_aliases_rgb(): + """CameraData allocates the intersection of requested + supported and aliases rgb into rgba.""" + cfg = _make_camera_cfg(["rgb", "rgba", "depth"]) + specs = { + RenderBufferKind.RGBA: RenderBufferSpec(4, torch.uint8), + RenderBufferKind.RGB: RenderBufferSpec(3, torch.uint8), + RenderBufferKind.DEPTH: RenderBufferSpec(1, torch.float32), + RenderBufferKind.NORMALS: RenderBufferSpec(3, torch.float32), + } + data = CameraData.allocate( + data_types=cfg.data_types, height=8, width=16, num_views=2, device="cpu", supported_specs=specs + ) + + assert set(data.output.keys()) == {"rgba", "rgb", "depth"} + assert data.output["rgba"].shape == (2, 8, 16, 4) + assert data.output["rgba"].dtype == torch.uint8 + assert data.output["depth"].shape == (2, 8, 16, 1) + assert data.output["depth"].dtype == torch.float32 + assert data.output["rgb"].data_ptr() == data.output["rgba"].data_ptr() + assert data.image_shape == (8, 16) + assert data.info == {"rgba": None, "rgb": None, "depth": None} + + +def test_camera_data_drops_requested_types_not_in_supported_specs(): + """Requested types absent from supported_specs are absent from data.output.""" + cfg = _make_camera_cfg(["rgb", "normals"]) + specs = { + RenderBufferKind.RGBA: RenderBufferSpec(4, torch.uint8), + RenderBufferKind.RGB: RenderBufferSpec(3, torch.uint8), + } + data = CameraData.allocate( + data_types=cfg.data_types, height=4, width=4, num_views=1, device="cpu", supported_specs=specs + ) + + assert "normals" not in data.output + assert {"rgb", "rgba"} <= set(data.output.keys()) + + +def test_camera_data_no_arg_construction_yields_empty_container(): + """Bare CameraData() produces an all-None container.""" + data = CameraData() + assert data.pos_w is None + assert data.quat_w_world is None + assert data.intrinsic_matrices is None + assert data.output is None + assert data.info is None + assert data.image_shape is None + + +def test_camera_data_segmentation_dtype_follows_supported_spec(): + """CameraData consumes the layout dtype declared by the renderer spec.""" + cfg = _make_camera_cfg(["instance_segmentation_fast"]) + raw_specs = {RenderBufferKind.INSTANCE_SEGMENTATION_FAST: RenderBufferSpec(1, torch.int32)} + colorized_specs = {RenderBufferKind.INSTANCE_SEGMENTATION_FAST: RenderBufferSpec(4, torch.uint8)} + + raw = CameraData.allocate( + data_types=cfg.data_types, height=4, width=4, num_views=1, device="cpu", supported_specs=raw_specs + ) + colorized = CameraData.allocate( + data_types=cfg.data_types, height=4, width=4, num_views=1, device="cpu", supported_specs=colorized_specs + ) + + assert raw.output["instance_segmentation_fast"].dtype == torch.int32 + assert raw.output["instance_segmentation_fast"].shape == (1, 4, 4, 1) + assert colorized.output["instance_segmentation_fast"].dtype == torch.uint8 + assert colorized.output["instance_segmentation_fast"].shape == (1, 4, 4, 4) + + +def test_camera_data_allocate_raises_on_unknown_name(): + """An unknown data_types name raises ValueError naming the offender.""" + supported_specs = {RenderBufferKind.RGBA: RenderBufferSpec(4, torch.uint8)} + with pytest.raises(ValueError) as exc_info: + CameraData.allocate( + data_types=["not_a_real_type"], + height=4, + width=4, + num_views=1, + device="cpu", + supported_specs=supported_specs, + ) + assert "not_a_real_type" in str(exc_info.value) + assert "RenderBufferKind" in str(exc_info.value) diff --git a/source/isaaclab/test/renderers/test_renderer_factory.py b/source/isaaclab/test/renderers/test_renderer_factory.py index 398c55fd0bd7..66bd76fba598 100644 --- a/source/isaaclab/test/renderers/test_renderer_factory.py +++ b/source/isaaclab/test/renderers/test_renderer_factory.py @@ -28,10 +28,13 @@ class MockRenderer(BaseRenderer): def __init__(self, cfg=None): pass + def supported_output_types(self): + return {} + def prepare_stage(self, stage, num_envs): pass - def create_render_data(self, sensor): + def create_render_data(self, spec): return None def set_outputs(self, render_data, output_data): @@ -46,7 +49,7 @@ def update_camera(self, render_data, positions, orientations, intrinsics): def render(self, render_data): pass - def write_output(self, render_data, output_name, output_data): + def read_output(self, render_data, camera_data): pass def cleanup(self, render_data): diff --git a/source/isaaclab/test/renderers/test_simulation_render_context.py b/source/isaaclab/test/renderers/test_simulation_render_context.py new file mode 100644 index 000000000000..905643eefed1 --- /dev/null +++ b/source/isaaclab/test/renderers/test_simulation_render_context.py @@ -0,0 +1,207 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Tests for :class:`~isaaclab.renderers.render_context.RenderContext`.""" + +from __future__ import annotations + +from collections.abc import Generator +from typing import Any, cast +from unittest.mock import patch + +import pytest +import torch + +from isaaclab.renderers.base_renderer import BaseRenderer +from isaaclab.renderers.output_contract import RenderBufferKind, RenderBufferSpec +from isaaclab.renderers.render_context import RenderContext +from isaaclab.renderers.renderer_cfg import RendererCfg +from isaaclab.sensors.camera.camera_data import CameraData + +pytest.importorskip("isaaclab_physx") +pytest.importorskip("isaaclab_newton") +pytest.importorskip("isaaclab_ov") + +from isaaclab_newton.renderers import NewtonWarpRendererCfg +from isaaclab_physx.renderers import IsaacRtxRendererCfg + + +class _FakeBackend(BaseRenderer): + """Test double for :class:`BaseRenderer`; does not load PhysX/Newton/OV renderer classes.""" + + __slots__ = ("_prepare_hits", "_update_transforms_hits", "_event_log") + + def __init__( + self, + *, + prepare_hits: list[int] | None = None, + update_transforms_hits: list[int] | None = None, + event_log: list[str] | None = None, + ) -> None: + super().__init__() + self._prepare_hits = prepare_hits + self._update_transforms_hits = update_transforms_hits + self._event_log = event_log + + def supported_output_types(self) -> dict[RenderBufferKind, RenderBufferSpec]: + return {} + + def prepare_stage(self, stage: Any, num_envs: int) -> None: + if self._prepare_hits is not None: + self._prepare_hits.append(1) + + def create_render_data(self, spec: Any) -> Any: + return object() + + def set_outputs(self, render_data: Any, output_data: dict[str, torch.Tensor]) -> None: + pass + + def update_transforms(self) -> None: + if self._update_transforms_hits is not None: + self._update_transforms_hits.append(1) + if self._event_log is not None: + self._event_log.append("ut") + + def update_camera( + self, + render_data: Any, + positions: torch.Tensor, + orientations: torch.Tensor, + intrinsics: torch.Tensor, + ) -> None: + pass + + def render(self, render_data: Any) -> None: + if self._event_log is not None: + self._event_log.append("render") + + def read_output(self, render_data: Any, camera_data: CameraData) -> None: + if self._event_log is not None: + self._event_log.append("read") + + def cleanup(self, render_data: Any) -> None: + pass + + +def _set_entries(ctx: RenderContext, *cfg_backend_pairs: tuple[RendererCfg, BaseRenderer]) -> None: + ctx._renderer_entries = list(cfg_backend_pairs) # type: ignore[assignment] # noqa: SLF001 + + +@pytest.fixture(autouse=True) +def _patch_renderer_factory() -> Generator[None, None, None]: + """Never construct :class:`~isaaclab.renderers.renderer.Renderer` (real backends) in this module.""" + + with patch( + "isaaclab.renderers.render_context.Renderer", + side_effect=lambda *_args, **_kwargs: _FakeBackend(), + ): + yield + + +def test_get_renderer_returns_equal_cfg_singleton(): + ctx = RenderContext() + cfg = IsaacRtxRendererCfg() + r1 = ctx.get_renderer(cfg) + r2 = ctx.get_renderer(cfg) + assert r1 is r2 + + +def test_get_renderer_two_different_concrete_types_coexist(): + """Different renderer_cfg concrete classes register distinct backends (no error).""" + + ctx = RenderContext() + rtx = ctx.get_renderer(IsaacRtxRendererCfg()) + nw = ctx.get_renderer(NewtonWarpRendererCfg()) + assert rtx is not nw + + +def test_ensure_prepare_stage_idempotent(): + """Second ``ensure_prepare_stage`` with same args does not call ``prepare_stage`` again.""" + + ctx = RenderContext() + prepares: list[int] = [] + cfg = IsaacRtxRendererCfg() + _set_entries(ctx, (cfg, _FakeBackend(prepare_hits=prepares))) + + ctx.ensure_prepare_stage(None, 4) + ctx.ensure_prepare_stage(None, 4) + assert len(prepares) == 1 + + +def test_ensure_prepare_stage_num_envs_mismatch(): + ctx = RenderContext() + cfg = IsaacRtxRendererCfg() + _set_entries(ctx, (cfg, _FakeBackend())) + + ctx.ensure_prepare_stage(None, 4) + with pytest.raises(RuntimeError, match="different num_envs"): + ctx.ensure_prepare_stage(None, 8) + + +def test_update_transforms_dedupes_per_physics_step(): + """All backends' update_transforms run once per physics step index.""" + + ctx = RenderContext() + hits: list[int] = [] + cfg = NewtonWarpRendererCfg() + _set_entries(ctx, (cfg, _FakeBackend(update_transforms_hits=hits))) + + ctx.update_transforms(1) + ctx.update_transforms(1) + assert len(hits) == 1 + + ctx.update_transforms(2) + assert len(hits) == 2 + + +def test_render_into_camera_calls_update_render_read_order(): + """render_into_camera runs update_transforms then render then read_output; dedupes UT per step.""" + ctx = RenderContext() + events: list[str] = [] + cfg = IsaacRtxRendererCfg() + fake = _FakeBackend(event_log=events) + _set_entries(ctx, (cfg, fake)) + + rd = object() + cam_data = CameraData() + ctx.render_into_camera(cast(BaseRenderer, fake), rd, cam_data, physics_step_count=1) + assert events == ["ut", "render", "read"] + + ctx.render_into_camera(cast(BaseRenderer, fake), rd, cam_data, physics_step_count=1) + assert events == ["ut", "render", "read", "render", "read"] + + +def test_reset_stage_prepare_flag_allows_second_prepare_stage(): + """After reset_stage_prepare_flag, ensure_prepare_stage invokes prepare_stage again.""" + ctx = RenderContext() + prepares: list[int] = [] + cfg = IsaacRtxRendererCfg() + _set_entries(ctx, (cfg, _FakeBackend(prepare_hits=prepares))) + + ctx.ensure_prepare_stage(None, 4) + assert len(prepares) == 1 + ctx.ensure_prepare_stage(None, 4) + assert len(prepares) == 1 + + ctx.reset_stage_prepare_flag() + ctx.ensure_prepare_stage(None, 4) + assert len(prepares) == 2 + + +def test_reset_transform_cadence_allows_repeat_update_transforms_same_step(): + """reset_transform_cadence clears step dedupe so the same physics_step_count can sync again.""" + ctx = RenderContext() + hits: list[int] = [] + cfg = IsaacRtxRendererCfg() + _set_entries(ctx, (cfg, _FakeBackend(update_transforms_hits=hits))) + + ctx.update_transforms(1) + assert len(hits) == 1 + ctx.update_transforms(1) + assert len(hits) == 1 + + ctx.reset_transform_cadence() + ctx.update_transforms(1) + assert len(hits) == 2 diff --git a/source/isaaclab/test/scene/check_interactive_scene.py b/source/isaaclab/test/scene/check_interactive_scene.py index 5b2463b315a9..df0c4a12a945 100644 --- a/source/isaaclab/test/scene/check_interactive_scene.py +++ b/source/isaaclab/test/scene/check_interactive_scene.py @@ -103,8 +103,8 @@ def main(): print("[INFO]: Setup complete...") # default joint targets - robot_1_actions = scene.articulations["robot_1"].data.default_joint_pos.clone() - robot_2_actions = scene.articulations["robot_2"].data.default_joint_pos.clone() + robot_1_actions = scene.articulations["robot_1"].data.default_joint_pos.torch.clone() + robot_2_actions = scene.articulations["robot_2"].data.default_joint_pos.torch.clone() # Define simulation stepping sim_dt = sim.get_physics_dt() sim_time = 0.0 @@ -124,10 +124,10 @@ def main(): sim_time = 0.0 count = 0 # reset root state - root_state = scene.articulations["robot_1"].data.default_root_state.clone() + root_state = scene.articulations["robot_1"].data.default_root_state.torch.clone() root_state[:, :3] += scene.env_origins - joint_pos = scene.articulations["robot_1"].data.default_joint_pos - joint_vel = scene.articulations["robot_1"].data.default_joint_vel + joint_pos = scene.articulations["robot_1"].data.default_joint_pos.torch + joint_vel = scene.articulations["robot_1"].data.default_joint_vel.torch # -- set root state # -- robot 1 scene.articulations["robot_1"].write_root_pose_to_sim(root_state[:, :7]) diff --git a/source/isaaclab/test/scene/test_interactive_scene.py b/source/isaaclab/test/scene/test_interactive_scene.py index 087474baa59e..31b577db634f 100644 --- a/source/isaaclab/test/scene/test_interactive_scene.py +++ b/source/isaaclab/test/scene/test_interactive_scene.py @@ -12,15 +12,16 @@ """Rest everything follows.""" +import contextlib from types import SimpleNamespace import pytest import torch -import warp as wp import isaaclab.sim as sim_utils from isaaclab.actuators import ImplicitActuatorCfg from isaaclab.assets import ArticulationCfg, RigidObjectCfg +from isaaclab.physics.scene_data_requirements import SceneDataRequirement from isaaclab.scene import InteractiveScene, InteractiveSceneCfg from isaaclab.sim import build_simulation_context from isaaclab.utils import configclass @@ -84,8 +85,8 @@ def test_relative_flag(device, setup_scene): # test is relative == False prev_state = scene.get_state(is_relative=False) scene["robot"].write_joint_state_to_sim( - position=torch.rand_like(wp.to_torch(scene["robot"].data.joint_pos)), - velocity=torch.rand_like(wp.to_torch(scene["robot"].data.joint_pos)), + position=torch.rand_like(scene["robot"].data.joint_pos.torch), + velocity=torch.rand_like(scene["robot"].data.joint_pos.torch), ) next_state = scene.get_state(is_relative=False) assert_state_different(prev_state, next_state) @@ -95,8 +96,8 @@ def test_relative_flag(device, setup_scene): # test is relative == True prev_state = scene.get_state(is_relative=True) scene["robot"].write_joint_state_to_sim( - position=torch.rand_like(wp.to_torch(scene["robot"].data.joint_pos)), - velocity=torch.rand_like(wp.to_torch(scene["robot"].data.joint_pos)), + position=torch.rand_like(scene["robot"].data.joint_pos.torch), + velocity=torch.rand_like(scene["robot"].data.joint_pos.torch), ) next_state = scene.get_state(is_relative=True) assert_state_different(prev_state, next_state) @@ -114,26 +115,50 @@ def test_reset_to_env_ids_input_types(device, setup_scene): # test env_ids = None prev_state = scene.get_state() scene["robot"].write_joint_state_to_sim( - position=torch.rand_like(wp.to_torch(scene["robot"].data.joint_pos)), - velocity=torch.rand_like(wp.to_torch(scene["robot"].data.joint_pos)), + position=torch.rand_like(scene["robot"].data.joint_pos.torch), + velocity=torch.rand_like(scene["robot"].data.joint_pos.torch), ) scene.reset_to(prev_state, env_ids=None) assert_state_equal(prev_state, scene.get_state()) # test env_ids = torch tensor scene["robot"].write_joint_state_to_sim( - position=torch.rand_like(wp.to_torch(scene["robot"].data.joint_pos)), - velocity=torch.rand_like(wp.to_torch(scene["robot"].data.joint_pos)), + position=torch.rand_like(scene["robot"].data.joint_pos.torch), + velocity=torch.rand_like(scene["robot"].data.joint_pos.torch), ) scene.reset_to(prev_state, env_ids=torch.arange(scene.num_envs, device=scene.device, dtype=torch.int32)) assert_state_equal(prev_state, scene.get_state()) -def test_clone_environments_non_cfg_invokes_visualizer_clone_fn(monkeypatch: pytest.MonkeyPatch): - """Non-cfg clone path should execute visualizer clone callback with replicate args.""" +def test_clone_environments_non_cfg_publishes_clone_plans(monkeypatch: pytest.MonkeyPatch): + """Non-cfg clone path must dispatch physics + USD replicate and publish a ``ClonePlan``. + + Replaces the old test that asserted a per-call visualizer clone callback was invoked. The + visualizer-fn callback was removed in favor of providers reading + :meth:`SimulationContext.get_clone_plans`; this test asserts the new contract: even + without prototype templates, the scene synthesizes a single trivial ClonePlan. + """ + from isaaclab.cloner import ClonePlan + scene = object.__new__(InteractiveScene) scene.cfg = SimpleNamespace(replicate_physics=False, num_envs=3) scene.stage = object() + scene.physics_backend = "physx" + scene._sensors = {} + + set_plans_calls: list = [] + sim_state: dict = {"plans": {}} + + def _set_clone_plans(plans): + sim_state["plans"] = plans + set_plans_calls.append(plans) + + scene.sim = SimpleNamespace( + get_scene_data_requirements=lambda: SceneDataRequirement(), + update_scene_data_requirements=lambda requirements: None, + set_clone_plans=_set_clone_plans, + get_clone_plans=lambda: sim_state["plans"], + ) scene.env_fmt = "/World/envs/env_{}" scene._ALL_INDICES = torch.arange(3, dtype=torch.long) scene._default_env_origins = torch.zeros((3, 3), dtype=torch.float32) @@ -142,41 +167,82 @@ def test_clone_environments_non_cfg_invokes_visualizer_clone_fn(monkeypatch: pyt # Avoid binding this unit test to global SimulationContext singleton state. monkeypatch.setattr(InteractiveScene, "device", property(lambda self: "cpu")) + # ``disabled_fabric_change_notifies`` resolves the stage via UsdUtils.StageCache and would + # crash on the bare ``object()`` mocked above. This unit test exercises clone-dispatch + # logic only; the fabric notice path has its own coverage in ``test_cloner.py``. + @contextlib.contextmanager + def _noop_fabric_notices(stage, *, restore=True): + yield + + monkeypatch.setattr("isaaclab.scene.interactive_scene.cloner.disabled_fabric_change_notifies", _noop_fabric_notices) + physics_calls = [] - visualizer_calls = [] usd_calls = [] def _physics_clone_fn(stage, *args, **kwargs): physics_calls.append((stage, args, kwargs)) - def _visualizer_clone_fn(stage, *args, **kwargs): - visualizer_calls.append((stage, args, kwargs)) - def _usd_replicate(stage, *args, **kwargs): usd_calls.append((stage, args, kwargs)) scene.cloner_cfg = SimpleNamespace( device="cpu", physics_clone_fn=_physics_clone_fn, - visualizer_clone_fn=_visualizer_clone_fn, + clone_usd=True, ) monkeypatch.setattr("isaaclab.scene.interactive_scene.cloner.usd_replicate", _usd_replicate) scene.clone_environments(copy_from_source=False) assert len(physics_calls) == 1 - assert len(visualizer_calls) == 1 assert len(usd_calls) == 1 mapping = physics_calls[0][1][3] assert mapping.dtype == torch.bool assert mapping.shape == (1, scene.num_envs) + # Plans are published once per clone, regardless of physics/usd flag combinations. + assert len(set_plans_calls) == 1 + plans = set_plans_calls[-1] + assert set(plans.keys()) == {scene.env_fmt} + plan = plans[scene.env_fmt] + assert isinstance(plan, ClonePlan) + assert plan.dest_template == scene.env_fmt + assert plan.prototype_paths == [scene.env_fmt.format(0)] + assert plan.clone_mask.shape == (1, scene.num_envs) + assert scene.clone_plans is plans physics_calls.clear() - visualizer_calls.clear() usd_calls.clear() + set_plans_calls.clear() scene.clone_environments(copy_from_source=True) assert len(physics_calls) == 0 - assert len(visualizer_calls) == 1 assert len(usd_calls) == 1 + assert len(set_plans_calls) == 1 + + +def test_aggregate_scene_data_requirements_merges_visualizers_and_renderers(monkeypatch: pytest.MonkeyPatch): + """Scene aggregation must OR visualizer and sensor-renderer requirements onto sim context. + + Replaces the old test that asserted a clone-time visualizer hook was installed from + requirements. The hook is gone; the only remaining behavior is publishing the merged + :class:`SceneDataRequirement` to the simulation context. + """ + scene = object.__new__(InteractiveScene) + scene.physics_backend = "physx" + scene.stage = object() + scene._sensors = { + "cam": SimpleNamespace(cfg=SimpleNamespace(renderer_cfg=SimpleNamespace(renderer_type="newton_warp"))) + } + + posted: list = [] + scene.sim = SimpleNamespace( + get_scene_data_requirements=lambda: SceneDataRequirement(), + update_scene_data_requirements=posted.append, + ) + + scene._aggregate_scene_data_requirements({"rerun"}) + + assert len(posted) == 1 + merged = posted[0] + assert merged.requires_newton_model def assert_state_equal(s1: dict, s2: dict, path=""): diff --git a/source/isaaclab/test/sensors/check_multi_mesh_ray_caster.py b/source/isaaclab/test/sensors/check_multi_mesh_ray_caster.py index 03221e1ce366..eed776431279 100644 --- a/source/isaaclab/test/sensors/check_multi_mesh_ray_caster.py +++ b/source/isaaclab/test/sensors/check_multi_mesh_ray_caster.py @@ -46,10 +46,9 @@ import torch -from isaacsim.core.cloner import GridCloner - import isaaclab.sim as sim_utils import isaaclab.terrains as terrain_gen +from isaaclab import cloner as lab_cloner from isaaclab.assets import RigidObject, RigidObjectCfg from isaaclab.sensors.ray_caster import MultiMeshRayCaster, MultiMeshRayCasterCfg, patterns from isaaclab.sim import SimulationCfg, SimulationContext @@ -63,8 +62,10 @@ def design_scene(sim: SimulationContext, num_envs: int = 2048): """Design the scene.""" # Create interface to clone the scene - cloner = GridCloner(spacing=10.0, stage=sim.stage) - cloner.define_base_env("/World/envs") + # Create environment clones using Lab's cloner utilities + env_fmt = "/World/envs/env_{}" + env_ids = torch.arange(num_envs, dtype=torch.long, device=sim.device) + env_origins, _ = lab_cloner.grid_transforms(num_envs, spacing=10.0, device=sim.device) # Everything under the namespace "/World/envs/env_0" will be cloned sim.stage.DefinePrim("/World/envs/env_0", "Xform") # Define the scene @@ -99,12 +100,11 @@ def design_scene(sim: SimulationContext, num_envs: int = 2048): ) # Clone the scene - cloner.define_base_env("/World/envs") - envs_prim_paths = cloner.generate_paths("/World/envs/env", num_paths=num_envs) - cloner.clone(source_prim_path="/World/envs/env_0", prim_paths=envs_prim_paths, replicate_physics=True) + envs_prim_paths = [f"/World/envs/env_{i}" for i in range(num_envs)] + lab_cloner.usd_replicate(sim.stage, [env_fmt.format(0)], [env_fmt], env_ids, positions=env_origins) physics_scene_path = sim.get_physics_context().prim_path - cloner.filter_collisions( - physics_scene_path, "/World/collisions", prim_paths=envs_prim_paths, global_paths=["/World/ground"] + lab_cloner.filter_collisions( + sim.stage, physics_scene_path, "/World/collisions", prim_paths=envs_prim_paths, global_paths=["/World/ground"] ) @@ -142,7 +142,7 @@ def main(): prim_path="/World/envs/env_.*/ball", mesh_prim_paths=mesh_targets, pattern_cfg=patterns.GridPatternCfg(resolution=0.1, size=(1.6, 1.0)), - attach_yaw_only=True, + ray_alignment="yaw", debug_vis=not args_cli.headless, ) ray_caster = MultiMeshRayCaster(cfg=ray_caster_cfg) @@ -164,8 +164,8 @@ def main(): print(ray_caster) # Get the initial positions of the balls - ball_initial_poses = balls.data.root_pose_w.clone() - ball_initial_velocities = balls.data.root_vel_w.clone() + ball_initial_poses = balls.data.root_pose_w.torch.clone() + ball_initial_velocities = balls.data.root_vel_w.torch.clone() # Create a counter for resetting the scene step_count = 0 diff --git a/source/isaaclab/test/sensors/check_ray_caster.py b/source/isaaclab/test/sensors/check_ray_caster.py index 5e1e88472ae5..821fc247743e 100644 --- a/source/isaaclab/test/sensors/check_ray_caster.py +++ b/source/isaaclab/test/sensors/check_ray_caster.py @@ -41,10 +41,9 @@ import torch -from isaacsim.core.cloner import GridCloner - import isaaclab.sim as sim_utils import isaaclab.terrains as terrain_gen +from isaaclab import cloner as lab_cloner from isaaclab.assets import RigidObject, RigidObjectCfg from isaaclab.sensors.ray_caster import RayCaster, RayCasterCfg, patterns from isaaclab.sim import SimulationCfg, SimulationContext @@ -57,8 +56,10 @@ def design_scene(sim: SimulationContext, num_envs: int = 2048): """Design the scene.""" # Create interface to clone the scene - cloner = GridCloner(spacing=2.0, stage=sim.stage) - cloner.define_base_env("/World/envs") + # Create environment clones using Lab's cloner utilities + env_fmt = "/World/envs/env_{}" + env_ids = torch.arange(num_envs, dtype=torch.long, device=sim.device) + env_origins, _ = lab_cloner.grid_transforms(num_envs, spacing=2.0, device=sim.device) # Everything under the namespace "/World/envs/env_0" will be cloned sim.stage.DefinePrim("/World/envs/env_0", "Xform") # Define the scene @@ -75,12 +76,11 @@ def design_scene(sim: SimulationContext, num_envs: int = 2048): ) cfg.func("/World/envs/env_0/ball", cfg, translation=(0.0, 0.0, 5.0)) # Clone the scene - cloner.define_base_env("/World/envs") - envs_prim_paths = cloner.generate_paths("/World/envs/env", num_paths=num_envs) - cloner.clone(source_prim_path="/World/envs/env_0", prim_paths=envs_prim_paths, replicate_physics=True) + envs_prim_paths = [f"/World/envs/env_{i}" for i in range(num_envs)] + lab_cloner.usd_replicate(sim.stage, [env_fmt.format(0)], [env_fmt], env_ids, positions=env_origins) physics_scene_path = sim.get_physics_context().prim_path - cloner.filter_collisions( - physics_scene_path, "/World/collisions", prim_paths=envs_prim_paths, global_paths=["/World/ground"] + lab_cloner.filter_collisions( + sim.stage, physics_scene_path, "/World/collisions", prim_paths=envs_prim_paths, global_paths=["/World/ground"] ) @@ -133,8 +133,8 @@ def main(): print(ray_caster) # Get the initial positions of the balls - ball_initial_poses = balls.data.root_pose_w.clone() - ball_initial_velocities = balls.data.root_vel_w.clone() + ball_initial_poses = balls.data.root_pose_w.torch.clone() + ball_initial_velocities = balls.data.root_vel_w.torch.clone() # Create a counter for resetting the scene step_count = 0 diff --git a/source/isaaclab/test/sensors/test_camera.py b/source/isaaclab/test/sensors/test_camera.py index f1effb9a70e7..daed8e95773d 100644 --- a/source/isaaclab/test/sensors/test_camera.py +++ b/source/isaaclab/test/sensors/test_camera.py @@ -29,6 +29,8 @@ import isaaclab.sim as sim_utils from isaaclab.sensors.camera import Camera, CameraCfg +pytestmark = pytest.mark.isaacsim_ci + # sample camera poses POSITION = (2.5, 2.5, 2.5) # Quaternions in xyzw format @@ -109,7 +111,7 @@ def test_camera_init(setup_sim_camera): assert camera.data.quat_w_opengl.shape == (1, 4) assert camera.data.intrinsic_matrices.shape == (1, 3, 3) assert camera.data.image_shape == (camera_cfg.height, camera_cfg.width) - assert camera.data.info == [{camera_cfg.data_types[0]: None}] + assert camera.data.info == {camera_cfg.data_types[0]: None} # Simulate physics for _ in range(10): @@ -406,12 +408,12 @@ def test_depth_clipping(setup_sim_camera): camera_cfg_none = copy.deepcopy(camera_cfg_zero) camera_cfg_none.prim_path = "/World/CameraNone" - camera_cfg_none.depth_clipping_behavior = "none" + camera_cfg_none.renderer_cfg.depth_clipping_behavior = "none" camera_none = Camera(camera_cfg_none) camera_cfg_max = copy.deepcopy(camera_cfg_zero) camera_cfg_max.prim_path = "/World/CameraMax" - camera_cfg_max.depth_clipping_behavior = "max" + camera_cfg_max.renderer_cfg.depth_clipping_behavior = "max" camera_max = Camera(camera_cfg_max) # Play sim @@ -502,9 +504,9 @@ def test_camera_resolution_all_colorize(setup_sim_camera): "instance_segmentation_fast", "instance_id_segmentation_fast", ] - camera_cfg.colorize_instance_id_segmentation = True - camera_cfg.colorize_instance_segmentation = True - camera_cfg.colorize_semantic_segmentation = True + camera_cfg.renderer_cfg.colorize_instance_id_segmentation = True + camera_cfg.renderer_cfg.colorize_instance_segmentation = True + camera_cfg.renderer_cfg.colorize_semantic_segmentation = True # Create camera camera = Camera(camera_cfg) @@ -564,9 +566,9 @@ def test_camera_resolution_no_colorize(setup_sim_camera): "instance_segmentation_fast", "instance_id_segmentation_fast", ] - camera_cfg.colorize_instance_id_segmentation = False - camera_cfg.colorize_instance_segmentation = False - camera_cfg.colorize_semantic_segmentation = False + camera_cfg.renderer_cfg.colorize_instance_id_segmentation = False + camera_cfg.renderer_cfg.colorize_instance_segmentation = False + camera_cfg.renderer_cfg.colorize_semantic_segmentation = False # Create camera camera = Camera(camera_cfg) @@ -625,9 +627,9 @@ def test_camera_large_resolution_all_colorize(setup_sim_camera): "instance_segmentation_fast", "instance_id_segmentation_fast", ] - camera_cfg.colorize_instance_id_segmentation = True - camera_cfg.colorize_instance_segmentation = True - camera_cfg.colorize_semantic_segmentation = True + camera_cfg.renderer_cfg.colorize_instance_id_segmentation = True + camera_cfg.renderer_cfg.colorize_instance_segmentation = True + camera_cfg.renderer_cfg.colorize_semantic_segmentation = True camera_cfg.width = 512 camera_cfg.height = 512 # Create camera @@ -797,6 +799,368 @@ def test_sensor_print(setup_sim_camera): print(sensor) +def setup_with_device(device) -> tuple[sim_utils.SimulationContext, CameraCfg, float]: + camera_cfg = CameraCfg( + height=128, + width=256, + offset=CameraCfg.OffsetCfg(pos=(0.0, 0.0, 4.0), rot=(0.0, 1.0, 0.0, 0.0), convention="ros"), + prim_path="/World/Camera", + update_period=0, + data_types=["rgb", "distance_to_camera"], + spawn=sim_utils.PinholeCameraCfg( + focal_length=24.0, focus_distance=400.0, horizontal_aperture=20.955, clipping_range=(0.1, 1.0e5) + ), + ) + sim_utils.create_new_stage() + dt = 0.01 + sim_cfg = sim_utils.SimulationCfg(dt=dt, device=device) + sim = sim_utils.SimulationContext(sim_cfg) + _populate_scene() + sim_utils.update_stage() + return sim, camera_cfg, dt + + +@pytest.fixture(scope="function") +def setup_camera_device(device): + """Fixture with explicit device parametrization for GPU/CPU testing.""" + sim, camera_cfg, dt = setup_with_device(device) + yield sim, camera_cfg, dt + teardown(sim) + + +@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) +def test_camera_multi_regex_init(setup_camera_device, device): + """Test multi-camera initialization with regex prim paths and content validation.""" + sim, camera_cfg, dt = setup_camera_device + + num_cameras = 9 + for i in range(num_cameras): + sim_utils.create_prim(f"/World/Origin_{i}", "Xform") + + camera_cfg = copy.deepcopy(camera_cfg) + camera_cfg.prim_path = "/World/Origin_.*/CameraSensor" + camera = Camera(camera_cfg) + + sim.reset() + + assert camera.is_initialized + assert camera._sensor_prims[1].GetPath().pathString == "/World/Origin_1/CameraSensor" + assert isinstance(camera._sensor_prims[0], UsdGeom.Camera) + + assert camera.data.pos_w.shape == (num_cameras, 3) + assert camera.data.quat_w_ros.shape == (num_cameras, 4) + assert camera.data.quat_w_world.shape == (num_cameras, 4) + assert camera.data.quat_w_opengl.shape == (num_cameras, 4) + assert camera.data.intrinsic_matrices.shape == (num_cameras, 3, 3) + assert camera.data.image_shape == (camera_cfg.height, camera_cfg.width) + + for _ in range(10): + sim.step() + camera.update(dt) + for im_type, im_data in camera.data.output.items(): + if im_type == "rgb": + assert im_data.shape == (num_cameras, camera_cfg.height, camera_cfg.width, 3) + for i in range(4): + assert (im_data[i] / 255.0).mean() > 0.0 + elif im_type == "distance_to_camera": + assert im_data.shape == (num_cameras, camera_cfg.height, camera_cfg.width, 1) + for i in range(4): + assert im_data[i].mean() > 0.0 + del camera + + +@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) +def test_camera_all_annotators(setup_camera_device, device): + """Test all supported annotators produce correct shapes, dtypes, content, and info.""" + sim, camera_cfg, dt = setup_camera_device + all_annotator_types = [ + "rgb", + "rgba", + "albedo", + "depth", + "distance_to_camera", + "distance_to_image_plane", + "normals", + "motion_vectors", + "semantic_segmentation", + "instance_segmentation_fast", + "instance_id_segmentation_fast", + ] + + num_cameras = 9 + for i in range(num_cameras): + sim_utils.create_prim(f"/World/Origin_{i}", "Xform") + + camera_cfg = copy.deepcopy(camera_cfg) + camera_cfg.data_types = all_annotator_types + camera_cfg.prim_path = "/World/Origin_.*/CameraSensor" + camera = Camera(camera_cfg) + + sim.reset() + + assert camera.is_initialized + assert sorted(camera.data.output.keys()) == sorted(all_annotator_types) + + for _ in range(10): + sim.step() + camera.update(dt) + for data_type, im_data in camera.data.output.items(): + if data_type in ["rgb", "normals"]: + assert im_data.shape == (num_cameras, camera_cfg.height, camera_cfg.width, 3) + elif data_type in [ + "rgba", + "albedo", + "semantic_segmentation", + "instance_segmentation_fast", + "instance_id_segmentation_fast", + ]: + assert im_data.shape == (num_cameras, camera_cfg.height, camera_cfg.width, 4) + for i in range(num_cameras): + assert (im_data[i] / 255.0).mean() > 0.0 + elif data_type in ["motion_vectors"]: + assert im_data.shape == (num_cameras, camera_cfg.height, camera_cfg.width, 2) + for i in range(num_cameras): + assert im_data[i].mean() != 0.0 + elif data_type in ["depth", "distance_to_camera", "distance_to_image_plane"]: + assert im_data.shape == (num_cameras, camera_cfg.height, camera_cfg.width, 1) + for i in range(num_cameras): + assert im_data[i].mean() > 0.0 + + output = camera.data.output + info = camera.data.info + assert output["rgb"].dtype == torch.uint8 + assert output["rgba"].dtype == torch.uint8 + assert output["albedo"].dtype == torch.uint8 + assert output["depth"].dtype == torch.float + assert output["distance_to_camera"].dtype == torch.float + assert output["distance_to_image_plane"].dtype == torch.float + assert output["normals"].dtype == torch.float + assert output["motion_vectors"].dtype == torch.float + assert output["semantic_segmentation"].dtype == torch.uint8 + assert output["instance_segmentation_fast"].dtype == torch.uint8 + assert output["instance_id_segmentation_fast"].dtype == torch.uint8 + assert isinstance(info["semantic_segmentation"], dict) + assert isinstance(info["instance_segmentation_fast"], dict) + assert isinstance(info["instance_id_segmentation_fast"], dict) + + del camera + + +@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) +def test_camera_segmentation_non_colorize(setup_camera_device, device): + """Test segmentation outputs with colorization disabled produce correct dtypes and info.""" + sim, camera_cfg, dt = setup_camera_device + num_cameras = 9 + for i in range(num_cameras): + sim_utils.create_prim(f"/World/Origin_{i}", "Xform") + + camera_cfg = copy.deepcopy(camera_cfg) + camera_cfg.data_types = ["semantic_segmentation", "instance_segmentation_fast", "instance_id_segmentation_fast"] + camera_cfg.prim_path = "/World/Origin_.*/CameraSensor" + camera_cfg.renderer_cfg.colorize_semantic_segmentation = False + camera_cfg.renderer_cfg.colorize_instance_segmentation = False + camera_cfg.renderer_cfg.colorize_instance_id_segmentation = False + camera = Camera(camera_cfg) + + sim.reset() + + for _ in range(5): + sim.step() + camera.update(dt) + + for seg_type in camera_cfg.data_types: + assert camera.data.output[seg_type].shape == (num_cameras, camera_cfg.height, camera_cfg.width, 1) + assert camera.data.output[seg_type].dtype == torch.int32 + assert isinstance(camera.data.info[seg_type], dict) + + del camera + + +@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) +def test_camera_normals_unit_length(setup_camera_device, device): + """Test that normals output vectors have approximately unit length.""" + sim, camera_cfg, dt = setup_camera_device + num_cameras = 9 + for i in range(num_cameras): + sim_utils.create_prim(f"/World/Origin_{i}", "Xform") + + camera_cfg = copy.deepcopy(camera_cfg) + camera_cfg.data_types = ["normals"] + camera_cfg.prim_path = "/World/Origin_.*/CameraSensor" + camera = Camera(camera_cfg) + + sim.reset() + + for _ in range(10): + sim.step() + camera.update(dt) + im_data = camera.data.output["normals"] + assert im_data.shape == (num_cameras, camera_cfg.height, camera_cfg.width, 3) + for i in range(4): + assert im_data[i].mean() > 0.0 + norms = torch.linalg.norm(im_data, dim=-1) + assert torch.allclose(norms, torch.ones_like(norms), atol=1e-9) + + assert camera.data.output["normals"].dtype == torch.float + del camera + + +@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) +def test_camera_data_types_ordering(setup_camera_device, device): + """Test that requesting specific data types produces the expected output keys.""" + sim, camera_cfg, dt = setup_camera_device + camera_cfg_distance = copy.deepcopy(camera_cfg) + camera_cfg_distance.data_types = ["distance_to_camera"] + camera_cfg_distance.prim_path = "/World/CameraDistance" + camera_distance = Camera(camera_cfg_distance) + + camera_cfg_depth = copy.deepcopy(camera_cfg) + camera_cfg_depth.data_types = ["depth"] + camera_cfg_depth.prim_path = "/World/CameraDepth" + camera_depth = Camera(camera_cfg_depth) + + camera_cfg_both = copy.deepcopy(camera_cfg) + camera_cfg_both.data_types = ["distance_to_camera", "depth"] + camera_cfg_both.prim_path = "/World/CameraBoth" + camera_both = Camera(camera_cfg_both) + + sim.reset() + + assert camera_distance.is_initialized + assert camera_depth.is_initialized + assert camera_both.is_initialized + assert list(camera_distance.data.output.keys()) == ["distance_to_camera"] + assert list(camera_depth.data.output.keys()) == ["depth"] + assert list(camera_both.data.output.keys()) == ["depth", "distance_to_camera"] + + del camera_distance + del camera_depth + del camera_both + + +@pytest.mark.parametrize("device", ["cuda:0"]) +def test_camera_frame_offset(setup_camera_device, device): + """Test that camera reflects scene color changes without frame-offset lag.""" + sim, camera_cfg, dt = setup_camera_device + camera_cfg = copy.deepcopy(camera_cfg) + camera_cfg.height = 480 + camera_cfg.width = 480 + camera = Camera(camera_cfg) + + stage = sim_utils.get_current_stage() + for i in range(10): + prim = stage.GetPrimAtPath(f"/World/Objects/Obj_{i:02d}") + color = Gf.Vec3f(1, 1, 1) + UsdGeom.Gprim(prim).GetDisplayColorAttr().Set([color]) + + sim.reset() + + for _ in range(100): + sim.step() + camera.update(dt) + + image_before = camera.data.output["rgb"].clone() / 255.0 + + for i in range(10): + prim = stage.GetPrimAtPath(f"/World/Objects/Obj_{i:02d}") + color = Gf.Vec3f(0, 0, 0) + UsdGeom.Gprim(prim).GetDisplayColorAttr().Set([color]) + + sim.step() + camera.update(dt) + + image_after = camera.data.output["rgb"].clone() / 255.0 + + assert torch.abs(image_after - image_before).mean() > 0.01 + + del camera + + +def test_camera_warns_once_on_unsupported_data_types(setup_sim_camera, caplog): + """Test Camera warns once and drops data types its renderer cannot produce.""" + import logging + + from isaaclab.renderers import Renderer + from isaaclab.renderers.base_renderer import BaseRenderer + + sim, camera_cfg, dt = setup_sim_camera + camera_cfg = copy.deepcopy(camera_cfg) + camera_cfg.data_types = ["rgba", "depth", "normals"] + + from isaaclab.sensors.camera.camera_data import RenderBufferKind, RenderBufferSpec + + class _PartialRenderer(BaseRenderer): + """Publishes only ``rgba`` in its supported-output contract.""" + + def __init__(self, cfg=None): + self.cfg = cfg + + def supported_output_types(self): + return {RenderBufferKind.RGBA: RenderBufferSpec(4, torch.uint8)} + + def prepare_stage(self, stage, num_envs): + pass + + def create_render_data(self, sensor): + return object() + + def set_outputs(self, render_data, output_data): + pass + + def update_transforms(self): + pass + + def update_camera(self, render_data, positions, orientations, intrinsics): + pass + + def render(self, render_data): + pass + + def read_output(self, render_data, camera_data): + pass + + def cleanup(self, render_data): + pass + + backend = Renderer._get_backend(camera_cfg.renderer_cfg) + original = Renderer._registry.get(backend) + Renderer._registry[backend] = _PartialRenderer + try: + camera = Camera(camera_cfg) + caplog.clear() + with caplog.at_level(logging.WARNING, logger="isaaclab.sensors.camera.camera"): + sim.reset() + # Step a few frames and confirm the warning is emitted once at init. + for _ in range(3): + sim.step() + camera.update(dt) + + warning_records = [ + r for r in caplog.records if r.levelno == logging.WARNING and "does not support" in r.getMessage() + ] + assert len(warning_records) == 1, ( + f"Expected exactly one 'does not support' warning, got {len(warning_records)}:" + f" {[r.getMessage() for r in warning_records]}" + ) + msg = warning_records[0].getMessage() + assert "_PartialRenderer" in msg + assert "depth" in msg + assert "normals" in msg + assert "rgba" not in msg + + # Only the supported subset is in ``data.output``; the rest were dropped. + assert set(camera.data.output.keys()) == {"rgba"} + # ``data.info`` mirrors the ``data.output`` keys. + assert set(camera.data.info.keys()) == {"rgba"} + + del camera + finally: + if original is not None: + Renderer._registry[backend] = original + else: + Renderer._registry.pop(backend, None) + + def _populate_scene(): """Add prims to the scene.""" # Ground-plane diff --git a/source/isaaclab/test/sensors/test_first_frame_textured_rendering.py b/source/isaaclab/test/sensors/test_first_frame_textured_rendering.py index 9fef377fc13d..1c2ef0ec7b00 100644 --- a/source/isaaclab/test/sensors/test_first_frame_textured_rendering.py +++ b/source/isaaclab/test/sensors/test_first_frame_textured_rendering.py @@ -3,12 +3,6 @@ # # SPDX-License-Identifier: BSD-3-Clause -# TODO: These tests appear to be flaky because 3 warmup steps may not be enough for textures to stream in. -# A polling-based fix was prototyped in https://github.com/isaac-sim/IsaacLab/pull/5097 — see commits: -# 69e73530c84 Fix test_first_frame_textured_rendering (core 1/3): poll for texture load instead of fixed warmup -# 1a7c4036da1 Fix test_first_frame_textured_rendering.py (core 1/3) - increase warmup time -# 1632d3ae859 test_first_frame_textured_rendering.py: increase # of warmup steps - """Launch Isaac Sim Simulator first.""" from isaaclab.app import AppLauncher @@ -24,7 +18,7 @@ import omni.replicator.core as rep import isaaclab.sim as sim_utils -from isaaclab.sensors.camera import Camera, CameraCfg, TiledCamera, TiledCameraCfg +from isaaclab.sensors.camera import Camera, CameraCfg from isaaclab.utils.assets import ISAAC_NUCLEUS_DIR # resolution @@ -35,9 +29,6 @@ GREY_CHANNEL_TOLERANCE = 3.0 GREY_MEAN_THRESHOLD = 85.0 -# number of sim steps to warm up before capturing the first frame -WARMUP_STEPS = 3 - # number of extra sim steps before capturing the stabilised reference frame STABILISATION_STEPS = 5 @@ -53,6 +44,15 @@ CUBE_SCALE = (0.9, 0.9, 0.9) +def _is_grey(mean_rgb: torch.Tensor) -> bool: + """Return True if mean_rgb looks like the grey default material.""" + channels_equal = (mean_rgb[1] - mean_rgb[0]).abs() < GREY_CHANNEL_TOLERANCE and ( + mean_rgb[2] - mean_rgb[0] + ).abs() < GREY_CHANNEL_TOLERANCE + all_low = mean_rgb.mean() < GREY_MEAN_THRESHOLD + return bool(channels_equal and all_low) + + @pytest.fixture(scope="function") def setup_sim(device): """Fixture to set up and tear down the textured rendering test environment.""" @@ -78,16 +78,12 @@ def _assert_first_frame_textured(first_frame: torch.Tensor, stable_frame: torch. """Verify that first_frame shows loaded textures and is consistent with stable_frame.""" mean_first = first_frame.mean(dim=(0, 1)) mean_stable = stable_frame.mean(dim=(0, 1)) - # Guard 1: not the grey default material - channels_equal = (mean_first[1] - mean_first[0]).abs() < GREY_CHANNEL_TOLERANCE and ( - mean_first[2] - mean_first[0] - ).abs() < GREY_CHANNEL_TOLERANCE - all_low = mean_first.mean() < GREY_MEAN_THRESHOLD - assert not (channels_equal and all_low), ( + assert not _is_grey(mean_first), ( f"First frame looks like the grey default material " f"(mean RGB: {mean_first[0]:.1f}, {mean_first[1]:.1f}, {mean_first[2]:.1f}). " - "Texture streaming may not have completed before the first capture." + "The renderer's streaming wait (ensure_isaac_rtx_render_update) " + "may not have completed texture loading before the first capture." ) # Guard 2: first frame and stabilised frame are broadly consistent @@ -123,64 +119,14 @@ def test_first_frame_is_textured_camera(setup_sim, device): # Create camera camera = Camera(camera_cfg) - # Play sim - sim.reset() - - # Warm up the renderer so textures have time to stream in - for _ in range(WARMUP_STEPS): - sim.step() - - # Capture the first frame after warm-up - sim.step() - camera.update(dt) - first_frame = camera.data.output["rgb"][0].clone().to(dtype=torch.float32) - - # Let the renderer step, then capture the reference frame - for _ in range(STABILISATION_STEPS): - sim.step() - camera.update(dt) - stable_frame = camera.data.output["rgb"][0].clone().to(dtype=torch.float32) - - del camera - - _assert_first_frame_textured(first_frame, stable_frame) - - -@pytest.mark.parametrize("device", ["cuda:0"]) -@pytest.mark.isaacsim_ci -def test_first_frame_is_textured_tiled_camera(setup_sim, device): - """First RTX frame from a TiledCamera must show loaded textures, not a grey placeholder.""" - sim, dt = setup_sim - camera_cfg = TiledCameraCfg( - height=HEIGHT, - width=WIDTH, - offset=TiledCameraCfg.OffsetCfg(pos=(0.0, 0.0, 0.75), rot=(0.0, 1.0, 0.0, 0.0), convention="ros"), - prim_path="/World/Camera", - update_period=0, - data_types=["rgb"], - spawn=sim_utils.PinholeCameraCfg( - focal_length=24.0, - focus_distance=400.0, - horizontal_aperture=20.955, - clipping_range=(0.1, 1.0e5), - ), - ) - # Create camera - camera = TiledCamera(camera_cfg) - - # Play sim sim.reset() - # Warm up the renderer so textures have time to stream in - for _ in range(WARMUP_STEPS): - sim.step() - - # Capture the first frame after warm-up + # The first sim step + camera update should produce textured output sim.step() camera.update(dt) first_frame = camera.data.output["rgb"][0].clone().to(dtype=torch.float32) - # Let the renderer step, then capture the reference frame + # Let the renderer stabilise, then capture the reference frame for _ in range(STABILISATION_STEPS): sim.step() camera.update(dt) diff --git a/source/isaaclab/test/sensors/test_multi_mesh_ray_caster_camera.py b/source/isaaclab/test/sensors/test_multi_mesh_ray_caster_camera.py index 20aa300c7a4a..8657c938c691 100644 --- a/source/isaaclab/test/sensors/test_multi_mesh_ray_caster_camera.py +++ b/source/isaaclab/test/sensors/test_multi_mesh_ray_caster_camera.py @@ -138,7 +138,7 @@ def test_camera_init(setup_simulation): assert camera.data.quat_w_opengl.shape == (1, 4) assert camera.data.intrinsic_matrices.shape == (1, 3, 3) assert camera.data.image_shape == (camera_cfg.pattern_cfg.height, camera_cfg.pattern_cfg.width) - assert camera.data.info == [{camera_cfg.data_types[0]: None}] + assert camera.data.info == {camera_cfg.data_types[0]: None} # Simulate physics for _ in range(10): # perform rendering @@ -777,3 +777,35 @@ def test_output_equal_to_usd_camera_when_intrinsics_set(setup_simulation): ) del camera_usd, camera_warp + + +@pytest.mark.isaacsim_ci +def test_image_mesh_ids_identifies_hit_mesh(setup_simulation): + """image_mesh_ids must contain 0 for ground-plane hits (only one mesh registered).""" + sim, dt, camera_cfg = setup_simulation + + cfg = copy.deepcopy(camera_cfg) + cfg.update_mesh_ids = True + cfg.data_types = ["distance_to_camera"] + + camera = MultiMeshRayCasterCamera(cfg=cfg) + sim.reset() + camera.update(dt) + + mesh_ids = camera.data.image_mesh_ids # shape (N, H, W, 1), dtype torch.int16 + assert mesh_ids is not None, "image_mesh_ids should not be None when update_mesh_ids=True" + assert mesh_ids.shape[-1] == 1 + assert mesh_ids.dtype == torch.int16 + + # Identify actual hits via distance < inf. This relies on depth_clipping_behavior="none" + # (the default), which leaves missed rays at the Warp-kernel fill value of inf. + # Under "max" clipping, missed rays would be clamped to a finite max_distance, making + # the inf comparison incorrect. + hit_mask = camera.data.output["distance_to_camera"][0, :, :, 0] < float("inf") + assert hit_mask.any(), "Expected at least some rays to hit the ground plane" + + # All hits against the single registered mesh must carry mesh_id=0 (first mesh index). + hit_mesh_ids = mesh_ids[0, :, :, 0][hit_mask] + assert torch.all(hit_mesh_ids == 0), ( + f"All hits against the single ground mesh must have mesh_id=0, got: {hit_mesh_ids.unique()}" + ) diff --git a/source/isaaclab/test/sensors/test_multi_tiled_camera.py b/source/isaaclab/test/sensors/test_multi_tiled_camera.py index 6c90ce2696ca..113524cfe934 100644 --- a/source/isaaclab/test/sensors/test_multi_tiled_camera.py +++ b/source/isaaclab/test/sensors/test_multi_tiled_camera.py @@ -29,6 +29,10 @@ import isaaclab.sim as sim_utils from isaaclab.sensors.camera import TiledCamera, TiledCameraCfg +# Deprecation warnings from TiledCamera/TiledCameraCfg are expected in this file; +# the deprecation mechanism itself is validated in test_tiled_camera.py. +pytestmark = pytest.mark.filterwarnings("ignore::DeprecationWarning") + @pytest.fixture() def setup_camera(): diff --git a/source/isaaclab/test/sensors/test_ray_caster.py b/source/isaaclab/test/sensors/test_ray_caster.py index 944287c549b4..6ac63cf0d041 100644 --- a/source/isaaclab/test/sensors/test_ray_caster.py +++ b/source/isaaclab/test/sensors/test_ray_caster.py @@ -18,7 +18,9 @@ # Import after app launch import warp as wp -from isaaclab.utils.math import matrix_from_quat, quat_from_euler_xyz, random_orientation +from isaaclab.sensors.ray_caster.kernels import quat_yaw_only as _quat_yaw_only_func +from isaaclab.utils.math import matrix_from_quat, quat_from_euler_xyz, random_orientation, yaw_quat +from isaaclab.utils.warp.kernels import raycast_mesh_masked_kernel as _raycast_mesh_masked_kernel from isaaclab.utils.warp.ops import convert_to_warp_mesh, raycast_dynamic_meshes, raycast_mesh @@ -239,3 +241,282 @@ def test_raycast_random_cube(raycast_setup): torch.testing.assert_close(ray_distance, ray_distance_m) torch.testing.assert_close(ray_normal, ray_normal_m) torch.testing.assert_close(ray_face_id, ray_face_id_m) + + +## +# RayCaster sensor-level tests +## + + +def test_raycaster_offset_does_not_affect_pos_w(): + """Verify that cfg.offset.pos shifts ray starts but NOT data.pos_w. + + data.pos_w must reflect the parent body position so that downstream + observations like height_scan (pos_w_z - hit_z - 0.5) produce values + relative to the body, not relative to the offset sensor frame. + + Regression test: previously the offset was baked into the FrameView's + Xform local transform, causing data.pos_w to include the 20m offset + and breaking height-scan observations during training. + """ + import isaaclab.sim as sim_utils + from isaaclab.sensors.ray_caster import RayCaster, RayCasterCfg, patterns + from isaaclab.terrains.trimesh.utils import make_plane + from isaaclab.terrains.utils import create_prim_from_mesh + + sim_utils.create_new_stage() + + # ground plane at z=0 + mesh = make_plane(size=(100, 100), height=0.0, center_zero=True) + create_prim_from_mesh("/World/ground", mesh) + + # parent body at known position + body_pos = (0.0, 0.0, 0.6) + sim_utils.create_prim("/World/Robot", "Xform", translation=body_pos) + + # large z-offset to make the regression obvious + offset_z = 20.0 + cfg = RayCasterCfg( + prim_path="/World/Robot", + offset=RayCasterCfg.OffsetCfg(pos=(0.0, 0.0, offset_z)), + mesh_prim_paths=["/World/ground"], + pattern_cfg=patterns.GridPatternCfg(resolution=0.5, size=[1.0, 1.0]), + ray_alignment="yaw", + ) + + dt = 0.01 + sim = sim_utils.SimulationContext(sim_utils.SimulationCfg(dt=dt)) + + sensor = RayCaster(cfg) + sim.reset() + sensor.update(dt) + + # data.pos_w / data.ray_hits_w return ProxyArray wrappers; use .torch for tensor indexing. + pos_w = sensor.data.pos_w.torch[0].cpu() + + # pos_w.z should be near the body height, NOT body_height + offset + assert abs(pos_w[2].item() - body_pos[2]) < 1.0, ( + f"data.pos_w.z = {pos_w[2].item():.2f}, expected near body height {body_pos[2]}." + f" If pos_w.z ≈ {body_pos[2] + offset_z}, the offset was incorrectly baked into the FrameView." + ) + + # ray_hits should be near z=0 (ground plane) + hits_z = sensor.data.ray_hits_w.torch[0, :, 2].cpu() + valid = hits_z[~torch.isinf(hits_z)] + if len(valid) > 0: + assert valid.abs().max().item() < 2.0, ( + f"Ray hits z range [{valid.min().item():.2f}, {valid.max().item():.2f}] — expected near ground (z≈0)." + ) + + # height_scan observation: pos_w_z - hit_z - 0.5 should be small, not ~20 + if len(valid) > 0: + height_obs = pos_w[2].item() - valid.mean().item() - 0.5 + assert abs(height_obs) < 5.0, ( + f"height_scan observation = {height_obs:.2f}, expected near 0." + f" If ≈{offset_z}, the offset leaked into data.pos_w." + ) + + sim.stop() + sim.clear_instance() + + +# --------------------------------------------------------------------------- +# Tests for raycast_mesh_masked_kernel (new kernel in utils/warp/kernels.py) +# --------------------------------------------------------------------------- + +_SENTINEL = -2.0 # value pre-filled into output buffers; chosen outside [-1, 1] so it cannot +# equal any component of a unit-length surface normal, making "not written" assertions unambiguous. + + +def _make_masked_buffers(device, n_envs, n_rays): + """Allocate all warp buffers needed by raycast_mesh_masked_kernel. + + ray_dist_w and ray_normal_w are pre-filled with _SENTINEL so that tests can + meaningfully assert those buffers were *not* written when the corresponding + return flag is 0. + """ + ray_starts_w = wp.zeros((n_envs, n_rays), dtype=wp.vec3f, device=device) + ray_dirs_w = wp.zeros((n_envs, n_rays), dtype=wp.vec3f, device=device) + ray_hits_w = wp.zeros((n_envs, n_rays), dtype=wp.vec3f, device=device) + ray_dist_w = wp.zeros((n_envs, n_rays), dtype=wp.float32, device=device) + wp.to_torch(ray_dist_w).fill_(_SENTINEL) + ray_normal_w = wp.zeros((n_envs, n_rays), dtype=wp.vec3f, device=device) + wp.to_torch(ray_normal_w).fill_(_SENTINEL) + return ray_starts_w, ray_dirs_w, ray_hits_w, ray_dist_w, ray_normal_w + + +def test_raycast_mesh_masked_kernel_hits_only(raycast_setup): + """return_distance=0, return_normal=0: only ray_hits are written on a hit.""" + device = raycast_setup["device"] + mesh_id = raycast_setup["single_mesh_id"] + expected_hits = raycast_setup["expected_ray_hits"] # shape (1, 2, 3) + + n_envs, n_rays = 1, 2 + ray_starts_w, ray_dirs_w, ray_hits_w, ray_dist_w, ray_normal_w = _make_masked_buffers(device, n_envs, n_rays) + env_mask = wp.array([True], dtype=wp.bool, device=device) + + wp.to_torch(ray_starts_w)[:] = torch.tensor([[[0, -0.35, -5], [0.25, 0.35, -5]]], device=device) + wp.to_torch(ray_dirs_w)[:] = torch.tensor([[[0, 0, 1], [0, 0, 1]]], device=device) + wp.to_torch(ray_hits_w).fill_(float("inf")) + + wp.launch( + _raycast_mesh_masked_kernel, + dim=(n_envs, n_rays), + inputs=[mesh_id, env_mask, ray_starts_w, ray_dirs_w, float(1e6), 0, 0, ray_hits_w, ray_dist_w, ray_normal_w], + device=device, + ) + + torch.testing.assert_close(wp.to_torch(ray_hits_w), expected_hits) + assert torch.all(wp.to_torch(ray_dist_w) == _SENTINEL), "Distance buffer must not be written when return_distance=0" + assert torch.all(wp.to_torch(ray_normal_w) == _SENTINEL), "Normal buffer must not be written when return_normal=0" + + +def test_raycast_mesh_masked_kernel_with_distance(raycast_setup): + """return_distance=1: distances are written in addition to hits.""" + device = raycast_setup["device"] + mesh_id = raycast_setup["single_mesh_id"] + + n_envs, n_rays = 1, 2 + ray_starts_w, ray_dirs_w, ray_hits_w, ray_dist_w, ray_normal_w = _make_masked_buffers(device, n_envs, n_rays) + env_mask = wp.array([True], dtype=wp.bool, device=device) + + wp.to_torch(ray_starts_w)[:] = torch.tensor([[[0, -0.35, -5], [0.25, 0.35, -5]]], device=device) + wp.to_torch(ray_dirs_w)[:] = torch.tensor([[[0, 0, 1], [0, 0, 1]]], device=device) + wp.to_torch(ray_hits_w).fill_(float("inf")) + + wp.launch( + _raycast_mesh_masked_kernel, + dim=(n_envs, n_rays), + inputs=[mesh_id, env_mask, ray_starts_w, ray_dirs_w, float(1e6), 1, 0, ray_hits_w, ray_dist_w, ray_normal_w], + device=device, + ) + + # Cube bottom at z=-0.5, rays start at z=-5 going +z, distance = 4.5 + torch.testing.assert_close(wp.to_torch(ray_dist_w), torch.tensor([[4.5, 4.5]], device=device)) + assert torch.all(wp.to_torch(ray_normal_w) == _SENTINEL), "Normal buffer must not be written when return_normal=0" + + +def test_raycast_mesh_masked_kernel_with_normal(raycast_setup): + """return_distance=1, return_normal=1: both distances and surface normals are written.""" + device = raycast_setup["device"] + mesh_id = raycast_setup["single_mesh_id"] + + n_envs, n_rays = 1, 2 + ray_starts_w, ray_dirs_w, ray_hits_w, ray_dist_w, ray_normal_w = _make_masked_buffers(device, n_envs, n_rays) + env_mask = wp.array([True], dtype=wp.bool, device=device) + + wp.to_torch(ray_starts_w)[:] = torch.tensor([[[0, -0.35, -5], [0.25, 0.35, -5]]], device=device) + wp.to_torch(ray_dirs_w)[:] = torch.tensor([[[0, 0, 1], [0, 0, 1]]], device=device) + wp.to_torch(ray_hits_w).fill_(float("inf")) + + wp.launch( + _raycast_mesh_masked_kernel, + dim=(n_envs, n_rays), + inputs=[mesh_id, env_mask, ray_starts_w, ray_dirs_w, float(1e6), 1, 1, ray_hits_w, ray_dist_w, ray_normal_w], + device=device, + ) + + # Cube bottom at z=-0.5, rays start at z=-5, distance = 4.5 + torch.testing.assert_close(wp.to_torch(ray_dist_w), torch.tensor([[4.5, 4.5]], device=device)) + torch.testing.assert_close( + wp.to_torch(ray_normal_w), + torch.tensor([[[0, 0, -1], [0, 0, -1]]], device=device, dtype=torch.float32), + ) + + +def test_raycast_mesh_masked_kernel_env_mask(raycast_setup): + """Masked-out environments must not be written.""" + device = raycast_setup["device"] + mesh_id = raycast_setup["single_mesh_id"] + + n_envs, n_rays = 2, 2 + ray_starts_w, ray_dirs_w, ray_hits_w, ray_dist_w, ray_normal_w = _make_masked_buffers(device, n_envs, n_rays) + env_mask = wp.array([True, False], dtype=wp.bool, device=device) + + starts = torch.tensor([[[0, -0.35, -5], [0.25, 0.35, -5]], [[0, -0.35, -5], [0.25, 0.35, -5]]], device=device) + dirs = torch.tensor([[[0, 0, 1], [0, 0, 1]], [[0, 0, 1], [0, 0, 1]]], device=device) + wp.to_torch(ray_starts_w)[:] = starts + wp.to_torch(ray_dirs_w)[:] = dirs + wp.to_torch(ray_hits_w).fill_(float("inf")) + + wp.launch( + _raycast_mesh_masked_kernel, + dim=(n_envs, n_rays), + inputs=[mesh_id, env_mask, ray_starts_w, ray_dirs_w, float(1e6), 1, 0, ray_hits_w, ray_dist_w, ray_normal_w], + device=device, + ) + + hits = wp.to_torch(ray_hits_w) + dist = wp.to_torch(ray_dist_w) + + assert not torch.isinf(hits[0]).any(), "Active env 0 should have valid hits" + torch.testing.assert_close(dist[0], torch.tensor([4.5, 4.5], device=device)) + assert torch.isinf(hits[1]).all(), "Masked env 1 hits must remain inf" + assert torch.all(dist[1] == _SENTINEL), "Masked env 1 distances must remain at sentinel" + assert torch.all(wp.to_torch(ray_normal_w) == _SENTINEL), "Normal buffer must not be written when return_normal=0" + + +# --------------------------------------------------------------------------- +# Test quat_yaw_only correctness (regression for atan2-based fix) +# --------------------------------------------------------------------------- + + +@wp.kernel(enable_backward=False) +def _call_quat_yaw_only(q_in: wp.array(dtype=wp.quatf), q_out: wp.array(dtype=wp.quatf)): + i = wp.tid() + q_out[i] = _quat_yaw_only_func(q_in[i]) + + +def test_quat_yaw_only_pure_yaw(): + """Pure yaw: quat_yaw_only should match the yaw_quat() reference for all yaw angles.""" + device = "cuda" if torch.cuda.is_available() else "cpu" + yaw_angles = torch.tensor([0.0, 0.5, 1.2, -0.8, np.pi], device=device) + + for yaw in yaw_angles: + q_torch = quat_from_euler_xyz( + torch.tensor([0.0], device=device), + torch.tensor([0.0], device=device), + yaw.unsqueeze(0), + ) # shape (1, 4), xyzw + + expected = yaw_quat(q_torch) # shape (1, 4) + + q_in = wp.from_torch(q_torch.contiguous(), dtype=wp.quatf) + q_out = wp.zeros(1, dtype=wp.quatf, device=device) + wp.launch(_call_quat_yaw_only, dim=1, inputs=[q_in, q_out], device=device) + result = wp.to_torch(q_out) # shape (1, 4) + + torch.testing.assert_close(result, expected, atol=1e-5, rtol=1e-5) + + +def test_quat_yaw_only_with_pitch_roll(): + """Non-zero pitch and roll: only the yaw component should be preserved. + + This is the regression test for the old bug where simply zeroing qx/qy and + renormalizing gave the wrong answer when pitch or roll was non-zero. + """ + device = "cuda" if torch.cuda.is_available() else "cpu" + + # Several combined pitch+roll+yaw orientations: (roll, pitch, yaw) + test_cases = [ + (0.3, 0.4, 1.2), + (0.5, 0.0, 0.7), + (-0.2, 0.6, -1.0), + (1.0, 1.0, 0.0), # heavy pitch+roll, zero yaw → result should be identity + ] + + for roll, pitch, yaw in test_cases: + q_torch = quat_from_euler_xyz( + torch.tensor([roll], device=device), + torch.tensor([pitch], device=device), + torch.tensor([yaw], device=device), + ) # shape (1, 4), xyzw + + expected = yaw_quat(q_torch) # shape (1, 4) + + q_in = wp.from_torch(q_torch.contiguous(), dtype=wp.quatf) + q_out = wp.zeros(1, dtype=wp.quatf, device=device) + wp.launch(_call_quat_yaw_only, dim=1, inputs=[q_in, q_out], device=device) + result = wp.to_torch(q_out) + + torch.testing.assert_close(result, expected, atol=1e-5, rtol=1e-5) diff --git a/source/isaaclab/test/sensors/test_ray_caster_camera.py b/source/isaaclab/test/sensors/test_ray_caster_camera.py index 0ae64e0e17e3..a913d38dd833 100644 --- a/source/isaaclab/test/sensors/test_ray_caster_camera.py +++ b/source/isaaclab/test/sensors/test_ray_caster_camera.py @@ -116,7 +116,7 @@ def test_camera_init(setup_sim): assert camera.data.quat_w_opengl.shape == (1, 4) assert camera.data.intrinsic_matrices.shape == (1, 3, 3) assert camera.data.image_shape == (camera_cfg.pattern_cfg.height, camera_cfg.pattern_cfg.width) - assert camera.data.info == [{camera_cfg.data_types[0]: None}] + assert camera.data.info == {camera_cfg.data_types[0]: None} # Simulate physics for _ in range(10): sim.step() @@ -898,11 +898,11 @@ def test_output_equal_to_usd_camera_when_intrinsics_set(setup_sim, focal_length_ # set camera position camera_warp.set_world_poses_from_view( - eyes=torch.tensor([[0.0, 0.0, 5.0]], device=camera_warp.device), + eyes=torch.tensor([[0.001, 0.0, 5.0]], device=camera_warp.device), targets=torch.tensor([[0.0, 0.0, 0.0]], device=camera_warp.device), ) camera_usd.set_world_poses_from_view( - eyes=torch.tensor([[0.0, 0.0, 5.0]], device=camera_usd.device), + eyes=torch.tensor([[0.001, 0.0, 5.0]], device=camera_usd.device), targets=torch.tensor([[0.0, 0.0, 0.0]], device=camera_usd.device), ) @@ -962,3 +962,142 @@ def test_sensor_print(setup_sim): sim.reset() # print info print(sensor) + + +@pytest.mark.isaacsim_ci +def test_depth_clipping_d2ip_and_d2c_are_independent(setup_sim): + """Clipping distance_to_image_plane must not corrupt distance_to_camera and vice versa. + + Both are derived from the same raw ray_distance buffer. If that buffer is modified + in-place by one clipping pass it would corrupt the other. This test verifies that + requesting both data types simultaneously gives results consistent with requesting + each one alone. + """ + sim, camera_cfg, dt = setup_sim + + base_cfg = RayCasterCameraCfg( + prim_path="/World/Camera", + mesh_prim_paths=["/World/defaultGroundPlane"], + offset=RayCasterCameraCfg.OffsetCfg(pos=(2.5, 2.5, 6.0), rot=(0.0, 0.1305, 0.0, 0.9914449), convention="world"), + pattern_cfg=patterns.PinholeCameraPatternCfg.from_intrinsic_matrix( + focal_length=38.0, + intrinsic_matrix=[380.08, 0.0, 467.79, 0.0, 380.08, 262.05, 0.0, 0.0, 1.0], + height=540, + width=960, + ), + max_distance=5.0, + data_types=["distance_to_image_plane", "distance_to_camera"], + depth_clipping_behavior="max", + update_period=0, + ) + + # Camera requesting both data types simultaneously + sim_utils.create_prim("/World/CameraJoint", "Xform") + cfg_joint = copy.deepcopy(base_cfg) + cfg_joint.prim_path = "/World/CameraJoint" + cam_joint = RayCasterCamera(cfg_joint) + + # Camera requesting only d2ip + sim_utils.create_prim("/World/CameraD2IP", "Xform") + cfg_d2ip = copy.deepcopy(base_cfg) + cfg_d2ip.prim_path = "/World/CameraD2IP" + cfg_d2ip.data_types = ["distance_to_image_plane"] + cam_d2ip = RayCasterCamera(cfg_d2ip) + + # Camera requesting only d2c + sim_utils.create_prim("/World/CameraD2C", "Xform") + cfg_d2c = copy.deepcopy(base_cfg) + cfg_d2c.prim_path = "/World/CameraD2C" + cfg_d2c.data_types = ["distance_to_camera"] + cam_d2c = RayCasterCamera(cfg_d2c) + + sim.reset() + + cam_joint.update(dt) + cam_d2ip.update(dt) + cam_d2c.update(dt) + + d2ip_joint = cam_joint.data.output["distance_to_image_plane"] + d2c_joint = cam_joint.data.output["distance_to_camera"] + d2ip_solo = cam_d2ip.data.output["distance_to_image_plane"] + d2c_solo = cam_d2c.data.output["distance_to_camera"] + + # Joint camera must match solo cameras (clipping one must not affect the other) + torch.testing.assert_close(d2ip_joint, d2ip_solo, atol=1e-5, rtol=1e-5) + torch.testing.assert_close(d2c_joint, d2c_solo, atol=1e-5, rtol=1e-5) + + # Both should be clipped to max_distance (camera is 6 m above ground, max_distance=5 m) + assert d2ip_joint.max().item() <= base_cfg.max_distance + 1e-4 + assert d2c_joint.max().item() <= base_cfg.max_distance + 1e-4 + + +@pytest.mark.isaacsim_ci +def test_frame_counter_increments_per_update(setup_sim): + """frame counter must increment by exactly 1 per update() call and reset to 0 on reset().""" + sim, camera_cfg, dt = setup_sim + camera = RayCasterCamera(cfg=camera_cfg) + sim.reset() + + assert torch.all(camera.frame == 0), "Frame must start at 0" + + n_steps = 7 + for step in range(1, n_steps + 1): + sim.step() + camera.update(dt, force_recompute=True) + assert camera.frame[0].item() == step, f"Frame must be {step} after {step} update(s)" + + # Partial reset: only env 0 (single-env camera, but API accepts env_ids) + camera.reset(env_ids=[0]) + assert camera.frame[0].item() == 0, "Frame must be 0 after reset(env_ids=[0])" + + # Full reset + for _ in range(3): + sim.step() + camera.update(dt, force_recompute=True) + camera.reset() + assert torch.all(camera.frame == 0), "Frame must be 0 after full reset()" + + +@pytest.mark.isaacsim_ci +def test_set_intrinsic_matrices_updates_output(setup_sim): + """Depth output must change when intrinsics are updated via set_intrinsic_matrices(). + + This tests that the warp view refresh in set_intrinsic_matrices() actually takes + effect: stale warp views would cause subsequent images to use the old ray pattern. + """ + sim, camera_cfg, dt = setup_sim + + # Place camera looking straight down at the ground + camera_cfg = copy.deepcopy(camera_cfg) + camera_cfg.offset = RayCasterCameraCfg.OffsetCfg(pos=(0.0, 0.0, 5.0), rot=(0.0, 0.0, 0.0, 1.0), convention="world") + camera_cfg.data_types = ["distance_to_camera"] + camera = RayCasterCamera(cfg=camera_cfg) + sim.reset() + + # Capture output with default focal length (24 mm → 20.955 mm aperture) + for _ in range(3): + sim.step() + camera.update(dt) + output_before = camera.data.output["distance_to_camera"].clone() + + # Change to a very different focal length (longer → tighter FOV → depth values differ at edges) + new_matrix = torch.tensor( + [[200.0, 0.0, 320.0], [0.0, 200.0, 240.0], [0.0, 0.0, 1.0]], + device=camera.device, + ).unsqueeze(0) + camera.set_intrinsic_matrices(new_matrix, focal_length=1.0) + + for _ in range(3): + sim.step() + camera.update(dt) + output_after = camera.data.output["distance_to_camera"].clone() + + # Outputs must differ after intrinsics change (different ray angles → different depths) + assert not torch.allclose(output_before, output_after, atol=1e-3), ( + "Depth output must change when intrinsic matrix is updated; unchanged output indicates stale warp ray buffers." + ) + # With depth_clipping_behavior="none" (default), missed rays produce inf — that is valid. + # No NaN values must appear; where rays hit, depth must be positive. + assert not torch.any(torch.isnan(output_after)), "Expected no NaN values in depth output after intrinsics update" + if torch.any(torch.isfinite(output_after)): + assert output_after[torch.isfinite(output_after)].min() > 0 diff --git a/source/isaaclab/test/sensors/test_ray_caster_integration.py b/source/isaaclab/test/sensors/test_ray_caster_integration.py new file mode 100644 index 000000000000..36b6d8ff4692 --- /dev/null +++ b/source/isaaclab/test/sensors/test_ray_caster_integration.py @@ -0,0 +1,439 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +# pyright: reportPrivateUsage=none + +"""Integration tests for ray caster sensor view paths, env_mask, and intrinsics. + +These tests require Isaac Sim (AppLauncher). They cover the integration-level +items from ``TODO_ray_caster_kernel_tests.md``: + +- ``_get_view_transforms_wp`` ArticulationView and RigidBodyView paths +- ``MultiMeshRayCaster`` env_mask behavior +- ``MultiMeshRayCasterCamera.set_intrinsic_matrices`` propagation +- ``_update_mesh_transforms`` non-identity orientation offset (known bug, xfail) +- Depth clipping ordering for ``MultiMeshRayCasterCamera`` +""" + +from isaaclab.app import AppLauncher + +simulation_app = AppLauncher(headless=True, enable_cameras=True).app + +import copy + +import numpy as np +import pytest +import torch +import warp as wp + +from pxr import UsdGeom, UsdPhysics + +import isaaclab.sim as sim_utils +from isaaclab.sensors.ray_caster import ( + MultiMeshRayCaster, + MultiMeshRayCasterCamera, + MultiMeshRayCasterCameraCfg, + MultiMeshRayCasterCfg, + RayCaster, + RayCasterCfg, + patterns, +) +from isaaclab.terrains.trimesh.utils import make_plane +from isaaclab.terrains.utils import create_prim_from_mesh + +_GROUND_PATH = "/World/Ground" +_DT = 0.01 + + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + + +def _make_sim_and_ground(): + """Create a blank stage with a flat ground plane at z=0.""" + sim_utils.create_new_stage() + sim = sim_utils.SimulationContext(sim_utils.SimulationCfg(dt=_DT)) + mesh = make_plane(size=(100, 100), height=0.0, center_zero=True) + create_prim_from_mesh(_GROUND_PATH, mesh) + sim_utils.update_stage() + return sim + + +def _single_downward_ray_cfg(prim_path: str) -> RayCasterCfg: + """RayCasterCfg with a single downward ray, no offset, world alignment.""" + return RayCasterCfg( + prim_path=prim_path, + mesh_prim_paths=[_GROUND_PATH], + update_period=0, + offset=RayCasterCfg.OffsetCfg(pos=(0.0, 0.0, 0.0), rot=(0.0, 0.0, 0.0, 1.0)), + debug_vis=False, + pattern_cfg=patterns.GridPatternCfg(resolution=1.0, size=(0.0, 0.0), direction=(0.0, 0.0, -1.0)), + ray_alignment="world", + ) + + +@pytest.fixture +def sim_ground(): + sim = _make_sim_and_ground() + yield sim + sim.stop() + sim.clear_instance() + + +# --------------------------------------------------------------------------- +# _get_view_transforms_wp: ArticulationView path +# --------------------------------------------------------------------------- + + +@pytest.mark.isaacsim_ci +def test_articulation_view_path(sim_ground): + """Mount a ray caster on a prim with ArticulationRootAPI. + + Verifies that sensor pos_w matches the prim's initial position and that + the downward ray hits the ground plane. This exercises the + ``ArticulationView.get_root_transforms()`` quaternion-convention path in + :meth:`_get_view_transforms_wp`. + """ + sim = sim_ground + expected_pos = (3.0, 4.0, 5.0) + + prim_path = "/World/ArticulatedBody" + sim_utils.create_prim(prim_path, "Xform", translation=expected_pos) + stage = sim_utils.get_current_stage() + prim = stage.GetPrimAtPath(prim_path) + UsdPhysics.RigidBodyAPI.Apply(prim) + UsdPhysics.ArticulationRootAPI.Apply(prim) + # Mass is needed for physics; collision is needed for PhysX to track the body. + mass_api = UsdPhysics.MassAPI.Apply(prim) + mass_api.CreateMassAttr().Set(1.0) + # Create a small collision cube so PhysX treats this as a real body. + cube_path = f"{prim_path}/CollisionCube" + cube_geom = UsdGeom.Cube.Define(stage, cube_path) + cube_geom.CreateSizeAttr().Set(0.1) + UsdPhysics.CollisionAPI.Apply(stage.GetPrimAtPath(cube_path)) + sim_utils.update_stage() + + sensor = RayCaster(_single_downward_ray_cfg(prim_path)) + sim.reset() + sensor.update(_DT) + + pos_w = sensor.data.pos_w.torch[0].cpu().numpy() + np.testing.assert_allclose( + pos_w, + expected_pos, + atol=0.15, + err_msg="ArticulationView: sensor pos_w must match initial prim position", + ) + + hits = sensor.data.ray_hits_w.torch[0, 0].cpu().numpy() + assert abs(hits[2]) < 0.5, f"ArticulationView: downward ray should hit near z=0, got z={hits[2]}" + + +# --------------------------------------------------------------------------- +# _get_view_transforms_wp: RigidBodyView path +# --------------------------------------------------------------------------- + + +@pytest.mark.isaacsim_ci +def test_rigid_body_view_path(sim_ground): + """Mount a ray caster on a prim with RigidBodyAPI (no ArticulationRootAPI). + + Exercises the ``RigidBodyView.get_transforms()`` path in + :meth:`_get_view_transforms_wp`. + """ + sim = sim_ground + expected_pos = (1.0, 2.0, 6.0) + + prim_path = "/World/RigidBody" + sim_utils.create_prim(prim_path, "Xform", translation=expected_pos) + stage = sim_utils.get_current_stage() + prim = stage.GetPrimAtPath(prim_path) + UsdPhysics.RigidBodyAPI.Apply(prim) + mass_api = UsdPhysics.MassAPI.Apply(prim) + mass_api.CreateMassAttr().Set(1.0) + cube_path = f"{prim_path}/CollisionCube" + cube_geom = UsdGeom.Cube.Define(stage, cube_path) + cube_geom.CreateSizeAttr().Set(0.1) + UsdPhysics.CollisionAPI.Apply(stage.GetPrimAtPath(cube_path)) + sim_utils.update_stage() + + sensor = RayCaster(_single_downward_ray_cfg(prim_path)) + sim.reset() + sensor.update(_DT) + + pos_w = sensor.data.pos_w.torch[0].cpu().numpy() + np.testing.assert_allclose( + pos_w, + expected_pos, + atol=0.15, + err_msg="RigidBodyView: sensor pos_w must match initial prim position", + ) + + hits = sensor.data.ray_hits_w.torch[0, 0].cpu().numpy() + assert abs(hits[2]) < 0.5, f"RigidBodyView: downward ray should hit near z=0, got z={hits[2]}" + + +# --------------------------------------------------------------------------- +# MultiMeshRayCasterCamera.set_intrinsic_matrices +# --------------------------------------------------------------------------- + + +@pytest.fixture +def sim_ground_camera(): + """Fixture providing sim + a base MultiMeshRayCasterCameraCfg.""" + sim = _make_sim_and_ground() + + camera_cfg = MultiMeshRayCasterCameraCfg( + prim_path="/World/Camera", + mesh_prim_paths=[_GROUND_PATH], + update_period=0, + offset=MultiMeshRayCasterCameraCfg.OffsetCfg(pos=(0.0, 0.0, 5.0), rot=(0.0, 0.0, 0.0, 1.0), convention="world"), + debug_vis=False, + pattern_cfg=patterns.PinholeCameraPatternCfg( + focal_length=24.0, + horizontal_aperture=20.955, + height=480, + width=640, + ), + data_types=["distance_to_camera"], + ) + + sim_utils.create_prim("/World/Camera", "Xform") + + yield sim, camera_cfg + + sim.stop() + sim.clear_instance() + + +@pytest.mark.isaacsim_ci +def test_multi_mesh_camera_set_intrinsic_matrices(sim_ground_camera): + """Depth output must change when intrinsics are updated on MultiMeshRayCasterCamera. + + The multi-mesh variant overrides ``_initialize_rays_impl`` without calling + ``super()``, so the warp view refresh path may differ from RayCasterCamera. + This test verifies that ``set_intrinsic_matrices`` actually takes effect. + """ + sim, camera_cfg = sim_ground_camera + + camera = MultiMeshRayCasterCamera(cfg=camera_cfg) + sim.reset() + + # Capture output with default intrinsics + for _ in range(3): + sim.step() + camera.update(_DT) + output_before = camera.data.output["distance_to_camera"].clone() + + # Change to a very different intrinsic matrix (different FOV) + new_matrix = torch.tensor( + [[200.0, 0.0, 320.0], [0.0, 200.0, 240.0], [0.0, 0.0, 1.0]], + device=camera.device, + ).unsqueeze(0) + camera.set_intrinsic_matrices(new_matrix, focal_length=1.0) + + for _ in range(3): + sim.step() + camera.update(_DT) + output_after = camera.data.output["distance_to_camera"].clone() + + assert not torch.allclose(output_before, output_after, atol=1e-3), ( + "MultiMeshRayCasterCamera: depth output must change after set_intrinsic_matrices; " + "unchanged output indicates stale warp ray buffers." + ) + assert not torch.any(torch.isnan(output_after)), "No NaN values expected after intrinsics update" + + +# --------------------------------------------------------------------------- +# Depth clipping ordering for MultiMeshRayCasterCamera +# --------------------------------------------------------------------------- + + +@pytest.mark.isaacsim_ci +def test_multi_mesh_camera_d2ip_and_d2c_independent(sim_ground_camera): + """Requesting both d2ip and d2c simultaneously must produce correct independent results. + + The ``distance_to_image_plane`` computation reads ``_ray_distance`` before + ``distance_to_camera`` clips it in-place. This test verifies the two data + types do not interfere with each other. + """ + sim, base_cfg = sim_ground_camera + + joint_cfg = copy.deepcopy(base_cfg) + joint_cfg.prim_path = "/World/CameraJoint" + joint_cfg.data_types = ["distance_to_image_plane", "distance_to_camera"] + joint_cfg.max_distance = 4.5 # camera is 5 m up, so some rays should be clipped + joint_cfg.depth_clipping_behavior = "max" + sim_utils.create_prim("/World/CameraJoint", "Xform") + cam_joint = MultiMeshRayCasterCamera(joint_cfg) + + d2ip_cfg = copy.deepcopy(base_cfg) + d2ip_cfg.prim_path = "/World/CameraD2IP" + d2ip_cfg.data_types = ["distance_to_image_plane"] + d2ip_cfg.max_distance = 4.5 + d2ip_cfg.depth_clipping_behavior = "max" + sim_utils.create_prim("/World/CameraD2IP", "Xform") + cam_d2ip = MultiMeshRayCasterCamera(d2ip_cfg) + + d2c_cfg = copy.deepcopy(base_cfg) + d2c_cfg.prim_path = "/World/CameraD2C" + d2c_cfg.data_types = ["distance_to_camera"] + d2c_cfg.max_distance = 4.5 + d2c_cfg.depth_clipping_behavior = "max" + sim_utils.create_prim("/World/CameraD2C", "Xform") + cam_d2c = MultiMeshRayCasterCamera(d2c_cfg) + + sim.reset() + + cam_joint.update(_DT) + cam_d2ip.update(_DT) + cam_d2c.update(_DT) + + d2ip_joint = cam_joint.data.output["distance_to_image_plane"] + d2c_joint = cam_joint.data.output["distance_to_camera"] + d2ip_solo = cam_d2ip.data.output["distance_to_image_plane"] + d2c_solo = cam_d2c.data.output["distance_to_camera"] + + # Joint camera must match solo cameras (clipping one must not corrupt the other) + torch.testing.assert_close(d2ip_joint, d2ip_solo, atol=1e-5, rtol=1e-5) + torch.testing.assert_close(d2c_joint, d2c_solo, atol=1e-5, rtol=1e-5) + + +# --------------------------------------------------------------------------- +# MultiMeshRayCaster env_mask behavior +# --------------------------------------------------------------------------- + + +@pytest.mark.isaacsim_ci +def test_multi_mesh_env_mask_preserves_masked_buffers(sim_ground): + """Masked environments must retain their pre-update buffer values. + + Creates a single-env MultiMeshRayCaster, captures output after one update, + then calls ``_update_buffers_impl`` with the environment masked out and + verifies the output buffers are unchanged. + """ + sim = sim_ground + + prim_path = "/World/Sensor" + sim_utils.create_prim(prim_path, "Xform", translation=(0.0, 0.0, 3.0)) + + cfg = MultiMeshRayCasterCfg( + prim_path=prim_path, + mesh_prim_paths=[_GROUND_PATH], + update_period=0, + offset=MultiMeshRayCasterCfg.OffsetCfg(pos=(0.0, 0.0, 0.0), rot=(0.0, 0.0, 0.0, 1.0)), + debug_vis=False, + pattern_cfg=patterns.GridPatternCfg(resolution=1.0, size=(0.0, 0.0), direction=(0.0, 0.0, -1.0)), + ray_alignment="world", + ) + sensor = MultiMeshRayCaster(cfg) + sim.reset() + + # First update: populate buffers with real values + sensor.update(_DT) + hits_before = sensor.data.ray_hits_w.torch.clone() + + # Second update with env masked out: buffers must not change + mask_all_false = wp.array([False], dtype=wp.bool, device=sensor.device) + sensor._update_buffers_impl(mask_all_false) + + hits_after = sensor.data.ray_hits_w.torch + torch.testing.assert_close( + hits_after, + hits_before, + atol=0.0, + rtol=0.0, + msg="Masked env: ray_hits_w must be unchanged after update with env masked out", + ) + + +# --------------------------------------------------------------------------- +# _update_mesh_transforms: non-identity orientation offset +# --------------------------------------------------------------------------- + + +@pytest.mark.isaacsim_ci +def test_update_mesh_transforms_non_identity_offset(sim_ground): + """Tracked mesh position must account for body orientation when applying offset. + + Setup: a kinematic rigid body at (0, 0, 2) rotated 90 deg around Z, with a + child mesh offset by (1, 0, 0) in the body's local frame. + + Correct world position of mesh = body_pos + rotate(body_ori, local_offset) + = (0, 0, 2) + rotate(90degZ, (1, 0, 0)) + = (0, 0, 2) + (0, 1, 0) + = (0, 1, 2) + + Naive subtraction (the old bug) would give: body_pos - offset = (-1, 0, 2). + """ + sim = sim_ground + + from isaaclab.utils.math import quat_from_euler_xyz + + # 90 deg yaw quaternion in xyzw + yaw90 = quat_from_euler_xyz(torch.tensor([0.0]), torch.tensor([0.0]), torch.tensor([torch.pi / 2])) + yaw90_xyzw = tuple(yaw90[0].tolist()) + + # Create a kinematic rigid body at (0, 0, 2) rotated 90 deg around Z + body_path = "/World/DynamicBody" + sim_utils.create_prim(body_path, "Xform", translation=(0.0, 0.0, 2.0), orientation=yaw90_xyzw) + stage = sim_utils.get_current_stage() + body_prim = stage.GetPrimAtPath(body_path) + UsdPhysics.RigidBodyAPI.Apply(body_prim) + mass_api = UsdPhysics.MassAPI.Apply(body_prim) + mass_api.CreateMassAttr().Set(1.0) + body_prim.GetAttribute("physics:kinematicEnabled").Set(True) + + # Create a child Xform offset by (1, 0, 0) in the body's local frame, + # then place mesh geometry under it. The Xform translation is the offset + # that _obtain_trackable_prim_view / resolve_prim_pose will discover. + child_mesh_path = f"{body_path}/OffsetMesh" + sim_utils.create_prim(child_mesh_path, "Xform", translation=(1.0, 0.0, 0.0)) + mesh_data = make_plane(size=(2, 2), height=0.0, center_zero=True) + create_prim_from_mesh(f"{child_mesh_path}/Plane", mesh_data) + # Add collision so PhysX tracks the body + col_path = f"{body_path}/CollisionCube" + cube_geom = UsdGeom.Cube.Define(stage, col_path) + cube_geom.CreateSizeAttr().Set(0.1) + UsdPhysics.CollisionAPI.Apply(stage.GetPrimAtPath(col_path)) + sim_utils.update_stage() + + # Create a sensor prim to mount the MultiMeshRayCaster on + sensor_path = "/World/SensorMount" + sim_utils.create_prim(sensor_path, "Xform", translation=(0.0, 0.0, 5.0)) + + # Configure MultiMeshRayCaster to track the child mesh + cfg = MultiMeshRayCasterCfg( + prim_path=sensor_path, + mesh_prim_paths=[ + MultiMeshRayCasterCfg.RaycastTargetCfg( + prim_expr=child_mesh_path, + track_mesh_transforms=True, + ), + ], + update_period=0, + offset=MultiMeshRayCasterCfg.OffsetCfg(pos=(0.0, 0.0, 0.0), rot=(0.0, 0.0, 0.0, 1.0)), + debug_vis=False, + pattern_cfg=patterns.GridPatternCfg(resolution=1.0, size=(0.0, 0.0), direction=(0.0, 0.0, -1.0)), + ray_alignment="world", + ) + sensor = MultiMeshRayCaster(cfg) + sim.reset() + sensor.update(_DT) + + # Verify mesh position: body at (0,0,2) rotated 90deg Z, child offset (1,0,0) local + # Expected: (0, 0, 2) + rotate(90degZ, (1,0,0)) = (0, 0, 2) + (0, 1, 0) = (0, 1, 2) + mesh_pos = sensor._mesh_positions_w_torch.clone() + np.testing.assert_allclose( + mesh_pos[0, 0].cpu().numpy(), + [0.0, 1.0, 2.0], + atol=0.15, + err_msg=( + "Mesh position should be (0, 1, 2) via proper frame decomposition: " + "body_pos + rotate(body_ori, local_offset). " + "If this fails, the offset is not being rotated by the body orientation." + ), + ) diff --git a/source/isaaclab/test/sensors/test_ray_caster_kernels.py b/source/isaaclab/test/sensors/test_ray_caster_kernels.py new file mode 100644 index 000000000000..cc57e4f1eec5 --- /dev/null +++ b/source/isaaclab/test/sensors/test_ray_caster_kernels.py @@ -0,0 +1,577 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Unit tests for ray caster kernels. + +Tests for kernels in ``sensors/ray_caster/kernels.py`` and +``utils/warp/kernels.py``. Exercised directly with hand-crafted warp arrays +and analytically computed expected outputs. No simulation, no stage, no +AppLauncher -- just warp and numpy on CPU (or CUDA when available). + +See ``test_update_ray_caster_kernel.py`` for tests of +:func:`update_ray_caster_kernel`. +""" + +from __future__ import annotations + +import importlib.util +import math +import os + +import numpy as np +import pytest +import warp as wp + +# --------------------------------------------------------------------------- +# Import kernel modules directly (avoids Isaac Sim / Omniverse dependencies) +# --------------------------------------------------------------------------- + +_SENSOR_KERNEL_PATH = os.path.join( + os.path.dirname(__file__), + os.pardir, + os.pardir, + "isaaclab", + "sensors", + "ray_caster", + "kernels.py", +) +_spec = importlib.util.spec_from_file_location("ray_caster_kernels", os.path.normpath(_SENSOR_KERNEL_PATH)) +_sensor_mod = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(_sensor_mod) + +_WARP_KERNEL_PATH = os.path.join( + os.path.dirname(__file__), + os.pardir, + os.pardir, + "isaaclab", + "utils", + "warp", + "kernels.py", +) +_warp_spec = importlib.util.spec_from_file_location("warp_kernels", os.path.normpath(_WARP_KERNEL_PATH)) +_warp_mod = importlib.util.module_from_spec(_warp_spec) +_warp_spec.loader.exec_module(_warp_mod) + +compute_distance_to_image_plane_masked_kernel = _sensor_mod.compute_distance_to_image_plane_masked_kernel +apply_depth_clipping_masked_kernel = _sensor_mod.apply_depth_clipping_masked_kernel +apply_z_drift_kernel = _sensor_mod.apply_z_drift_kernel +quat_yaw_only = _sensor_mod.quat_yaw_only + +raycast_dynamic_meshes_kernel = _warp_mod.raycast_dynamic_meshes_kernel + +# --------------------------------------------------------------------------- +# Constants & setup +# --------------------------------------------------------------------------- + +wp.init() +DEVICE = "cuda:0" if wp.is_cuda_available() else "cpu" +ATOL = 1e-5 + + +# --------------------------------------------------------------------------- +# Wrapper kernel for quat_yaw_only (@wp.func cannot be launched directly) +# --------------------------------------------------------------------------- + + +@wp.kernel(enable_backward=False) +def _quat_yaw_only_test_kernel( + q_in: wp.array(dtype=wp.quatf), + q_out: wp.array(dtype=wp.quatf), +): + tid = wp.tid() + q_out[tid] = quat_yaw_only(q_in[tid]) + + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + + +def _euler_to_quat_xyzw(roll: float, pitch: float, yaw: float) -> tuple[float, float, float, float]: + """Euler angles (intrinsic XYZ) to quaternion in xyzw convention.""" + cr, sr = math.cos(roll / 2), math.sin(roll / 2) + cp, sp = math.cos(pitch / 2), math.sin(pitch / 2) + cy, sy = math.cos(yaw / 2), math.sin(yaw / 2) + qx = sr * cp * cy - cr * sp * sy + qy = cr * sp * cy + sr * cp * sy + qz = cr * cp * sy - sr * sp * cy + qw = cr * cp * cy + sr * sp * sy + return (qx, qy, qz, qw) + + +def _make_flat_mesh(size: float = 4.0) -> wp.Mesh: + """Create a flat square mesh in the XY plane at z=0, centered at origin.""" + half = size / 2.0 + vertices = np.array( + [[-half, -half, 0.0], [half, -half, 0.0], [half, half, 0.0], [-half, half, 0.0]], + dtype=np.float32, + ) + indices = np.array([0, 1, 2, 0, 2, 3], dtype=np.int32) + return wp.Mesh( + points=wp.array(vertices, dtype=wp.vec3, device=DEVICE), + indices=wp.array(indices, dtype=wp.int32, device=DEVICE), + ) + + +def _to_numpy(a: wp.array) -> np.ndarray: + """Convert a warp array to numpy, handling GPU arrays transparently.""" + return a.numpy() + + +# --------------------------------------------------------------------------- +# Tests: raycast_dynamic_meshes_kernel +# --------------------------------------------------------------------------- + + +class TestRaycastDynamicMeshesKernel: + """Tests for :func:`raycast_dynamic_meshes_kernel` from ``utils/warp/kernels.py``. + + Each test creates trivial warp meshes (flat quads) and verifies raycasting + results against analytical expectations. + """ + + IDENT_Q = [0.0, 0.0, 0.0, 1.0] + + @staticmethod + def _launch( + num_envs: int, + num_meshes: int, + num_rays: int, + env_mask: np.ndarray, + mesh_ids: np.ndarray, + ray_starts: np.ndarray, + ray_dirs: np.ndarray, + mesh_pos: np.ndarray, + mesh_rot: np.ndarray, + max_dist: float = 1e6, + sentinel: float | None = None, + ) -> dict[str, np.ndarray]: + """Build warp arrays, launch kernel, return outputs as numpy dicts.""" + env_mask_wp = wp.array(env_mask.astype(np.bool_), dtype=wp.bool, device=DEVICE) + mesh_wp = wp.array(mesh_ids, dtype=wp.uint64, device=DEVICE) + starts_wp = wp.array(ray_starts, dtype=wp.vec3f, device=DEVICE) + dirs_wp = wp.array(ray_dirs, dtype=wp.vec3f, device=DEVICE) + mpos_wp = wp.array(mesh_pos, dtype=wp.vec3f, device=DEVICE) + mrot_wp = wp.array(mesh_rot, dtype=wp.quatf, device=DEVICE) + + fill = sentinel if sentinel is not None else float("inf") + + hits_np = np.full((num_envs, num_rays, 3), fill, dtype=np.float32) + ray_hits = wp.array(hits_np, dtype=wp.vec3f, device=DEVICE) + + dist_np = np.full((num_envs, num_rays), fill, dtype=np.float32) + ray_distance = wp.array(dist_np, dtype=wp.float32, device=DEVICE) + + normal_np = np.full((num_envs, num_rays, 3), fill, dtype=np.float32) + ray_normal = wp.array(normal_np, dtype=wp.vec3f, device=DEVICE) + + face_np = np.full((num_envs, num_rays), -1, dtype=np.int32) + ray_face_id = wp.array(face_np, dtype=wp.int32, device=DEVICE) + + mesh_id_np = np.full((num_envs, num_rays), -1, dtype=np.int16) + ray_mesh_id = wp.array(mesh_id_np, dtype=wp.int16, device=DEVICE) + + wp.launch( + raycast_dynamic_meshes_kernel, + dim=(num_meshes, num_envs, num_rays), + inputs=[ + env_mask_wp, + mesh_wp, + starts_wp, + dirs_wp, + ray_hits, + ray_distance, + ray_normal, + ray_face_id, + ray_mesh_id, + mpos_wp, + mrot_wp, + max_dist, + 1, # return_normal + 1, # return_face_id + 1, # return_mesh_id + ], + device=DEVICE, + ) + wp.synchronize_device(DEVICE) + + return { + "hits": _to_numpy(ray_hits), + "distance": _to_numpy(ray_distance), + "normal": _to_numpy(ray_normal), + "face_id": _to_numpy(ray_face_id), + "mesh_id": _to_numpy(ray_mesh_id), + } + + def test_env_mask_skipping(self): + """Env 0 masked out -- verify output buffers retain sentinel values.""" + mesh = _make_flat_mesh() + iq = self.IDENT_Q + out = self._launch( + num_envs=2, + num_meshes=1, + num_rays=1, + env_mask=np.array([False, True]), + mesh_ids=np.array([[mesh.id], [mesh.id]], dtype=np.uint64), + ray_starts=np.array([[[0, 0, 10]], [[0, 0, 10]]], dtype=np.float32), + ray_dirs=np.array([[[0, 0, -1]], [[0, 0, -1]]], dtype=np.float32), + mesh_pos=np.array([[[0, 0, 2]], [[0, 0, 2]]], dtype=np.float32), + mesh_rot=np.array([[iq], [iq]], dtype=np.float32), + sentinel=999.0, + ) + + # Env 0 (masked): all outputs retain sentinel / initial fill + np.testing.assert_allclose(out["hits"][0, 0], [999, 999, 999], atol=ATOL) + assert out["distance"][0, 0] == pytest.approx(999.0, abs=ATOL) + np.testing.assert_allclose(out["normal"][0, 0], [999, 999, 999], atol=ATOL) + assert out["face_id"][0, 0] == -1 + assert out["mesh_id"][0, 0] == -1 + + # Env 1 (active): should have hit the mesh at z=2, distance 8 + np.testing.assert_allclose(out["hits"][1, 0], [0, 0, 2], atol=ATOL) + assert out["distance"][1, 0] == pytest.approx(8.0, abs=ATOL) + assert out["mesh_id"][1, 0] == 0 + + def test_closest_hit_overlapping_meshes(self): + """Two meshes at different distances -- closer hit wins. + + Mesh A at z=2 (farther), Mesh B at z=4 (closer to ray origin at z=10). + Ray from (0,0,10) going (0,0,-1). Expected: hit Mesh B at distance 6. + """ + mesh_a = _make_flat_mesh() + mesh_b = _make_flat_mesh() + iq = self.IDENT_Q + + out = self._launch( + num_envs=1, + num_meshes=2, + num_rays=1, + env_mask=np.array([True]), + mesh_ids=np.array([[mesh_a.id, mesh_b.id]], dtype=np.uint64), + ray_starts=np.array([[[0, 0, 10]]], dtype=np.float32), + ray_dirs=np.array([[[0, 0, -1]]], dtype=np.float32), + mesh_pos=np.array([[[0, 0, 2], [0, 0, 4]]], dtype=np.float32), + mesh_rot=np.array([[iq, iq]], dtype=np.float32), + ) + + np.testing.assert_allclose(out["hits"][0, 0], [0, 0, 4], atol=ATOL) + assert out["distance"][0, 0] == pytest.approx(6.0, abs=ATOL) + np.testing.assert_allclose(out["normal"][0, 0], [0, 0, 1], atol=ATOL) + assert out["mesh_id"][0, 0] == 1 # mesh_b is closer + + def test_mesh_transform_application(self): + """Mesh translated/rotated -- verify hits in correct world-space coordinates. + + Mesh: flat XY quad at z=0 (local), placed at world (5,0,0) with 90 deg + Y rotation. This turns it into a vertical plane at x=5. + Ray from (10,0,0) going (-1,0,0) should hit at (5,0,0), distance=5. + World-space normal: local (0,0,1) rotated by 90 deg Y = (1,0,0). + """ + mesh = _make_flat_mesh() + rot90y = [0.0, math.sin(math.pi / 4), 0.0, math.cos(math.pi / 4)] + + out = self._launch( + num_envs=1, + num_meshes=1, + num_rays=1, + env_mask=np.array([True]), + mesh_ids=np.array([[mesh.id]], dtype=np.uint64), + ray_starts=np.array([[[10, 0, 0]]], dtype=np.float32), + ray_dirs=np.array([[[-1, 0, 0]]], dtype=np.float32), + mesh_pos=np.array([[[5, 0, 0]]], dtype=np.float32), + mesh_rot=np.array([[rot90y]], dtype=np.float32), + ) + + np.testing.assert_allclose(out["hits"][0, 0], [5, 0, 0], atol=ATOL) + assert out["distance"][0, 0] == pytest.approx(5.0, abs=ATOL) + np.testing.assert_allclose(out["normal"][0, 0], [1, 0, 0], atol=ATOL) + + def test_equidistant_meshes(self): + """Two meshes at exact same distance -- hit position is always correct. + + Known limitation (warp#1058): when two meshes are equidistant, the + ``atomic_min`` + equality-check pattern is not fully thread-safe. + Normals, face_ids, and mesh_ids may come from either mesh. The hit + *position* is always correct because both threads compute the same + world-space point. + """ + mesh_a = _make_flat_mesh() + mesh_b = _make_flat_mesh() + iq = self.IDENT_Q + + out = self._launch( + num_envs=1, + num_meshes=2, + num_rays=1, + env_mask=np.array([True]), + mesh_ids=np.array([[mesh_a.id, mesh_b.id]], dtype=np.uint64), + ray_starts=np.array([[[0, 0, 10]]], dtype=np.float32), + ray_dirs=np.array([[[0, 0, -1]]], dtype=np.float32), + mesh_pos=np.array([[[0, 0, 3], [0, 0, 3]]], dtype=np.float32), + mesh_rot=np.array([[iq, iq]], dtype=np.float32), + ) + + # Position and distance are always correct, even under the race + np.testing.assert_allclose(out["hits"][0, 0], [0, 0, 3], atol=ATOL) + assert out["distance"][0, 0] == pytest.approx(7.0, abs=ATOL) + # mesh_id can be 0 or 1 -- both are valid under the race condition + assert out["mesh_id"][0, 0] in (0, 1) + + +# --------------------------------------------------------------------------- +# Tests: compute_distance_to_image_plane_masked_kernel +# --------------------------------------------------------------------------- + + +class TestComputeDistanceToImagePlaneMaskedKernel: + """Tests for :func:`compute_distance_to_image_plane_masked_kernel`.""" + + @staticmethod + def _launch( + quat_xyzw: list[float], + ray_distance: list[list[float]], + ray_dirs: list[list[list[float]]], + env_mask: list[bool] | None = None, + ) -> np.ndarray: + """Launch kernel and return distance_to_image_plane as numpy.""" + num_envs = len(ray_distance) + num_rays = len(ray_distance[0]) + if env_mask is None: + env_mask = [True] * num_envs + + mask_wp = wp.array(np.array(env_mask, dtype=np.bool_), dtype=wp.bool, device=DEVICE) + quat_np = np.array([quat_xyzw] * num_envs, dtype=np.float32) + quat_wp = wp.array(quat_np, dtype=wp.quatf, device=DEVICE) + ray_dist_wp = wp.array(np.array(ray_distance, dtype=np.float32), dtype=wp.float32, device=DEVICE) + dirs_wp = wp.array(np.array(ray_dirs, dtype=np.float32), dtype=wp.vec3f, device=DEVICE) + out_wp = wp.zeros((num_envs, num_rays), dtype=wp.float32, device=DEVICE) + + wp.launch( + compute_distance_to_image_plane_masked_kernel, + dim=(num_envs, num_rays), + inputs=[mask_wp, quat_wp, ray_dist_wp, dirs_wp], + outputs=[out_wp], + device=DEVICE, + ) + wp.synchronize_device(DEVICE) + return _to_numpy(out_wp) + + def test_known_camera_orientation(self): + """Identity camera, ray along +X at distance 5 -- d2ip equals 5.""" + result = self._launch( + quat_xyzw=[0, 0, 0, 1], + ray_distance=[[5.0]], + ray_dirs=[[[1, 0, 0]]], + ) + assert result[0, 0] == pytest.approx(5.0, abs=ATOL) + + def test_off_axis_camera(self): + """Camera pitched 45 deg around Y, ray going world -Z. + + Camera forward (+X_cam) in world = (cos45, 0, -sin45). + Displacement = 10 * (0, 0, -1) = (0, 0, -10). + Projection onto camera forward = dot((0,0,-10), (cos45,0,-sin45)) + = 10 * sin(45 deg). + """ + pitch45 = list(_euler_to_quat_xyzw(0, math.pi / 4, 0)) + result = self._launch( + quat_xyzw=pitch45, + ray_distance=[[10.0]], + ray_dirs=[[[0, 0, -1]]], + ) + expected = 10.0 * math.sin(math.pi / 4) + assert result[0, 0] == pytest.approx(expected, abs=ATOL) + + def test_inf_distance(self): + """Inf distance produces NaN through the projection (inf * 0 = NaN). + + When a ray misses, ray_distance is inf. Multiplying inf by zero-valued + ray-direction components yields NaN (IEEE 754), which propagates through + the quaternion rotation. The downstream + :func:`apply_depth_clipping_masked_kernel` handles NaN correctly via + ``wp.isnan()``, so the overall pipeline is sound. + """ + result = self._launch( + quat_xyzw=[0, 0, 0, 1], + ray_distance=[[float("inf")]], + ray_dirs=[[[1, 0, 0]]], + ) + assert np.isnan(result[0, 0]), f"Expected NaN from inf*0 contamination, got {result[0, 0]}" + + +# --------------------------------------------------------------------------- +# Tests: apply_depth_clipping_masked_kernel +# --------------------------------------------------------------------------- + + +class TestApplyDepthClippingMaskedKernel: + """Tests for :func:`apply_depth_clipping_masked_kernel`.""" + + @staticmethod + def _launch( + depth_values: list[list[float]], + max_dist: float, + fill_val: float, + env_mask: list[bool] | None = None, + ) -> np.ndarray: + """Launch kernel and return clipped depth as numpy.""" + num_envs = len(depth_values) + num_rays = len(depth_values[0]) + if env_mask is None: + env_mask = [True] * num_envs + + mask_wp = wp.array(np.array(env_mask, dtype=np.bool_), dtype=wp.bool, device=DEVICE) + depth_wp = wp.array(np.array(depth_values, dtype=np.float32), dtype=wp.float32, device=DEVICE) + + wp.launch( + apply_depth_clipping_masked_kernel, + dim=(num_envs, num_rays), + inputs=[mask_wp, max_dist, fill_val], + outputs=[depth_wp], + device=DEVICE, + ) + wp.synchronize_device(DEVICE) + return _to_numpy(depth_wp) + + def test_boundary_at_max_dist(self): + """Value at exactly max_dist is preserved (not clipped).""" + result = self._launch([[10.0]], max_dist=10.0, fill_val=0.0) + assert result[0, 0] == pytest.approx(10.0, abs=ATOL) + + def test_above_max_dist(self): + """Value above max_dist is replaced with fill_val.""" + result = self._launch([[10.001]], max_dist=10.0, fill_val=0.0) + assert result[0, 0] == pytest.approx(0.0, abs=ATOL) + + def test_nan_value(self): + """NaN value is replaced with fill_val.""" + result = self._launch([[float("nan")]], max_dist=10.0, fill_val=0.0) + assert result[0, 0] == pytest.approx(0.0, abs=ATOL) + + def test_inf_value(self): + """Inf is clipped (inf > max_dist is true).""" + result = self._launch([[float("inf")]], max_dist=10.0, fill_val=0.0) + assert result[0, 0] == pytest.approx(0.0, abs=ATOL) + + def test_negative_depth(self): + """Negative depth passes through unclipped (valid for distance-to-image-plane).""" + result = self._launch([[-3.5]], max_dist=10.0, fill_val=0.0) + assert result[0, 0] == pytest.approx(-3.5, abs=ATOL) + + def test_env_mask(self): + """Masked env retains original value -- clipping is not applied.""" + result = self._launch( + depth_values=[[15.0], [15.0]], + max_dist=10.0, + fill_val=0.0, + env_mask=[False, True], + ) + # Env 0 (masked): unchanged + assert result[0, 0] == pytest.approx(15.0, abs=ATOL) + # Env 1 (active): clipped + assert result[1, 0] == pytest.approx(0.0, abs=ATOL) + + def test_fill_val_zero_vs_max(self): + """fill_val=0.0 and fill_val=max_dist produce correct replacements.""" + max_dist = 10.0 + + result_zero = self._launch([[15.0]], max_dist=max_dist, fill_val=0.0) + assert result_zero[0, 0] == pytest.approx(0.0, abs=ATOL) + + result_max = self._launch([[15.0]], max_dist=max_dist, fill_val=max_dist) + assert result_max[0, 0] == pytest.approx(max_dist, abs=ATOL) + + +# --------------------------------------------------------------------------- +# Tests: apply_z_drift_kernel +# --------------------------------------------------------------------------- + + +class TestApplyZDriftKernel: + """Tests for :func:`apply_z_drift_kernel`.""" + + @staticmethod + def _launch( + hits: list[list[list[float]]], + drift: list[list[float]], + env_mask: list[bool] | None = None, + ) -> np.ndarray: + """Launch kernel and return modified ray_hits as numpy.""" + num_envs = len(hits) + num_rays = len(hits[0]) + if env_mask is None: + env_mask = [True] * num_envs + + mask_wp = wp.array(np.array(env_mask, dtype=np.bool_), dtype=wp.bool, device=DEVICE) + drift_wp = wp.array(np.array(drift, dtype=np.float32), dtype=wp.vec3f, device=DEVICE) + hits_wp = wp.array(np.array(hits, dtype=np.float32), dtype=wp.vec3f, device=DEVICE) + + wp.launch( + apply_z_drift_kernel, + dim=(num_envs, num_rays), + inputs=[mask_wp, drift_wp], + outputs=[hits_wp], + device=DEVICE, + ) + wp.synchronize_device(DEVICE) + return _to_numpy(hits_wp) + + def test_known_drift(self): + """ray_cast_drift = (0, 0, 1.5) shifts ray hit z by exactly 1.5.""" + result = self._launch( + hits=[[[3.0, 4.0, 5.0]]], + drift=[[0.0, 0.0, 1.5]], + ) + np.testing.assert_allclose(result[0, 0], [3.0, 4.0, 6.5], atol=ATOL) + + def test_only_z_component(self): + """Only z-component of drift is applied; x and y are unchanged.""" + result = self._launch( + hits=[[[3.0, 4.0, 5.0]]], + drift=[[0.5, 0.3, 1.0]], + ) + np.testing.assert_allclose(result[0, 0], [3.0, 4.0, 6.0], atol=ATOL) + + +# --------------------------------------------------------------------------- +# Tests: quat_yaw_only +# --------------------------------------------------------------------------- + + +class TestQuatYawOnly: + """Tests for :func:`quat_yaw_only` (a ``@wp.func`` tested via wrapper kernel).""" + + def test_gimbal_lock(self): + """At pitch = +/-pi/2, atan2 is near-degenerate but should produce a + finite, unit-norm, pure-yaw quaternion (only z and w components). + """ + q_down = _euler_to_quat_xyzw(0, math.pi / 2, 0) # pitch = +pi/2 + q_up = _euler_to_quat_xyzw(0, -math.pi / 2, 0) # pitch = -pi/2 + + q_in_np = np.array([list(q_down), list(q_up)], dtype=np.float32) + q_in = wp.array(q_in_np, dtype=wp.quatf, device=DEVICE) + q_out = wp.zeros(2, dtype=wp.quatf, device=DEVICE) + + wp.launch( + _quat_yaw_only_test_kernel, + dim=2, + inputs=[q_in], + outputs=[q_out], + device=DEVICE, + ) + wp.synchronize_device(DEVICE) + + result = _to_numpy(q_out) + + for i in range(2): + qx, qy, qz, qw = result[i] + # Must be finite (no NaN / inf) + assert np.isfinite(result[i]).all(), f"Non-finite output at index {i}: {result[i]}" + # Must be a pure-yaw quaternion: x ~ 0, y ~ 0 + assert abs(qx) < ATOL, f"x-component should be ~0 at gimbal lock, got {qx}" + assert abs(qy) < ATOL, f"y-component should be ~0 at gimbal lock, got {qy}" + # Must be unit-norm + norm = math.sqrt(float(qx) ** 2 + float(qy) ** 2 + float(qz) ** 2 + float(qw) ** 2) + assert norm == pytest.approx(1.0, abs=ATOL), f"Non-unit quaternion at index {i}: norm={norm}" diff --git a/source/isaaclab/test/sensors/test_ray_caster_sensor.py b/source/isaaclab/test/sensors/test_ray_caster_sensor.py new file mode 100644 index 000000000000..3326c524f958 --- /dev/null +++ b/source/isaaclab/test/sensors/test_ray_caster_sensor.py @@ -0,0 +1,271 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +# pyright: reportPrivateUsage=none + +"""Tests for RayCaster sensor behavior: alignment modes and reset.""" + +from isaaclab.app import AppLauncher + +simulation_app = AppLauncher(headless=True).app + +import numpy as np +import pytest +import torch + +import isaaclab.sim as sim_utils +from isaaclab.sensors.ray_caster import RayCaster, RayCasterCfg, patterns +from isaaclab.terrains.trimesh.utils import make_plane +from isaaclab.terrains.utils import create_prim_from_mesh +from isaaclab.utils.math import quat_from_euler_xyz + +# ------------------------------------------------------------------- +# Helpers +# ------------------------------------------------------------------- + +_GROUND_PATH = "/World/Ground" + + +def _make_sim_and_ground(): + """Create a blank stage with a flat ground plane at z=0 and return the SimulationContext.""" + sim_utils.create_new_stage() + dt = 0.01 + sim_cfg = sim_utils.SimulationCfg(dt=dt) + sim = sim_utils.SimulationContext(sim_cfg) + mesh = make_plane(size=(100, 100), height=0.0, center_zero=True) + create_prim_from_mesh(_GROUND_PATH, mesh) + sim_utils.update_stage() + return sim + + +def _ray_caster_cfg(prim_path: str, alignment: str) -> RayCasterCfg: + """Single downward ray, no offset from prim.""" + return RayCasterCfg( + prim_path=prim_path, + mesh_prim_paths=[_GROUND_PATH], + update_period=0, + offset=RayCasterCfg.OffsetCfg(pos=(0.0, 0.0, 0.0), rot=(0.0, 0.0, 0.0, 1.0)), + debug_vis=False, + pattern_cfg=patterns.GridPatternCfg(resolution=1.0, size=(0.0, 0.0), direction=(0.0, 0.0, -1.0)), + ray_alignment=alignment, + ) + + +@pytest.fixture +def sim_ground(): + sim = _make_sim_and_ground() + yield sim + sim.stop() + sim.clear_instance() + + +# ------------------------------------------------------------------- +# Alignment mode tests +# ------------------------------------------------------------------- + + +@pytest.mark.isaacsim_ci +def test_world_alignment_ignores_sensor_pitch(sim_ground): + """In 'world' alignment, ray direction is always (0,0,-1) regardless of sensor pitch. + + Two sensors at the same location: one upright (identity), one pitched 30°. + World-mode sensors must produce the same hit position (straight below at z=0). + """ + sim = sim_ground + + # Upright sensor: identity orientation + sim_utils.create_prim("/World/SensorUpright", "Xform", translation=(0.0, 0.0, 2.0)) + # Pitched 30° sensor — orientation=(x,y,z,w) per Isaac Lab convention + pitch_quat = quat_from_euler_xyz( + torch.tensor([0.0]), torch.tensor([np.pi / 6]), torch.tensor([0.0]) + ) # shape (1, 4), xyzw + sim_utils.create_prim( + "/World/SensorPitched", + "Xform", + translation=(0.0, 0.0, 2.0), + orientation=tuple(pitch_quat[0].tolist()), # xyzw + ) + + sensor_upright = RayCaster(_ray_caster_cfg("/World/SensorUpright", "world")) + sensor_pitched = RayCaster(_ray_caster_cfg("/World/SensorPitched", "world")) + sim.reset() + + dt = 0.01 + sensor_upright.update(dt) + sensor_pitched.update(dt) + + # ray_hits_w returns a ProxyArray; use .torch for tensor indexing. + hits_upright = sensor_upright.data.ray_hits_w.torch # (1, 1, 3) + hits_pitched = sensor_pitched.data.ray_hits_w.torch + + # Both must hit z=0 (straight down, world frame direction) + assert abs(hits_upright[0, 0, 2].item()) < 0.02, ( + f"Upright world sensor must hit z≈0, got {hits_upright[0, 0, 2].item()}" + ) + assert abs(hits_pitched[0, 0, 2].item()) < 0.02, ( + f"Pitched world sensor must hit z≈0, got {hits_pitched[0, 0, 2].item()}" + ) + # Lateral positions must agree (same start at [0,0,2] + same direction [0,0,-1]) + torch.testing.assert_close(hits_upright, hits_pitched, atol=0.02, rtol=0) + + +@pytest.mark.isaacsim_ci +def test_base_alignment_rotates_ray_direction(sim_ground): + """In 'base' alignment, ray direction follows the full sensor orientation. + + A sensor pitched +30° around Y (quat_from_euler_xyz(pitch=pi/6)): + - Rotates (0,0,-1) to (-sin(30°), 0, -cos(30°)) = (-0.5, 0, -0.866) + - world mode → ray still goes straight down, hits x≈0, z≈0 + - base mode → ray tilts, hits at x ≈ -2*tan(30°) ≈ -1.155 + """ + sim = sim_ground + + pitch_quat = quat_from_euler_xyz( + torch.tensor([0.0]), torch.tensor([np.pi / 6]), torch.tensor([0.0]) + ) # shape (1, 4), xyzw + orientation = tuple(pitch_quat[0].tolist()) + + sim_utils.create_prim("/World/SensorWorld", "Xform", translation=(0.0, 0.0, 2.0), orientation=orientation) + sim_utils.create_prim("/World/SensorBase", "Xform", translation=(0.0, 0.0, 2.0), orientation=orientation) + + sensor_world = RayCaster(_ray_caster_cfg("/World/SensorWorld", "world")) + sensor_base = RayCaster(_ray_caster_cfg("/World/SensorBase", "base")) + sim.reset() + + dt = 0.01 + sensor_world.update(dt) + sensor_base.update(dt) + + hits_world = sensor_world.data.ray_hits_w.torch # (1, 1, 3) + hits_base = sensor_base.data.ray_hits_w.torch + + # World mode: ray still hits directly below (x≈0, y≈0, z≈0) + assert abs(hits_world[0, 0, 0].item()) < 0.05, f"World mode hit x must be near 0, got {hits_world[0, 0, 0].item()}" + assert abs(hits_world[0, 0, 2].item()) < 0.05, f"World mode must hit z≈0, got {hits_world[0, 0, 2].item()}" + + # Base mode: pitch +30° around Y rotates (0,0,-1) to (-0.5, 0, -0.866). + # From height 2, the ray hits x = -2 * tan(30°) ≈ -1.155. + expected_x = -2.0 * np.tan(np.pi / 6) + assert abs(hits_base[0, 0, 0].item() - expected_x) < 0.05, ( + f"Base mode hit x should be ≈{expected_x:.3f}, got {hits_base[0, 0, 0].item():.3f}" + ) + assert abs(hits_base[0, 0, 2].item()) < 0.05, f"Base mode must hit ground (z≈0), got {hits_base[0, 0, 2].item()}" + + +@pytest.mark.isaacsim_ci +def test_yaw_alignment_direction_unchanged(sim_ground): + """In 'yaw' alignment, ray directions stay world-down despite pitch+roll. + + Setup: sensor at (0,0,2), pitched 30° and yawed 45°; pattern has a single ray + at local offset (+1, 0, 0). + + - world mode: start = sensor_pos + (1,0,0) (no rotation applied to offset) + - yaw mode: start = sensor_pos + yaw_rot(45°) @ (1,0,0) = (cos45°, sin45°, 0) + + Both modes fire the ray straight down (direction unchanged), so both hit z=0. + The hit x-coordinate differs between modes, confirming the yaw-only rotation of + start positions is applied in 'yaw' mode but not in 'world' mode. + """ + sim = sim_ground + + combined_quat = quat_from_euler_xyz( + torch.tensor([0.0]), + torch.tensor([np.pi / 6]), # 30° pitch + torch.tensor([np.pi / 4]), # 45° yaw + ) # shape (1, 4), xyzw + orientation = tuple(combined_quat[0].tolist()) + + sim_utils.create_prim("/World/SensorWorldY", "Xform", translation=(0.0, 0.0, 2.0), orientation=orientation) + sim_utils.create_prim("/World/SensorYaw", "Xform", translation=(0.0, 0.0, 2.0), orientation=orientation) + + # Use a single ray at local offset (+1, 0, 0), still pointing down + def _cfg_with_offset(prim_path, alignment): + return RayCasterCfg( + prim_path=prim_path, + mesh_prim_paths=[_GROUND_PATH], + update_period=0, + offset=RayCasterCfg.OffsetCfg(pos=(1.0, 0.0, 0.0), rot=(0.0, 0.0, 0.0, 1.0)), + debug_vis=False, + pattern_cfg=patterns.GridPatternCfg(resolution=1.0, size=(0.0, 0.0), direction=(0.0, 0.0, -1.0)), + ray_alignment=alignment, + ) + + sensor_world = RayCaster(_cfg_with_offset("/World/SensorWorldY", "world")) + sensor_yaw = RayCaster(_cfg_with_offset("/World/SensorYaw", "yaw")) + sim.reset() + + dt = 0.01 + sensor_world.update(dt) + sensor_yaw.update(dt) + + hits_world = sensor_world.data.ray_hits_w.torch # (1, 1, 3) + hits_yaw = sensor_yaw.data.ray_hits_w.torch + + # Both modes must hit the ground (direction unchanged = straight down in both modes) + assert abs(hits_world[0, 0, 2].item()) < 0.05, "World mode must hit z≈0" + assert abs(hits_yaw[0, 0, 2].item()) < 0.05, "Yaw mode must hit z≈0 (direction straight down)" + + # world mode: offset (1,0,0) not rotated → ray starts at sensor_pos+(1,0,0) → hits x≈1 + assert abs(hits_world[0, 0, 0].item() - 1.0) < 0.05, ( + f"World mode: hit x should be ≈1.0 (unrotated offset), got {hits_world[0, 0, 0].item():.3f}" + ) + + # yaw mode: offset (1,0,0) rotated by 45° yaw → starts at sensor_pos+(cos45°, sin45°, 0) → hits x≈cos45° + expected_x_yaw = np.cos(np.pi / 4) # ≈ 0.707 + assert abs(hits_yaw[0, 0, 0].item() - expected_x_yaw) < 0.05, ( + f"Yaw mode: hit x should be ≈{expected_x_yaw:.3f} (yaw-rotated offset), got {hits_yaw[0, 0, 0].item():.3f}" + ) + # Confirm they differ — if they were the same, the test would not cover the yaw rotation + assert not torch.allclose(hits_world, hits_yaw, atol=0.1), ( + "Yaw and world modes must produce different hit positions for non-zero lateral offset" + ) + + +# ------------------------------------------------------------------- +# Reset / drift test +# ------------------------------------------------------------------- + + +@pytest.mark.isaacsim_ci +def test_ray_caster_reset_resamples_drift(sim_ground): + """reset() resamples drift values within the configured drift_range.""" + sim = sim_ground + + sim_utils.create_prim("/World/Sensor", "Xform", translation=(0.0, 0.0, 2.0)) + cfg = _ray_caster_cfg("/World/Sensor", "world") + cfg.drift_range = (0.01, 0.05) # force non-zero drift + sensor = RayCaster(cfg) + sim.reset() + # sim.reset() initializes the sensor with zero drift; call sensor.reset() to resample + # from the configured drift_range before we capture the baseline. + sensor.reset() + + dt = 0.01 + sensor.update(dt) + drift_before = sensor.drift.clone() # (1, 3) torch tensor + + lo, hi = cfg.drift_range + + # After sensor.reset(), drift should be within the configured range + assert drift_before.shape == (1, 3), f"Drift shape should be (1, 3), got {drift_before.shape}" + assert (drift_before >= lo - 1e-6).all() and (drift_before <= hi + 1e-6).all(), ( + f"Initial drift must be in [{lo}, {hi}], got [{drift_before.min():.4f}, {drift_before.max():.4f}]" + ) + + # reset() resamples drift; values should remain within the configured range + # Call reset() multiple times until we get a different sample (probability of same is near zero + # for continuous uniform distribution, but we retry to avoid flakiness). + for _ in range(5): + sensor.reset() + drift_after = sensor.drift.clone() + if not torch.allclose(drift_after, drift_before): + break + assert drift_after.shape == drift_before.shape, "Drift shape must be preserved after reset" + assert (drift_after >= lo - 1e-6).all() and (drift_after <= hi + 1e-6).all(), ( + f"Drift after reset must be in [{lo}, {hi}], got [{drift_after.min():.4f}, {drift_after.max():.4f}]" + ) + assert not torch.allclose(drift_after, drift_before), ( + "reset() must resample drift; values must change from initial sample" + ) diff --git a/source/isaaclab/test/sensors/test_tiled_camera.py b/source/isaaclab/test/sensors/test_tiled_camera.py index 0fcf5f26c612..4ce62cd5336f 100644 --- a/source/isaaclab/test/sensors/test_tiled_camera.py +++ b/source/isaaclab/test/sensors/test_tiled_camera.py @@ -6,6 +6,14 @@ # ignore private usage of variables warning # pyright: reportPrivateUsage=none +"""Tests for the deprecated TiledCamera / TiledCameraCfg aliases. + +TiledCamera is now a thin subclass of Camera that emits a DeprecationWarning. +All substantive Camera tests live in ``test_camera.py``. This file only verifies +that the deprecation mechanism works correctly and that TiledCamera remains a +functional Camera alias. +""" + """Launch Isaac Sim Simulator first.""" from isaaclab.app import AppLauncher @@ -15,30 +23,27 @@ """Rest everything follows.""" -import copy import random +import warnings import numpy as np import pytest import torch -import warp as wp import omni.replicator.core as rep -from pxr import Gf, UsdGeom, UsdPhysics +from pxr import Gf, UsdGeom import isaaclab.sim as sim_utils from isaaclab.sensors.camera import Camera, CameraCfg, TiledCamera, TiledCameraCfg -from isaaclab.utils.assets import ISAAC_NUCLEUS_DIR -from isaaclab.utils.timer import Timer @pytest.fixture(scope="function") -def setup_camera(device) -> tuple[sim_utils.SimulationContext, TiledCameraCfg, float]: +def setup_camera(device) -> tuple[sim_utils.SimulationContext, CameraCfg, float]: """Fixture to set up and tear down the camera simulation environment.""" - camera_cfg = TiledCameraCfg( + camera_cfg = CameraCfg( height=128, width=256, - offset=TiledCameraCfg.OffsetCfg(pos=(0.0, 0.0, 4.0), rot=(0.0, 1.0, 0.0, 0.0), convention="ros"), + offset=CameraCfg.OffsetCfg(pos=(0.0, 0.0, 4.0), rot=(0.0, 1.0, 0.0, 0.0), convention="ros"), prim_path="/World/Camera", update_period=0, data_types=["rgb", "distance_to_camera"], @@ -66,189 +71,73 @@ def setup_camera(device) -> tuple[sim_utils.SimulationContext, TiledCameraCfg, f @pytest.mark.parametrize("device", ["cuda:0", "cpu"]) @pytest.mark.isaacsim_ci -def test_single_camera_init(setup_camera, device): - """Test single camera initialization.""" +def test_tiled_camera_deprecation_warning(setup_camera, device): + """TiledCamera instantiation emits a DeprecationWarning.""" sim, camera_cfg, dt = setup_camera - # Create camera - camera = TiledCamera(camera_cfg) - # Check simulation parameter is set correctly - assert sim.get_setting("/isaaclab/render/rtx_sensors") - # Play sim - sim.reset() - # Check if camera is initialized - assert camera.is_initialized - # Check if camera prim is set correctly and that it is a camera prim - assert camera._sensor_prims[0].GetPath().pathString == camera_cfg.prim_path - assert isinstance(camera._sensor_prims[0], UsdGeom.Camera) - - # Check buffers that exists and have correct shapes - assert camera.data.pos_w.shape == (1, 3) - assert camera.data.quat_w_ros.shape == (1, 4) - assert camera.data.quat_w_world.shape == (1, 4) - assert camera.data.quat_w_opengl.shape == (1, 4) - assert camera.data.intrinsic_matrices.shape == (1, 3, 3) - assert camera.data.image_shape == (camera_cfg.height, camera_cfg.width) - - # Simulate physics - for _ in range(10): - # perform rendering - sim.step() - # update camera - camera.update(dt) - # check image data - for im_type, im_data in camera.data.output.items(): - if im_type == "rgb": - assert im_data.shape == (1, camera_cfg.height, camera_cfg.width, 3) - assert (im_data / 255.0).mean() > 0.0 - elif im_type == "distance_to_camera": - assert im_data.shape == (1, camera_cfg.height, camera_cfg.width, 1) - assert im_data.mean() > 0.0 - del camera - - -@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) -@pytest.mark.isaacsim_ci -def test_depth_clipping_max(setup_camera, device): - """Test depth max clipping.""" - sim, _, dt = setup_camera - # get camera cfgs - camera_cfg = TiledCameraCfg( - prim_path="/World/Camera", - offset=TiledCameraCfg.OffsetCfg(pos=(2.5, 2.5, 6.0), rot=(0.362, 0.873, -0.302, -0.125), convention="ros"), - spawn=sim_utils.PinholeCameraCfg().from_intrinsic_matrix( - focal_length=38.0, - intrinsic_matrix=[380.08, 0.0, 467.79, 0.0, 380.08, 262.05, 0.0, 0.0, 1.0], - height=540, - width=960, - clipping_range=(4.9, 5.0), - ), - height=540, - width=960, - data_types=["depth"], - depth_clipping_behavior="max", - ) - camera = TiledCamera(camera_cfg) - - # Play sim - sim.reset() - - camera.update(dt) - - assert len(camera.data.output["depth"][torch.isinf(camera.data.output["depth"])]) == 0 - assert camera.data.output["depth"].min() >= camera_cfg.spawn.clipping_range[0] - assert camera.data.output["depth"].max() <= camera_cfg.spawn.clipping_range[1] - + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter("always") + camera = TiledCamera(camera_cfg) + deprecation_warnings = [x for x in w if issubclass(x.category, DeprecationWarning)] + assert len(deprecation_warnings) >= 1 + assert "TiledCamera is deprecated" in str(deprecation_warnings[0].message) del camera @pytest.mark.parametrize("device", ["cuda:0", "cpu"]) @pytest.mark.isaacsim_ci -def test_depth_clipping_none(setup_camera, device): - """Test depth none clipping.""" - sim, _, dt = setup_camera - # get camera cfgs - camera_cfg = TiledCameraCfg( - prim_path="/World/Camera", - offset=TiledCameraCfg.OffsetCfg(pos=(2.5, 2.5, 6.0), rot=(0.362, 0.873, -0.302, -0.125), convention="ros"), - spawn=sim_utils.PinholeCameraCfg().from_intrinsic_matrix( - focal_length=38.0, - intrinsic_matrix=[380.08, 0.0, 467.79, 0.0, 380.08, 262.05, 0.0, 0.0, 1.0], - height=540, - width=960, - clipping_range=(4.9, 5.0), - ), - height=540, - width=960, - data_types=["depth"], - depth_clipping_behavior="none", - ) - camera = TiledCamera(camera_cfg) - - # Play sim - sim.reset() - - camera.update(dt) - - assert len(camera.data.output["depth"][torch.isinf(camera.data.output["depth"])]) > 0 - assert camera.data.output["depth"].min() >= camera_cfg.spawn.clipping_range[0] - if len(camera.data.output["depth"][~torch.isinf(camera.data.output["depth"])]) > 0: - assert ( - camera.data.output["depth"][~torch.isinf(camera.data.output["depth"])].max() - <= camera_cfg.spawn.clipping_range[1] +def test_tiled_camera_cfg_deprecation_warning(setup_camera, device): + """TiledCameraCfg instantiation emits a DeprecationWarning.""" + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter("always") + _cfg = TiledCameraCfg( + height=128, + width=256, + prim_path="/World/Camera", + data_types=["rgb"], + spawn=sim_utils.PinholeCameraCfg( + focal_length=24.0, focus_distance=400.0, horizontal_aperture=20.955, clipping_range=(0.1, 1.0e5) + ), ) - - del camera + deprecation_warnings = [x for x in w if issubclass(x.category, DeprecationWarning)] + assert len(deprecation_warnings) >= 1 + assert "TiledCameraCfg is deprecated" in str(deprecation_warnings[0].message) +@pytest.mark.filterwarnings("ignore::DeprecationWarning") @pytest.mark.parametrize("device", ["cuda:0", "cpu"]) @pytest.mark.isaacsim_ci -def test_depth_clipping_zero(setup_camera, device): - """Test depth zero clipping.""" - sim, _, dt = setup_camera - # get camera cfgs - camera_cfg = TiledCameraCfg( - prim_path="/World/Camera", - offset=TiledCameraCfg.OffsetCfg(pos=(2.5, 2.5, 6.0), rot=(0.362, 0.873, -0.302, -0.125), convention="ros"), - spawn=sim_utils.PinholeCameraCfg().from_intrinsic_matrix( - focal_length=38.0, - intrinsic_matrix=[380.08, 0.0, 467.79, 0.0, 380.08, 262.05, 0.0, 0.0, 1.0], - height=540, - width=960, - clipping_range=(4.9, 5.0), - ), - height=540, - width=960, - data_types=["depth"], - depth_clipping_behavior="zero", - ) +def test_tiled_camera_is_camera_subclass(setup_camera, device): + """TiledCamera is a subclass of Camera, so isinstance checks work.""" + sim, camera_cfg, dt = setup_camera camera = TiledCamera(camera_cfg) - - # Play sim - sim.reset() - - camera.update(dt) - - assert len(camera.data.output["depth"][torch.isinf(camera.data.output["depth"])]) == 0 - assert camera.data.output["depth"].min() == 0.0 - assert camera.data.output["depth"].max() <= camera_cfg.spawn.clipping_range[1] - + assert isinstance(camera, Camera) + assert isinstance(camera, TiledCamera) del camera +@pytest.mark.filterwarnings("ignore::DeprecationWarning") @pytest.mark.parametrize("device", ["cuda:0", "cpu"]) @pytest.mark.isaacsim_ci -def test_multi_camera_init(setup_camera, device): - """Test multi-camera initialization.""" +def test_tiled_camera_basic_functionality(setup_camera, device): + """TiledCamera produces correct output (proving it delegates to Camera).""" sim, camera_cfg, dt = setup_camera - - num_cameras = 9 - for i in range(num_cameras): - sim_utils.create_prim(f"/World/Origin_{i}", "Xform") - # Create camera - camera_cfg = copy.deepcopy(camera_cfg) - camera_cfg.prim_path = "/World/Origin_.*/CameraSensor" camera = TiledCamera(camera_cfg) - # Check simulation parameter is set correctly - assert sim.get_setting("/isaaclab/render/rtx_sensors") # Play sim sim.reset() # Check if camera is initialized assert camera.is_initialized # Check if camera prim is set correctly and that it is a camera prim - assert camera._sensor_prims[1].GetPath().pathString == "/World/Origin_1/CameraSensor" + assert camera._sensor_prims[0].GetPath().pathString == camera_cfg.prim_path assert isinstance(camera._sensor_prims[0], UsdGeom.Camera) # Check buffers that exists and have correct shapes - assert camera.data.pos_w.shape == (num_cameras, 3) - assert camera.data.quat_w_ros.shape == (num_cameras, 4) - assert camera.data.quat_w_world.shape == (num_cameras, 4) - assert camera.data.quat_w_opengl.shape == (num_cameras, 4) - assert camera.data.intrinsic_matrices.shape == (num_cameras, 3, 3) + assert camera.data.pos_w.shape == (1, 3) + assert camera.data.intrinsic_matrices.shape == (1, 3, 3) assert camera.data.image_shape == (camera_cfg.height, camera_cfg.width) # Simulate physics - for _ in range(10): + for _ in range(5): # perform rendering sim.step() # update camera @@ -256,1477 +145,19 @@ def test_multi_camera_init(setup_camera, device): # check image data for im_type, im_data in camera.data.output.items(): if im_type == "rgb": - assert im_data.shape == (num_cameras, camera_cfg.height, camera_cfg.width, 3) - for i in range(4): - assert (im_data[i] / 255.0).mean() > 0.0 + assert im_data.shape == (1, camera_cfg.height, camera_cfg.width, 3) + assert (im_data / 255.0).mean() > 0.0 elif im_type == "distance_to_camera": - assert im_data.shape == (num_cameras, camera_cfg.height, camera_cfg.width, 1) - for i in range(4): - assert im_data[i].mean() > 0.0 - del camera - - -@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) -@pytest.mark.isaacsim_ci -def test_rgb_only_camera(setup_camera, device): - """Test initialization with only RGB data type.""" - sim, camera_cfg, dt = setup_camera - num_cameras = 9 - for i in range(num_cameras): - sim_utils.create_prim(f"/World/Origin_{i}", "Xform") - - # Create camera - camera_cfg = copy.deepcopy(camera_cfg) - camera_cfg.data_types = ["rgb"] - camera_cfg.prim_path = "/World/Origin_.*/CameraSensor" - camera = TiledCamera(camera_cfg) - # Check simulation parameter is set correctly - assert sim.get_setting("/isaaclab/render/rtx_sensors") - # Play sim - sim.reset() - # Check if camera is initialized - assert camera.is_initialized - # Check if camera prim is set correctly and that it is a camera prim - assert camera._sensor_prims[1].GetPath().pathString == "/World/Origin_1/CameraSensor" - assert isinstance(camera._sensor_prims[0], UsdGeom.Camera) - assert list(camera.data.output.keys()) == ["rgba", "rgb"] - - # Check buffers that exists and have correct shapes - assert camera.data.pos_w.shape == (num_cameras, 3) - assert camera.data.quat_w_ros.shape == (num_cameras, 4) - assert camera.data.quat_w_world.shape == (num_cameras, 4) - assert camera.data.quat_w_opengl.shape == (num_cameras, 4) - assert camera.data.intrinsic_matrices.shape == (num_cameras, 3, 3) - assert camera.data.image_shape == (camera_cfg.height, camera_cfg.width) - - # Simulate physics - for _ in range(10): - # perform rendering - sim.step() - # update camera - camera.update(dt) - # check image data - im_data = camera.data.output["rgb"] - assert im_data.shape == (num_cameras, camera_cfg.height, camera_cfg.width, 3) - for i in range(4): - assert (im_data[i] / 255.0).mean() > 0.0 - assert camera.data.output["rgb"].dtype == torch.uint8 - del camera - - -@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) -@pytest.mark.isaacsim_ci -def test_data_types(setup_camera, device): - """Test different data types for camera initialization.""" - sim, camera_cfg, dt = setup_camera - # Create camera - camera_cfg_distance = copy.deepcopy(camera_cfg) - camera_cfg_distance.data_types = ["distance_to_camera"] - camera_cfg_distance.prim_path = "/World/CameraDistance" - camera_distance = TiledCamera(camera_cfg_distance) - camera_cfg_depth = copy.deepcopy(camera_cfg) - camera_cfg_depth.data_types = ["depth"] - camera_cfg_depth.prim_path = "/World/CameraDepth" - camera_depth = TiledCamera(camera_cfg_depth) - camera_cfg_both = copy.deepcopy(camera_cfg) - camera_cfg_both.data_types = ["distance_to_camera", "depth"] - camera_cfg_both.prim_path = "/World/CameraBoth" - camera_both = TiledCamera(camera_cfg_both) - - # Play sim - sim.reset() - - # Check if cameras are initialized - assert camera_distance.is_initialized - assert camera_depth.is_initialized - assert camera_both.is_initialized - - # Check if camera prims are set correctly and that they are camera prims - assert camera_distance._sensor_prims[0].GetPath().pathString == "/World/CameraDistance" - assert isinstance(camera_distance._sensor_prims[0], UsdGeom.Camera) - assert camera_depth._sensor_prims[0].GetPath().pathString == "/World/CameraDepth" - assert isinstance(camera_depth._sensor_prims[0], UsdGeom.Camera) - assert camera_both._sensor_prims[0].GetPath().pathString == "/World/CameraBoth" - assert isinstance(camera_both._sensor_prims[0], UsdGeom.Camera) - assert list(camera_distance.data.output.keys()) == ["distance_to_camera"] - assert list(camera_depth.data.output.keys()) == ["depth"] - assert list(camera_both.data.output.keys()) == ["depth", "distance_to_camera"] - - del camera_distance - del camera_depth - del camera_both - - -@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) -@pytest.mark.isaacsim_ci -def test_depth_only_camera(setup_camera, device): - """Test initialization with only depth.""" - sim, camera_cfg, dt = setup_camera - num_cameras = 9 - for i in range(num_cameras): - sim_utils.create_prim(f"/World/Origin_{i}", "Xform") - - # Create camera - camera_cfg = copy.deepcopy(camera_cfg) - camera_cfg.data_types = ["distance_to_camera"] - camera_cfg.prim_path = "/World/Origin_.*/CameraSensor" - camera = TiledCamera(camera_cfg) - # Check simulation parameter is set correctly - assert sim.get_setting("/isaaclab/render/rtx_sensors") - # Play sim - sim.reset() - # Check if camera is initialized - assert camera.is_initialized - # Check if camera prim is set correctly and that it is a camera prim - assert camera._sensor_prims[1].GetPath().pathString == "/World/Origin_1/CameraSensor" - assert isinstance(camera._sensor_prims[0], UsdGeom.Camera) - assert list(camera.data.output.keys()) == ["distance_to_camera"] - - # Check buffers that exists and have correct shapes - assert camera.data.pos_w.shape == (num_cameras, 3) - assert camera.data.quat_w_ros.shape == (num_cameras, 4) - assert camera.data.quat_w_world.shape == (num_cameras, 4) - assert camera.data.quat_w_opengl.shape == (num_cameras, 4) - assert camera.data.intrinsic_matrices.shape == (num_cameras, 3, 3) - assert camera.data.image_shape == (camera_cfg.height, camera_cfg.width) - - # Simulate physics - for _ in range(10): - # perform rendering - sim.step() - # update camera - camera.update(dt) - # check image data - im_data = camera.data.output["distance_to_camera"] - assert im_data.shape == (num_cameras, camera_cfg.height, camera_cfg.width, 1) - for i in range(4): - assert im_data[i].mean() > 0.0 - assert camera.data.output["distance_to_camera"].dtype == torch.float - del camera - - -@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) -@pytest.mark.isaacsim_ci -def test_rgba_only_camera(setup_camera, device): - """Test initialization with only RGBA.""" - sim, camera_cfg, dt = setup_camera - num_cameras = 9 - for i in range(num_cameras): - sim_utils.create_prim(f"/World/Origin_{i}", "Xform") - - # Create camera - camera_cfg = copy.deepcopy(camera_cfg) - camera_cfg.data_types = ["rgba"] - camera_cfg.prim_path = "/World/Origin_.*/CameraSensor" - camera = TiledCamera(camera_cfg) - # Check simulation parameter is set correctly - assert sim.get_setting("/isaaclab/render/rtx_sensors") - # Play sim - sim.reset() - # Check if camera is initialized - assert camera.is_initialized - # Check if camera prim is set correctly and that it is a camera prim - assert camera._sensor_prims[1].GetPath().pathString == "/World/Origin_1/CameraSensor" - assert isinstance(camera._sensor_prims[0], UsdGeom.Camera) - assert list(camera.data.output.keys()) == ["rgba"] - - # Check buffers that exists and have correct shapes - assert camera.data.pos_w.shape == (num_cameras, 3) - assert camera.data.quat_w_ros.shape == (num_cameras, 4) - assert camera.data.quat_w_world.shape == (num_cameras, 4) - assert camera.data.quat_w_opengl.shape == (num_cameras, 4) - assert camera.data.intrinsic_matrices.shape == (num_cameras, 3, 3) - assert camera.data.image_shape == (camera_cfg.height, camera_cfg.width) - - # Simulate physics - for _ in range(10): - # perform rendering - sim.step() - # update camera - camera.update(dt) - # check image data - for _, im_data in camera.data.output.items(): - assert im_data.shape == (num_cameras, camera_cfg.height, camera_cfg.width, 4) - for i in range(4): - assert (im_data[i] / 255.0).mean() > 0.0 - assert camera.data.output["rgba"].dtype == torch.uint8 - del camera - - -@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) -@pytest.mark.isaacsim_ci -def test_albedo_only_camera(setup_camera, device): - """Test initialization with only albedo.""" - sim, camera_cfg, dt = setup_camera - num_cameras = 9 - for i in range(num_cameras): - sim_utils.create_prim(f"/World/Origin_{i}", "Xform") - - # Create camera - camera_cfg = copy.deepcopy(camera_cfg) - camera_cfg.data_types = ["albedo"] - camera_cfg.prim_path = "/World/Origin_.*/CameraSensor" - camera = TiledCamera(camera_cfg) - # Check simulation parameter is set correctly - assert sim.get_setting("/isaaclab/render/rtx_sensors") - # Play sim - sim.reset() - # Check if camera is initialized - assert camera.is_initialized - # Check if camera prim is set correctly and that it is a camera prim - assert camera._sensor_prims[1].GetPath().pathString == "/World/Origin_1/CameraSensor" - assert isinstance(camera._sensor_prims[0], UsdGeom.Camera) - assert list(camera.data.output.keys()) == ["albedo"] - - # Check buffers that exists and have correct shapes - assert camera.data.pos_w.shape == (num_cameras, 3) - assert camera.data.quat_w_ros.shape == (num_cameras, 4) - assert camera.data.quat_w_world.shape == (num_cameras, 4) - assert camera.data.quat_w_opengl.shape == (num_cameras, 4) - assert camera.data.intrinsic_matrices.shape == (num_cameras, 3, 3) - assert camera.data.image_shape == (camera_cfg.height, camera_cfg.width) - - # Simulate physics - for _ in range(10): - # perform rendering - sim.step() - # update camera - camera.update(dt) - # check image data - for _, im_data in camera.data.output.items(): - assert im_data.shape == (num_cameras, camera_cfg.height, camera_cfg.width, 4) - for i in range(4): - assert (im_data[i] / 255.0).mean() > 0.0 - assert camera.data.output["albedo"].dtype == torch.uint8 - del camera - - -@pytest.mark.parametrize( - "data_type", - ["simple_shading_constant_diffuse", "simple_shading_diffuse_mdl", "simple_shading_full_mdl"], -) -@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) -@pytest.mark.isaacsim_ci -def test_simple_shading_only_camera(setup_camera, device, data_type): - """Test initialization with only simple shading.""" - sim, camera_cfg, dt = setup_camera - num_cameras = 9 - for i in range(num_cameras): - sim_utils.create_prim(f"/World/Origin_{i}", "Xform") - - # Create camera - camera_cfg = copy.deepcopy(camera_cfg) - camera_cfg.data_types = [data_type] - camera_cfg.prim_path = "/World/Origin_.*/CameraSensor" - camera = TiledCamera(camera_cfg) - # Check simulation parameter is set correctly - assert sim.get_setting("/isaaclab/render/rtx_sensors") - # Play sim - sim.reset() - # Check if camera is initialized - assert camera.is_initialized - # Check if camera prim is set correctly and that it is a camera prim - assert camera._sensor_prims[1].GetPath().pathString == "/World/Origin_1/CameraSensor" - assert isinstance(camera._sensor_prims[0], UsdGeom.Camera) - assert list(camera.data.output.keys()) == [data_type] - - # Check buffers that exists and have correct shapes - assert camera.data.pos_w.shape == (num_cameras, 3) - assert camera.data.quat_w_ros.shape == (num_cameras, 4) - assert camera.data.quat_w_world.shape == (num_cameras, 4) - assert camera.data.quat_w_opengl.shape == (num_cameras, 4) - assert camera.data.intrinsic_matrices.shape == (num_cameras, 3, 3) - assert camera.data.image_shape == (camera_cfg.height, camera_cfg.width) - - # Simulate physics - for _ in range(10): - # perform rendering - sim.step() - # update camera - camera.update(dt) - # check image data - for _, im_data in camera.data.output.items(): - assert im_data.shape == (num_cameras, camera_cfg.height, camera_cfg.width, 3) - for i in range(4): - assert (im_data[i] / 255.0).mean() > 0.0 - assert camera.data.output[data_type].dtype == torch.uint8 - del camera - - -@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) -@pytest.mark.isaacsim_ci -def test_distance_to_camera_only_camera(setup_camera, device): - """Test initialization with only distance_to_camera.""" - sim, camera_cfg, dt = setup_camera - num_cameras = 9 - for i in range(num_cameras): - sim_utils.create_prim(f"/World/Origin_{i}", "Xform") - - # Create camera - camera_cfg = copy.deepcopy(camera_cfg) - camera_cfg.data_types = ["distance_to_camera"] - camera_cfg.prim_path = "/World/Origin_.*/CameraSensor" - camera = TiledCamera(camera_cfg) - # Check simulation parameter is set correctly - assert sim.get_setting("/isaaclab/render/rtx_sensors") - # Play sim - sim.reset() - # Check if camera is initialized - assert camera.is_initialized - # Check if camera prim is set correctly and that it is a camera prim - assert camera._sensor_prims[1].GetPath().pathString == "/World/Origin_1/CameraSensor" - assert isinstance(camera._sensor_prims[0], UsdGeom.Camera) - assert list(camera.data.output.keys()) == ["distance_to_camera"] - - # Check buffers that exists and have correct shapes - assert camera.data.pos_w.shape == (num_cameras, 3) - assert camera.data.quat_w_ros.shape == (num_cameras, 4) - assert camera.data.quat_w_world.shape == (num_cameras, 4) - assert camera.data.quat_w_opengl.shape == (num_cameras, 4) - assert camera.data.intrinsic_matrices.shape == (num_cameras, 3, 3) - assert camera.data.image_shape == (camera_cfg.height, camera_cfg.width) - - # Simulate physics - for _ in range(10): - # perform rendering - sim.step() - # update camera - camera.update(dt) - # check image data - for _, im_data in camera.data.output.items(): - assert im_data.shape == (num_cameras, camera_cfg.height, camera_cfg.width, 1) - for i in range(4): - assert im_data[i].mean() > 0.0 - assert camera.data.output["distance_to_camera"].dtype == torch.float + assert im_data.shape == (1, camera_cfg.height, camera_cfg.width, 1) + assert im_data.mean() > 0.0 del camera -@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) -@pytest.mark.isaacsim_ci -def test_distance_to_image_plane_only_camera(setup_camera, device): - """Test initialization with only distance_to_image_plane.""" - sim, camera_cfg, dt = setup_camera - num_cameras = 9 - for i in range(num_cameras): - sim_utils.create_prim(f"/World/Origin_{i}", "Xform") - - # Create camera - camera_cfg = copy.deepcopy(camera_cfg) - camera_cfg.data_types = ["distance_to_image_plane"] - camera_cfg.prim_path = "/World/Origin_.*/CameraSensor" - camera = TiledCamera(camera_cfg) - # Check simulation parameter is set correctly - assert sim.get_setting("/isaaclab/render/rtx_sensors") - # Play sim - sim.reset() - # Check if camera is initialized - assert camera.is_initialized - # Check if camera prim is set correctly and that it is a camera prim - assert camera._sensor_prims[1].GetPath().pathString == "/World/Origin_1/CameraSensor" - assert isinstance(camera._sensor_prims[0], UsdGeom.Camera) - assert list(camera.data.output.keys()) == ["distance_to_image_plane"] - - # Check buffers that exists and have correct shapes - assert camera.data.pos_w.shape == (num_cameras, 3) - assert camera.data.quat_w_ros.shape == (num_cameras, 4) - assert camera.data.quat_w_world.shape == (num_cameras, 4) - assert camera.data.quat_w_opengl.shape == (num_cameras, 4) - assert camera.data.intrinsic_matrices.shape == (num_cameras, 3, 3) - assert camera.data.image_shape == (camera_cfg.height, camera_cfg.width) - - # Simulate physics - for _ in range(10): - # perform rendering - sim.step() - # update camera - camera.update(dt) - # check image data - for _, im_data in camera.data.output.items(): - assert im_data.shape == (num_cameras, camera_cfg.height, camera_cfg.width, 1) - for i in range(4): - assert im_data[i].mean() > 0.0 - assert camera.data.output["distance_to_image_plane"].dtype == torch.float - del camera - - -@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) -@pytest.mark.isaacsim_ci -def test_normals_only_camera(setup_camera, device): - """Test initialization with only normals.""" - sim, camera_cfg, dt = setup_camera - num_cameras = 9 - for i in range(num_cameras): - sim_utils.create_prim(f"/World/Origin_{i}", "Xform") - - # Create camera - camera_cfg = copy.deepcopy(camera_cfg) - camera_cfg.data_types = ["normals"] - camera_cfg.prim_path = "/World/Origin_.*/CameraSensor" - camera = TiledCamera(camera_cfg) - # Check simulation parameter is set correctly - assert sim.get_setting("/isaaclab/render/rtx_sensors") - # Play sim - sim.reset() - # Check if camera is initialized - assert camera.is_initialized - # Check if camera prim is set correctly and that it is a camera prim - assert camera._sensor_prims[1].GetPath().pathString == "/World/Origin_1/CameraSensor" - assert isinstance(camera._sensor_prims[0], UsdGeom.Camera) - assert list(camera.data.output.keys()) == ["normals"] - - # Check buffers that exists and have correct shapes - assert camera.data.pos_w.shape == (num_cameras, 3) - assert camera.data.quat_w_ros.shape == (num_cameras, 4) - assert camera.data.quat_w_world.shape == (num_cameras, 4) - assert camera.data.quat_w_opengl.shape == (num_cameras, 4) - assert camera.data.intrinsic_matrices.shape == (num_cameras, 3, 3) - assert camera.data.image_shape == (camera_cfg.height, camera_cfg.width) - - # Simulate physics - for _ in range(10): - # perform rendering - sim.step() - # update camera - camera.update(dt) - # check image data - for _, im_data in camera.data.output.items(): - assert im_data.shape == (num_cameras, camera_cfg.height, camera_cfg.width, 3) - for i in range(4): - assert im_data[i].mean() > 0.0 - # check normal norm is approximately 1 - norms = torch.linalg.norm(im_data, dim=-1) - assert torch.allclose(norms, torch.ones_like(norms), atol=1e-9) - assert camera.data.output["normals"].dtype == torch.float - del camera - - -@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) -@pytest.mark.isaacsim_ci -def test_motion_vectors_only_camera(setup_camera, device): - """Test initialization with only motion_vectors.""" - sim, camera_cfg, dt = setup_camera - num_cameras = 9 - for i in range(num_cameras): - sim_utils.create_prim(f"/World/Origin_{i}", "Xform") - - # Create camera - camera_cfg = copy.deepcopy(camera_cfg) - camera_cfg.data_types = ["motion_vectors"] - camera_cfg.prim_path = "/World/Origin_.*/CameraSensor" - camera = TiledCamera(camera_cfg) - # Check simulation parameter is set correctly - assert sim.get_setting("/isaaclab/render/rtx_sensors") - # Play sim - sim.reset() - # Check if camera is initialized - assert camera.is_initialized - # Check if camera prim is set correctly and that it is a camera prim - assert camera._sensor_prims[1].GetPath().pathString == "/World/Origin_1/CameraSensor" - assert isinstance(camera._sensor_prims[0], UsdGeom.Camera) - assert list(camera.data.output.keys()) == ["motion_vectors"] - - # Check buffers that exists and have correct shapes - assert camera.data.pos_w.shape == (num_cameras, 3) - assert camera.data.quat_w_ros.shape == (num_cameras, 4) - assert camera.data.quat_w_world.shape == (num_cameras, 4) - assert camera.data.quat_w_opengl.shape == (num_cameras, 4) - assert camera.data.intrinsic_matrices.shape == (num_cameras, 3, 3) - assert camera.data.image_shape == (camera_cfg.height, camera_cfg.width) - - # Simulate physics - for _ in range(10): - # perform rendering - sim.step() - # update camera - camera.update(dt) - # check image data - for _, im_data in camera.data.output.items(): - assert im_data.shape == (num_cameras, camera_cfg.height, camera_cfg.width, 2) - for i in range(4): - assert im_data[i].mean() != 0.0 - assert camera.data.output["motion_vectors"].dtype == torch.float - del camera - - -@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) -@pytest.mark.isaacsim_ci -def test_semantic_segmentation_colorize_only_camera(setup_camera, device): - """Test initialization with only semantic_segmentation.""" - sim, camera_cfg, dt = setup_camera - num_cameras = 9 - for i in range(num_cameras): - sim_utils.create_prim(f"/World/Origin_{i}", "Xform") - - # Create camera - camera_cfg = copy.deepcopy(camera_cfg) - camera_cfg.data_types = ["semantic_segmentation"] - camera_cfg.prim_path = "/World/Origin_.*/CameraSensor" - camera = TiledCamera(camera_cfg) - # Check simulation parameter is set correctly - assert sim.get_setting("/isaaclab/render/rtx_sensors") - # Play sim - sim.reset() - # Check if camera is initialized - assert camera.is_initialized - # Check if camera prim is set correctly and that it is a camera prim - assert camera._sensor_prims[1].GetPath().pathString == "/World/Origin_1/CameraSensor" - assert isinstance(camera._sensor_prims[0], UsdGeom.Camera) - assert list(camera.data.output.keys()) == ["semantic_segmentation"] - - # Check buffers that exists and have correct shapes - assert camera.data.pos_w.shape == (num_cameras, 3) - assert camera.data.quat_w_ros.shape == (num_cameras, 4) - assert camera.data.quat_w_world.shape == (num_cameras, 4) - assert camera.data.quat_w_opengl.shape == (num_cameras, 4) - assert camera.data.intrinsic_matrices.shape == (num_cameras, 3, 3) - assert camera.data.image_shape == (camera_cfg.height, camera_cfg.width) - - # Simulate physics - for _ in range(10): - # perform rendering - sim.step() - # update camera - camera.update(dt) - # check image data - for _, im_data in camera.data.output.items(): - assert im_data.shape == (num_cameras, camera_cfg.height, camera_cfg.width, 4) - for i in range(4): - assert (im_data[i] / 255.0).mean() > 0.0 - assert camera.data.output["semantic_segmentation"].dtype == torch.uint8 - assert isinstance(camera.data.info["semantic_segmentation"], dict) - del camera - - -@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) -@pytest.mark.isaacsim_ci -def test_instance_segmentation_fast_colorize_only_camera(setup_camera, device): - """Test initialization with only instance_segmentation_fast.""" - sim, camera_cfg, dt = setup_camera - num_cameras = 9 - for i in range(num_cameras): - sim_utils.create_prim(f"/World/Origin_{i}", "Xform") - - # Create camera - camera_cfg = copy.deepcopy(camera_cfg) - camera_cfg.data_types = ["instance_segmentation_fast"] - camera_cfg.prim_path = "/World/Origin_.*/CameraSensor" - camera = TiledCamera(camera_cfg) - # Check simulation parameter is set correctly - assert sim.get_setting("/isaaclab/render/rtx_sensors") - # Play sim - sim.reset() - # Check if camera is initialized - assert camera.is_initialized - # Check if camera prim is set correctly and that it is a camera prim - assert camera._sensor_prims[1].GetPath().pathString == "/World/Origin_1/CameraSensor" - assert isinstance(camera._sensor_prims[0], UsdGeom.Camera) - assert list(camera.data.output.keys()) == ["instance_segmentation_fast"] - - # Check buffers that exists and have correct shapes - assert camera.data.pos_w.shape == (num_cameras, 3) - assert camera.data.quat_w_ros.shape == (num_cameras, 4) - assert camera.data.quat_w_world.shape == (num_cameras, 4) - assert camera.data.quat_w_opengl.shape == (num_cameras, 4) - assert camera.data.intrinsic_matrices.shape == (num_cameras, 3, 3) - assert camera.data.image_shape == (camera_cfg.height, camera_cfg.width) - - # Simulate physics - for _ in range(10): - # perform rendering - sim.step() - # update camera - camera.update(dt) - # check image data - for _, im_data in camera.data.output.items(): - assert im_data.shape == (num_cameras, camera_cfg.height, camera_cfg.width, 4) - for i in range(num_cameras): - assert (im_data[i] / 255.0).mean() > 0.0 - assert camera.data.output["instance_segmentation_fast"].dtype == torch.uint8 - assert isinstance(camera.data.info["instance_segmentation_fast"], dict) - del camera - - -@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) -@pytest.mark.isaacsim_ci -def test_instance_id_segmentation_fast_colorize_only_camera(setup_camera, device): - """Test initialization with only instance_id_segmentation_fast.""" - sim, camera_cfg, dt = setup_camera - num_cameras = 9 - for i in range(num_cameras): - sim_utils.create_prim(f"/World/Origin_{i}", "Xform") - - # Create camera - camera_cfg = copy.deepcopy(camera_cfg) - camera_cfg.data_types = ["instance_id_segmentation_fast"] - camera_cfg.prim_path = "/World/Origin_.*/CameraSensor" - camera = TiledCamera(camera_cfg) - # Check simulation parameter is set correctly - assert sim.get_setting("/isaaclab/render/rtx_sensors") - # Play sim - sim.reset() - # Check if camera is initialized - assert camera.is_initialized - # Check if camera prim is set correctly and that it is a camera prim - assert camera._sensor_prims[1].GetPath().pathString == "/World/Origin_1/CameraSensor" - assert isinstance(camera._sensor_prims[0], UsdGeom.Camera) - assert list(camera.data.output.keys()) == ["instance_id_segmentation_fast"] - - # Check buffers that exists and have correct shapes - assert camera.data.pos_w.shape == (num_cameras, 3) - assert camera.data.quat_w_ros.shape == (num_cameras, 4) - assert camera.data.quat_w_world.shape == (num_cameras, 4) - assert camera.data.quat_w_opengl.shape == (num_cameras, 4) - assert camera.data.intrinsic_matrices.shape == (num_cameras, 3, 3) - assert camera.data.image_shape == (camera_cfg.height, camera_cfg.width) - - # Simulate physics - for _ in range(10): - # perform rendering - sim.step() - # update camera - camera.update(dt) - # check image data - for _, im_data in camera.data.output.items(): - assert im_data.shape == (num_cameras, camera_cfg.height, camera_cfg.width, 4) - for i in range(num_cameras): - assert (im_data[i] / 255.0).mean() > 0.0 - assert camera.data.output["instance_id_segmentation_fast"].dtype == torch.uint8 - assert isinstance(camera.data.info["instance_id_segmentation_fast"], dict) - del camera - - -@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) -@pytest.mark.isaacsim_ci -def test_semantic_segmentation_non_colorize_only_camera(setup_camera, device): - """Test initialization with only semantic_segmentation.""" - sim, camera_cfg, dt = setup_camera - num_cameras = 9 - for i in range(num_cameras): - sim_utils.create_prim(f"/World/Origin_{i}", "Xform") - - # Create camera - camera_cfg = copy.deepcopy(camera_cfg) - camera_cfg.data_types = ["semantic_segmentation"] - camera_cfg.prim_path = "/World/Origin_.*/CameraSensor" - camera_cfg.colorize_semantic_segmentation = False - camera = TiledCamera(camera_cfg) - # Check simulation parameter is set correctly - assert sim.get_setting("/isaaclab/render/rtx_sensors") - # Play sim - sim.reset() - # Check if camera is initialized - assert camera.is_initialized - # Check if camera prim is set correctly and that it is a camera prim - assert camera._sensor_prims[1].GetPath().pathString == "/World/Origin_1/CameraSensor" - assert isinstance(camera._sensor_prims[0], UsdGeom.Camera) - assert list(camera.data.output.keys()) == ["semantic_segmentation"] - - # Check buffers that exists and have correct shapes - assert camera.data.pos_w.shape == (num_cameras, 3) - assert camera.data.quat_w_ros.shape == (num_cameras, 4) - assert camera.data.quat_w_world.shape == (num_cameras, 4) - assert camera.data.quat_w_opengl.shape == (num_cameras, 4) - assert camera.data.intrinsic_matrices.shape == (num_cameras, 3, 3) - assert camera.data.image_shape == (camera_cfg.height, camera_cfg.width) - - # Simulate physics - for _ in range(10): - # perform rendering - sim.step() - # update camera - camera.update(dt) - # check image data - for _, im_data in camera.data.output.items(): - assert im_data.shape == (num_cameras, camera_cfg.height, camera_cfg.width, 1) - for i in range(num_cameras): - assert im_data[i].to(dtype=float).mean() > 0.0 - assert camera.data.output["semantic_segmentation"].dtype == torch.int32 - assert isinstance(camera.data.info["semantic_segmentation"], dict) - - del camera - - -@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) -@pytest.mark.isaacsim_ci -def test_instance_segmentation_fast_non_colorize_only_camera(setup_camera, device): - """Test initialization with only instance_segmentation_fast.""" - sim, camera_cfg, dt = setup_camera - num_cameras = 9 - for i in range(num_cameras): - sim_utils.create_prim(f"/World/Origin_{i}", "Xform") - - # Create camera - camera_cfg = copy.deepcopy(camera_cfg) - camera_cfg.data_types = ["instance_segmentation_fast"] - camera_cfg.prim_path = "/World/Origin_.*/CameraSensor" - camera_cfg.colorize_instance_segmentation = False - camera = TiledCamera(camera_cfg) - # Check simulation parameter is set correctly - assert sim.get_setting("/isaaclab/render/rtx_sensors") - # Play sim - sim.reset() - # Check if camera is initialized - assert camera.is_initialized - # Check if camera prim is set correctly and that it is a camera prim - assert camera._sensor_prims[1].GetPath().pathString == "/World/Origin_1/CameraSensor" - assert isinstance(camera._sensor_prims[0], UsdGeom.Camera) - assert list(camera.data.output.keys()) == ["instance_segmentation_fast"] - - # Check buffers that exists and have correct shapes - assert camera.data.pos_w.shape == (num_cameras, 3) - assert camera.data.quat_w_ros.shape == (num_cameras, 4) - assert camera.data.quat_w_world.shape == (num_cameras, 4) - assert camera.data.quat_w_opengl.shape == (num_cameras, 4) - assert camera.data.intrinsic_matrices.shape == (num_cameras, 3, 3) - assert camera.data.image_shape == (camera_cfg.height, camera_cfg.width) - - # Simulate physics - for _ in range(10): - # perform rendering - sim.step() - # update camera - camera.update(dt) - # check image data - for _, im_data in camera.data.output.items(): - assert im_data.shape == (num_cameras, camera_cfg.height, camera_cfg.width, 1) - for i in range(num_cameras): - assert im_data[i].to(dtype=float).mean() > 0.0 - assert camera.data.output["instance_segmentation_fast"].dtype == torch.int32 - assert isinstance(camera.data.info["instance_segmentation_fast"], dict) - del camera - - -@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) -def test_instance_id_segmentation_fast_non_colorize_only_camera(setup_camera, device): - """Test initialization with only instance_id_segmentation_fast.""" - sim, camera_cfg, dt = setup_camera - num_cameras = 9 - for i in range(num_cameras): - sim_utils.create_prim(f"/World/Origin_{i}", "Xform") - - # Create camera - camera_cfg = copy.deepcopy(camera_cfg) - camera_cfg.data_types = ["instance_id_segmentation_fast"] - camera_cfg.prim_path = "/World/Origin_.*/CameraSensor" - camera_cfg.colorize_instance_id_segmentation = False - camera = TiledCamera(camera_cfg) - # Check simulation parameter is set correctly - assert sim.get_setting("/isaaclab/render/rtx_sensors") - # Play sim - sim.reset() - # Check if camera is initialized - assert camera.is_initialized - # Check if camera prim is set correctly and that it is a camera prim - assert camera._sensor_prims[1].GetPath().pathString == "/World/Origin_1/CameraSensor" - assert isinstance(camera._sensor_prims[0], UsdGeom.Camera) - assert list(camera.data.output.keys()) == ["instance_id_segmentation_fast"] - - # Check buffers that exists and have correct shapes - assert camera.data.pos_w.shape == (num_cameras, 3) - assert camera.data.quat_w_ros.shape == (num_cameras, 4) - assert camera.data.quat_w_world.shape == (num_cameras, 4) - assert camera.data.quat_w_opengl.shape == (num_cameras, 4) - assert camera.data.intrinsic_matrices.shape == (num_cameras, 3, 3) - assert camera.data.image_shape == (camera_cfg.height, camera_cfg.width) - - # Simulate physics - for _ in range(10): - # perform rendering - sim.step() - # update camera - camera.update(dt) - # check image data - for _, im_data in camera.data.output.items(): - assert im_data.shape == (num_cameras, camera_cfg.height, camera_cfg.width, 1) - for i in range(num_cameras): - assert im_data[i].to(dtype=float).mean() > 0.0 - assert camera.data.output["instance_id_segmentation_fast"].dtype == torch.int32 - assert isinstance(camera.data.info["instance_id_segmentation_fast"], dict) - del camera - - -@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) -@pytest.mark.isaacsim_ci -def test_all_annotators_camera(setup_camera, device): - """Test initialization with all supported annotators.""" - sim, camera_cfg, dt = setup_camera - all_annotator_types = [ - "rgb", - "rgba", - "albedo", - "depth", - "distance_to_camera", - "distance_to_image_plane", - "normals", - "motion_vectors", - "semantic_segmentation", - "instance_segmentation_fast", - "instance_id_segmentation_fast", - ] - - num_cameras = 9 - for i in range(num_cameras): - sim_utils.create_prim(f"/World/Origin_{i}", "Xform") - - # Create camera - camera_cfg = copy.deepcopy(camera_cfg) - camera_cfg.data_types = all_annotator_types - camera_cfg.prim_path = "/World/Origin_.*/CameraSensor" - camera = TiledCamera(camera_cfg) - # Check simulation parameter is set correctly - assert sim.get_setting("/isaaclab/render/rtx_sensors") - # Play sim - sim.reset() - # Check if camera is initialized - assert camera.is_initialized - # Check if camera prim is set correctly and that it is a camera prim - assert camera._sensor_prims[1].GetPath().pathString == "/World/Origin_1/CameraSensor" - assert isinstance(camera._sensor_prims[0], UsdGeom.Camera) - assert sorted(camera.data.output.keys()) == sorted(all_annotator_types) - - # Check buffers that exists and have correct shapes - assert camera.data.pos_w.shape == (num_cameras, 3) - assert camera.data.quat_w_ros.shape == (num_cameras, 4) - assert camera.data.quat_w_world.shape == (num_cameras, 4) - assert camera.data.quat_w_opengl.shape == (num_cameras, 4) - assert camera.data.intrinsic_matrices.shape == (num_cameras, 3, 3) - assert camera.data.image_shape == (camera_cfg.height, camera_cfg.width) - - # Simulate physics - for _ in range(10): - # perform rendering - sim.step() - # update camera - camera.update(dt) - # check image data - for data_type, im_data in camera.data.output.items(): - if data_type in ["rgb", "normals"]: - assert im_data.shape == (num_cameras, camera_cfg.height, camera_cfg.width, 3) - elif data_type in [ - "rgba", - "albedo", - "semantic_segmentation", - "instance_segmentation_fast", - "instance_id_segmentation_fast", - ]: - assert im_data.shape == (num_cameras, camera_cfg.height, camera_cfg.width, 4) - for i in range(num_cameras): - assert (im_data[i] / 255.0).mean() > 0.0 - elif data_type in ["motion_vectors"]: - assert im_data.shape == (num_cameras, camera_cfg.height, camera_cfg.width, 2) - for i in range(num_cameras): - assert im_data[i].mean() != 0.0 - elif data_type in ["depth", "distance_to_camera", "distance_to_image_plane"]: - assert im_data.shape == (num_cameras, camera_cfg.height, camera_cfg.width, 1) - for i in range(num_cameras): - assert im_data[i].mean() > 0.0 - - # access image data and compare dtype - output = camera.data.output - info = camera.data.info - assert output["rgb"].dtype == torch.uint8 - assert output["rgba"].dtype == torch.uint8 - assert output["albedo"].dtype == torch.uint8 - assert output["depth"].dtype == torch.float - assert output["distance_to_camera"].dtype == torch.float - assert output["distance_to_image_plane"].dtype == torch.float - assert output["normals"].dtype == torch.float - assert output["motion_vectors"].dtype == torch.float - assert output["semantic_segmentation"].dtype == torch.uint8 - assert output["instance_segmentation_fast"].dtype == torch.uint8 - assert output["instance_id_segmentation_fast"].dtype == torch.uint8 - assert isinstance(info["semantic_segmentation"], dict) - assert isinstance(info["instance_segmentation_fast"], dict) - assert isinstance(info["instance_id_segmentation_fast"], dict) - - del camera - - -@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) -@pytest.mark.isaacsim_ci -def test_all_annotators_low_resolution_camera(setup_camera, device): - """Test initialization with all supported annotators.""" - sim, camera_cfg, dt = setup_camera - all_annotator_types = [ - "rgb", - "rgba", - "albedo", - "depth", - "distance_to_camera", - "distance_to_image_plane", - "normals", - "motion_vectors", - "semantic_segmentation", - "instance_segmentation_fast", - "instance_id_segmentation_fast", - ] - - num_cameras = 2 - for i in range(num_cameras): - sim_utils.create_prim(f"/World/Origin_{i}", "Xform") - - # Create camera - camera_cfg = copy.deepcopy(camera_cfg) - camera_cfg.height = 40 - camera_cfg.width = 40 - camera_cfg.data_types = all_annotator_types - camera_cfg.prim_path = "/World/Origin_.*/CameraSensor" - camera = TiledCamera(camera_cfg) - # Check simulation parameter is set correctly - assert sim.get_setting("/isaaclab/render/rtx_sensors") - # Play sim - sim.reset() - # Check if camera is initialized - assert camera.is_initialized - # Check if camera prim is set correctly and that it is a camera prim - assert camera._sensor_prims[1].GetPath().pathString == "/World/Origin_1/CameraSensor" - assert isinstance(camera._sensor_prims[0], UsdGeom.Camera) - assert sorted(camera.data.output.keys()) == sorted(all_annotator_types) - - # Check buffers that exists and have correct shapes - assert camera.data.pos_w.shape == (num_cameras, 3) - assert camera.data.quat_w_ros.shape == (num_cameras, 4) - assert camera.data.quat_w_world.shape == (num_cameras, 4) - assert camera.data.quat_w_opengl.shape == (num_cameras, 4) - assert camera.data.intrinsic_matrices.shape == (num_cameras, 3, 3) - assert camera.data.image_shape == (camera_cfg.height, camera_cfg.width) - - # Simulate physics - for _ in range(10): - # perform rendering - sim.step() - # update camera - camera.update(dt) - # check image data - for data_type, im_data in camera.data.output.items(): - if data_type in ["rgb", "normals"]: - assert im_data.shape == (num_cameras, camera_cfg.height, camera_cfg.width, 3) - elif data_type in [ - "rgba", - "albedo", - "semantic_segmentation", - "instance_segmentation_fast", - "instance_id_segmentation_fast", - ]: - assert im_data.shape == (num_cameras, camera_cfg.height, camera_cfg.width, 4) - for i in range(num_cameras): - assert (im_data[i] / 255.0).mean() > 0.0 - elif data_type in ["motion_vectors"]: - assert im_data.shape == (num_cameras, camera_cfg.height, camera_cfg.width, 2) - for i in range(num_cameras): - assert im_data[i].mean() != 0.0 - elif data_type in ["depth", "distance_to_camera", "distance_to_image_plane"]: - assert im_data.shape == (num_cameras, camera_cfg.height, camera_cfg.width, 1) - for i in range(num_cameras): - assert im_data[i].mean() > 0.0 - - # access image data and compare dtype - output = camera.data.output - info = camera.data.info - assert output["rgb"].dtype == torch.uint8 - assert output["rgba"].dtype == torch.uint8 - assert output["albedo"].dtype == torch.uint8 - assert output["depth"].dtype == torch.float - assert output["distance_to_camera"].dtype == torch.float - assert output["distance_to_image_plane"].dtype == torch.float - assert output["normals"].dtype == torch.float - assert output["motion_vectors"].dtype == torch.float - assert output["semantic_segmentation"].dtype == torch.uint8 - assert output["instance_segmentation_fast"].dtype == torch.uint8 - assert output["instance_id_segmentation_fast"].dtype == torch.uint8 - assert isinstance(info["semantic_segmentation"], dict) - assert isinstance(info["instance_segmentation_fast"], dict) - assert isinstance(info["instance_id_segmentation_fast"], dict) - - del camera - - -@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) -@pytest.mark.isaacsim_ci -def test_all_annotators_non_perfect_square_number_camera(setup_camera, device): - """Test initialization with all supported annotators.""" - sim, camera_cfg, dt = setup_camera - all_annotator_types = [ - "rgb", - "rgba", - "albedo", - "depth", - "distance_to_camera", - "distance_to_image_plane", - "normals", - "motion_vectors", - "semantic_segmentation", - "instance_segmentation_fast", - "instance_id_segmentation_fast", - ] - - num_cameras = 11 - for i in range(num_cameras): - sim_utils.create_prim(f"/World/Origin_{i}", "Xform") - - # Create camera - camera_cfg = copy.deepcopy(camera_cfg) - camera_cfg.data_types = all_annotator_types - camera_cfg.prim_path = "/World/Origin_.*/CameraSensor" - camera = TiledCamera(camera_cfg) - # Check simulation parameter is set correctly - assert sim.get_setting("/isaaclab/render/rtx_sensors") - # Play sim - sim.reset() - # Check if camera is initialized - assert camera.is_initialized - # Check if camera prim is set correctly and that it is a camera prim - assert camera._sensor_prims[1].GetPath().pathString == "/World/Origin_1/CameraSensor" - assert isinstance(camera._sensor_prims[0], UsdGeom.Camera) - assert sorted(camera.data.output.keys()) == sorted(all_annotator_types) - - # Check buffers that exists and have correct shapes - assert camera.data.pos_w.shape == (num_cameras, 3) - assert camera.data.quat_w_ros.shape == (num_cameras, 4) - assert camera.data.quat_w_world.shape == (num_cameras, 4) - assert camera.data.quat_w_opengl.shape == (num_cameras, 4) - assert camera.data.intrinsic_matrices.shape == (num_cameras, 3, 3) - assert camera.data.image_shape == (camera_cfg.height, camera_cfg.width) - - # Simulate physics - for _ in range(10): - # perform rendering - sim.step() - # update camera - camera.update(dt) - # check image data - for data_type, im_data in camera.data.output.items(): - if data_type in ["rgb", "normals"]: - assert im_data.shape == (num_cameras, camera_cfg.height, camera_cfg.width, 3) - elif data_type in [ - "rgba", - "albedo", - "semantic_segmentation", - "instance_segmentation_fast", - "instance_id_segmentation_fast", - ]: - assert im_data.shape == (num_cameras, camera_cfg.height, camera_cfg.width, 4) - for i in range(num_cameras): - assert (im_data[i] / 255.0).mean() > 0.0 - elif data_type in ["motion_vectors"]: - assert im_data.shape == (num_cameras, camera_cfg.height, camera_cfg.width, 2) - for i in range(num_cameras): - assert im_data[i].mean() != 0.0 - elif data_type in ["depth", "distance_to_camera", "distance_to_image_plane"]: - assert im_data.shape == (num_cameras, camera_cfg.height, camera_cfg.width, 1) - for i in range(num_cameras): - assert im_data[i].mean() > 0.0 - - # access image data and compare dtype - output = camera.data.output - info = camera.data.info - assert output["rgb"].dtype == torch.uint8 - assert output["rgba"].dtype == torch.uint8 - assert output["albedo"].dtype == torch.uint8 - assert output["depth"].dtype == torch.float - assert output["distance_to_camera"].dtype == torch.float - assert output["distance_to_image_plane"].dtype == torch.float - assert output["normals"].dtype == torch.float - assert output["motion_vectors"].dtype == torch.float - assert output["semantic_segmentation"].dtype == torch.uint8 - assert output["instance_segmentation_fast"].dtype == torch.uint8 - assert output["instance_id_segmentation_fast"].dtype == torch.uint8 - assert isinstance(info["semantic_segmentation"], dict) - assert isinstance(info["instance_segmentation_fast"], dict) - assert isinstance(info["instance_id_segmentation_fast"], dict) - - del camera - - -@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) -@pytest.mark.isaacsim_ci -def test_all_annotators_instanceable(setup_camera, device): - """Test initialization with all supported annotators on instanceable assets.""" - sim, camera_cfg, dt = setup_camera - all_annotator_types = [ - "rgb", - "rgba", - "albedo", - "depth", - "distance_to_camera", - "distance_to_image_plane", - "normals", - "motion_vectors", - "semantic_segmentation", - "instance_segmentation_fast", - "instance_id_segmentation_fast", - ] - - num_cameras = 10 - for i in range(num_cameras): - sim_utils.create_prim(f"/World/Origin_{i}", "Xform", translation=(0.0, i, 0.0)) - - # Create a stage with 10 instanceable cubes, where each camera points to one cube - stage = sim_utils.get_current_stage() - for i in range(10): - # Remove objects added to stage by default - stage.RemovePrim(f"/World/Objects/Obj_{i:02d}") - # Add instanceable cubes - sim_utils.create_prim( - f"/World/Cube_{i}", - "Xform", - usd_path=f"{ISAAC_NUCLEUS_DIR}/Props/Blocks/DexCube/dex_cube_instanceable.usd", - translation=(0.0, i, 5.0), - orientation=(0.0, 0.0, 0.0, 1.0), - scale=(1.0, 1.0, 1.0), - ) - prim = stage.GetPrimAtPath(f"/World/Cube_{i}") - sim_utils.add_labels(prim, labels=["cube"], instance_name="class") - - # Disable gravity — we teleport cubes explicitly to get deterministic motion vectors - physics_scene = UsdPhysics.Scene(stage.GetPrimAtPath(sim.cfg.physics_prim_path)) - physics_scene.GetGravityMagnitudeAttr().Set(0.0) - - # Create camera - camera_cfg = copy.deepcopy(camera_cfg) - camera_cfg.height = 120 - camera_cfg.width = 80 - camera_cfg.data_types = all_annotator_types - camera_cfg.prim_path = "/World/Origin_.*/CameraSensor" - camera_cfg.offset.pos = (0.0, 0.0, 5.5) - camera = TiledCamera(camera_cfg) - # Check simulation parameter is set correctly - assert sim.get_setting("/isaaclab/render/rtx_sensors") - # Play sim - sim.reset() - # Check if camera is initialized - assert camera.is_initialized - # Check if camera prim is set correctly and that it is a camera prim - assert camera._sensor_prims[1].GetPath().pathString == "/World/Origin_1/CameraSensor" - assert isinstance(camera._sensor_prims[0], UsdGeom.Camera) - assert sorted(camera.data.output.keys()) == sorted(all_annotator_types) - - # Check buffers that exists and have correct shapes - assert camera.data.pos_w.shape == (num_cameras, 3) - assert camera.data.quat_w_ros.shape == (num_cameras, 4) - assert camera.data.quat_w_world.shape == (num_cameras, 4) - assert camera.data.quat_w_opengl.shape == (num_cameras, 4) - assert camera.data.intrinsic_matrices.shape == (num_cameras, 3, 3) - assert camera.data.image_shape == (camera_cfg.height, camera_cfg.width) - - # Create a rigid body view so we can teleport the cubes each frame - physics_sim_view = sim.physics_manager.get_physics_sim_view() - cube_view = physics_sim_view.create_rigid_body_view("/World/Cube_*") - all_indices = torch.arange(num_cameras, dtype=torch.int32, device=device) - - for frame in range(2): - # Build transforms: [x, y, z, qx, qy, qz, qw] — move cubes down by 0.5 each frame - transforms = torch.zeros(num_cameras, 7, device=device) - for i in range(num_cameras): - transforms[i, 0] = 0.0 # x - transforms[i, 1] = float(i) # y - transforms[i, 2] = 5.0 - frame * 0.5 # z — moves down 0.5 per frame - transforms[i, 6] = 1.0 # qw (identity orientation, xyzw format) - cube_view.set_transforms(wp.from_torch(transforms), wp.from_torch(all_indices)) - # Zero out velocities so physics doesn't fight the teleport - cube_view.set_velocities(wp.from_torch(torch.zeros(num_cameras, 6, device=device)), wp.from_torch(all_indices)) - sim.step() - - # Teleport cubes to explicit positions each frame so motion vectors are deterministic - for frame in range(3): - # Build transforms: [x, y, z, qx, qy, qz, qw] — move cubes down by 0.5 each frame - transforms = torch.zeros(num_cameras, 7, device=device) - for i in range(num_cameras): - transforms[i, 0] = 0.0 # x - transforms[i, 1] = float(i) # y - transforms[i, 2] = 5.0 - frame * 0.5 # z — moves down 0.5 per frame - transforms[i, 6] = 1.0 # qw (identity orientation, xyzw format) - cube_view.set_transforms(wp.from_torch(transforms), wp.from_torch(all_indices)) - # Zero out velocities so physics doesn't fight the teleport - cube_view.set_velocities(wp.from_torch(torch.zeros(num_cameras, 6, device=device)), wp.from_torch(all_indices)) - - # perform rendering - sim.step() - # update camera - camera.update(dt) - # check image data - for data_type, im_data in camera.data.output.items(): - if data_type in ["rgb", "normals"]: - assert im_data.shape == (num_cameras, camera_cfg.height, camera_cfg.width, 3) - elif data_type in [ - "rgba", - "albedo", - "semantic_segmentation", - "instance_segmentation_fast", - "instance_id_segmentation_fast", - ]: - assert im_data.shape == (num_cameras, camera_cfg.height, camera_cfg.width, 4) - for i in range(num_cameras): - assert (im_data[i] / 255.0).mean() > 0.2 - elif data_type in ["motion_vectors"]: - assert im_data.shape == (num_cameras, camera_cfg.height, camera_cfg.width, 2) - for i in range(num_cameras): - # TODO: this looks broken on tot - # assert im_data[i].abs().mean() > 0.001 - print(im_data[i].abs().mean()) - elif data_type in ["depth", "distance_to_camera", "distance_to_image_plane"]: - assert im_data.shape == (num_cameras, camera_cfg.height, camera_cfg.width, 1) - for i in range(num_cameras): - assert im_data[i].mean() > 2.0 - - # access image data and compare dtype - output = camera.data.output - info = camera.data.info - assert output["rgb"].dtype == torch.uint8 - assert output["rgba"].dtype == torch.uint8 - assert output["albedo"].dtype == torch.uint8 - assert output["depth"].dtype == torch.float - assert output["distance_to_camera"].dtype == torch.float - assert output["distance_to_image_plane"].dtype == torch.float - assert output["normals"].dtype == torch.float - assert output["motion_vectors"].dtype == torch.float - assert output["semantic_segmentation"].dtype == torch.uint8 - assert output["instance_segmentation_fast"].dtype == torch.uint8 - assert output["instance_id_segmentation_fast"].dtype == torch.uint8 - assert isinstance(info["semantic_segmentation"], dict) - assert isinstance(info["instance_segmentation_fast"], dict) - assert isinstance(info["instance_id_segmentation_fast"], dict) - - del camera - - -@pytest.mark.parametrize("device", ["cuda:0"]) -@pytest.mark.isaacsim_ci -def test_throughput(setup_camera, device): - """Test tiled camera throughput.""" - sim, camera_cfg, dt = setup_camera - # create camera - camera_cfg = copy.deepcopy(camera_cfg) - camera_cfg.height = 480 - camera_cfg.width = 640 - camera = TiledCamera(camera_cfg) - - # Play simulator - sim.reset() - - # Simulate physics - for _ in range(5): - # perform rendering - sim.step() - # update camera - with Timer(f"Time taken for updating camera with shape {camera.image_shape}"): - camera.update(dt) - # Check image data - for im_type, im_data in camera.data.output.items(): - if im_type == "rgb": - assert im_data.shape == (1, camera_cfg.height, camera_cfg.width, 3) - assert (im_data / 255.0).mean() > 0.0 - elif im_type == "distance_to_camera": - assert im_data.shape == (1, camera_cfg.height, camera_cfg.width, 1) - assert im_data.mean() > 0.0 - del camera - - -@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) -@pytest.mark.isaacsim_ci -def test_output_equal_to_usd_camera_intrinsics(setup_camera, device): - """ - Test that the output of the ray caster camera and the usd camera are the same when both are - initialized with the same intrinsic matrix. - """ - sim, _, dt = setup_camera - # create cameras - offset_rot = (-0.1251, 0.3617, 0.8731, -0.3020) - offset_pos = (2.5, 2.5, 4.0) - intrinsics = [380.08, 0.0, 467.79, 0.0, 380.08, 262.05, 0.0, 0.0, 1.0] - # get camera cfgs - # TODO: add clipping range back, once correctly supported by tiled camera - camera_tiled_cfg = TiledCameraCfg( - prim_path="/World/Camera_tiled", - offset=TiledCameraCfg.OffsetCfg(pos=offset_pos, rot=offset_rot, convention="ros"), - spawn=sim_utils.PinholeCameraCfg.from_intrinsic_matrix( - intrinsic_matrix=intrinsics, - height=540, - width=960, - ), - height=540, - width=960, - data_types=["depth"], - ) - camera_usd_cfg = CameraCfg( - prim_path="/World/Camera_usd", - offset=CameraCfg.OffsetCfg(pos=offset_pos, rot=offset_rot, convention="ros"), - spawn=sim_utils.PinholeCameraCfg.from_intrinsic_matrix( - intrinsic_matrix=intrinsics, - height=540, - width=960, - ), - height=540, - width=960, - data_types=["distance_to_image_plane"], - ) - - # set aperture offsets to 0, as currently not supported for usd/ tiled camera - camera_tiled_cfg.spawn.horizontal_aperture_offset = 0 - camera_tiled_cfg.spawn.vertical_aperture_offset = 0 - camera_usd_cfg.spawn.horizontal_aperture_offset = 0 - camera_usd_cfg.spawn.vertical_aperture_offset = 0 - # init cameras - camera_tiled = TiledCamera(camera_tiled_cfg) - camera_usd = Camera(camera_usd_cfg) - - # play sim - sim.reset() - sim.play() - - # perform steps - for _ in range(5): - sim.step() - - # update camera - camera_usd.update(dt) - camera_tiled.update(dt) - - # filter nan and inf from output - cam_tiled_output = camera_tiled.data.output["depth"].clone() - cam_usd_output = camera_usd.data.output["distance_to_image_plane"].clone() - cam_tiled_output[torch.isnan(cam_tiled_output)] = 0 - cam_tiled_output[torch.isinf(cam_tiled_output)] = 0 - cam_usd_output[torch.isnan(cam_usd_output)] = 0 - cam_usd_output[torch.isinf(cam_usd_output)] = 0 - - # check that both have the same intrinsic matrices - torch.testing.assert_close(camera_tiled.data.intrinsic_matrices[0], camera_usd.data.intrinsic_matrices[0]) - - # check the apertures - torch.testing.assert_close( - camera_usd._sensor_prims[0].GetHorizontalApertureAttr().Get(), - camera_tiled._sensor_prims[0].GetHorizontalApertureAttr().Get(), - ) - torch.testing.assert_close( - camera_usd._sensor_prims[0].GetVerticalApertureAttr().Get(), - camera_tiled._sensor_prims[0].GetVerticalApertureAttr().Get(), - ) - - # check image data - torch.testing.assert_close( - cam_tiled_output[..., 0], - cam_usd_output[..., 0], - atol=5e-5, - rtol=5e-6, - ) - - del camera_tiled - del camera_usd - - -@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) -@pytest.mark.isaacsim_ci -def test_sensor_print(setup_camera, device): - """Test sensor print is working correctly.""" - sim, camera_cfg, _ = setup_camera - # Create sensor - sensor = TiledCamera(cfg=camera_cfg) - # Play sim - sim.reset() - # print info - print(sensor) - - -@pytest.mark.parametrize("device", ["cuda:0"]) -@pytest.mark.isaacsim_ci -def test_frame_offset_small_resolution(setup_camera, device): - """Test frame offset issue with small resolution camera.""" - sim, camera_cfg, dt = setup_camera - # Create sensor - camera_cfg = copy.deepcopy(camera_cfg) - camera_cfg.height = 80 - camera_cfg.width = 80 - # Objects are scaled to (1,1,1): USD default cube is 2×2×2, so half-height=1.0, - # settled objects rest at z=1.0 (center) with top at z=2.0. Place the camera - # above the objects so they are fully visible from above. - camera_cfg.offset.pos = (0.0, 0.0, 3.0) - tiled_camera = TiledCamera(camera_cfg) - # play sim - sim.reset() - # simulate some steps first to make sure objects are settled - stage = sim_utils.get_current_stage() - for i in range(10): - prim = stage.GetPrimAtPath(f"/World/Objects/Obj_{i:02d}") - UsdGeom.Gprim(prim).GetOrderedXformOps()[2].Set(Gf.Vec3d(1.0, 1.0, 1.0)) - for i in range(100): - # step simulation - sim.step() - # update camera - tiled_camera.update(dt) - # collect image data - image_before = tiled_camera.data.output["rgb"].clone() / 255.0 - - # update scene - for i in range(10): - prim = stage.GetPrimAtPath(f"/World/Objects/Obj_{i:02d}") - color = Gf.Vec3f(0.0, 0.0, 0.0) - UsdGeom.Gprim(prim).GetDisplayColorAttr().Set([color]) - - # update rendering (step 1 – replicator annotator has a one-frame offset, - # so the colour change may not be reflected yet) - sim.step() - tiled_camera.update(dt) - - # make sure the image is different - image_after = tiled_camera.data.output["rgb"].clone() / 255.0 - - # check difference is above threshold - assert torch.abs(image_after - image_before).mean() > 0.02 # images of same color should be below 0.01 - - -@pytest.mark.parametrize("device", ["cuda:0"]) -@pytest.mark.isaacsim_ci -def test_frame_offset_large_resolution(setup_camera, device): - """Test frame offset issue with large resolution camera.""" - sim, camera_cfg, dt = setup_camera - # Create sensor - camera_cfg = copy.deepcopy(camera_cfg) - camera_cfg.height = 480 - camera_cfg.width = 480 - tiled_camera = TiledCamera(camera_cfg) - - # modify scene to be less stochastic - stage = sim_utils.get_current_stage() - for i in range(10): - prim = stage.GetPrimAtPath(f"/World/Objects/Obj_{i:02d}") - color = Gf.Vec3f(1, 1, 1) - UsdGeom.Gprim(prim).GetDisplayColorAttr().Set([color]) - - # play sim - sim.reset() - # simulate some steps first to make sure objects are settled - for i in range(100): - # step simulation - sim.step() - # update camera - tiled_camera.update(dt) - # collect image data - image_before = tiled_camera.data.output["rgb"].clone() / 255.0 - - # update scene - for i in range(10): - prim = stage.GetPrimAtPath(f"/World/Objects/Obj_{i:02d}") - color = Gf.Vec3f(0, 0, 0) - UsdGeom.Gprim(prim).GetDisplayColorAttr().Set([color]) - - # update rendering - sim.step() - tiled_camera.update(dt) - - # make sure the image is different - image_after = tiled_camera.data.output["rgb"].clone() / 255.0 - - # check difference is above threshold - assert torch.abs(image_after - image_before).mean() > 0.01 # images of same color should be below 0.001 - - """ Helper functions. """ -@staticmethod def _populate_scene(): """Add prims to the scene.""" # Ground-plane diff --git a/source/isaaclab/test/sensors/test_tiled_camera_env.py b/source/isaaclab/test/sensors/test_tiled_camera_env.py index 69dbd448972f..c2d2982d336f 100644 --- a/source/isaaclab/test/sensors/test_tiled_camera_env.py +++ b/source/isaaclab/test/sensors/test_tiled_camera_env.py @@ -41,6 +41,8 @@ import isaaclab_tasks # noqa: F401 from isaaclab_tasks.utils.parse_cfg import parse_env_cfg +pytestmark = pytest.mark.isaacsim_ci + @pytest.mark.skip(reason="Currently takes too long to run") def test_tiled_resolutions_tiny(): diff --git a/source/isaaclab/test/sensors/test_update_ray_caster_kernel.py b/source/isaaclab/test/sensors/test_update_ray_caster_kernel.py new file mode 100644 index 000000000000..65402518b7a0 --- /dev/null +++ b/source/isaaclab/test/sensors/test_update_ray_caster_kernel.py @@ -0,0 +1,510 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Unit tests for :func:`update_ray_caster_kernel`. + +These tests exercise the kernel directly with hand-crafted warp arrays and +analytically computed expected outputs. No simulation, no stage, no AppLauncher +— just warp on CPU (or CUDA when available). +""" + +from __future__ import annotations + +import importlib.util +import math +import os + +import numpy as np +import pytest +import torch +import warp as wp + +# Import the kernel module directly to avoid pulling in the full isaaclab package +# (which requires Isaac Sim / Omniverse dependencies). The kernel file itself only +# depends on warp. +_KERNEL_PATH = os.path.join( + os.path.dirname(__file__), + os.pardir, + os.pardir, + "isaaclab", + "sensors", + "ray_caster", + "kernels.py", +) +_spec = importlib.util.spec_from_file_location("ray_caster_kernels", os.path.normpath(_KERNEL_PATH)) +_mod = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(_mod) + +update_ray_caster_kernel = _mod.update_ray_caster_kernel +ALIGNMENT_WORLD = _mod.ALIGNMENT_WORLD +ALIGNMENT_YAW = _mod.ALIGNMENT_YAW +ALIGNMENT_BASE = _mod.ALIGNMENT_BASE + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + +wp.init() +DEVICE = "cuda:0" if wp.is_cuda_available() else "cpu" +TORCH_DEVICE = torch.device(DEVICE) +ATOL = 1e-5 + + +def _make_transform(pos: tuple[float, float, float], quat_xyzw: tuple[float, float, float, float]) -> wp.array: + """Create a warp transformf array (1,) from position and xyzw quaternion.""" + t = torch.tensor([[pos[0], pos[1], pos[2], quat_xyzw[0], quat_xyzw[1], quat_xyzw[2], quat_xyzw[3]]], device=DEVICE) + return wp.from_torch(t.contiguous()).view(wp.transformf) + + +def _identity_quat() -> tuple[float, float, float, float]: + """Return identity quaternion in xyzw.""" + return (0.0, 0.0, 0.0, 1.0) + + +def _yaw_quat(yaw_rad: float) -> tuple[float, float, float, float]: + """Pure yaw quaternion in xyzw.""" + return (0.0, 0.0, math.sin(yaw_rad / 2), math.cos(yaw_rad / 2)) + + +def _euler_to_quat_xyzw(roll: float, pitch: float, yaw: float) -> tuple[float, float, float, float]: + """Euler angles (intrinsic XYZ) to quaternion in xyzw convention.""" + q = torch.zeros(1, 4) + cr, sr = math.cos(roll / 2), math.sin(roll / 2) + cp, sp = math.cos(pitch / 2), math.sin(pitch / 2) + cy, sy = math.cos(yaw / 2), math.sin(yaw / 2) + # xyzw + q[0, 0] = sr * cp * cy - cr * sp * sy + q[0, 1] = cr * sp * cy + sr * cp * sy + q[0, 2] = cr * cp * sy - sr * sp * cy + q[0, 3] = cr * cp * cy + sr * sp * sy + return tuple(q[0].tolist()) + + +def _quat_rotate(q_xyzw: tuple, v: tuple) -> np.ndarray: + """Rotate vector v by quaternion q (xyzw) using numpy.""" + qx, qy, qz, qw = q_xyzw + # quaternion rotation: v' = q * v * q^-1 + # Using the formula: v' = v + 2*w*(w×v) + 2*(q_vec × (q_vec × v + w*v)) + # Simpler: v' = v + 2w(q×v) + 2(q×(q×v)) + q_vec = np.array([qx, qy, qz]) + v = np.array(v) + t = 2.0 * np.cross(q_vec, v) + return v + qw * t + np.cross(q_vec, t) + + +def _launch_kernel( + transforms: wp.array, + env_mask: wp.array, + offset_pos: wp.array, + offset_quat: wp.array, + drift: wp.array, + ray_cast_drift: wp.array, + ray_starts_local: wp.array, + ray_directions_local: wp.array, + alignment_mode: int, + num_envs: int, + num_rays: int, +) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: + """Launch the kernel and return (pos_w, quat_w, ray_starts_w, ray_directions_w) as numpy arrays.""" + pos_w = wp.zeros(num_envs, dtype=wp.vec3f, device=DEVICE) + quat_w = wp.zeros(num_envs, dtype=wp.quatf, device=DEVICE) + ray_starts_w = wp.zeros((num_envs, num_rays), dtype=wp.vec3f, device=DEVICE) + ray_directions_w = wp.zeros((num_envs, num_rays), dtype=wp.vec3f, device=DEVICE) + + wp.launch( + update_ray_caster_kernel, + dim=(num_envs, num_rays), + inputs=[ + transforms, + env_mask, + offset_pos, + offset_quat, + drift, + ray_cast_drift, + ray_starts_local, + ray_directions_local, + alignment_mode, + ], + outputs=[pos_w, quat_w, ray_starts_w, ray_directions_w], + device=DEVICE, + ) + wp.synchronize_device(DEVICE) + + return ( + wp.to_torch(pos_w).cpu().numpy(), + wp.to_torch(quat_w).cpu().numpy(), + wp.to_torch(ray_starts_w).cpu().numpy(), + wp.to_torch(ray_directions_w).cpu().numpy(), + ) + + +def _make_inputs( + view_pos=(0.0, 0.0, 0.0), + view_quat=None, + offset_pos=(0.0, 0.0, 0.0), + offset_quat=None, + drift=(0.0, 0.0, 0.0), + ray_cast_drift=(0.0, 0.0, 0.0), + ray_start=(0.0, 0.0, 0.0), + ray_dir=(0.0, 0.0, -1.0), + num_envs=1, +): + """Build all kernel input arrays for a single-ray, single (or multi)-env scenario.""" + if view_quat is None: + view_quat = _identity_quat() + if offset_quat is None: + offset_quat = _identity_quat() + + transforms = _make_transform(view_pos, view_quat) + if num_envs > 1: + # Replicate the same transform for all envs + t_torch = wp.to_torch(transforms).repeat(num_envs, 1) + transforms = wp.from_torch(t_torch.contiguous()).view(wp.transformf) + + mask_t = torch.ones(num_envs, dtype=torch.bool, device=TORCH_DEVICE) + env_mask = wp.from_torch(mask_t) + + op = torch.tensor( + [[offset_pos[0], offset_pos[1], offset_pos[2]]] * num_envs, dtype=torch.float32, device=TORCH_DEVICE + ) + offset_pos_wp = wp.from_torch(op.contiguous(), dtype=wp.vec3f) + + oq = torch.tensor( + [[offset_quat[0], offset_quat[1], offset_quat[2], offset_quat[3]]] * num_envs, + dtype=torch.float32, + device=TORCH_DEVICE, + ) + offset_quat_wp = wp.from_torch(oq.contiguous(), dtype=wp.quatf) + + d = torch.tensor([[drift[0], drift[1], drift[2]]] * num_envs, dtype=torch.float32, device=TORCH_DEVICE) + drift_wp = wp.from_torch(d.contiguous(), dtype=wp.vec3f) + + rcd = torch.tensor( + [[ray_cast_drift[0], ray_cast_drift[1], ray_cast_drift[2]]] * num_envs, dtype=torch.float32, device=TORCH_DEVICE + ) + rcd_wp = wp.from_torch(rcd.contiguous(), dtype=wp.vec3f) + + rs = torch.tensor( + [[[ray_start[0], ray_start[1], ray_start[2]]]] * num_envs, dtype=torch.float32, device=TORCH_DEVICE + ) + rs_wp = wp.from_torch(rs.contiguous(), dtype=wp.vec3f) + + rd = torch.tensor([[[ray_dir[0], ray_dir[1], ray_dir[2]]]] * num_envs, dtype=torch.float32, device=TORCH_DEVICE) + rd_wp = wp.from_torch(rd.contiguous(), dtype=wp.vec3f) + + return transforms, env_mask, offset_pos_wp, offset_quat_wp, drift_wp, rcd_wp, rs_wp, rd_wp + + +# --------------------------------------------------------------------------- +# Tests +# --------------------------------------------------------------------------- + + +class TestUpdateRayCasterKernel: + """Unit tests for update_ray_caster_kernel launched directly with warp arrays.""" + + def test_identity_passthrough(self): + """All identity/zero inputs → pos_w = origin, quat_w = identity, rays unchanged.""" + inputs = _make_inputs(ray_start=(1.0, 2.0, 3.0), ray_dir=(0.0, 0.0, -1.0)) + pos_w, quat_w, starts_w, dirs_w = _launch_kernel(*inputs, alignment_mode=0, num_envs=1, num_rays=1) + + np.testing.assert_allclose(pos_w[0], [0, 0, 0], atol=ATOL) + np.testing.assert_allclose(quat_w[0], [0, 0, 0, 1], atol=ATOL) + # World mode, identity: ray_start_w = local_start + pos (= local_start + origin) + np.testing.assert_allclose(starts_w[0, 0], [1, 2, 3], atol=ATOL) + np.testing.assert_allclose(dirs_w[0, 0], [0, 0, -1], atol=ATOL) + + # Same for yaw and base — all should agree at identity + for mode in [1, 2]: + inputs = _make_inputs(ray_start=(1.0, 2.0, 3.0), ray_dir=(0.0, 0.0, -1.0)) + _, _, starts_w2, dirs_w2 = _launch_kernel(*inputs, alignment_mode=mode, num_envs=1, num_rays=1) + np.testing.assert_allclose(starts_w2[0, 0], [1, 2, 3], atol=ATOL) + np.testing.assert_allclose(dirs_w2[0, 0], [0, 0, -1], atol=ATOL) + + def test_offset_composition(self): + """View at (1,0,2) yawed 90° + offset (0,1,0) → combined_pos = (1,-1,2). + + 90° yaw: quat = (0, 0, sin(45°), cos(45°)) = (0, 0, 0.7071, 0.7071) + quat_rotate(90°yaw, (0,1,0)) = (-1, 0, 0) [Y axis maps to -X] + combined_pos = (1,0,2) + (-1,0,0) = (0,0,2) + combined_quat = yaw90 * identity = yaw90 + """ + yaw90 = _yaw_quat(math.pi / 2) + inputs = _make_inputs( + view_pos=(1.0, 0.0, 2.0), + view_quat=yaw90, + offset_pos=(0.0, 1.0, 0.0), + ) + pos_w, quat_w, _, _ = _launch_kernel(*inputs, alignment_mode=2, num_envs=1, num_rays=1) + + expected_offset_rotated = _quat_rotate(yaw90, (0, 1, 0)) # (-1, 0, 0) + expected_pos = np.array([1, 0, 2]) + expected_offset_rotated + np.testing.assert_allclose(pos_w[0], expected_pos, atol=ATOL) + np.testing.assert_allclose(quat_w[0], list(yaw90), atol=ATOL) + + def test_world_alignment_ignores_rotation(self): + """World mode: ray starts = local_start + combined_pos, directions unchanged. + + Sensor at (0,0,5), pitched 45° around Y. Local ray at (+1,0,0), direction (0,0,-1). + World mode should NOT rotate the ray start or direction. + """ + pitch45 = _euler_to_quat_xyzw(0, math.pi / 4, 0) + inputs = _make_inputs( + view_pos=(0.0, 0.0, 5.0), + view_quat=pitch45, + ray_start=(1.0, 0.0, 0.0), + ray_dir=(0.0, 0.0, -1.0), + ) + pos_w, _, starts_w, dirs_w = _launch_kernel(*inputs, alignment_mode=0, num_envs=1, num_rays=1) + + # ray_start_w = local_start + combined_pos = (1,0,0) + (0,0,5) = (1,0,5) + np.testing.assert_allclose(starts_w[0, 0], [1, 0, 5], atol=ATOL) + # direction unchanged + np.testing.assert_allclose(dirs_w[0, 0], [0, 0, -1], atol=ATOL) + + def test_yaw_alignment_rotates_starts_only(self): + """Yaw mode: ray starts rotated by yaw-only quaternion, directions unchanged. + + Sensor yawed 90° + pitched 30°. Local ray start at (+1, 0, 0). + Yaw-only extracts 90° yaw → rotates (+1,0,0) to (0,+1,0). + Direction (0,0,-1) is NOT rotated in yaw mode. + """ + q = _euler_to_quat_xyzw(0, math.pi / 6, math.pi / 2) # pitch 30°, yaw 90° + inputs = _make_inputs( + view_pos=(0.0, 0.0, 3.0), + view_quat=q, + ray_start=(1.0, 0.0, 0.0), + ray_dir=(0.0, 0.0, -1.0), + ) + pos_w, _, starts_w, dirs_w = _launch_kernel(*inputs, alignment_mode=1, num_envs=1, num_rays=1) + + # yaw-only of 90° yaw + 30° pitch → pure 90° yaw + yaw_only = _yaw_quat(math.pi / 2) + rotated_start = _quat_rotate(yaw_only, (1, 0, 0)) # (0, 1, 0) + expected_start = rotated_start + np.array([0, 0, 3]) # + combined_pos + np.testing.assert_allclose(starts_w[0, 0], expected_start, atol=ATOL) + + # direction unchanged in yaw mode + np.testing.assert_allclose(dirs_w[0, 0], [0, 0, -1], atol=ATOL) + + def test_base_alignment_rotates_starts_and_directions(self): + """Base mode: both ray starts and directions rotated by full combined quaternion. + + Sensor yawed 90°. Local ray at (+1, 0, 0), direction (0, 0, -1). + 90° yaw rotates: + (+1,0,0) → (0,+1,0) + (0,0,-1) → (0,0,-1) [yaw doesn't affect Z-down] + """ + yaw90 = _yaw_quat(math.pi / 2) + inputs = _make_inputs( + view_pos=(0.0, 0.0, 4.0), + view_quat=yaw90, + ray_start=(1.0, 0.0, 0.0), + ray_dir=(0.0, 0.0, -1.0), + ) + _, _, starts_w, dirs_w = _launch_kernel(*inputs, alignment_mode=2, num_envs=1, num_rays=1) + + rotated_start = _quat_rotate(yaw90, (1, 0, 0)) # (0, 1, 0) + expected_start = rotated_start + np.array([0, 0, 4]) + np.testing.assert_allclose(starts_w[0, 0], expected_start, atol=ATOL) + + rotated_dir = _quat_rotate(yaw90, (0, 0, -1)) # (0, 0, -1) — Z unaffected by yaw + np.testing.assert_allclose(dirs_w[0, 0], rotated_dir, atol=ATOL) + + def test_base_alignment_with_pitch_rotates_direction(self): + """Base mode with pitch: direction is rotated by the full orientation. + + Sensor pitched 90° around Y (looking forward instead of down). + Direction (0,0,-1) rotated by 90° pitch around Y → (-1,0,0). + """ + pitch90 = _euler_to_quat_xyzw(0, math.pi / 2, 0) + inputs = _make_inputs( + view_pos=(0.0, 0.0, 2.0), + view_quat=pitch90, + ray_start=(0.0, 0.0, 0.0), + ray_dir=(0.0, 0.0, -1.0), + ) + _, _, _, dirs_w = _launch_kernel(*inputs, alignment_mode=2, num_envs=1, num_rays=1) + + rotated_dir = _quat_rotate(pitch90, (0, 0, -1)) # (-1, 0, 0) + np.testing.assert_allclose(dirs_w[0, 0], rotated_dir, atol=ATOL) + + def test_ray_cast_drift_world_mode(self): + """World mode: ray_cast_drift XY is added raw to position, Z is NOT applied. + + drift = (0.5, 0.3, 0.7). In world mode: + pos_drifted = (combined_pos.x + 0.5, combined_pos.y + 0.3, combined_pos.z) + Note: Z component of ray_cast_drift is NOT added to position in any mode. + """ + inputs = _make_inputs( + view_pos=(1.0, 2.0, 3.0), + ray_cast_drift=(0.5, 0.3, 0.7), + ray_start=(0.0, 0.0, 0.0), + ray_dir=(0.0, 0.0, -1.0), + ) + _, _, starts_w, dirs_w = _launch_kernel(*inputs, alignment_mode=0, num_envs=1, num_rays=1) + + # World mode: pos_drifted = (1+0.5, 2+0.3, 3) = (1.5, 2.3, 3) + # ray_start_w = local_start + pos_drifted = (0,0,0) + (1.5, 2.3, 3) + np.testing.assert_allclose(starts_w[0, 0], [1.5, 2.3, 3.0], atol=ATOL) + np.testing.assert_allclose(dirs_w[0, 0], [0, 0, -1], atol=ATOL) + + def test_ray_cast_drift_yaw_mode(self): + """Yaw mode: ray_cast_drift XY is rotated by yaw-only quat, Z is NOT applied. + + Sensor yawed 90°, drift = (1.0, 0.0, 0.5). + yaw-rotated drift = quat_rotate(yaw90, (1,0,0.5)) — but only XY of the result + is used for pos_drifted. Actually looking at the kernel: + rot_drift = quat_rotate(yaw_q, rcd) # full rotation of the drift vector + pos_drifted = (combined_pos.x + rot_drift.x, combined_pos.y + rot_drift.y, combined_pos.z) + So the drift vector is fully rotated, but only XY of the result is added. + """ + yaw90 = _yaw_quat(math.pi / 2) + inputs = _make_inputs( + view_pos=(0.0, 0.0, 5.0), + view_quat=yaw90, + ray_cast_drift=(1.0, 0.0, 0.5), + ray_start=(0.0, 0.0, 0.0), + ray_dir=(0.0, 0.0, -1.0), + ) + _, _, starts_w, _ = _launch_kernel(*inputs, alignment_mode=1, num_envs=1, num_rays=1) + + # yaw90 rotates (1, 0, 0.5) → (0, 1, 0.5) [X→Y under 90° yaw, Z unchanged] + rot_drift = _quat_rotate(yaw90, (1, 0, 0.5)) + # pos_drifted = (0 + rot_drift.x, 0 + rot_drift.y, 5) — Z from combined_pos + expected_start = np.array([rot_drift[0], rot_drift[1], 5.0]) + # local_start = (0,0,0), rotated by yaw_q → still (0,0,0) + np.testing.assert_allclose(starts_w[0, 0], expected_start, atol=ATOL) + + def test_ray_cast_drift_base_mode(self): + """Base mode: ray_cast_drift XY is rotated by full combined_quat, Z is NOT applied. + + Sensor pitched 90° around Y, drift = (1.0, 0.0, 0.0). + Full rotation of (1,0,0) by 90° pitch around Y → (0, 0, -1). + pos_drifted = (combined_pos.x + 0, combined_pos.y + 0, combined_pos.z) — both XY of + rotated drift happen to be 0 in this case. + """ + pitch90 = _euler_to_quat_xyzw(0, math.pi / 2, 0) + inputs = _make_inputs( + view_pos=(0.0, 0.0, 5.0), + view_quat=pitch90, + ray_cast_drift=(1.0, 0.0, 0.0), + ray_start=(0.0, 0.0, 0.0), + ray_dir=(0.0, 0.0, -1.0), + ) + _, _, starts_w, _ = _launch_kernel(*inputs, alignment_mode=2, num_envs=1, num_rays=1) + + rot_drift = _quat_rotate(pitch90, (1, 0, 0)) # (0, 0, -1) + # pos_drifted = (0 + rot_drift.x, 0 + rot_drift.y, 5) = (0, 0, 5) + # local_start (0,0,0) rotated by pitch90 → still (0,0,0) + expected_start = np.array([rot_drift[0], rot_drift[1], 5.0]) + np.testing.assert_allclose(starts_w[0, 0], expected_start, atol=ATOL) + + def test_env_mask_skips_masked_envs(self): + """Masked-out environments retain sentinel values in output buffers. + + 2 envs, env 0 masked out (False), env 1 active (True). + Output buffers are pre-filled with sentinel (999). After kernel launch, + env 0 should still have 999, env 1 should have computed values. + """ + yaw90 = _yaw_quat(math.pi / 2) + + # Build transforms for 2 envs: both at (0,0,2) with yaw90 + t_single = torch.tensor( + [[0, 0, 2, yaw90[0], yaw90[1], yaw90[2], yaw90[3]]], + dtype=torch.float32, + device=DEVICE, + ) + t_both = t_single.repeat(2, 1).contiguous() + transforms = wp.from_torch(t_both).view(wp.transformf) + + # Mask: env 0 = False, env 1 = True + mask_t = torch.tensor([False, True], dtype=torch.bool, device=TORCH_DEVICE) + env_mask = wp.from_torch(mask_t) + + # Zero offsets and drifts for both envs + zero3 = torch.zeros(2, 3, dtype=torch.float32, device=TORCH_DEVICE) + offset_pos_wp = wp.from_torch(zero3.clone().contiguous(), dtype=wp.vec3f) + iq = torch.tensor([[0, 0, 0, 1]] * 2, dtype=torch.float32, device=TORCH_DEVICE) + offset_quat_wp = wp.from_torch(iq.contiguous(), dtype=wp.quatf) + drift_wp = wp.from_torch(zero3.clone().contiguous(), dtype=wp.vec3f) + rcd_wp = wp.from_torch(zero3.clone().contiguous(), dtype=wp.vec3f) + + # Single ray per env + rs = torch.tensor([[[1, 0, 0]]] * 2, dtype=torch.float32, device=TORCH_DEVICE) + rs_wp = wp.from_torch(rs.contiguous(), dtype=wp.vec3f) + rd = torch.tensor([[[0, 0, -1]]] * 2, dtype=torch.float32, device=TORCH_DEVICE) + rd_wp = wp.from_torch(rd.contiguous(), dtype=wp.vec3f) + + # Pre-fill outputs with sentinel + sentinel = 999.0 + pos_w_t = torch.full((2, 3), sentinel, dtype=torch.float32, device=TORCH_DEVICE) + pos_w = wp.from_torch(pos_w_t.contiguous(), dtype=wp.vec3f) + quat_w_t = torch.full((2, 4), sentinel, dtype=torch.float32, device=TORCH_DEVICE) + quat_w = wp.from_torch(quat_w_t.contiguous(), dtype=wp.quatf) + starts_w_t = torch.full((2, 1, 3), sentinel, dtype=torch.float32, device=TORCH_DEVICE) + starts_w = wp.from_torch(starts_w_t.contiguous(), dtype=wp.vec3f) + dirs_w_t = torch.full((2, 1, 3), sentinel, dtype=torch.float32, device=TORCH_DEVICE) + dirs_w = wp.from_torch(dirs_w_t.contiguous(), dtype=wp.vec3f) + + wp.launch( + update_ray_caster_kernel, + dim=(2, 1), + inputs=[transforms, env_mask, offset_pos_wp, offset_quat_wp, drift_wp, rcd_wp, rs_wp, rd_wp, 2], + outputs=[pos_w, quat_w, starts_w, dirs_w], + device=DEVICE, + ) + wp.synchronize_device(DEVICE) + + pos_np = wp.to_torch(pos_w).cpu().numpy() + quat_np = wp.to_torch(quat_w).cpu().numpy() + starts_np = wp.to_torch(starts_w).cpu().numpy() + dirs_np = wp.to_torch(dirs_w).cpu().numpy() + + # Env 0 (masked): all outputs should still be sentinel + np.testing.assert_allclose(pos_np[0], [sentinel] * 3, atol=ATOL) + np.testing.assert_allclose(quat_np[0], [sentinel] * 4, atol=ATOL) + np.testing.assert_allclose(starts_np[0, 0], [sentinel] * 3, atol=ATOL) + np.testing.assert_allclose(dirs_np[0, 0], [sentinel] * 3, atol=ATOL) + + # Env 1 (active): should have computed values + np.testing.assert_allclose(pos_np[1], [0, 0, 2], atol=ATOL) + np.testing.assert_allclose(quat_np[1], list(yaw90), atol=ATOL) + # Base mode: (1,0,0) rotated by yaw90 = (0,1,0), + pos (0,0,2) + expected_start = _quat_rotate(yaw90, (1, 0, 0)) + np.array([0, 0, 2]) + np.testing.assert_allclose(starts_np[1, 0], expected_start, atol=ATOL) + expected_dir = _quat_rotate(yaw90, (0, 0, -1)) # (0, 0, -1) unaffected by yaw + np.testing.assert_allclose(dirs_np[1, 0], expected_dir, atol=ATOL) + + def test_positional_drift_added_before_alignment(self): + """The `drift` parameter is added to combined_pos before ray transformation. + + Verify that drift shifts the sensor position (and therefore ray starts) + equally across all alignment modes. + """ + drift_val = (0.0, 0.0, 1.5) # shift up 1.5m + results = {} + for mode_name, mode_int in [("world", 0), ("yaw", 1), ("base", 2)]: + inputs = _make_inputs( + view_pos=(0.0, 0.0, 3.0), + drift=drift_val, + ray_start=(0.0, 0.0, 0.0), + ray_dir=(0.0, 0.0, -1.0), + ) + pos_w, _, starts_w, _ = _launch_kernel(*inputs, alignment_mode=mode_int, num_envs=1, num_rays=1) + results[mode_name] = (pos_w, starts_w) + + # All modes: pos_w should be (0, 0, 4.5) = view_pos + drift + for mode_name in ["world", "yaw", "base"]: + np.testing.assert_allclose( + results[mode_name][0][0], + [0, 0, 4.5], + atol=ATOL, + err_msg=f"{mode_name} mode: pos_w should include drift", + ) + # ray_start_w Z should also reflect the drifted position + assert results[mode_name][1][0, 0, 2] == pytest.approx(4.5, abs=ATOL), ( + f"{mode_name} mode: ray start Z should be 4.5" + ) diff --git a/source/isaaclab/test/sim/frame_view_contract_utils.py b/source/isaaclab/test/sim/frame_view_contract_utils.py new file mode 100644 index 000000000000..4336f94bd3d7 --- /dev/null +++ b/source/isaaclab/test/sim/frame_view_contract_utils.py @@ -0,0 +1,404 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Shared FrameView contract tests. + +This module defines the invariants that **every** FrameView backend +(USD, Fabric, Newton) must satisfy. Backend test files import these tests +via ``from frame_view_contract_utils import *`` and provide a +``view_factory`` pytest fixture that builds the backend-specific scene. + +The factory signature is:: + + def view_factory() -> Callable[[int, str], ViewBundle]: ... + +Where ``ViewBundle`` is a :class:`NamedTuple`:: + + class ViewBundle(NamedTuple): + view: BaseFrameView + get_parent_pos: Callable[[int, str], torch.Tensor] + set_parent_pos: Callable[[torch.Tensor, int], None] + teardown: Callable[[], None] + +- ``view``: The FrameView under test. Must track child prims at + :data:`CHILD_OFFSET` under parent prims/bodies. +- ``get_parent_pos(n, device)``: Read the parent prim/body positions. +- ``set_parent_pos(positions, n)``: Write the parent prim/body positions. +- ``teardown()``: Cleanup (close context, clear stage, etc.). + +Tolerance policy: + - Indexed reads (exact copy): ``atol=0`` + - Composition / decomposition through float32 transforms: ``atol=ATOL`` + - Parent position identity checks (should be untouched): ``atol=0`` +""" + +from __future__ import annotations + +from collections.abc import Callable +from typing import NamedTuple + +import pytest +import torch +import warp as wp + +from isaaclab.utils.warp import ProxyArray + +CHILD_OFFSET = (0.1, 0.0, 0.05) +"""Local offset of the child prim from its parent, shared by all backend fixtures.""" + +ATOL = 1e-5 +"""Default absolute tolerance for float32 transform composition.""" + + +class ViewBundle(NamedTuple): + """Return type of the ``view_factory`` fixture.""" + + view: object + get_parent_pos: Callable + set_parent_pos: Callable + teardown: Callable + + +def _t(a): + """Convert a wp.array or ProxyArray return to a torch.Tensor (pass-through otherwise).""" + if isinstance(a, ProxyArray): + return a.torch + return wp.to_torch(a) if isinstance(a, wp.array) else a + + +def _wp_vec3f(data, device="cpu"): + return wp.array([wp.vec3f(*row) for row in data], dtype=wp.vec3f, device=device) + + +def _wp_vec4f(data, device="cpu"): + return wp.array([wp.vec4f(*row) for row in data], dtype=wp.vec4f, device=device) + + +# ================================================================== +# Contract: Getters +# ================================================================== + + +@pytest.mark.parametrize("device", ["cpu", "cuda:0"]) +def test_world_pose_equals_parent_plus_offset(device, view_factory): + """world_pose == parent_pos + local offset (identity parent orientation).""" + bundle = view_factory(num_envs=4, device=device) + try: + child_pos = _t(bundle.view.get_world_poses()[0]) + parent_pos = bundle.get_parent_pos(4, device) + offset = torch.tensor(CHILD_OFFSET, device=device) + + torch.testing.assert_close(child_pos, parent_pos + offset.unsqueeze(0), atol=ATOL, rtol=0) + finally: + bundle.teardown() + + +@pytest.mark.parametrize("device", ["cpu", "cuda:0"]) +def test_local_pose_equals_structural_offset(device, view_factory): + """local_pose == the authored offset (0.1, 0, 0.05) for every prim.""" + bundle = view_factory(num_envs=4, device=device) + try: + local_pos, local_quat = bundle.view.get_local_poses() + expected_pos = torch.tensor(CHILD_OFFSET, device=device).expand(4, -1) + expected_quat = torch.tensor([0.0, 0.0, 0.0, 1.0], device=device).expand(4, -1) + + torch.testing.assert_close(_t(local_pos), expected_pos, atol=ATOL, rtol=0) + torch.testing.assert_close(_t(local_quat), expected_quat, atol=ATOL, rtol=0) + finally: + bundle.teardown() + + +@pytest.mark.parametrize("device", ["cpu", "cuda:0"]) +def test_local_differs_from_world(device, view_factory): + """local != world when parent is not at the origin. + + Asserts |world - local| > 0.5 to catch any implementation that returns + world as local. The parent is offset from the origin so the z-component + alone provides > 0.5 difference. + """ + bundle = view_factory(num_envs=2, device=device) + try: + world_pos = _t(bundle.view.get_world_poses()[0]) + local_pos = _t(bundle.view.get_local_poses()[0]) + + diff = (world_pos - local_pos).abs().max().item() + assert diff > 0.5, ( + f"Expected |world - local| > 0.5, got {diff:.4f}. world={world_pos.tolist()}, local={local_pos.tolist()}" + ) + finally: + bundle.teardown() + + +@pytest.mark.parametrize("device", ["cpu", "cuda:0"]) +def test_local_stable_after_parent_move(device, view_factory): + """Moving the parent changes world but NOT local.""" + bundle = view_factory(num_envs=2, device=device) + try: + local_before = _t(bundle.view.get_local_poses()[0]).clone() + bundle.set_parent_pos(torch.tensor([[99.0, 0.0, 0.0], [0.0, 99.0, 0.0]], device=device), 2) + local_after = _t(bundle.view.get_local_poses()[0]) + + torch.testing.assert_close(local_after, local_before, atol=ATOL, rtol=0) + finally: + bundle.teardown() + + +@pytest.mark.parametrize("device", ["cpu", "cuda:0"]) +def test_world_tracks_parent_move(device, view_factory): + """Moving the parent shifts world poses by the same amount.""" + bundle = view_factory(num_envs=2, device=device) + try: + new_parent_pos = torch.tensor([[5.0, 0.0, 0.0], [0.0, 5.0, 0.0]], device=device) + bundle.set_parent_pos(new_parent_pos, 2) + + child_pos = _t(bundle.view.get_world_poses()[0]) + offset = torch.tensor(CHILD_OFFSET, device=device) + + torch.testing.assert_close(child_pos, new_parent_pos + offset.unsqueeze(0), atol=ATOL, rtol=0) + finally: + bundle.teardown() + + +@pytest.mark.parametrize("device", ["cpu", "cuda:0"]) +def test_indexed_get_returns_correct_subset(device, view_factory): + """Indexed get (out-of-order) returns exact copies for both world and local.""" + bundle = view_factory(num_envs=5, device=device) + try: + all_world = _t(bundle.view.get_world_poses()[0]) + all_local = _t(bundle.view.get_local_poses()[0]) + + indices_list = [4, 1, 3] + indices = wp.array(indices_list, dtype=wp.int32, device=device) + sub_world = _t(bundle.view.get_world_poses(indices)[0]) + sub_local = _t(bundle.view.get_local_poses(indices)[0]) + + for out_i, view_i in enumerate(indices_list): + torch.testing.assert_close(sub_world[out_i], all_world[view_i], atol=0, rtol=0) + torch.testing.assert_close(sub_local[out_i], all_local[view_i], atol=0, rtol=0) + finally: + bundle.teardown() + + +# ================================================================== +# Contract: Setters +# ================================================================== + + +@pytest.mark.parametrize("device", ["cpu", "cuda:0"]) +def test_set_world_roundtrip(device, view_factory): + """set_world_poses -> get_world_poses returns the same values.""" + bundle = view_factory(num_envs=2, device=device) + try: + new_pos = _wp_vec3f([[10.0, 20.0, 30.0], [40.0, 50.0, 60.0]], device=device) + new_quat = _wp_vec4f([[0.0, 0.0, 0.7071068, 0.7071068], [0.0, 0.0, 0.0, 1.0]], device=device) + bundle.view.set_world_poses(new_pos, new_quat) + + ret_pos, ret_quat = bundle.view.get_world_poses() + torch.testing.assert_close(_t(ret_pos), _t(new_pos), atol=ATOL, rtol=0) + torch.testing.assert_close(_t(ret_quat), _t(new_quat), atol=ATOL, rtol=0) + finally: + bundle.teardown() + + +@pytest.mark.parametrize("device", ["cpu", "cuda:0"]) +def test_set_local_roundtrip(device, view_factory): + """set_local_poses -> get_local_poses returns the same values.""" + bundle = view_factory(num_envs=2, device=device) + try: + new_pos = _wp_vec3f([[0.5, 0.3, 0.1], [0.2, 0.7, 0.4]], device=device) + new_quat = _wp_vec4f([[0.0, 0.0, 0.0, 1.0]] * 2, device=device) + bundle.view.set_local_poses(new_pos, new_quat) + + ret_pos, ret_quat = bundle.view.get_local_poses() + torch.testing.assert_close(_t(ret_pos), _t(new_pos), atol=ATOL, rtol=0) + torch.testing.assert_close(_t(ret_quat), _t(new_quat), atol=ATOL, rtol=0) + finally: + bundle.teardown() + + +@pytest.mark.parametrize("device", ["cpu", "cuda:0"]) +def test_set_world_does_not_move_parent(device, view_factory): + """set_world_poses must not modify the parent prim/body position.""" + bundle = view_factory(num_envs=2, device=device) + try: + parent_before = bundle.get_parent_pos(2, device).clone() + bundle.view.set_world_poses( + _wp_vec3f([[99.0, 99.0, 99.0], [88.0, 88.0, 88.0]], device=device), + _wp_vec4f([[0.0, 0.0, 0.0, 1.0]] * 2, device=device), + ) + parent_after = bundle.get_parent_pos(2, device) + + torch.testing.assert_close(parent_after, parent_before, atol=0, rtol=0) + finally: + bundle.teardown() + + +@pytest.mark.parametrize("device", ["cpu", "cuda:0"]) +def test_set_local_does_not_move_parent(device, view_factory): + """set_local_poses must not modify the parent prim/body position.""" + bundle = view_factory(num_envs=2, device=device) + try: + parent_before = bundle.get_parent_pos(2, device).clone() + bundle.view.set_local_poses( + _wp_vec3f([[0.5, 0.5, 0.5], [1.0, 1.0, 1.0]], device=device), + _wp_vec4f([[0.0, 0.0, 0.0, 1.0]] * 2, device=device), + ) + parent_after = bundle.get_parent_pos(2, device) + + torch.testing.assert_close(parent_after, parent_before, atol=0, rtol=0) + finally: + bundle.teardown() + + +@pytest.mark.parametrize("device", ["cpu", "cuda:0"]) +def test_set_world_updates_local(device, view_factory): + """After set_world_poses, get_local_poses reflects the new offset. + + Uses non-axis-aligned offsets to catch coordinate swap bugs. + """ + bundle = view_factory(num_envs=2, device=device) + try: + parent_pos = bundle.get_parent_pos(2, device) + desired_offset = torch.tensor([[0.3, 0.7, 0.2], [0.8, 0.1, 0.6]], device=device) + new_world = parent_pos + desired_offset + + bundle.view.set_world_poses( + _wp_vec3f(new_world.tolist(), device=device), + _wp_vec4f([[0.0, 0.0, 0.0, 1.0]] * 2, device=device), + ) + + local_pos = _t(bundle.view.get_local_poses()[0]) + torch.testing.assert_close(local_pos, desired_offset, atol=ATOL, rtol=0) + finally: + bundle.teardown() + + +@pytest.mark.parametrize("device", ["cpu", "cuda:0"]) +def test_set_local_updates_world(device, view_factory): + """After set_local_poses, get_world_poses == parent + new_local. + + Uses non-axis-aligned offsets to catch coordinate swap bugs. + """ + bundle = view_factory(num_envs=2, device=device) + try: + parent_pos = bundle.get_parent_pos(2, device) + new_offset = torch.tensor([[0.4, 0.9, 0.15], [0.6, 0.2, 0.85]], device=device) + bundle.view.set_local_poses( + _wp_vec3f(new_offset.tolist(), device=device), + _wp_vec4f([[0.0, 0.0, 0.0, 1.0]] * 2, device=device), + ) + + world_pos = _t(bundle.view.get_world_poses()[0]) + torch.testing.assert_close(world_pos, parent_pos + new_offset, atol=ATOL, rtol=0) + finally: + bundle.teardown() + + +@pytest.mark.parametrize("device", ["cpu", "cuda:0"]) +def test_set_world_partial_position_only(device, view_factory): + """Setting only positions: new positions written, orientations preserved.""" + bundle = view_factory(num_envs=2, device=device) + try: + _, orig_quat = bundle.view.get_world_poses() + new_pos = _wp_vec3f([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]], device=device) + bundle.view.set_world_poses(positions=new_pos) + + ret_pos, ret_quat = bundle.view.get_world_poses() + torch.testing.assert_close(_t(ret_pos), _t(new_pos), atol=ATOL, rtol=0) + torch.testing.assert_close(_t(ret_quat), _t(orig_quat), atol=ATOL, rtol=0) + finally: + bundle.teardown() + + +@pytest.mark.parametrize("device", ["cpu", "cuda:0"]) +def test_set_world_partial_orientation_only(device, view_factory): + """Setting only orientations: new orientations written, positions preserved.""" + bundle = view_factory(num_envs=2, device=device) + try: + orig_pos, _ = bundle.view.get_world_poses() + new_quat = _wp_vec4f([[0.0, 0.0, 0.7071068, 0.7071068], [0.7071068, 0.0, 0.0, 0.7071068]], device=device) + bundle.view.set_world_poses(orientations=new_quat) + + ret_pos, ret_quat = bundle.view.get_world_poses() + torch.testing.assert_close(_t(ret_pos), _t(orig_pos), atol=ATOL, rtol=0) + torch.testing.assert_close(_t(ret_quat), _t(new_quat), atol=ATOL, rtol=0) + finally: + bundle.teardown() + + +@pytest.mark.parametrize("device", ["cpu", "cuda:0"]) +def test_set_local_partial_position_only(device, view_factory): + """Setting only local translations: new translations written, orientations preserved.""" + bundle = view_factory(num_envs=2, device=device) + try: + _, orig_quat = bundle.view.get_local_poses() + new_pos = _wp_vec3f([[0.2, 0.3, 0.4], [0.5, 0.6, 0.7]], device=device) + bundle.view.set_local_poses(translations=new_pos) + + ret_pos, ret_quat = bundle.view.get_local_poses() + torch.testing.assert_close(_t(ret_pos), _t(new_pos), atol=ATOL, rtol=0) + torch.testing.assert_close(_t(ret_quat), _t(orig_quat), atol=ATOL, rtol=0) + finally: + bundle.teardown() + + +@pytest.mark.parametrize("device", ["cpu", "cuda:0"]) +def test_set_world_indexed_only_affects_subset(device, view_factory): + """Indexed set_world_poses writes requested indices, leaves others untouched.""" + bundle = view_factory(num_envs=4, device=device) + try: + orig_pos = _t(bundle.view.get_world_poses()[0]).clone() + indices = wp.array([1, 3], dtype=wp.int32, device=device) + new_pos = _wp_vec3f([[10.0, 20.0, 30.0], [40.0, 50.0, 60.0]], device=device) + bundle.view.set_world_poses(positions=new_pos, indices=indices) + + updated = _t(bundle.view.get_world_poses()[0]) + torch.testing.assert_close(updated[0], orig_pos[0], atol=0, rtol=0) + torch.testing.assert_close(updated[2], orig_pos[2], atol=0, rtol=0) + torch.testing.assert_close(updated[1], _t(new_pos)[0], atol=ATOL, rtol=0) + torch.testing.assert_close(updated[3], _t(new_pos)[1], atol=ATOL, rtol=0) + finally: + bundle.teardown() + + +@pytest.mark.parametrize("device", ["cpu", "cuda:0"]) +def test_return_types_are_torcharray(device, view_factory): + """Public API contract — every backend returns ProxyArray from the pose getters.""" + bundle = view_factory(num_envs=2, device=device) + try: + pos_full, quat_full = bundle.view.get_world_poses() + assert isinstance(pos_full, ProxyArray), ( + f"get_world_poses()[0] must be ProxyArray, got {type(pos_full).__name__}" + ) + assert isinstance(quat_full, ProxyArray), ( + f"get_world_poses()[1] must be ProxyArray, got {type(quat_full).__name__}" + ) + + indices = wp.array([0], dtype=wp.int32, device=bundle.view.device) + pos_idx, quat_idx = bundle.view.get_world_poses(indices) + assert isinstance(pos_idx, ProxyArray), ( + f"get_world_poses(indices)[0] must be ProxyArray, got {type(pos_idx).__name__}" + ) + assert isinstance(quat_idx, ProxyArray), ( + f"get_world_poses(indices)[1] must be ProxyArray, got {type(quat_idx).__name__}" + ) + + lpos_full, lquat_full = bundle.view.get_local_poses() + assert isinstance(lpos_full, ProxyArray), ( + f"get_local_poses()[0] must be ProxyArray, got {type(lpos_full).__name__}" + ) + assert isinstance(lquat_full, ProxyArray), ( + f"get_local_poses()[1] must be ProxyArray, got {type(lquat_full).__name__}" + ) + + lpos_idx, lquat_idx = bundle.view.get_local_poses(indices) + assert isinstance(lpos_idx, ProxyArray), ( + f"get_local_poses(indices)[0] must be ProxyArray, got {type(lpos_idx).__name__}" + ) + assert isinstance(lquat_idx, ProxyArray), ( + f"get_local_poses(indices)[1] must be ProxyArray, got {type(lquat_idx).__name__}" + ) + finally: + bundle.teardown() diff --git a/source/isaaclab/test/sim/test_cloner.py b/source/isaaclab/test/sim/test_cloner.py index 4784f59dcd0a..1f8af90387b5 100644 --- a/source/isaaclab/test/sim/test_cloner.py +++ b/source/isaaclab/test/sim/test_cloner.py @@ -20,11 +20,11 @@ from pxr import UsdGeom import isaaclab.sim as sim_utils -from isaaclab.cloner import usd_replicate -from isaaclab.cloner.cloner_utils import resolve_visualizer_clone_fn -from isaaclab.physics.scene_data_requirements import SceneDataRequirement, VisualizerPrebuiltArtifacts +from isaaclab.cloner import ClonePlan, TemplateCloneCfg, clone_from_template, sequential, usd_replicate from isaaclab.sim import build_simulation_context +pytestmark = pytest.mark.isaacsim_ci + @pytest.fixture(params=["cpu", "cuda"]) def sim(request): @@ -221,79 +221,56 @@ def test_clone_decorator_wildcard_patterns( ) -def test_resolve_visualizer_clone_fn_returns_none_when_not_physx_backend(): - """Resolver should ignore non-PhysX backends.""" - hook = resolve_visualizer_clone_fn( - physics_backend="newton", - requirements=SceneDataRequirement(requires_newton_model=True), - stage=object(), - set_visualizer_artifact=lambda artifact: artifact, - ) - assert hook is None - - -def test_resolve_visualizer_clone_fn_returns_none_when_newton_model_not_required(): - """Resolver should not load optional hook when requirement is not requested.""" - hook = resolve_visualizer_clone_fn( - physics_backend="physx", - requirements=SceneDataRequirement(requires_newton_model=False), - stage=object(), - set_visualizer_artifact=lambda artifact: artifact, - ) - assert hook is None - - -def test_resolve_visualizer_clone_fn_returns_callable_when_available(sim): - """Resolver should return a callable hook when backend helper is available.""" - pytest.importorskip("isaaclab_newton.cloner.newton_replicate") - hook = resolve_visualizer_clone_fn( - physics_backend="physx", - requirements=SceneDataRequirement(requires_newton_model=True), - stage=sim_utils.get_current_stage(), - set_visualizer_artifact=lambda artifact: artifact, - ) - assert callable(hook) - - -def test_physx_newton_requirement_hook_populates_prebuilt_artifact(sim, monkeypatch: pytest.MonkeyPatch): - """PhysX + Newton requirement path should populate prebuilt visualizer artifact.""" - newton_replicate = pytest.importorskip("isaaclab_newton.cloner.newton_replicate") +def test_clone_from_template_returns_clone_plan(sim): + """clone_from_template exposes per-group ClonePlan dicts with prototype-to-env masks. - class _FakeModel: - body_label = ["/World/envs/env_0/A", "/World/envs/env_1/A"] - articulation_label = ["/World/envs/env_0/Robot", "/World/envs/env_1/Robot"] - - fake_model = _FakeModel() - fake_state = object() - - def _fake_prebuild(*args, **kwargs): - return fake_model, fake_state + Builds two USD prototypes under one group, clones across four envs with the deterministic + sequential strategy, and asserts the returned dict has one entry keyed by the group's + destination template, with a ``[2, 4]`` boolean mask whose columns sum to one. + """ + num_clones = 4 + cfg = TemplateCloneCfg(device=sim.cfg.device, clone_strategy=sequential, clone_physics=False) - monkeypatch.setattr(newton_replicate, "newton_visualizer_prebuild", _fake_prebuild) + sim_utils.create_prim(cfg.template_root, "Xform") + sim_utils.create_prim(f"{cfg.template_root}/Object", "Xform") + sim_utils.create_prim(f"{cfg.template_root}/Object/proto_asset_0", "Xform") + sim_utils.create_prim(f"{cfg.template_root}/Object/proto_asset_1", "Xform") + sim_utils.create_prim("/World/envs", "Xform") + for i in range(num_clones): + sim_utils.create_prim(f"/World/envs/env_{i}", "Xform", translation=(0, 0, 0)) - captured: list[VisualizerPrebuiltArtifacts] = [] - hook = resolve_visualizer_clone_fn( - physics_backend="physx", - requirements=SceneDataRequirement(requires_newton_model=True), - stage=sim_utils.get_current_stage(), - set_visualizer_artifact=lambda artifact: captured.append(artifact), - ) + stage = sim_utils.get_current_stage() + plans = clone_from_template(stage, num_clones=num_clones, template_clone_cfg=cfg) + + assert isinstance(plans, dict) + assert list(plans.keys()) == ["/World/envs/env_{}/Object"] + plan = plans["/World/envs/env_{}/Object"] + assert isinstance(plan, ClonePlan) + assert plan.dest_template == "/World/envs/env_{}/Object" + assert sorted(plan.prototype_paths) == [ + "/World/template/Object/proto_asset_0", + "/World/template/Object/proto_asset_1", + ] + assert plan.clone_mask.shape == (2, num_clones) + assert plan.clone_mask.dtype == torch.bool + # Each env gets exactly one prototype (column-sum invariant) + assert torch.all(plan.clone_mask.sum(dim=0) == 1) + # Sequential strategy assigns env i → prototype (i % num_protos) + actual_proto_idx = plan.clone_mask.to(torch.int).argmax(dim=0).cpu() + assert torch.equal(actual_proto_idx, torch.tensor([0, 1, 0, 1])) + + +def test_clone_from_template_returns_empty_dict_when_no_prototypes(sim): + """clone_from_template returns an empty dict when no prototypes match the identifier.""" + num_clones = 2 + cfg = TemplateCloneCfg(device=sim.cfg.device, clone_strategy=sequential, clone_physics=False) + + sim_utils.create_prim(cfg.template_root, "Xform") + sim_utils.create_prim("/World/envs", "Xform") + for i in range(num_clones): + sim_utils.create_prim(f"/World/envs/env_{i}", "Xform", translation=(0, 0, 0)) - assert callable(hook) - hook( - stage=sim_utils.get_current_stage(), - sources=["/World/template/A"], - destinations=["/World/envs/env_{}/A"], - env_ids=torch.tensor([0, 1], dtype=torch.long), - mapping=torch.ones((1, 2), dtype=torch.bool), - device="cpu", - ) + stage = sim_utils.get_current_stage() + plans = clone_from_template(stage, num_clones=num_clones, template_clone_cfg=cfg) - assert len(captured) == 1 - artifact = captured[0] - assert isinstance(artifact, VisualizerPrebuiltArtifacts) - assert artifact.model is fake_model - assert artifact.state is fake_state - assert artifact.rigid_body_paths == fake_model.body_label - assert artifact.articulation_paths == fake_model.articulation_label - assert artifact.num_envs == 2 + assert plans == {} diff --git a/source/isaaclab/test/sim/test_mjcf_converter.py b/source/isaaclab/test/sim/test_mjcf_converter.py index e927d2572756..2e68b66a2fc0 100644 --- a/source/isaaclab/test/sim/test_mjcf_converter.py +++ b/source/isaaclab/test/sim/test_mjcf_converter.py @@ -16,12 +16,14 @@ import pytest -from isaacsim.core.utils.extensions import enable_extension, get_extension_path_from_name +from isaacsim.core.experimental.utils.app import enable_extension, get_extension_path import isaaclab.sim as sim_utils from isaaclab.sim import SimulationCfg, SimulationContext from isaaclab.sim.converters import MjcfConverter, MjcfConverterCfg +pytestmark = pytest.mark.isaacsim_ci + @pytest.fixture(autouse=True) def test_setup_teardown(): @@ -35,7 +37,7 @@ def test_setup_teardown(): # Setup: Create MJCF config enable_extension("isaacsim.asset.importer.mjcf") - extension_path = get_extension_path_from_name("isaacsim.asset.importer.mjcf") + extension_path = get_extension_path("isaacsim.asset.importer.mjcf") config = MjcfConverterCfg( asset_path=f"{extension_path}/data/mjcf/nv_ant.xml", self_collision=False, @@ -49,7 +51,6 @@ def test_setup_teardown(): sim.clear_instance() -@pytest.mark.isaacsim_ci def test_no_change(test_setup_teardown): """Call conversion twice. This should not generate a new USD file.""" sim, mjcf_config = test_setup_teardown @@ -67,7 +68,6 @@ def test_no_change(test_setup_teardown): assert time_usd_file_created == new_time_usd_file_created -@pytest.mark.isaacsim_ci def test_config_change(test_setup_teardown): """Call conversion twice but change the config in the second call. This should generate a new USD file.""" sim, mjcf_config = test_setup_teardown @@ -87,7 +87,6 @@ def test_config_change(test_setup_teardown): assert time_usd_file_created != new_time_usd_file_created -@pytest.mark.isaacsim_ci def test_create_prim_from_usd(test_setup_teardown): """Call conversion and create a prim from it.""" sim, mjcf_config = test_setup_teardown diff --git a/source/isaaclab/test/sim/test_newton_model_utils.py b/source/isaaclab/test/sim/test_newton_model_utils.py new file mode 100644 index 000000000000..cc157074fd42 --- /dev/null +++ b/source/isaaclab/test/sim/test_newton_model_utils.py @@ -0,0 +1,516 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Tests for :mod:`isaaclab.sim.utils.newton_model_utils` (no Kit required).""" + +# pyright: reportPrivateUsage=false + +from __future__ import annotations + +import warnings +from types import SimpleNamespace + +import numpy as np +import pytest +import torch +import warp as wp + +from pxr import Gf, Sdf, Usd, UsdGeom, UsdShade + +from isaaclab.sim.utils.newton_model_utils import ( + _OMNIPBR_DEFAULTS, + _UNBOUND_DEFAULT_FALLBACK_GRAY, + _get_omnipbr_albedo, + _resolve_shape_color, + _scatter_shape_color_rows_kernel, + replace_newton_shape_colors, +) + +_WARNING_MESSAGE = "Newton shape color replacement is enabled; this workaround will be deprecated in a future release." + + +def _replace_newton_shape_colors_wrapper(model: object, stage: Usd.Stage | None = None) -> int: + """Call :func:`replace_newton_shape_colors` with :class:`FutureWarning` suppressed in test reports.""" + with warnings.catch_warnings(): + warnings.filterwarnings("ignore", message=_WARNING_MESSAGE, category=FutureWarning) + return replace_newton_shape_colors(model, stage) + + +_OMNIPBR_ALBEDO_INPUT_CASES = [ + pytest.param((0.2, 0.4, 0.6), (0.5, 0.25, 2.0), id="both_authored"), + pytest.param((0.25, 0.5, 0.75), None, id="diffuse_only"), + pytest.param(None, (0.4, 0.5, 2.0), id="tint_only"), + pytest.param(None, None, id="defaults"), +] + + +def _expected_omnipbr_linear_albedo( + diffuse_color_constant: tuple[float, float, float] | None, + diffuse_tint: tuple[float, float, float] | None, +) -> tuple[float, float, float]: + cd = diffuse_color_constant or _OMNIPBR_DEFAULTS["diffuse_color_constant"] + td = diffuse_tint or _OMNIPBR_DEFAULTS["diffuse_tint"] + return (cd[0] * td[0], cd[1] * td[1], cd[2] * td[2]) + + +def _make_omnipbr_test_shader( + stage: Usd.Stage, + material_prim_path: str, +) -> UsdShade.Shader: + """Define a ``UsdShade.Material`` and minimal OmniPBR ``UsdShade.Shader`` (MDL asset only). + + Diffuse and tint inputs are unauthored until the caller sets them (MDL defaults apply in readers). + + Args: + stage: Stage to author on. + material_prim_path: Absolute prim path for ``UsdShade.Material.Define``. + + Returns: + The defined shader API. + """ + UsdShade.Material.Define(stage, material_prim_path) + shader = UsdShade.Shader.Define(stage, f"{material_prim_path}/OmniPBRShader") + assert shader.GetPrim().IsValid() + shader_prim = shader.GetPrim() + mdl_asset_attr = shader_prim.CreateAttribute("info:mdl:sourceAsset", Sdf.ValueTypeNames.Asset) + assert mdl_asset_attr.IsValid() + mdl_asset_attr.Set(Sdf.AssetPath("OmniPBR.mdl")) + return shader + + +def _define_mesh_and_bind_material(stage: Usd.Stage, mesh_path: str, material: UsdShade.Material) -> UsdGeom.Mesh: + """Define a mesh at ``mesh_path`` and bind ``material`` via :class:`UsdShade.MaterialBindingAPI`.""" + mesh = UsdGeom.Mesh.Define(stage, mesh_path) + assert mesh.GetPrim().IsValid() + mesh_prim = mesh.GetPrim() + UsdShade.MaterialBindingAPI.Apply(mesh_prim) + UsdShade.MaterialBindingAPI(mesh_prim).Bind(material) + return mesh + + +def _make_preview_surface_bound_mesh_stage() -> tuple[Usd.Stage, str]: + """In-memory stage with ``/World/Mesh`` bound to ``UsdPreviewSurface``.""" + stage = Usd.Stage.CreateInMemory() + + mat = UsdShade.Material.Define(stage, "/World/Mat") + shader = UsdShade.Shader.Define(stage, "/World/Mat/PreviewSurface") + assert mat.GetPrim().IsValid() and shader.GetPrim().IsValid() + shader.CreateIdAttr("UsdPreviewSurface") + shader.CreateInput("diffuseColor", Sdf.ValueTypeNames.Color3f).Set(Gf.Vec3f(1.0, 0.0, 0.0)) + mat.CreateSurfaceOutput().ConnectToSource(shader.ConnectableAPI(), "surface") + _define_mesh_and_bind_material(stage, "/World/Mesh", mat) + return stage, "/World/Mesh" + + +def _make_mesh_bound_to_omnipbr_test_material( + diffuse_color_constant: tuple[float, float, float] | None, + diffuse_tint: tuple[float, float, float] | None, +) -> tuple[Usd.Stage, UsdShade.Shader, str]: + """Reuse :func:`_make_omnipbr_test_shader`, author inputs, add ``/World/Mesh`` bound to ``/World/Mat``.""" + stage = Usd.Stage.CreateInMemory() + + shader = _make_omnipbr_test_shader(stage, "/World/Mat") + if diffuse_color_constant is not None: + diffuse_inp = shader.CreateInput("diffuse_color_constant", Sdf.ValueTypeNames.Color3f) + diffuse_inp.Set(Gf.Vec3f(*diffuse_color_constant)) + if diffuse_tint is not None: + tint_inp = shader.CreateInput("diffuse_tint", Sdf.ValueTypeNames.Color3f) + tint_inp.Set(Gf.Vec3f(*diffuse_tint)) + + mat_prim = stage.GetPrimAtPath("/World/Mat") + assert mat_prim.IsValid() + mat = UsdShade.Material(mat_prim) + _define_mesh_and_bind_material(stage, "/World/Mesh", mat) + return stage, shader, "/World/Mesh" + + +def _reference_linear_to_srgb(rgb: tuple[float, float, float]) -> tuple[float, float, float]: + """Host sRGB OETF for linear ``rgb``. + + Args: + rgb: Linear RGB triple; channels may lie outside ``[0, 1]``. + + Returns: + Encoded RGB in ``[0, 1]`` as three floats. + """ + + def linear_to_srgb(c: float) -> float: + if c <= 0.0: + return 0.0 + if c >= 1.0: + return 1.0 + if c <= 0.0031308: + return 12.92 * c + return 1.055 * (c ** (1.0 / 2.4)) - 0.055 + + r, g, b = rgb + return (linear_to_srgb(r), linear_to_srgb(g), linear_to_srgb(b)) + + +def _run_scatter_shape_color_rows_kernel( + linear_colors: list[tuple[float, float, float]], + device: str, +) -> torch.Tensor: + """Launch :func:`_scatter_shape_color_rows_kernel` on ``device``.""" + num_colors = len(linear_colors) + row_indices = list(range(num_colors)) + + shape_colors = wp.zeros(num_colors, dtype=wp.vec3, device=device) + idx_wp = wp.array(row_indices, dtype=wp.int32, device=device) + colors_np = np.asarray(linear_colors, dtype=np.float32).reshape(num_colors, 3) + row_colors = wp.from_numpy(colors_np, dtype=wp.vec3, device=device) + wp.launch( + _scatter_shape_color_rows_kernel, + dim=num_colors, + inputs=[shape_colors, idx_wp, row_colors], + device=device, + ) + return wp.to_torch(shape_colors) + + +@pytest.mark.parametrize( + "linear_rgb", + [ + pytest.param((0.002, 0.0, 0.21404114048), id="low_linear_zero_pow"), + pytest.param((-0.25, 1.75, 0.5), id="oob_clamps_pow"), + ], +) +@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) +def test_scatter_shape_color_rows_kernel(device: str, linear_rgb: tuple[float, float, float]): + """Packed RGB per case; the two parametrized cases jointly cover every ``_linear_channel_to_srgb_warp`` branch.""" + after = _run_scatter_shape_color_rows_kernel([linear_rgb], device=device) + exp = _reference_linear_to_srgb(linear_rgb) + for ch in range(3): + assert after[0, ch].item() == pytest.approx(exp[ch], rel=1e-5) + + +@pytest.mark.parametrize(("diffuse_color_constant", "diffuse_tint"), _OMNIPBR_ALBEDO_INPUT_CASES) +def test_get_omnipbr_albedo( + diffuse_color_constant: tuple[float, float, float] | None, + diffuse_tint: tuple[float, float, float] | None, +): + """``_get_omnipbr_albedo`` is diffuse × tint per channel; ``None`` means that shader input is not authored. + + Unauthored inputs use ``_OMNIPBR_DEFAULTS`` in ``newton_model_utils``. + """ + stage = Usd.Stage.CreateInMemory() + + shader = _make_omnipbr_test_shader(stage, "/World/Mat") + if diffuse_color_constant is not None: + diffuse_inp = shader.CreateInput("diffuse_color_constant", Sdf.ValueTypeNames.Color3f) + diffuse_inp.Set(Gf.Vec3f(*diffuse_color_constant)) + if diffuse_tint is not None: + tint_inp = shader.CreateInput("diffuse_tint", Sdf.ValueTypeNames.Color3f) + tint_inp.Set(Gf.Vec3f(*diffuse_tint)) + + expected_albedo = _expected_omnipbr_linear_albedo(diffuse_color_constant, diffuse_tint) + + shader_prim = shader.GetPrim() + assert shader_prim.IsValid() + assert _get_omnipbr_albedo(shader_prim) == pytest.approx(expected_albedo, rel=1e-5) + + +def test_resolve_shape_color_invalid_prim(): + """Invalid prim path yields ``None`` (no replacement).""" + stage = Usd.Stage.CreateInMemory() + assert _resolve_shape_color(stage, "/World/Missing", {}) is None + + +def test_resolve_shape_color_guide_purpose(): + """Guide-purpose geometry is left on Newton's palette (no resolved replacement).""" + stage = Usd.Stage.CreateInMemory() + + mesh = UsdGeom.Mesh.Define(stage, "/World/GuideMesh") + assert mesh.GetPrim().IsValid() + purpose_attr = UsdGeom.Imageable(mesh).GetPurposeAttr() + assert purpose_attr.IsValid() + purpose_attr.Set(UsdGeom.Tokens.guide) + + assert _resolve_shape_color(stage, "/World/GuideMesh", {}) is None + + +def test_resolve_shape_color_no_material_binding(): + """Unbound mesh without ``displayColor``: neutral linear gray fallback.""" + stage = Usd.Stage.CreateInMemory() + + mesh = UsdGeom.Mesh.Define(stage, "/World/Mesh") + assert mesh.GetPrim().IsValid() + + # Default fallback gray should be returned when there is no material binding and no display color. + material_color_cache: dict[str, tuple[float, float, float] | None] = {} + out = _resolve_shape_color(stage, "/World/Mesh", material_color_cache) + assert out == pytest.approx(_UNBOUND_DEFAULT_FALLBACK_GRAY, rel=1e-5) + + # Add display color primvar + pv = UsdGeom.PrimvarsAPI(mesh).CreatePrimvar( + "displayColor", Sdf.ValueTypeNames.Color3fArray, UsdGeom.Tokens.constant, 1 + ) + + # Set an arbitrary color. + display_color = (0.11, 0.55, 0.9) + pv.Set([Gf.Vec3f(*display_color)]) + + # The display color should be returned instead of the fallback gray. + out = _resolve_shape_color(stage, "/World/Mesh", material_color_cache) + assert out == pytest.approx(display_color, rel=1e-5) + + +@pytest.mark.parametrize(("diffuse_color_constant", "diffuse_tint"), _OMNIPBR_ALBEDO_INPUT_CASES) +def test_resolve_shape_color_omnipbr_binding( + diffuse_color_constant: tuple[float, float, float] | None, + diffuse_tint: tuple[float, float, float] | None, +): + """Bound OmniPBR mesh: :func:`_resolve_shape_color` matches diffuse × tint.""" + stage, _shader, mesh_path = _make_mesh_bound_to_omnipbr_test_material(diffuse_color_constant, diffuse_tint) + expected_albedo = _expected_omnipbr_linear_albedo(diffuse_color_constant, diffuse_tint) + + out = _resolve_shape_color(stage, mesh_path, {}) + assert out == pytest.approx(expected_albedo, rel=1e-5) + + +def test_resolve_shape_color_neutral_material_binding(): + """Bound ``UsdPreviewSurface`` material: not OmniPBR, so resolution is ``None`` (Newton row unchanged).""" + stage, mesh_path = _make_preview_surface_bound_mesh_stage() + assert _resolve_shape_color(stage, mesh_path, {}) is None + + +def test_replace_newton_shape_colors_warning(): + """A :exc:`FutureWarning` is expected by default.""" + model = SimpleNamespace(shape_label=None, shape_color=None) + + with pytest.warns(FutureWarning, match=_WARNING_MESSAGE): + replace_newton_shape_colors(model) + + +@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) +def test_replace_newton_shape_colors_env_var_switch(monkeypatch: pytest.MonkeyPatch, device: str): + """Setting ``ISAACLAB_REPLACE_NEWTON_SHAPE_COLORS`` to ``0`` disables the workaround.""" + monkeypatch.setenv("ISAACLAB_REPLACE_NEWTON_SHAPE_COLORS", "0") + + # Set up a stage that has a prim with display color primvar and no material binding. If the workaround was enabled, + # the prim's color in the model would be synced with the display color primvar. + stage = Usd.Stage.CreateInMemory() + mesh = UsdGeom.Mesh.Define(stage, "/World/A") + assert mesh.GetPrim().IsValid() + pv = UsdGeom.PrimvarsAPI(mesh).CreatePrimvar( + "displayColor", Sdf.ValueTypeNames.Color3fArray, UsdGeom.Tokens.constant, 1 + ) + pv.Set([Gf.Vec3f(0.2, 0.4, 0.6)]) + + shape_color = wp.zeros(1, dtype=wp.vec3, device=device) + before = wp.to_torch(shape_color).clone() + model = SimpleNamespace(shape_label=["/World/A"], shape_color=shape_color) + + # The workaround is disabled, so the shape color is expected to be unchanged + with warnings.catch_warnings(record=True) as recorded: + warnings.simplefilter("always") + num_colors_updated = replace_newton_shape_colors(model, stage) + + assert num_colors_updated == 0 + assert torch.allclose(wp.to_torch(shape_color), before) + + # No FutureWarning is expected + assert not any(issubclass(w.category, FutureWarning) for w in recorded) + + +@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) +def test_replace_newton_shape_colors_invalid_prim(device: str): + """Invalid prim path leaves ``shape_color`` unchanged.""" + stage = Usd.Stage.CreateInMemory() + + shape_color = wp.array([(0.1, 0.2, 0.3)], dtype=wp.vec3, device=device) + before = wp.to_torch(shape_color).clone() + + model = SimpleNamespace(shape_label=["/World/Missing"], shape_color=shape_color) + + count = _replace_newton_shape_colors_wrapper(model, stage) + assert count == 0 + assert torch.allclose(wp.to_torch(shape_color), before) + + +@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) +def test_replace_newton_shape_colors_guide_purpose(device: str): + """Guide-purpose mesh leaves ``shape_color`` unchanged.""" + stage = Usd.Stage.CreateInMemory() + mesh = UsdGeom.Mesh.Define(stage, "/World/GuideMesh") + assert mesh.GetPrim().IsValid() + purpose_attr = UsdGeom.Imageable(mesh).GetPurposeAttr() + assert purpose_attr.IsValid() + purpose_attr.Set(UsdGeom.Tokens.guide) + + shape_color = wp.array([(0.1, 0.2, 0.3)], dtype=wp.vec3, device=device) + before = wp.to_torch(shape_color).clone() + model = SimpleNamespace(shape_label=["/World/GuideMesh"], shape_color=shape_color) + + count = _replace_newton_shape_colors_wrapper(model, stage) + assert count == 0 + assert torch.allclose(wp.to_torch(shape_color), before) + + +@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) +def test_replace_newton_shape_colors_no_material_binding(device: str): + """No material: ``displayColor`` or unbound gray as linear RGB, then sRGB OETF into ``shape_color``.""" + stage = Usd.Stage.CreateInMemory() + + # Mesh A has a display color primvar. + mesh_a = UsdGeom.Mesh.Define(stage, "/World/A") + pv = UsdGeom.PrimvarsAPI(mesh_a).CreatePrimvar( + "displayColor", Sdf.ValueTypeNames.Color3fArray, UsdGeom.Tokens.constant, 1 + ) + color_a = (0.1, 0.2, 0.3) + pv.Set([Gf.Vec3f(*color_a)]) + + # Mesh B has no material binding and no display color primvar. + UsdGeom.Mesh.Define(stage, "/World/B") + + shape_labels = ["/World/A", "/World/B"] + num_shapes = len(shape_labels) + shape_colors = wp.zeros(num_shapes, dtype=wp.vec3, device=device) + model = SimpleNamespace(shape_label=shape_labels, shape_color=shape_colors) + + num_colors_updated = _replace_newton_shape_colors_wrapper(model, stage) + assert num_colors_updated == 2 + + after = wp.to_torch(shape_colors) + exp_a = _reference_linear_to_srgb(color_a) + exp_b = _reference_linear_to_srgb(_UNBOUND_DEFAULT_FALLBACK_GRAY) + expected = torch.tensor([exp_a, exp_b], dtype=after.dtype, device=after.device) + torch.testing.assert_close(after, expected, rtol=1e-5, atol=1e-5) + + +@pytest.mark.parametrize(("diffuse_color_constant", "diffuse_tint"), _OMNIPBR_ALBEDO_INPUT_CASES) +@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) +def test_replace_newton_shape_colors_omnipbr_binding( + device: str, + diffuse_color_constant: tuple[float, float, float] | None, + diffuse_tint: tuple[float, float, float] | None, +): + """Bound OmniPBR: diffuse × tint then sRGB OETF.""" + stage, _shader, mesh_path = _make_mesh_bound_to_omnipbr_test_material(diffuse_color_constant, diffuse_tint) + + shape_color = wp.zeros(1, dtype=wp.vec3, device=device) + model = SimpleNamespace(shape_label=[mesh_path], shape_color=shape_color) + + assert _replace_newton_shape_colors_wrapper(model, stage) == 1 + + exp = _reference_linear_to_srgb(_expected_omnipbr_linear_albedo(diffuse_color_constant, diffuse_tint)) + after = wp.to_torch(shape_color)[0] + torch.testing.assert_close( + after, + torch.tensor(exp, dtype=after.dtype, device=after.device), + rtol=1e-5, + atol=1e-5, + ) + + +@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) +def test_replace_newton_shape_colors_neutral_material(device: str): + """Bound ``UsdPreviewSurface`` material leaves ``shape_color`` unchanged.""" + stage, mesh_path = _make_preview_surface_bound_mesh_stage() + + shape_color = wp.array([(0.1, 0.2, 0.3)], dtype=wp.vec3, device=device) + before = wp.to_torch(shape_color).clone() + model = SimpleNamespace(shape_label=[mesh_path], shape_color=shape_color) + + assert _replace_newton_shape_colors_wrapper(model, stage) == 0 + assert torch.allclose(wp.to_torch(shape_color), before) + + +@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) +def test_replace_newton_shape_colors_respects_binding_strength(device: str): + """Parent stronger-than-descendants binding overrides direct child binding.""" + # Scene graph (``ComputeBoundMaterial`` on the mesh yields ParentMat / green, not ChildMat / red): + # + # /World + # +-- Parent ........................ [bind: GreenMat, strongerThanDescendants] + # | \-- Mesh .................... [bind: RedMat] + # +-- GreenMat ...................... OmniPBRShader .. diffuse (0, 1, 0) + # +-- RedMat ........................ OmniPBRShader .. diffuse (1, 0, 0) + # + stage = Usd.Stage.CreateInMemory() + + parent = UsdGeom.Xform.Define(stage, "/World/Parent") + mesh = UsdGeom.Mesh.Define(stage, "/World/Parent/Mesh") + assert parent.GetPrim().IsValid() and mesh.GetPrim().IsValid() + + # Parent material is green + green_shader = _make_omnipbr_test_shader(stage, "/World/GreenMat") + green_shader.CreateInput("diffuse_color_constant", Sdf.ValueTypeNames.Color3f).Set(Gf.Vec3f(0.0, 1.0, 0.0)) + + # Child material is red + red_shader = _make_omnipbr_test_shader(stage, "/World/RedMat") + red_shader.CreateInput("diffuse_color_constant", Sdf.ValueTypeNames.Color3f).Set(Gf.Vec3f(1.0, 0.0, 0.0)) + + # Bind GreenMat to Parent + parent_prim = parent.GetPrim() + parent_mat = UsdShade.Material(stage.GetPrimAtPath("/World/GreenMat")) + UsdShade.MaterialBindingAPI.Apply(parent_prim) + UsdShade.MaterialBindingAPI(parent_prim).Bind(parent_mat, bindingStrength=UsdShade.Tokens.strongerThanDescendants) + + # Bind RedMat to Mesh + mesh_prim = mesh.GetPrim() + child_mat = UsdShade.Material(stage.GetPrimAtPath("/World/RedMat")) + UsdShade.MaterialBindingAPI.Apply(mesh_prim) + UsdShade.MaterialBindingAPI(mesh_prim).Bind(child_mat) + + shape_color = wp.zeros(1, dtype=wp.vec3, device=device) + model = SimpleNamespace(shape_label=["/World/Parent/Mesh"], shape_color=shape_color) + assert _replace_newton_shape_colors_wrapper(model, stage) == 1 + + # Expected color is green which is inherited from the parent xform prim + exp = (0.0, 1.0, 0.0) + after = wp.to_torch(shape_color)[0] + torch.testing.assert_close( + after, + torch.tensor(exp, dtype=after.dtype, device=after.device), + rtol=1e-5, + atol=1e-5, + ) + + +@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) +def test_replace_newton_shape_colors_instanced(device: str): + """Instance-proxy labels deduplicate via canonical prototype paths in the per-key cache.""" + stage = Usd.Stage.CreateInMemory() + + prototype = UsdGeom.Xform.Define(stage, "/World/Prototype") + assert prototype.GetPrim().IsValid() + mesh = UsdGeom.Mesh.Define(stage, "/World/Prototype/Mesh") + assert mesh.GetPrim().IsValid() + UsdGeom.PrimvarsAPI(mesh).CreatePrimvar( + "displayColor", Sdf.ValueTypeNames.Color3fArray, UsdGeom.Tokens.constant, 1 + ).Set([Gf.Vec3f(0.1, 0.2, 0.3)]) + + # Create an instance from the prototype + env_0 = stage.DefinePrim("/World/envs/env_0", "Xform") + env_0.GetReferences().AddInternalReference("/World/Prototype") + env_0.SetInstanceable(True) + + # Create another instance from the prototype + env_1 = stage.DefinePrim("/World/envs/env_1", "Xform") + env_1.GetReferences().AddInternalReference("/World/Prototype") + env_1.SetInstanceable(True) + + proxy_paths = [ + "/World/envs/env_0/Mesh", + "/World/envs/env_1/Mesh", + ] + for proxy_path in proxy_paths: + inst_proxy = stage.GetPrimAtPath(proxy_path) + assert inst_proxy.IsValid(), f"Proxy path {proxy_path} is not valid" + assert inst_proxy.IsInstanceProxy(), f"Proxy path {proxy_path} is not an instance proxy" + + # Create the dummy model + shape_color = wp.zeros(2, dtype=wp.vec3, device=device) + model = SimpleNamespace( + shape_label=proxy_paths, + shape_color=shape_color, + ) + assert _replace_newton_shape_colors_wrapper(model, stage) == 2 + + after = wp.to_torch(shape_color) + exp = _reference_linear_to_srgb((0.1, 0.2, 0.3)) + expected = torch.tensor([exp, exp], dtype=after.dtype, device=after.device) + torch.testing.assert_close(after, expected, rtol=1e-5, atol=1e-5) diff --git a/source/isaaclab/test/sim/test_physx_scene_data_provider_visualizer_contract.py b/source/isaaclab/test/sim/test_physx_scene_data_provider_visualizer_contract.py index 4f76671f89cc..979d66cc4a7e 100644 --- a/source/isaaclab/test/sim/test_physx_scene_data_provider_visualizer_contract.py +++ b/source/isaaclab/test/sim/test_physx_scene_data_provider_visualizer_contract.py @@ -7,119 +7,215 @@ from __future__ import annotations +import sys from types import SimpleNamespace +import pytest +import torch from isaaclab_physx.scene_data_providers import PhysxSceneDataProvider -from isaaclab.physics.scene_data_requirements import VisualizerPrebuiltArtifacts +from isaaclab.cloner import ClonePlan +PROVIDER_MOD = "isaaclab_physx.scene_data_providers.physx_scene_data_provider" -def _make_provider(): - provider = object.__new__(PhysxSceneDataProvider) - provider._force_usd_fallback_for_newton_model_build = False - return provider +def _silent_stage() -> SimpleNamespace: + """Stage stub whose ``GetPrimAtPath`` returns an invalid prim — env xforms read as zero.""" + return SimpleNamespace(GetPrimAtPath=lambda path: SimpleNamespace(IsValid=lambda: False)) -def test_get_newton_model_for_env_ids_builds_and_caches_sorted_keys(): - provider = _make_provider() - provider._needs_newton_sync = True - provider._newton_model = "full-model" - provider._filtered_newton_model = None - provider._filtered_env_ids_key = None - build_calls = [] +@pytest.fixture +def stub_provider(): + """Bare :class:`PhysxSceneDataProvider` with all buffer attrs initialized to defaults. - def _fake_build(env_ids): - build_calls.append(env_ids) - provider._filtered_newton_model = f"filtered-{env_ids}" + Tests assign ``_simulation_context`` and ``_stage`` themselves; everything else is the + pre-build state the build path expects. + """ + p = object.__new__(PhysxSceneDataProvider) + p._device = "cpu" + p._xform_views = {} + p._view_body_index_map = {} + p._view_order_tensors = {} + p._pose_buf_num_bodies = 0 + p._positions_buf = None + p._orientations_buf = None + p._covered_buf = None + p._xform_mask_buf = None + return p - provider._build_filtered_newton_model = _fake_build - # None asks for the full model. - assert provider.get_newton_model_for_env_ids(None) == "full-model" +@pytest.fixture +def newton_stub(monkeypatch): + """Stub the ``isaaclab_newton`` newton-prebuild module and the side-effect helpers. - # First subset request builds using sorted env id key. - model_a = provider.get_newton_model_for_env_ids([3, 1]) - assert model_a == "filtered-[1, 3]" - assert build_calls == [[1, 3]] + Returned :class:`SimpleNamespace` exposes: - # Equivalent request should use cache and not rebuild. - model_b = provider.get_newton_model_for_env_ids([1, 3]) - assert model_b == "filtered-[1, 3]" - assert build_calls == [[1, 3]] - - # Different subset rebuilds. - model_c = provider.get_newton_model_for_env_ids([2]) - assert model_c == "filtered-[2]" - assert build_calls == [[1, 3], [2]] + * ``calls`` — list of kwargs from each prebuild invocation, + * ``model`` / ``state_obj`` — what prebuild returns; tests can override before invoking. + """ + state = SimpleNamespace( + calls=[], + model=SimpleNamespace(body_label=[], articulation_label=[]), + state_obj=object(), + ) + def _prebuild(**kwargs): + state.calls.append(dict(kwargs)) + return state.model, state.state_obj -def test_try_use_prebuilt_artifact_populates_provider_state(): - """Provider should consume scene-time prebuilt artifact as fast path.""" - provider = _make_provider() - artifact = VisualizerPrebuiltArtifacts( - model="prebuilt-model", - state="prebuilt-state", - rigid_body_paths=["/World/envs/env_0/A"], - articulation_paths=["/World/envs/env_0/Robot"], - num_envs=4, + monkeypatch.setitem( + sys.modules, "isaaclab_newton.cloner.newton_replicate", SimpleNamespace(newton_visualizer_prebuild=_prebuild) ) - provider._simulation_context = SimpleNamespace(get_scene_data_visualizer_prebuilt_artifact=lambda: artifact) - - provider._xform_views = {"old": object()} - provider._view_body_index_map = {"old": [1]} - provider._view_order_tensors = {"old": object()} - provider._pose_buf_num_bodies = 7 - provider._positions_buf = object() - provider._orientations_buf = object() - provider._covered_buf = object() - provider._xform_mask_buf = object() - provider._env_id_to_body_indices = {0: [0]} - provider._filtered_newton_model = "old-filtered-model" - provider._filtered_newton_state = "old-filtered-state" - provider._filtered_env_ids_key = (0,) - provider._filtered_body_indices = [0] - - assert provider._try_use_prebuilt_newton_artifact() is True - assert provider._newton_model == "prebuilt-model" - assert provider._newton_state == "prebuilt-state" - assert provider._rigid_body_paths == ["/World/envs/env_0/A"] - assert provider._rigid_body_view_paths == ["/World/envs/env_0/A", "/World/envs/env_0/Robot"] - assert provider._num_envs_at_last_newton_build == 4 - assert provider._xform_views == {} - assert provider._view_body_index_map == {} - assert provider._view_order_tensors == {} - assert provider._pose_buf_num_bodies == 0 - assert provider._positions_buf is None - assert provider._orientations_buf is None - assert provider._covered_buf is None - assert provider._xform_mask_buf is None - assert provider._env_id_to_body_indices == {} - assert provider._filtered_newton_model is None - assert provider._filtered_newton_state is None - assert provider._filtered_env_ids_key is None - assert provider._filtered_body_indices == [] - - -def test_try_use_prebuilt_artifact_respects_force_usd_fallback_flag(): - """Force flag should disable prebuilt fast path even when artifact is available.""" - provider = _make_provider() - provider._force_usd_fallback_for_newton_model_build = True - artifact = VisualizerPrebuiltArtifacts( - model="prebuilt-model", - state="prebuilt-state", - rigid_body_paths=["/World/envs/env_0/A"], - articulation_paths=["/World/envs/env_0/Robot"], - num_envs=4, - ) - provider._simulation_context = SimpleNamespace(get_scene_data_visualizer_prebuilt_artifact=lambda: artifact) + monkeypatch.setattr(f"{PROVIDER_MOD}.UsdGeom.GetStageUpAxis", lambda stage: "Z") + monkeypatch.setattr(f"{PROVIDER_MOD}.replace_newton_shape_colors", lambda m, s: None) + return state + - assert provider._try_use_prebuilt_newton_artifact() is False +def test_get_newton_model_returns_model_when_sync_enabled(stub_provider): + """Callers receive the full Newton model from :meth:`get_newton_model`.""" + stub_provider._needs_newton_sync = True + stub_provider._newton_model = "full-model" + assert stub_provider.get_newton_model() == "full-model" -def test_build_newton_model_from_usd_short_circuits_when_prebuilt_available(): - """If prebuilt artifact is available, USD fallback should not run.""" - provider = _make_provider() - provider._try_use_prebuilt_newton_artifact = lambda: True - provider._build_newton_model_from_usd() - assert provider._last_newton_model_build_source == "prebuilt" +def test_build_from_clone_plans_populates_provider_state(stub_provider, newton_stub): + """Building from per-group clone plans sets model, state, and rigid-body paths. + + Asserts the provider derives its own (sources, destinations, mask) from the plans + without consulting any auxiliary spec object: representative source paths are recovered + from ``dest_template.format()``, masks are concatenated + along the prototype axis, and per-env positions are read from stage xforms. + """ + newton_stub.model = SimpleNamespace( + body_label=["/World/envs/env_0/Object/A"], + articulation_label=["/World/envs/env_0/Robot"], + ) + plans = { + "/World/envs/env_{}/Object": ClonePlan( + dest_template="/World/envs/env_{}/Object", + prototype_paths=["/World/template/Object/proto_0", "/World/template/Object/proto_1"], + # proto 0 → env 0, 2 ; proto 1 → env 1, 3 + clone_mask=torch.tensor([[True, False, True, False], [False, True, False, True]], dtype=torch.bool), + ), + "/World/envs/env_{}/Robot": ClonePlan( + dest_template="/World/envs/env_{}/Robot", + prototype_paths=["/World/template/Robot/proto_0"], + clone_mask=torch.ones((1, 4), dtype=torch.bool), + ), + } + stub_provider._simulation_context = SimpleNamespace(get_clone_plans=lambda: plans) + stub_provider._stage = _silent_stage() + + stub_provider._build_newton_model_from_clone_plans() + + assert stub_provider._newton_model is newton_stub.model + assert stub_provider._newton_state is newton_stub.state_obj + assert stub_provider._rigid_body_paths == newton_stub.model.body_label + assert stub_provider._rigid_body_view_paths == newton_stub.model.body_label + newton_stub.model.articulation_label + assert stub_provider._num_envs_at_last_newton_build == 4 + assert stub_provider._last_newton_model_build_source == "built" + + kw = newton_stub.calls[-1] + # Source recovery picks the first-env user per prototype. + assert kw["sources"] == [ + "/World/envs/env_0/Object", + "/World/envs/env_1/Object", + "/World/envs/env_0/Robot", + ] + assert kw["destinations"] == ["/World/envs/env_{}/Object", "/World/envs/env_{}/Object", "/World/envs/env_{}/Robot"] + assert kw["mapping"].shape == (3, 4) + assert kw["positions"].shape == (4, 3) + + +def test_build_from_clone_plans_missing_sets_error_state(stub_provider): + """When no clone plans are published, model/state stay unset.""" + stub_provider._simulation_context = SimpleNamespace(get_clone_plans=lambda: {}) + stub_provider._stage = object() + + stub_provider._build_newton_model_from_clone_plans() + + assert stub_provider._last_newton_model_build_source == "missing" + assert stub_provider._newton_model is None + assert stub_provider._newton_state is None + + +def test_build_from_clone_plans_skips_unused_prototype_rows(stub_provider, newton_stub): + """A prototype row with no assigned env (all-False mask row) is dropped, not raised on. + + When ``num_prototypes > num_envs`` under a sequential strategy (or any strategy that + leaves some prototypes unused), ``clone_mask[row].nonzero()[0]`` would otherwise raise + ``IndexError``. The provider must filter unused rows out of sources/destinations/mask. + """ + # 3 prototypes, 2 envs, sequential: env 0 → proto 0, env 1 → proto 1, proto 2 unused. + plans = { + "/World/envs/env_{}/Object": ClonePlan( + dest_template="/World/envs/env_{}/Object", + prototype_paths=[ + "/World/template/Object/proto_0", + "/World/template/Object/proto_1", + "/World/template/Object/proto_2", + ], + clone_mask=torch.tensor([[True, False], [False, True], [False, False]], dtype=torch.bool), + ) + } + stub_provider._simulation_context = SimpleNamespace(get_clone_plans=lambda: plans) + stub_provider._stage = _silent_stage() + + stub_provider._build_newton_model_from_clone_plans() + + assert stub_provider._last_newton_model_build_source == "built" + kw = newton_stub.calls[-1] + # Unused proto_2 row dropped; only the two assigned prototypes survive. + assert kw["sources"] == ["/World/envs/env_0/Object", "/World/envs/env_1/Object"] + assert kw["mapping"].shape == (2, 2) + + +def test_build_from_clone_plans_uses_dest_template_for_env_lookup(stub_provider, newton_stub): + """Env-origin lookup uses the per-plan ``dest_template`` prefix, not a hardcoded path. + + A scene with a non-default env path (``/Stage/scenes/env_``) should still have its + xform translates read correctly. Replaces the prior hardcoded ``/World/envs/env_``. + """ + visited: list[str] = [] + + def _get_prim(path): + visited.append(path) + return SimpleNamespace(IsValid=lambda: False) + + plans = { + "/Stage/scenes/env_{}/Object": ClonePlan( + dest_template="/Stage/scenes/env_{}/Object", + prototype_paths=["/Stage/template/Object/proto_0"], + clone_mask=torch.ones((1, 3), dtype=torch.bool), + ) + } + stub_provider._simulation_context = SimpleNamespace(get_clone_plans=lambda: plans) + stub_provider._stage = SimpleNamespace(GetPrimAtPath=_get_prim) + + stub_provider._build_newton_model_from_clone_plans() + + assert {f"/Stage/scenes/env_{i}" for i in range(3)} <= set(visited) + assert not any(p.startswith("/World/envs/") for p in visited) + + +def test_clone_plan_is_hashable_with_unhashable_fields(): + """``ClonePlan`` must hash despite carrying a tensor and a list. + + With ``field(hash=False)`` on the unhashable members, hashing operates on + ``dest_template`` only — the natural identity (it is the dict key in + :meth:`SimulationContext.get_clone_plans`). + """ + plan_a = ClonePlan( + dest_template="/World/envs/env_{}/Object", + prototype_paths=["/World/template/Object/proto_0"], + clone_mask=torch.ones((1, 4), dtype=torch.bool), + ) + plan_b = ClonePlan( + dest_template="/World/envs/env_{}/Object", + prototype_paths=["/World/template/Object/proto_99"], + clone_mask=torch.zeros((1, 4), dtype=torch.bool), + ) + assert isinstance(hash(plan_a), int) + # Equality folds in only dest_template, so two plans with the same destination compare + # equal regardless of prototype/mask differences. + assert plan_a == plan_b diff --git a/source/isaaclab/test/sim/test_schemas.py b/source/isaaclab/test/sim/test_schemas.py index f5628d842655..1acda3b149c6 100644 --- a/source/isaaclab/test/sim/test_schemas.py +++ b/source/isaaclab/test/sim/test_schemas.py @@ -424,7 +424,7 @@ def _validate_joint_drive_properties_on_prim(prim_path: str, joint_cfg, verbose: # iterate over the joint properties for attr_name, attr_value in joint_cfg.__dict__.items(): # skip names we know are not present - if attr_name == "func": + if attr_name in ["func", "ensure_drives_exist"]: continue # resolve the drive (linear or angular) drive_model = "linear" if joint_prim.IsA(UsdPhysics.PrismaticJoint) else "angular" diff --git a/source/isaaclab/test/sim/test_simulation_context.py b/source/isaaclab/test/sim/test_simulation_context.py index c03413838e3e..6ea578a85e30 100644 --- a/source/isaaclab/test/sim/test_simulation_context.py +++ b/source/isaaclab/test/sim/test_simulation_context.py @@ -290,6 +290,86 @@ def test_render(): assert sim.is_playing() +@pytest.mark.isaacsim_ci +def test_render_pumps_app_update_without_visualizer(): + """Regression test for issue #5052: headless video must pump Kit when no visualizer does. + + Originally ``SimulationContext.render()`` called ``omni.kit.app.get_app().update()`` when + no visualizer had ``pumps_app_update()`` (see PR #5056). The same contract is now implemented + from :func:`~isaaclab.envs.utils.recording_hooks.run_recording_hooks_after_visualizers`, which calls + :func:`~isaaclab_physx.renderers.isaac_rtx_renderer_utils.pump_kit_app_for_headless_video_render_if_needed` + when ``/isaaclab/video/enabled`` is set (as with ``--video``), which in turn calls + ``ensure_isaac_rtx_render_update()`` (guarded by ``is_rendering`` and the no-pumping-visualizer check). + + Without this path, replicator render products used for ``rgb_array`` / RecordVideo stay stale (black frames). + """ + from unittest.mock import MagicMock, patch + + cfg = SimulationCfg(dt=0.01) + sim = SimulationContext(cfg) + sim.reset() + + sim.set_setting("/isaaclab/video/enabled", True) + sim.set_setting("/isaaclab/render/rtx_sensors", True) + + mock_app = MagicMock() + mock_app.is_running.return_value = True + + with ( + patch("isaaclab.utils.version.has_kit", return_value=True), + patch( + "isaaclab_physx.renderers.isaac_rtx_renderer_utils._get_stage_streaming_busy", + return_value=False, + ), + patch("omni.kit.app.get_app", return_value=mock_app), + ): + sim.render() + + mock_app.update.assert_called_once() + + +@pytest.mark.isaacsim_ci +def test_render_skips_app_update_when_visualizer_pumps_it(): + """Regression test: do not pump Kit in the headless-video path when a visualizer already does. + + A visualizer with ``pumps_app_update() == True`` (e.g. KitVisualizer) calls ``app.update()`` in + its own ``step()``. The recording-hook pump must then skip + ``ensure_isaac_rtx_render_update`` so we do not double-pump the Kit loop. + """ + from unittest.mock import MagicMock, patch + + from isaaclab.visualizers.base_visualizer import BaseVisualizer + + cfg = SimulationCfg(dt=0.01) + sim = SimulationContext(cfg) + sim.reset() + + sim.set_setting("/isaaclab/video/enabled", True) + sim.set_setting("/isaaclab/render/rtx_sensors", True) + + mock_viz = MagicMock(spec=BaseVisualizer) + mock_viz.pumps_app_update.return_value = True + mock_viz.is_closed = False + mock_viz.is_running.return_value = True + mock_viz.is_rendering_paused.return_value = False + mock_viz.is_training_paused.return_value = False + mock_viz.get_rendering_dt.return_value = None + sim._visualizers = [mock_viz] + + mock_app = MagicMock() + mock_app.is_running.return_value = True + + with ( + patch("isaaclab.utils.version.has_kit", return_value=True), + patch("omni.kit.app.get_app", return_value=mock_app), + ): + sim.render() + + mock_app.update.assert_not_called() + + sim._visualizers = [] + + """ Stage Operations Tests """ diff --git a/source/isaaclab/test/sim/test_simulation_context_visualizers.py b/source/isaaclab/test/sim/test_simulation_context_visualizers.py index f0a1294d2b4a..1f86f32872c9 100644 --- a/source/isaaclab/test/sim/test_simulation_context_visualizers.py +++ b/source/isaaclab/test/sim/test_simulation_context_visualizers.py @@ -30,11 +30,13 @@ class _FakeProvider: def __init__(self): self.update_calls = [] - def update(self, env_ids=None): - self.update_calls.append(env_ids) + def update(self): + self.update_calls.append(True) class _FakeVisualizer: + """Minimal visualizer for orchestration tests.""" + def __init__( self, *, @@ -45,6 +47,7 @@ def __init__( training_paused_steps=0, raises_on_step=False, requires_forward=False, + pumps_app_update=False, ): self._env_ids = env_ids self._running = running @@ -53,6 +56,7 @@ def __init__( self._training_paused_steps = training_paused_steps self._raises_on_step = raises_on_step self._requires_forward = requires_forward + self._pumps_app_update = pumps_app_update self.step_calls = [] self.close_calls = 0 @@ -87,6 +91,9 @@ def get_visualized_env_ids(self): def requires_forward_before_step(self): return self._requires_forward + def pumps_app_update(self): + return self._pumps_app_update + def _make_context(visualizers, provider=None): ctx = object.__new__(SimulationContext) @@ -97,7 +104,7 @@ def _make_context(visualizers, provider=None): return ctx -def test_update_scene_data_provider_unions_env_ids_and_forwards(): +def test_update_scene_data_provider_forwards_and_updates_provider(): provider = _FakeProvider() viz_a = _FakeVisualizer(env_ids=[0, 2], requires_forward=True) viz_b = _FakeVisualizer(env_ids=[2, 3]) @@ -107,7 +114,7 @@ def test_update_scene_data_provider_unions_env_ids_and_forwards(): ctx.update_scene_data_provider() assert ctx.physics_manager.forward_calls == 1 - assert provider.update_calls == [[0, 2, 3]] + assert provider.update_calls == [True] assert ctx._visualizer_step_counter == 1 @@ -116,7 +123,7 @@ def test_update_scene_data_provider_force_forward_with_no_visualizers(): ctx = _make_context([], provider=provider) ctx.update_scene_data_provider(force_require_forward=True) assert ctx.physics_manager.forward_calls == 1 - assert provider.update_calls == [None] + assert provider.update_calls == [True] def test_update_visualizers_removes_closed_nonrunning_and_failed(caplog): @@ -136,10 +143,21 @@ def test_update_visualizers_removes_closed_nonrunning_and_failed(caplog): assert stopped_viz.close_calls == 1 assert failing_viz.close_calls == 1 assert paused_viz.close_calls == 0 + assert paused_viz.step_calls == [0.0] assert healthy_viz.step_calls == [0.1] assert any("Error stepping visualizer" in r.message for r in caplog.records) +def test_update_visualizers_skips_zero_dt_for_paused_app_pumping_visualizer(): + provider = _FakeProvider() + paused_app_pumping_viz = _FakeVisualizer(rendering_paused=True, pumps_app_update=True) + ctx = _make_context([paused_app_pumping_viz], provider=provider) + + ctx.update_visualizers(0.3) + + assert paused_app_pumping_viz.step_calls == [] + + def test_update_visualizers_handles_training_pause_loop(): provider = _FakeProvider() viz = _FakeVisualizer(training_paused_steps=1) @@ -161,9 +179,12 @@ def get_metadata(self) -> dict: def get_newton_model(self): return "dummy-model" - def get_newton_state(self, env_ids: list[int] | None): - self.state_calls.append(env_ids) - return {"state_call": len(self.state_calls), "env_ids": env_ids} + def get_newton_state(self): + self.state_calls.append(None) + return {"state_call": len(self.state_calls)} + + def get_camera_transforms(self): + return {} class _DummyViserViewer: @@ -203,20 +224,23 @@ def _fake_create_viewer(self, record_to_viser: str | None, metadata: dict | None assert visualizer._sim_time == pytest.approx(0.25) assert viewer.calls[0][0] == "begin_frame" assert viewer.calls[0][1] == pytest.approx(0.25) - assert viewer.calls[1] == ("log_state", {"state_call": 2, "env_ids": None}) + # log_state passes through get_newton_state() as-is; no env_ids (or other) keys are merged in. + assert viewer.calls[1] == ("log_state", {"state_call": 2}) assert viewer.calls[2] == ("end_frame",) @pytest.mark.parametrize( - ("cfg_max_worlds", "expected_max_worlds"), + ("cfg_max_visible_envs", "expected_visible"), [ (None, None), - (0, 0), - (3, 3), + (0, []), + (3, [0, 1, 2]), ], ) -def test_viser_visualizer_create_viewer_forwards_max_worlds( - monkeypatch: pytest.MonkeyPatch, cfg_max_worlds: int | None, expected_max_worlds: int | None +def test_viser_visualizer_create_viewer_applies_visible_worlds( + monkeypatch: pytest.MonkeyPatch, + cfg_max_visible_envs: int | None, + expected_visible: list[int] | None, ): captured = {} @@ -240,8 +264,11 @@ def __init__( "metadata": metadata, } - def set_model(self, model: Any, max_worlds: int | None) -> None: - captured["set_model"] = {"model": model, "max_worlds": max_worlds} + def set_model(self, model: Any) -> None: + captured["set_model"] = model + + def set_visible_worlds(self, worlds) -> None: + captured["visible_worlds"] = worlds def set_world_offsets(self, spacing) -> None: captured["set_world_offsets"] = tuple(spacing) @@ -254,25 +281,33 @@ def set_world_offsets(self, spacing) -> None: ) monkeypatch.setattr(viser_visualizer.ViserVisualizer, "_set_viser_camera_view", lambda self, pose: None) - cfg = ViserVisualizerCfg(max_worlds=cfg_max_worlds, open_browser=False) + cfg = ViserVisualizerCfg( + max_visible_envs=cfg_max_visible_envs, + open_browser=False, + randomly_sample_visible_envs=False, + ) visualizer = viser_visualizer.ViserVisualizer(cfg) visualizer._model = "dummy-model" + visualizer._env_ids = None # normally set by initialize() -> _compute_visualized_env_ids() visualizer._create_viewer(record_to_viser="record.viser", metadata={"num_envs": 8}) - assert captured["set_model"] == {"model": "dummy-model", "max_worlds": expected_max_worlds} + assert captured["set_model"] == "dummy-model" + assert captured["visible_worlds"] == expected_visible assert captured["set_world_offsets"] == (0.0, 0.0, 0.0) @pytest.mark.parametrize( - ("cfg_max_worlds", "expected_max_worlds"), + ("cfg_max_visible_envs", "expected_visible"), [ (None, None), - (0, 0), - (3, 3), + (0, []), + (3, [0, 1, 2]), ], ) -def test_rerun_visualizer_initialize_forwards_max_worlds_and_world_offsets( - monkeypatch: pytest.MonkeyPatch, cfg_max_worlds: int | None, expected_max_worlds: int | None +def test_rerun_visualizer_initialize_applies_visible_worlds_and_world_offsets( + monkeypatch: pytest.MonkeyPatch, + cfg_max_visible_envs: int | None, + expected_visible: list[int] | None, ): captured = {} @@ -300,8 +335,11 @@ def __init__( "record_to_rrd": record_to_rrd, } - def set_model(self, model: Any, max_worlds: int | None = None) -> None: - captured["set_model"] = {"model": model, "max_worlds": max_worlds} + def set_model(self, model: Any) -> None: + captured["set_model"] = model + + def set_visible_worlds(self, worlds) -> None: + captured["visible_worlds"] = worlds def set_world_offsets(self, spacing) -> None: captured["set_world_offsets"] = tuple(spacing) @@ -316,8 +354,11 @@ def get_metadata(self) -> dict: def get_newton_model(self): return "dummy-model" - def get_newton_state(self, env_ids: list[int] | None): - return {"env_ids": env_ids} + def get_newton_state(self): + return {"ok": True} + + def get_camera_transforms(self): + return {} monkeypatch.setattr(rerun_visualizer, "NewtonViewerRerun", _FakeNewtonViewerRerun) monkeypatch.setattr( @@ -331,11 +372,16 @@ def get_newton_state(self, env_ids: list[int] | None): ) monkeypatch.setattr(rerun_visualizer.RerunVisualizer, "_apply_camera_pose", lambda self, pose: None) - cfg = RerunVisualizerCfg(open_browser=False, max_worlds=cfg_max_worlds) + cfg = RerunVisualizerCfg( + open_browser=False, + max_visible_envs=cfg_max_visible_envs, + randomly_sample_visible_envs=False, + ) visualizer = rerun_visualizer.RerunVisualizer(cfg) visualizer.initialize(cast(Any, _DummyRerunSceneDataProvider())) - assert captured["set_model"] == {"model": "dummy-model", "max_worlds": expected_max_worlds} + assert captured["set_model"] == "dummy-model" + assert captured["visible_worlds"] == expected_visible assert captured["set_world_offsets"] == (0.0, 0.0, 0.0) @@ -398,10 +444,12 @@ def _make_context_with_settings( ctx._has_gui = has_gui ctx._has_offscreen_render = has_offscreen_render ctx._xr_enabled = False + ctx._pending_camera_view = None + ctx._render_generation = 0 ctx._visualizers = [] ctx._scene_data_provider = _FakeProvider() ctx._scene_data_requirements = None - ctx._visualizer_prebuilt_artifact = None + ctx._clone_plans = {} ctx._visualizer_step_counter = 0 ctx._viz_dt = 0.01 ctx.get_setting = lambda name: settings.get(name) @@ -438,7 +486,7 @@ def test_explicit_unknown_visualizer_type_raises(): "/isaaclab/visualizer/types": "bogus_viz", "/isaaclab/visualizer/explicit": True, "/isaaclab/visualizer/disable_all": False, - "/isaaclab/visualizer/max_worlds": None, + "/isaaclab/visualizer/max_visible_envs": None, } ctx = _make_context_with_settings(settings) @@ -452,7 +500,7 @@ def test_explicit_missing_package_raises(monkeypatch: pytest.MonkeyPatch): "/isaaclab/visualizer/types": "rerun", "/isaaclab/visualizer/explicit": True, "/isaaclab/visualizer/disable_all": False, - "/isaaclab/visualizer/max_worlds": None, + "/isaaclab/visualizer/max_visible_envs": None, } ctx = _make_context_with_settings(settings) @@ -479,7 +527,7 @@ def test_explicit_visualizer_create_failure_raises(monkeypatch: pytest.MonkeyPat "/isaaclab/visualizer/types": "newton", "/isaaclab/visualizer/explicit": True, "/isaaclab/visualizer/disable_all": False, - "/isaaclab/visualizer/max_worlds": None, + "/isaaclab/visualizer/max_visible_envs": None, } ctx = _make_context_with_settings(settings, visualizer_cfgs=[failing_cfg]) @@ -498,7 +546,7 @@ def test_explicit_visualizer_init_failure_raises(monkeypatch: pytest.MonkeyPatch "/isaaclab/visualizer/types": "newton", "/isaaclab/visualizer/explicit": True, "/isaaclab/visualizer/disable_all": False, - "/isaaclab/visualizer/max_worlds": None, + "/isaaclab/visualizer/max_visible_envs": None, } ctx = _make_context_with_settings(settings, visualizer_cfgs=[failing_cfg]) @@ -516,7 +564,7 @@ def test_explicit_partial_valid_types_raises_for_invalid(): "/isaaclab/visualizer/types": "newton,bogus_viz", "/isaaclab/visualizer/explicit": True, "/isaaclab/visualizer/disable_all": False, - "/isaaclab/visualizer/max_worlds": None, + "/isaaclab/visualizer/max_visible_envs": None, } ctx = _make_context_with_settings(settings) @@ -530,7 +578,7 @@ def test_non_explicit_unknown_type_silently_skipped(caplog): "/isaaclab/visualizer/types": "bogus_viz", "/isaaclab/visualizer/explicit": False, "/isaaclab/visualizer/disable_all": False, - "/isaaclab/visualizer/max_worlds": None, + "/isaaclab/visualizer/max_visible_envs": None, } ctx = _make_context_with_settings(settings) @@ -546,7 +594,7 @@ def test_non_explicit_create_failure_silently_logged(monkeypatch: pytest.MonkeyP "/isaaclab/visualizer/types": "", "/isaaclab/visualizer/explicit": False, "/isaaclab/visualizer/disable_all": False, - "/isaaclab/visualizer/max_worlds": None, + "/isaaclab/visualizer/max_visible_envs": None, } ctx = _make_context_with_settings(settings, visualizer_cfgs=[failing_cfg]) diff --git a/source/isaaclab/test/sim/test_simulation_stage_in_memory.py b/source/isaaclab/test/sim/test_simulation_stage_in_memory.py index ebe8158750fe..1add70c70989 100644 --- a/source/isaaclab/test/sim/test_simulation_stage_in_memory.py +++ b/source/isaaclab/test/sim/test_simulation_stage_in_memory.py @@ -17,13 +17,14 @@ import pytest +import torch import omni.physx import omni.usd import usdrt -from isaacsim.core.cloner import GridCloner import isaaclab.sim as sim_utils +from isaaclab import cloner from isaaclab.sim.simulation_context import SimulationCfg, SimulationContext from isaaclab.utils.assets import ISAACLAB_NUCLEUS_DIR from isaaclab.utils.version import get_isaac_sim_version @@ -194,23 +195,19 @@ def test_stage_in_memory_with_clone_in_fabric(sim): base_env_path = "/World/envs" source_prim_path = f"{base_env_path}/env_0" - # create cloner - cloner = GridCloner(spacing=3, stage=stage_in_memory) - cloner.define_base_env(base_env_path) + # create environment clones using Isaac Lab's cloner utilities + env_ids = torch.arange(num_clones, dtype=torch.long, device="cpu") + env_origins, _ = cloner.grid_transforms(num_clones, spacing=3.0, device="cpu") # create source prim + stage_in_memory.DefinePrim(source_prim_path, "Xform") sim_utils.create_prim(f"{source_prim_path}/Robot", "Xform", usd_path=usd_path) # generate target paths - target_paths = cloner.generate_paths("/World/envs/env", num_clones) + env_fmt = "/World/envs/env_{}" # clone robots at target paths - cloner.clone( - source_prim_path=source_prim_path, - base_env_path=base_env_path, - prim_paths=target_paths, - replicate_physics=True, - ) + cloner.usd_replicate(stage_in_memory, [env_fmt.format(0)], [env_fmt], env_ids, positions=env_origins) # verify prims exist in fabric stage using usdrt apis stage_id = sim_utils.get_current_stage_id() diff --git a/source/isaaclab/test/sim/test_spawn_lights.py b/source/isaaclab/test/sim/test_spawn_lights.py index 94add58bc11b..3a019c2f90b2 100644 --- a/source/isaaclab/test/sim/test_spawn_lights.py +++ b/source/isaaclab/test/sim/test_spawn_lights.py @@ -21,6 +21,8 @@ from isaaclab.sim import SimulationCfg, SimulationContext from isaaclab.utils.string import to_camel_case +pytestmark = pytest.mark.isaacsim_ci + @pytest.fixture(autouse=True) def sim(): diff --git a/source/isaaclab/test/sim/test_spawn_materials.py b/source/isaaclab/test/sim/test_spawn_materials.py index 5edf351e40da..7f517f2bc1f6 100644 --- a/source/isaaclab/test/sim/test_spawn_materials.py +++ b/source/isaaclab/test/sim/test_spawn_materials.py @@ -21,6 +21,8 @@ from isaaclab.sim import SimulationCfg, SimulationContext from isaaclab.utils.assets import NVIDIA_NUCLEUS_DIR +pytestmark = pytest.mark.isaacsim_ci + @pytest.fixture def sim(): @@ -98,31 +100,6 @@ def test_spawn_rigid_body_material(sim): assert prim.GetAttribute("physxMaterial:frictionCombineMode").Get() == cfg.friction_combine_mode -def test_spawn_deformable_body_material(sim): - """Test spawning a deformable body material.""" - cfg = sim_utils.DeformableBodyMaterialCfg( - density=1.0, - dynamic_friction=0.25, - youngs_modulus=50000000.0, - poissons_ratio=0.5, - elasticity_damping=0.005, - damping_scale=1.0, - ) - prim = cfg.func("/Looks/DeformableBodyMaterial", cfg) - # Check validity - assert prim.IsValid() - assert sim.stage.GetPrimAtPath("/Looks/DeformableBodyMaterial").IsValid() - # Check properties - assert prim.GetAttribute("physxDeformableBodyMaterial:density").Get() == cfg.density - assert prim.GetAttribute("physxDeformableBodyMaterial:dynamicFriction").Get() == cfg.dynamic_friction - assert prim.GetAttribute("physxDeformableBodyMaterial:youngsModulus").Get() == cfg.youngs_modulus - assert prim.GetAttribute("physxDeformableBodyMaterial:poissonsRatio").Get() == cfg.poissons_ratio - assert prim.GetAttribute("physxDeformableBodyMaterial:elasticityDamping").Get() == pytest.approx( - cfg.elasticity_damping - ) - assert prim.GetAttribute("physxDeformableBodyMaterial:dampingScale").Get() == cfg.damping_scale - - def test_apply_rigid_body_material_on_visual_material(sim): """Test applying a rigid body material on a visual material.""" cfg = sim_utils.GlassMdlCfg(thin_walled=False, glass_ior=1.0, glass_color=(0.0, 1.0, 0.0)) diff --git a/source/isaaclab/test/sim/test_spawn_meshes.py b/source/isaaclab/test/sim/test_spawn_meshes.py index 082049a59dec..7b4c4678ca54 100644 --- a/source/isaaclab/test/sim/test_spawn_meshes.py +++ b/source/isaaclab/test/sim/test_spawn_meshes.py @@ -18,6 +18,8 @@ import isaaclab.sim as sim_utils from isaaclab.sim import SimulationCfg, SimulationContext +pytestmark = pytest.mark.isaacsim_ci + @pytest.fixture def sim(): @@ -117,110 +119,25 @@ def test_spawn_sphere(sim): assert prim.GetPrimTypeInfo().GetTypeName() == "Mesh" -""" -Physics properties. -""" - - -def test_spawn_cone_with_deformable_props(sim): - """Test spawning of UsdGeomMesh prim for a cone with deformable body API.""" - # Spawn cone - cfg = sim_utils.MeshConeCfg( - radius=1.0, - height=2.0, - deformable_props=sim_utils.DeformableBodyPropertiesCfg(deformable_enabled=True), - ) - prim = cfg.func("/World/Cone", cfg) - - # Check validity - assert prim.IsValid() - assert sim.stage.GetPrimAtPath("/World/Cone").IsValid() - - # Check properties - # Unlike rigid body, deformable body properties are on the mesh prim - prim = sim.stage.GetPrimAtPath("/World/Cone/geometry/mesh") - assert prim.GetAttribute("physxDeformable:deformableEnabled").Get() == cfg.deformable_props.deformable_enabled - - -def test_spawn_cone_with_deformable_and_mass_props(sim): - """Test spawning of UsdGeomMesh prim for a cone with deformable body and mass API.""" - # Spawn cone - cfg = sim_utils.MeshConeCfg( - radius=1.0, - height=2.0, - deformable_props=sim_utils.DeformableBodyPropertiesCfg(deformable_enabled=True), - mass_props=sim_utils.MassPropertiesCfg(mass=1.0), - ) - prim = cfg.func("/World/Cone", cfg) +@pytest.mark.parametrize("resolution", [(1, 1), (3, 2)]) +def test_spawn_square(sim, resolution): + """Test spawning of UsdGeomMesh as a square prim.""" + # Spawn square + cfg = sim_utils.MeshSquareCfg(size=1.0, resolution=resolution) + prim = cfg.func("/World/Square", cfg) # Check validity assert prim.IsValid() - assert sim.stage.GetPrimAtPath("/World/Cone").IsValid() - # Check properties - prim = sim.stage.GetPrimAtPath("/World/Cone/geometry/mesh") - assert prim.GetAttribute("physics:mass").Get() == cfg.mass_props.mass - - # check sim playing - sim.play() - for _ in range(10): - sim.step() - - -def test_spawn_cone_with_deformable_and_density_props(sim): - """Test spawning of UsdGeomMesh prim for a cone with deformable body and mass API. - - Note: - In this case, we specify the density instead of the mass. In that case, physics need to know - the collision shape to compute the mass. Thus, we have to set the collider properties. In - order to not have a collision shape, we disable the collision. - """ - # Spawn cone - cfg = sim_utils.MeshConeCfg( - radius=1.0, - height=2.0, - deformable_props=sim_utils.DeformableBodyPropertiesCfg(deformable_enabled=True), - mass_props=sim_utils.MassPropertiesCfg(density=10.0), - ) - prim = cfg.func("/World/Cone", cfg) - - # Check validity - assert prim.IsValid() - assert sim.stage.GetPrimAtPath("/World/Cone").IsValid() + assert sim.stage.GetPrimAtPath("/World/Square").IsValid() + assert prim.GetPrimTypeInfo().GetTypeName() == "Xform" # Check properties - prim = sim.stage.GetPrimAtPath("/World/Cone/geometry/mesh") - assert prim.GetAttribute("physics:density").Get() == cfg.mass_props.density - # check sim playing - sim.play() - for _ in range(10): - sim.step() - - -def test_spawn_cone_with_all_deformable_props(sim): - """Test spawning of UsdGeomMesh prim for a cone with all deformable properties.""" - # Spawn cone - cfg = sim_utils.MeshConeCfg( - radius=1.0, - height=2.0, - mass_props=sim_utils.MassPropertiesCfg(mass=5.0), - deformable_props=sim_utils.DeformableBodyPropertiesCfg(), - visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(0.0, 0.75, 0.5)), - physics_material=sim_utils.DeformableBodyMaterialCfg(), - ) - prim = cfg.func("/World/Cone", cfg) + prim = sim.stage.GetPrimAtPath("/World/Square/geometry/mesh") + assert prim.GetPrimTypeInfo().GetTypeName() == "Mesh" - # Check validity - assert prim.IsValid() - assert sim.stage.GetPrimAtPath("/World/Cone").IsValid() - assert sim.stage.GetPrimAtPath("/World/Cone/geometry/material").IsValid() - # Check properties - # -- deformable body - prim = sim.stage.GetPrimAtPath("/World/Cone/geometry/mesh") - assert prim.GetAttribute("physxDeformable:deformableEnabled").Get() is True - # check sim playing - sim.play() - for _ in range(10): - sim.step() +""" +Physics properties. +""" def test_spawn_cone_with_all_rigid_props(sim): diff --git a/source/isaaclab/test/sim/test_spawn_sensors.py b/source/isaaclab/test/sim/test_spawn_sensors.py index d9f58b98dc75..f8604b99e54b 100644 --- a/source/isaaclab/test/sim/test_spawn_sensors.py +++ b/source/isaaclab/test/sim/test_spawn_sensors.py @@ -22,6 +22,8 @@ from isaaclab.sim.spawners.sensors.sensors import CUSTOM_FISHEYE_CAMERA_ATTRIBUTES, CUSTOM_PINHOLE_CAMERA_ATTRIBUTES from isaaclab.utils.string import to_camel_case +pytestmark = pytest.mark.isaacsim_ci + @pytest.fixture def sim(): diff --git a/source/isaaclab/test/sim/test_spawn_shapes.py b/source/isaaclab/test/sim/test_spawn_shapes.py index 0d2bb33bf6d3..532b29c22849 100644 --- a/source/isaaclab/test/sim/test_spawn_shapes.py +++ b/source/isaaclab/test/sim/test_spawn_shapes.py @@ -17,6 +17,8 @@ import isaaclab.sim as sim_utils from isaaclab.sim import SimulationCfg, SimulationContext +pytestmark = pytest.mark.isaacsim_ci + @pytest.fixture def sim(): diff --git a/source/isaaclab/test/sim/test_spawn_wrappers.py b/source/isaaclab/test/sim/test_spawn_wrappers.py index 67bb0de4cf0d..c053a6362f4d 100644 --- a/source/isaaclab/test/sim/test_spawn_wrappers.py +++ b/source/isaaclab/test/sim/test_spawn_wrappers.py @@ -19,6 +19,8 @@ from isaaclab.sim import SimulationCfg, SimulationContext from isaaclab.utils.assets import ISAACLAB_NUCLEUS_DIR +pytestmark = pytest.mark.isaacsim_ci + @pytest.fixture def sim(): diff --git a/source/isaaclab/test/sim/test_urdf_converter.py b/source/isaaclab/test/sim/test_urdf_converter.py index ddd07c9f5617..65c697029f97 100644 --- a/source/isaaclab/test/sim/test_urdf_converter.py +++ b/source/isaaclab/test/sim/test_urdf_converter.py @@ -12,16 +12,15 @@ """Rest everything follows.""" +import math import os import tempfile import warnings import xml.etree.ElementTree as ET -import numpy as np import pytest import omni.kit.app -from isaacsim.core.prims import Articulation import isaaclab.sim as sim_utils from isaaclab.sim import SimulationCfg, SimulationContext @@ -110,43 +109,62 @@ def test_create_prim_from_usd(sim_config): @pytest.mark.isaacsim_ci def test_config_drive_type(sim_config): - """Change the drive mechanism of the robot to be position.""" + """Verify that ``target_type='position'`` plus uniform PD gains are written into every joint's DriveAPI. + + Reads the converter's USD output directly via :class:`pxr.UsdPhysics.DriveAPI` so the assertion does + not depend on a running PhysX simulation. Revolute joints are checked in N·m/deg (the USD storage + convention) and prismatic joints in N/m. + """ sim, config = sim_config - # Create directory to dump results test_dir = os.path.dirname(os.path.abspath(__file__)) output_dir = os.path.join(test_dir, "output", "urdf_converter") - if not os.path.exists(output_dir): - os.makedirs(output_dir, exist_ok=True) + os.makedirs(output_dir, exist_ok=True) + + stiffness = 42.0 + damping = 4.2 - # change the config config.force_usd_conversion = True config.joint_drive.target_type = "position" - config.joint_drive.gains.stiffness = 42.0 - config.joint_drive.gains.damping = 4.2 + config.joint_drive.gains.stiffness = stiffness + config.joint_drive.gains.damping = damping config.usd_dir = output_dir urdf_converter = UrdfConverter(config) - # check the drive type of the robot - prim_path = "/World/Robot" - sim_utils.create_prim(prim_path, usd_path=urdf_converter.usd_path) - # access the robot - robot = Articulation(prim_path, reset_xform_properties=False) - # play the simulator and initialize the robot - sim.reset() - robot.initialize() + from pxr import Usd, UsdPhysics - # check drive values for the robot (read from physx) - drive_stiffness, drive_damping = robot.get_gains() - np.testing.assert_allclose(drive_stiffness.cpu().numpy(), config.joint_drive.gains.stiffness) - np.testing.assert_allclose(drive_damping.cpu().numpy(), config.joint_drive.gains.damping) + stage = Usd.Stage.Open(urdf_converter.usd_path) - # check drive values for the robot (read from usd) - # Note: Disable the app control callback to prevent hanging during sim.stop() - sim._disable_app_control_on_stop_handle = True - sim.stop() - drive_stiffness, drive_damping = robot.get_gains() - np.testing.assert_allclose(drive_stiffness.cpu().numpy(), config.joint_drive.gains.stiffness) - np.testing.assert_allclose(drive_damping.cpu().numpy(), config.joint_drive.gains.damping) + revolute_count = 0 + prismatic_count = 0 + for prim in stage.Traverse(): + is_revolute = prim.IsA(UsdPhysics.RevoluteJoint) + is_prismatic = prim.IsA(UsdPhysics.PrismaticJoint) + if not (is_revolute or is_prismatic): + continue + instance_name = "angular" if is_revolute else "linear" + drive = UsdPhysics.DriveAPI.Get(prim, instance_name) + actual_stiffness = drive.GetStiffnessAttr().Get() + actual_damping = drive.GetDampingAttr().Get() + + if is_revolute: + expected_stiffness = stiffness * math.pi / 180.0 + expected_damping = damping * math.pi / 180.0 + revolute_count += 1 + else: + expected_stiffness = stiffness + expected_damping = damping + prismatic_count += 1 + + assert abs(actual_stiffness - expected_stiffness) < 1e-4, ( + f"Joint {prim.GetName()}: expected stiffness {expected_stiffness}, got {actual_stiffness}" + ) + assert abs(actual_damping - expected_damping) < 1e-4, ( + f"Joint {prim.GetName()}: expected damping {expected_damping}, got {actual_damping}" + ) + + # Franka Panda has 7 revolute arm joints and 2 prismatic finger joints. + assert revolute_count == 7, f"Expected 7 revolute joints, got {revolute_count}" + assert prismatic_count == 2, f"Expected 2 prismatic joints, got {prismatic_count}" @pytest.mark.isaacsim_ci @@ -405,7 +423,7 @@ def test_drive_type_acceleration(sim_config): @pytest.mark.isaacsim_ci def test_target_type_none_zeros_gains(sim_config): - """Verify that target_type='none' sets stiffness and damping to 0.""" + """Verify that ``target_type='none'`` zeros the DriveAPI stiffness and damping on every joint.""" sim, config = sim_config test_dir = os.path.dirname(os.path.abspath(__file__)) output_dir = os.path.join(test_dir, "output", "urdf_target_none") @@ -416,15 +434,27 @@ def test_target_type_none_zeros_gains(sim_config): config.usd_dir = output_dir urdf_converter = UrdfConverter(config) - prim_path = "/World/Robot" - sim_utils.create_prim(prim_path, usd_path=urdf_converter.usd_path) - robot = Articulation(prim_path, reset_xform_properties=False) - sim.reset() - robot.initialize() + from pxr import Usd, UsdPhysics - drive_stiffness, drive_damping = robot.get_gains() - np.testing.assert_allclose(drive_stiffness.cpu().numpy(), 0.0, atol=1e-6) - np.testing.assert_allclose(drive_damping.cpu().numpy(), 0.0, atol=1e-6) + stage = Usd.Stage.Open(urdf_converter.usd_path) + + joint_count = 0 + for prim in stage.Traverse(): + is_revolute = prim.IsA(UsdPhysics.RevoluteJoint) + is_prismatic = prim.IsA(UsdPhysics.PrismaticJoint) + if not (is_revolute or is_prismatic): + continue + instance_name = "angular" if is_revolute else "linear" + drive = UsdPhysics.DriveAPI.Get(prim, instance_name) + assert abs(drive.GetStiffnessAttr().Get()) < 1e-6, ( + f"Joint {prim.GetName()}: expected zero stiffness, got {drive.GetStiffnessAttr().Get()}" + ) + assert abs(drive.GetDampingAttr().Get()) < 1e-6, ( + f"Joint {prim.GetName()}: expected zero damping, got {drive.GetDampingAttr().Get()}" + ) + joint_count += 1 + + assert joint_count > 0, "No joints found in the output USD" @pytest.mark.isaacsim_ci @@ -474,8 +504,6 @@ def test_per_joint_dict_gains(sim_config): if "panda_joint" in name and "finger" not in name: # arm joint (revolute) — USD stores in Nm/deg, so expected = value * pi/180 - import math - expected_s = arm_stiffness * math.pi / 180.0 expected_d = arm_damping * math.pi / 180.0 assert abs(stiffness_attr.Get() - expected_s) < 0.01, ( diff --git a/source/isaaclab/test/sim/test_utils_prims.py b/source/isaaclab/test/sim/test_utils_prims.py index c107656f5a15..0d11afe22f45 100644 --- a/source/isaaclab/test/sim/test_utils_prims.py +++ b/source/isaaclab/test/sim/test_utils_prims.py @@ -25,6 +25,8 @@ from isaaclab.sim.utils.prims import _to_tuple # type: ignore[reportPrivateUsage] from isaaclab.utils.assets import ISAAC_NUCLEUS_DIR, ISAACLAB_NUCLEUS_DIR, retrieve_file_path +pytestmark = pytest.mark.isaacsim_ci + @pytest.fixture(autouse=True) def test_setup_teardown(): diff --git a/source/isaaclab/test/sim/test_utils_stage.py b/source/isaaclab/test/sim/test_utils_stage.py index 9e2e29602eed..f6d73d518662 100644 --- a/source/isaaclab/test/sim/test_utils_stage.py +++ b/source/isaaclab/test/sim/test_utils_stage.py @@ -23,6 +23,8 @@ import isaaclab.sim as sim_utils +pytestmark = pytest.mark.isaacsim_ci + def test_create_new_stage(): """Test creating a new stage attached to USD context.""" diff --git a/source/isaaclab/test/sim/test_views_xform_prim.py b/source/isaaclab/test/sim/test_views_xform_prim.py index 3de7a0b357a2..64cd86a7466f 100644 --- a/source/isaaclab/test/sim/test_views_xform_prim.py +++ b/source/isaaclab/test/sim/test_views_xform_prim.py @@ -3,1513 +3,295 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""Launch Isaac Sim Simulator first.""" +"""USD backend tests for FrameView. + +Imports the shared contract tests and provides the USD-specific +``view_factory`` fixture. Also includes USD-only tests for visibility, +prim ordering, xformOp standardization, and Isaac Sim comparison. +""" from isaaclab.app import AppLauncher -# launch omniverse app simulation_app = AppLauncher(headless=True).app -"""Rest everything follows.""" - import pytest # noqa: E402 import torch # noqa: E402 +import warp as wp # noqa: E402 + +from pxr import Gf, UsdGeom # noqa: E402 try: - from isaacsim.core.prims import XFormPrim as _IsaacSimXformPrimView + from isaacsim.core.experimental.prims import XformPrim as _IsaacSimXformPrimView except (ModuleNotFoundError, ImportError): _IsaacSimXformPrimView = None +from frame_view_contract_utils import * # noqa: F401, F403, E402 +from frame_view_contract_utils import CHILD_OFFSET, ViewBundle # noqa: E402 import isaaclab.sim as sim_utils # noqa: E402 -from isaaclab.sim.views import XformPrimView as XformPrimView # noqa: E402 +from isaaclab.sim.views import UsdFrameView as FrameView # noqa: E402 from isaaclab.utils.assets import ISAAC_NUCLEUS_DIR # noqa: E402 +pytestmark = pytest.mark.isaacsim_ci +PARENT_POS = (0.0, 0.0, 1.0) + @pytest.fixture(autouse=True) def test_setup_teardown(): - """Create a blank new stage for each test.""" - # Setup: Create a new stage sim_utils.create_new_stage() sim_utils.update_stage() - - # Yield for the test yield - - # Teardown: Clear stage after each test sim_utils.clear_stage() sim_utils.SimulationContext.clear_instance() -""" -Helper functions. -""" - - -def _prepare_indices(index_type, target_indices, num_prims, device): - """Helper function to prepare indices based on type.""" - if index_type == "list": - return target_indices, target_indices - elif index_type == "torch_tensor": - return torch.tensor(target_indices, dtype=torch.int64, device=device), target_indices - elif index_type == "slice_none": - return slice(None), list(range(num_prims)) - else: - raise ValueError(f"Unknown index type: {index_type}") - - -def _skip_if_backend_unavailable(backend: str, device: str): - """Skip tests when the requested backend is unavailable.""" - if device.startswith("cuda") and not torch.cuda.is_available(): - pytest.skip("CUDA not available") - if backend == "fabric" and device == "cpu": - pytest.skip("Warp fabricarray operations on CPU have known issues") - - -def _prim_type_for_backend(backend: str) -> str: - """Return a prim type that is compatible with the backend.""" - return "Camera" if backend == "fabric" else "Xform" - - -def _create_view(pattern: str, device: str, backend: str) -> XformPrimView: - """Create an XformPrimView for the requested backend.""" - if backend == "fabric": - sim_utils.SimulationContext(sim_utils.SimulationCfg(dt=0.01, device=device, use_fabric=True)) - return XformPrimView(pattern, device=device) - - -""" -Tests - Initialization. -""" - - -@pytest.mark.parametrize("device", ["cpu", "cuda"]) -def test_xform_prim_view_initialization_single_prim(device): - """Test XformPrimView initialization with a single prim.""" - # check if CUDA is available - if device == "cuda" and not torch.cuda.is_available(): - pytest.skip("CUDA not available") - - # Create a single xform prim - stage = sim_utils.get_current_stage() - sim_utils.create_prim("/World/Object", "Xform", translation=(1.0, 2.0, 3.0), stage=stage) - - # Create view - view = XformPrimView("/World/Object", device=device) - - # Verify properties - assert view.count == 1 - assert view.prim_paths == ["/World/Object"] - assert view.device == device - assert len(view.prims) == 1 - - -@pytest.mark.parametrize("device", ["cpu", "cuda"]) -def test_xform_prim_view_initialization_multiple_prims(device): - """Test XformPrimView initialization with multiple prims using pattern matching.""" - # check if CUDA is available - if device == "cuda" and not torch.cuda.is_available(): - pytest.skip("CUDA not available") - - # Create multiple prims - num_prims = 10 - stage = sim_utils.get_current_stage() - for i in range(num_prims): - sim_utils.create_prim(f"/World/Env_{i}/Object", "Xform", translation=(i * 2.0, 0.0, 1.0), stage=stage) - - # Create view with pattern - view = XformPrimView("/World/Env_.*/Object", device=device) - - # Verify properties - assert view.count == num_prims - assert view.device == device - assert len(view.prims) == num_prims - assert view.prim_paths == [f"/World/Env_{i}/Object" for i in range(num_prims)] - - -@pytest.mark.parametrize("device", ["cpu", "cuda"]) -def test_xform_prim_view_initialization_multiple_prims_order(device): - """Test XformPrimView initialization with multiple prims using pattern matching with multiple objects per prim. - - This test validates that XformPrimView respects USD stage traversal order, which is based on - creation order (depth-first search), NOT alphabetical/lexical sorting. This is an important - edge case that ensures deterministic prim ordering that matches USD's internal representation. - - The test creates prims in a deliberately non-alphabetical order (1, 0, A, a, 2) and verifies - that they are retrieved in creation order, not sorted order (0, 1, 2, A, a). - """ - # check if CUDA is available - if device == "cuda" and not torch.cuda.is_available(): - pytest.skip("CUDA not available") - - # Create multiple prims - num_prims = 10 - stage = sim_utils.get_current_stage() - - # NOTE: Prims are created in a specific order to test that XformPrimView respects - # USD stage traversal order (DFS based on creation order), NOT alphabetical/lexical order. - # This is an important edge case: children under the same parent are returned in the - # order they were created, not sorted by name. - - # First batch: Create Object_1, Object_0, Object_A for each environment - # (intentionally non-alphabetical: 1, 0, A instead of 0, 1, A) - for i in range(num_prims): - sim_utils.create_prim(f"/World/Env_{i}/Object_1", "Xform", translation=(i * 2.0, -2.0, 1.0), stage=stage) - sim_utils.create_prim(f"/World/Env_{i}/Object_0", "Xform", translation=(i * 2.0, 2.0, 1.0), stage=stage) - sim_utils.create_prim(f"/World/Env_{i}/Object_A", "Xform", translation=(i * 2.0, 0.0, -1.0), stage=stage) - - # Second batch: Create Object_a, Object_2 for each environment - # (created after the first batch to verify traversal is depth-first per environment) - for i in range(num_prims): - sim_utils.create_prim(f"/World/Env_{i}/Object_a", "Xform", translation=(i * 2.0, 2.0, -1.0), stage=stage) - sim_utils.create_prim(f"/World/Env_{i}/Object_2", "Xform", translation=(i * 2.0, 2.0, 1.0), stage=stage) - - # Create view with pattern - view = XformPrimView("/World/Env_.*/Object_.*", device=device) - - # Expected ordering: DFS traversal by environment, with children in creation order - # For each Env_i, we expect: Object_1, Object_0, Object_A, Object_a, Object_2 - # (matches creation order, NOT alphabetical: would be 0, 1, 2, A, a if sorted) - expected_prim_paths_ordering = [] - for i in range(num_prims): - expected_prim_paths_ordering.append(f"/World/Env_{i}/Object_1") - expected_prim_paths_ordering.append(f"/World/Env_{i}/Object_0") - expected_prim_paths_ordering.append(f"/World/Env_{i}/Object_A") - expected_prim_paths_ordering.append(f"/World/Env_{i}/Object_a") - expected_prim_paths_ordering.append(f"/World/Env_{i}/Object_2") - - # Verify properties - assert view.count == num_prims * 5 - assert view.device == device - assert len(view.prims) == num_prims * 5 - assert view.prim_paths == expected_prim_paths_ordering - - # Additional validation: Verify ordering is NOT alphabetical - # If it were alphabetical, Object_0 would come before Object_1 - alphabetical_order = [] - for i in range(num_prims): - alphabetical_order.append(f"/World/Env_{i}/Object_0") - alphabetical_order.append(f"/World/Env_{i}/Object_1") - alphabetical_order.append(f"/World/Env_{i}/Object_2") - alphabetical_order.append(f"/World/Env_{i}/Object_A") - alphabetical_order.append(f"/World/Env_{i}/Object_a") - - assert view.prim_paths != alphabetical_order, ( - "Prim paths should follow creation order, not alphabetical order. " - "This test validates that USD stage traversal respects creation order." - ) - - -@pytest.mark.parametrize("device", ["cpu", "cuda"]) -def test_xform_prim_view_standardizes_transform_op(device): - """Test that XformPrimView standardizes a prim with xformOp:transform to translate/orient/scale.""" - from pxr import Gf, UsdGeom - - if device == "cuda" and not torch.cuda.is_available(): - pytest.skip("CUDA not available") - - expected_pos = (3.0, -1.0, 0.5) - matrix = Gf.Matrix4d(1.0) - matrix.SetTranslateOnly(Gf.Vec3d(*expected_pos)) - - stage = sim_utils.get_current_stage() - prim = stage.DefinePrim("/World/TransformPrim", "Xform") - UsdGeom.Xformable(prim).AddTransformOp().Set(matrix) - - view = XformPrimView("/World/TransformPrim", device=device) - - assert view.count == 1 - assert sim_utils.validate_standard_xform_ops(view.prims[0]) - - xformable = UsdGeom.Xformable(view.prims[0]) - ordered_ops = xformable.GetOrderedXformOps() - op_names = [op.GetOpName() for op in ordered_ops] - assert op_names == ["xformOp:translate", "xformOp:orient", "xformOp:scale"] - - assert ordered_ops[0].Get() == Gf.Vec3d(*expected_pos) - assert ordered_ops[1].Get() == Gf.Quatd(1.0, 0.0, 0.0, 0.0) - assert ordered_ops[2].Get() == Gf.Vec3d(1.0, 1.0, 1.0) - - -@pytest.mark.parametrize("device", ["cpu", "cuda"]) -def test_xform_prim_view_initialization_empty_pattern(device): - """Test XformPrimView initialization with pattern that matches no prims.""" - # check if CUDA is available - if device == "cuda" and not torch.cuda.is_available(): - pytest.skip("CUDA not available") - - sim_utils.create_new_stage() - - # Create view with pattern that matches nothing - view = XformPrimView("/World/NonExistent_.*", device=device) - - # Should have zero count - assert view.count == 0 - assert len(view.prims) == 0 - - -""" -Tests - Getters. -""" - - -@pytest.mark.parametrize("device", ["cpu", "cuda"]) -@pytest.mark.parametrize("backend", ["usd", "fabric"]) -def test_get_world_poses(device, backend): - """Test getting world poses from XformPrimView.""" - _skip_if_backend_unavailable(backend, device) - - stage = sim_utils.get_current_stage() - prim_type = _prim_type_for_backend(backend) - - # Create prims with known world poses - expected_positions = [(1.0, 2.0, 3.0), (4.0, 5.0, 6.0), (7.0, 8.0, 9.0)] - expected_orientations = [(0.0, 0.0, 0.0, 1.0), (0.0, 0.0, 0.7071068, 0.7071068), (0.7071068, 0.0, 0.0, 0.7071068)] - - for i, (pos, quat) in enumerate(zip(expected_positions, expected_orientations)): - sim_utils.create_prim(f"/World/Object_{i}", prim_type, translation=pos, orientation=quat, stage=stage) - - # Create view - view = _create_view("/World/Object_.*", device=device, backend=backend) - - # Convert expected values to tensors - expected_positions_tensor = torch.tensor(expected_positions, dtype=torch.float32, device=device) - expected_orientations_tensor = torch.tensor(expected_orientations, dtype=torch.float32, device=device) - - # Get world poses - positions, orientations = view.get_world_poses() - - # Verify shapes - assert positions.shape == (3, 3) - assert orientations.shape == (3, 4) - - # Verify positions - torch.testing.assert_close(positions, expected_positions_tensor, atol=1e-5, rtol=0) - - # Verify orientations (allow for quaternion sign ambiguity) - try: - torch.testing.assert_close(orientations, expected_orientations_tensor, atol=1e-5, rtol=0) - except AssertionError: - torch.testing.assert_close(orientations, -expected_orientations_tensor, atol=1e-5, rtol=0) - - -@pytest.mark.parametrize("device", ["cpu", "cuda"]) -@pytest.mark.parametrize("backend", ["usd", "fabric"]) -def test_get_local_poses(device, backend): - """Test getting local poses from XformPrimView.""" - _skip_if_backend_unavailable(backend, device) - - stage = sim_utils.get_current_stage() - prim_type = _prim_type_for_backend(backend) - - # Create parent and child prims - sim_utils.create_prim("/World/Parent", "Xform", translation=(10.0, 0.0, 0.0), stage=stage) - - # Children with different local poses - expected_local_positions = [(1.0, 0.0, 0.0), (0.0, 2.0, 0.0), (0.0, 0.0, 3.0)] - expected_local_orientations = [ - (0.0, 0.0, 0.0, 1.0), - (0.0, 0.0, 0.7071068, 0.7071068), - (0.7071068, 0.0, 0.0, 0.7071068), - ] - - for i, (pos, quat) in enumerate(zip(expected_local_positions, expected_local_orientations)): - sim_utils.create_prim(f"/World/Parent/Child_{i}", prim_type, translation=pos, orientation=quat, stage=stage) - - # Create view - view = _create_view("/World/Parent/Child_.*", device=device, backend=backend) - - # Get local poses - translations, orientations = view.get_local_poses() - - # Verify shapes - assert translations.shape == (3, 3) - assert orientations.shape == (3, 4) - - # Convert expected values to tensors - expected_translations_tensor = torch.tensor(expected_local_positions, dtype=torch.float32, device=device) - expected_orientations_tensor = torch.tensor(expected_local_orientations, dtype=torch.float32, device=device) - - # Verify translations - torch.testing.assert_close(translations, expected_translations_tensor, atol=1e-5, rtol=0) - - # Verify orientations (allow for quaternion sign ambiguity) - try: - torch.testing.assert_close(orientations, expected_orientations_tensor, atol=1e-5, rtol=0) - except AssertionError: - torch.testing.assert_close(orientations, -expected_orientations_tensor, atol=1e-5, rtol=0) - - -@pytest.mark.parametrize("device", ["cpu", "cuda"]) -@pytest.mark.parametrize("backend", ["usd", "fabric"]) -def test_get_scales(device, backend): - """Test getting scales from XformPrimView.""" - _skip_if_backend_unavailable(backend, device) - - stage = sim_utils.get_current_stage() - prim_type = _prim_type_for_backend(backend) - - # Create prims with different scales - expected_scales = [(1.0, 1.0, 1.0), (2.0, 2.0, 2.0), (1.0, 2.0, 3.0)] - - for i, scale in enumerate(expected_scales): - sim_utils.create_prim(f"/World/Object_{i}", prim_type, scale=scale, stage=stage) - - # Create view - view = _create_view("/World/Object_.*", device=device, backend=backend) - - expected_scales_tensor = torch.tensor(expected_scales, dtype=torch.float32, device=device) - - # Get scales - scales = view.get_scales() - - # Verify shape and values - assert scales.shape == (3, 3) - torch.testing.assert_close(scales, expected_scales_tensor, atol=1e-5, rtol=0) - - -@pytest.mark.parametrize("device", ["cpu", "cuda"]) -def test_get_visibility(device): - """Test getting visibility when all prims are visible.""" - if device == "cuda" and not torch.cuda.is_available(): - pytest.skip("CUDA not available") - - stage = sim_utils.get_current_stage() - - # Create prims (default is visible) - num_prims = 5 - for i in range(num_prims): - sim_utils.create_prim(f"/World/Object_{i}", "Xform", translation=(float(i), 0.0, 0.0), stage=stage) - - # Create view - view = XformPrimView("/World/Object_.*", device=device) - - # Get visibility - visibility = view.get_visibility() - - # Verify shape and values - assert visibility.shape == (num_prims,) - assert visibility.dtype == torch.bool - assert torch.all(visibility), "All prims should be visible by default" - - -""" -Tests - Setters. -""" - - -@pytest.mark.parametrize("device", ["cpu", "cuda"]) -@pytest.mark.parametrize("backend", ["usd", "fabric"]) -def test_set_world_poses(device, backend): - """Test setting world poses in XformPrimView.""" - _skip_if_backend_unavailable(backend, device) - - stage = sim_utils.get_current_stage() - prim_type = _prim_type_for_backend(backend) - - # Create prims - num_prims = 5 - for i in range(num_prims): - sim_utils.create_prim(f"/World/Object_{i}", prim_type, translation=(0.0, 0.0, 0.0), stage=stage) - - # Create view - view = _create_view("/World/Object_.*", device=device, backend=backend) - - # Set new world poses - new_positions = torch.tensor( - [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0], [10.0, 11.0, 12.0], [13.0, 14.0, 15.0]], device=device - ) - new_orientations = torch.tensor( - [ - [0.0, 0.0, 0.0, 1.0], - [0.0, 0.0, 0.7071068, 0.7071068], - [0.7071068, 0.0, 0.0, 0.7071068], - [0.3826834, 0.0, 0.0, 0.9238795], - [0.0, 0.7071068, 0.0, 0.7071068], - ], - device=device, - ) - - view.set_world_poses(new_positions, new_orientations) - - # Get the poses back - retrieved_positions, retrieved_orientations = view.get_world_poses() - - # Verify they match - torch.testing.assert_close(retrieved_positions, new_positions, atol=1e-5, rtol=0) - # Check quaternions (allow sign flip) - try: - torch.testing.assert_close(retrieved_orientations, new_orientations, atol=1e-5, rtol=0) - except AssertionError: - torch.testing.assert_close(retrieved_orientations, -new_orientations, atol=1e-5, rtol=0) - - -@pytest.mark.parametrize("device", ["cpu", "cuda"]) -@pytest.mark.parametrize("backend", ["usd", "fabric"]) -def test_set_world_poses_only_positions(device, backend): - """Test setting only positions, leaving orientations unchanged.""" - _skip_if_backend_unavailable(backend, device) - - stage = sim_utils.get_current_stage() - prim_type = _prim_type_for_backend(backend) - - # Create prims with specific orientations - initial_quat = (0.0, 0.0, 0.7071068, 0.7071068) # 90 deg around Z - for i in range(3): - sim_utils.create_prim( - f"/World/Object_{i}", prim_type, translation=(0.0, 0.0, 0.0), orientation=initial_quat, stage=stage - ) - - # Create view - view = _create_view("/World/Object_.*", device=device, backend=backend) - - # Get initial orientations - _, initial_orientations = view.get_world_poses() - - # Set only positions - new_positions = torch.tensor([[1.0, 0.0, 0.0], [0.0, 2.0, 0.0], [0.0, 0.0, 3.0]], device=device) - view.set_world_poses(positions=new_positions, orientations=None) - - # Get poses back - retrieved_positions, retrieved_orientations = view.get_world_poses() - - # Positions should be updated - torch.testing.assert_close(retrieved_positions, new_positions, atol=1e-5, rtol=0) - - # Orientations should be unchanged - try: - torch.testing.assert_close(retrieved_orientations, initial_orientations, atol=1e-5, rtol=0) - except AssertionError: - torch.testing.assert_close(retrieved_orientations, -initial_orientations, atol=1e-5, rtol=0) - - -@pytest.mark.parametrize("device", ["cpu", "cuda"]) -@pytest.mark.parametrize("backend", ["usd", "fabric"]) -def test_set_world_poses_only_orientations(device, backend): - """Test setting only orientations, leaving positions unchanged.""" - _skip_if_backend_unavailable(backend, device) - - stage = sim_utils.get_current_stage() - prim_type = _prim_type_for_backend(backend) - - # Create prims with specific positions - for i in range(3): - sim_utils.create_prim(f"/World/Object_{i}", prim_type, translation=(float(i), 0.0, 0.0), stage=stage) - - # Create view - view = _create_view("/World/Object_.*", device=device, backend=backend) - - # Get initial positions - initial_positions, _ = view.get_world_poses() - - # Set only orientations - new_orientations = torch.tensor( - [[0.0, 0.0, 0.7071068, 0.7071068], [0.7071068, 0.0, 0.0, 0.7071068], [0.3826834, 0.0, 0.0, 0.9238795]], - device=device, - ) - view.set_world_poses(positions=None, orientations=new_orientations) - - # Get poses back - retrieved_positions, retrieved_orientations = view.get_world_poses() - - # Positions should be unchanged - torch.testing.assert_close(retrieved_positions, initial_positions, atol=1e-5, rtol=0) - - # Orientations should be updated - try: - torch.testing.assert_close(retrieved_orientations, new_orientations, atol=1e-5, rtol=0) - except AssertionError: - torch.testing.assert_close(retrieved_orientations, -new_orientations, atol=1e-5, rtol=0) - +# ------------------------------------------------------------------ +# Contract fixture +# ------------------------------------------------------------------ -@pytest.mark.parametrize("device", ["cpu", "cuda"]) -@pytest.mark.parametrize("backend", ["usd", "fabric"]) -def test_set_world_poses_with_hierarchy(device, backend): - """Test setting world poses correctly handles parent transformations.""" - _skip_if_backend_unavailable(backend, device) - - stage = sim_utils.get_current_stage() - child_prim_type = _prim_type_for_backend(backend) - - # Create parent prims - for i in range(3): - parent_pos = (i * 10.0, 0.0, 0.0) - parent_quat = (0.0, 0.0, 0.7071068, 0.7071068) # 90 deg around Z - sim_utils.create_prim( - f"/World/Parent_{i}", "Xform", translation=parent_pos, orientation=parent_quat, stage=stage - ) - # Create child prims - sim_utils.create_prim(f"/World/Parent_{i}/Child", child_prim_type, translation=(0.0, 0.0, 0.0), stage=stage) - - # Create view for children - view = _create_view("/World/Parent_.*/Child", device=device, backend=backend) - - # Set world poses for children - desired_world_positions = torch.tensor([[5.0, 5.0, 0.0], [15.0, 5.0, 0.0], [25.0, 5.0, 0.0]], device=device) - desired_world_orientations = torch.tensor( - [[0.0, 0.0, 0.0, 1.0], [0.0, 0.0, 0.0, 1.0], [0.0, 0.0, 0.0, 1.0]], device=device - ) - - view.set_world_poses(desired_world_positions, desired_world_orientations) - - # Get world poses back - retrieved_positions, retrieved_orientations = view.get_world_poses() - - # Should match desired world poses - torch.testing.assert_close(retrieved_positions, desired_world_positions, atol=1e-4, rtol=0) - try: - torch.testing.assert_close(retrieved_orientations, desired_world_orientations, atol=1e-4, rtol=0) - except AssertionError: - torch.testing.assert_close(retrieved_orientations, -desired_world_orientations, atol=1e-4, rtol=0) - - -@pytest.mark.parametrize("device", ["cpu", "cuda"]) -@pytest.mark.parametrize("backend", ["usd", "fabric"]) -def test_set_local_poses(device, backend): - """Test setting local poses in XformPrimView.""" - _skip_if_backend_unavailable(backend, device) +def _get_parent_positions(num_envs, device="cpu"): + """Read parent Xform positions from USD.""" stage = sim_utils.get_current_stage() - prim_type = _prim_type_for_backend(backend) - - # Create parent - sim_utils.create_prim("/World/Parent", "Xform", translation=(5.0, 5.0, 5.0), stage=stage) - - # Create children - num_prims = 4 - for i in range(num_prims): - sim_utils.create_prim(f"/World/Parent/Child_{i}", prim_type, translation=(0.0, 0.0, 0.0), stage=stage) - - # Create view - view = _create_view("/World/Parent/Child_.*", device=device, backend=backend) - - # Set new local poses - new_translations = torch.tensor([[1.0, 0.0, 0.0], [0.0, 2.0, 0.0], [0.0, 0.0, 3.0], [4.0, 4.0, 4.0]], device=device) - new_orientations = torch.tensor( - [ - [0.0, 0.0, 0.0, 1.0], - [0.0, 0.0, 0.7071068, 0.7071068], - [0.7071068, 0.0, 0.0, 0.7071068], - [0.3826834, 0.0, 0.0, 0.9238795], - ], - device=device, - ) - - view.set_local_poses(new_translations, new_orientations) + xform_cache = UsdGeom.XformCache() + positions = [] + for i in range(num_envs): + prim = stage.GetPrimAtPath(f"/World/Parent_{i}") + tf = xform_cache.GetLocalToWorldTransform(prim) + t = tf.ExtractTranslation() + positions.append([float(t[0]), float(t[1]), float(t[2])]) + return torch.tensor(positions, dtype=torch.float32, device=device) - # Get local poses back - retrieved_translations, retrieved_orientations = view.get_local_poses() - # Verify they match - torch.testing.assert_close(retrieved_translations, new_translations, atol=1e-5, rtol=0) - try: - torch.testing.assert_close(retrieved_orientations, new_orientations, atol=1e-5, rtol=0) - except AssertionError: - torch.testing.assert_close(retrieved_orientations, -new_orientations, atol=1e-5, rtol=0) - - -@pytest.mark.parametrize("device", ["cpu", "cuda"]) -@pytest.mark.parametrize("backend", ["usd", "fabric"]) -def test_set_local_poses_only_translations(device, backend): - """Test setting only local translations.""" - _skip_if_backend_unavailable(backend, device) +def _set_parent_positions(positions, num_envs): + """Write parent Xform positions to USD.""" + from pxr import Sdf # noqa: PLC0415 stage = sim_utils.get_current_stage() - prim_type = _prim_type_for_backend(backend) - - # Create parent and children with specific orientations - sim_utils.create_prim("/World/Parent", "Xform", translation=(0.0, 0.0, 0.0), stage=stage) - initial_quat = (0.0, 0.0, 0.7071068, 0.7071068) - - for i in range(3): - sim_utils.create_prim( - f"/World/Parent/Child_{i}", - prim_type, - translation=(0.0, 0.0, 0.0), - orientation=initial_quat, - stage=stage, + with Sdf.ChangeBlock(): + for i in range(num_envs): + prim = stage.GetPrimAtPath(f"/World/Parent_{i}") + pos = positions[i] + prim.GetAttribute("xformOp:translate").Set(Gf.Vec3d(float(pos[0]), float(pos[1]), float(pos[2]))) + + +@pytest.fixture +def view_factory(): + """USD factory: parent Xform at PARENT_POS + child Xform at CHILD_OFFSET.""" + + def factory(num_envs: int, device: str) -> ViewBundle: + stage = sim_utils.get_current_stage() + for i in range(num_envs): + sim_utils.create_prim(f"/World/Parent_{i}", "Xform", translation=PARENT_POS, stage=stage) + sim_utils.create_prim(f"/World/Parent_{i}/Child", "Xform", translation=CHILD_OFFSET, stage=stage) + + view = FrameView("/World/Parent_.*/Child", device=device) + return ViewBundle( + view=view, + get_parent_pos=_get_parent_positions, + set_parent_pos=_set_parent_positions, + teardown=lambda: None, ) - # Create view - view = _create_view("/World/Parent/Child_.*", device=device, backend=backend) - - # Get initial orientations - _, initial_orientations = view.get_local_poses() + return factory - # Set only translations - new_translations = torch.tensor([[1.0, 0.0, 0.0], [0.0, 2.0, 0.0], [0.0, 0.0, 3.0]], device=device) - view.set_local_poses(translations=new_translations, orientations=None) - # Get poses back - retrieved_translations, retrieved_orientations = view.get_local_poses() - - # Translations should be updated - torch.testing.assert_close(retrieved_translations, new_translations, atol=1e-5, rtol=0) - - # Orientations should be unchanged - try: - torch.testing.assert_close(retrieved_orientations, initial_orientations, atol=1e-5, rtol=0) - except AssertionError: - torch.testing.assert_close(retrieved_orientations, -initial_orientations, atol=1e-5, rtol=0) - - -@pytest.mark.parametrize("device", ["cpu", "cuda"]) -@pytest.mark.parametrize("backend", ["usd", "fabric"]) -def test_set_scales(device, backend): - """Test setting scales in XformPrimView.""" - _skip_if_backend_unavailable(backend, device) - - stage = sim_utils.get_current_stage() - prim_type = _prim_type_for_backend(backend) - - # Create prims - num_prims = 5 - for i in range(num_prims): - sim_utils.create_prim(f"/World/Object_{i}", prim_type, scale=(1.0, 1.0, 1.0), stage=stage) - - # Create view - view = _create_view("/World/Object_.*", device=device, backend=backend) - - # Set new scales - new_scales = torch.tensor( - [[2.0, 2.0, 2.0], [1.0, 2.0, 3.0], [0.5, 0.5, 0.5], [3.0, 1.0, 2.0], [1.5, 1.5, 1.5]], device=device - ) - - view.set_scales(new_scales) - - # Get scales back - retrieved_scales = view.get_scales() - - # Verify they match - torch.testing.assert_close(retrieved_scales, new_scales, atol=1e-5, rtol=0) +# ================================================================== +# USD-only: Visibility +# ================================================================== @pytest.mark.parametrize("device", ["cpu", "cuda"]) -def test_set_visibility(device): +def test_visibility_toggle(device): """Test toggling visibility multiple times.""" if device == "cuda" and not torch.cuda.is_available(): pytest.skip("CUDA not available") stage = sim_utils.get_current_stage() - - # Create prims num_prims = 3 for i in range(num_prims): sim_utils.create_prim(f"/World/Object_{i}", "Xform", stage=stage) - # Create view - view = XformPrimView("/World/Object_.*", device=device) + view = FrameView("/World/Object_.*", device=device) - # Initial state: all visible - visibility = view.get_visibility() - assert torch.all(visibility), "All should be visible initially" + assert torch.all(view.get_visibility()) - # Make all invisible view.set_visibility(torch.zeros(num_prims, dtype=torch.bool, device=device)) - visibility = view.get_visibility() - assert not torch.any(visibility), "All should be invisible" + assert not torch.any(view.get_visibility()) - # Make all visible again view.set_visibility(torch.ones(num_prims, dtype=torch.bool, device=device)) - visibility = view.get_visibility() - assert torch.all(visibility), "All should be visible again" - - # Toggle individual prims - view.set_visibility(torch.tensor([False], dtype=torch.bool, device=device), indices=[1]) - visibility = view.get_visibility() - assert visibility[0] and not visibility[1] and visibility[2], "Only middle prim should be invisible" - - -""" -Tests - Index Handling. -""" - - -@pytest.mark.parametrize("device", ["cpu", "cuda"]) -@pytest.mark.parametrize("index_type", ["list", "torch_tensor", "slice_none"]) -@pytest.mark.parametrize("method", ["world_poses", "local_poses", "scales", "visibility"]) -def test_index_types_get_methods(device, index_type, method): - """Test that getter methods work with different index types.""" - if device == "cuda" and not torch.cuda.is_available(): - pytest.skip("CUDA not available") - - stage = sim_utils.get_current_stage() - - # Create prims based on method type - num_prims = 10 - if method == "local_poses": - # Create parent and children for local poses - sim_utils.create_prim("/World/Parent", "Xform", translation=(10.0, 0.0, 0.0), stage=stage) - for i in range(num_prims): - sim_utils.create_prim( - f"/World/Parent/Child_{i}", "Xform", translation=(float(i), float(i) * 0.5, 0.0), stage=stage - ) - view = XformPrimView("/World/Parent/Child_.*", device=device) - elif method == "scales": - # Create prims with different scales - for i in range(num_prims): - scale = (1.0 + i * 0.5, 1.0 + i * 0.3, 1.0 + i * 0.2) - sim_utils.create_prim(f"/World/Object_{i}", "Xform", scale=scale, stage=stage) - view = XformPrimView("/World/Object_.*", device=device) - else: # world_poses - # Create prims with different positions - for i in range(num_prims): - sim_utils.create_prim(f"/World/Object_{i}", "Xform", translation=(float(i), 0.0, 0.0), stage=stage) - view = XformPrimView("/World/Object_.*", device=device) - - # Get all data as reference - if method == "world_poses": - all_data1, all_data2 = view.get_world_poses() - elif method == "local_poses": - all_data1, all_data2 = view.get_local_poses() - elif method == "scales": - all_data1 = view.get_scales() - all_data2 = None - else: # visibility - all_data1 = view.get_visibility() - all_data2 = None - - # Prepare indices - target_indices_base = [2, 5, 7] - indices, target_indices = _prepare_indices(index_type, target_indices_base, num_prims, device) - - # Get subset - if method == "world_poses": - subset_data1, subset_data2 = view.get_world_poses(indices=indices) # type: ignore[arg-type] - elif method == "local_poses": - subset_data1, subset_data2 = view.get_local_poses(indices=indices) # type: ignore[arg-type] - elif method == "scales": - subset_data1 = view.get_scales(indices=indices) # type: ignore[arg-type] - subset_data2 = None - else: # visibility - subset_data1 = view.get_visibility(indices=indices) # type: ignore[arg-type] - subset_data2 = None - - # Verify shapes - expected_count = len(target_indices) - if method == "visibility": - assert subset_data1.shape == (expected_count,) - else: - assert subset_data1.shape == (expected_count, 3) - if subset_data2 is not None: - assert subset_data2.shape == (expected_count, 4) - - # Verify values - target_indices_tensor = torch.tensor(target_indices, dtype=torch.int64, device=device) - torch.testing.assert_close(subset_data1, all_data1[target_indices_tensor], atol=1e-5, rtol=0) - if subset_data2 is not None and all_data2 is not None: - torch.testing.assert_close(subset_data2, all_data2[target_indices_tensor], atol=1e-5, rtol=0) - - -@pytest.mark.parametrize("device", ["cpu", "cuda"]) -@pytest.mark.parametrize("index_type", ["list", "torch_tensor", "slice_none"]) -@pytest.mark.parametrize("method", ["world_poses", "local_poses", "scales", "visibility"]) -def test_index_types_set_methods(device, index_type, method): - """Test that setter methods work with different index types.""" - if device == "cuda" and not torch.cuda.is_available(): - pytest.skip("CUDA not available") - - stage = sim_utils.get_current_stage() - - # Create prims based on method type - num_prims = 10 - if method == "local_poses": - # Create parent and children for local poses - sim_utils.create_prim("/World/Parent", "Xform", translation=(5.0, 5.0, 0.0), stage=stage) - for i in range(num_prims): - sim_utils.create_prim(f"/World/Parent/Child_{i}", "Xform", translation=(float(i), 0.0, 0.0), stage=stage) - view = XformPrimView("/World/Parent/Child_.*", device=device) - else: # world_poses or scales - for i in range(num_prims): - sim_utils.create_prim(f"/World/Object_{i}", "Xform", translation=(0.0, 0.0, 0.0), stage=stage) - view = XformPrimView("/World/Object_.*", device=device) - - # Get initial data - if method == "world_poses": - initial_data1, initial_data2 = view.get_world_poses() - elif method == "local_poses": - initial_data1, initial_data2 = view.get_local_poses() - elif method == "scales": - initial_data1 = view.get_scales() - initial_data2 = None - else: # visibility - initial_data1 = view.get_visibility() - initial_data2 = None - - # Prepare indices - target_indices_base = [2, 5, 7] - indices, target_indices = _prepare_indices(index_type, target_indices_base, num_prims, device) - - # Prepare new data - num_to_set = len(target_indices) - if method in ["world_poses", "local_poses"]: - new_data1 = torch.randn(num_to_set, 3, device=device) * 10.0 - new_data2 = torch.tensor([[0.0, 0.0, 0.0, 1.0]] * num_to_set, dtype=torch.float32, device=device) - elif method == "scales": - new_data1 = torch.rand(num_to_set, 3, device=device) * 2.0 + 0.5 - new_data2 = None - else: # visibility - # Set to False to test change (default is True) - new_data1 = torch.zeros(num_to_set, dtype=torch.bool, device=device) - new_data2 = None - - # Set data - if method == "world_poses": - view.set_world_poses(positions=new_data1, orientations=new_data2, indices=indices) # type: ignore[arg-type] - elif method == "local_poses": - view.set_local_poses(translations=new_data1, orientations=new_data2, indices=indices) # type: ignore[arg-type] - elif method == "scales": - view.set_scales(scales=new_data1, indices=indices) # type: ignore[arg-type] - else: # visibility - view.set_visibility(visibility=new_data1, indices=indices) # type: ignore[arg-type] - - # Get all data after update - if method == "world_poses": - updated_data1, updated_data2 = view.get_world_poses() - elif method == "local_poses": - updated_data1, updated_data2 = view.get_local_poses() - elif method == "scales": - updated_data1 = view.get_scales() - updated_data2 = None - else: # visibility - updated_data1 = view.get_visibility() - updated_data2 = None - - # Verify that specified indices were updated - for i, target_idx in enumerate(target_indices): - torch.testing.assert_close(updated_data1[target_idx], new_data1[i], atol=1e-5, rtol=0) - if new_data2 is not None and updated_data2 is not None: - try: - torch.testing.assert_close(updated_data2[target_idx], new_data2[i], atol=1e-5, rtol=0) - except AssertionError: - # Account for quaternion sign ambiguity - torch.testing.assert_close(updated_data2[target_idx], -new_data2[i], atol=1e-5, rtol=0) - - # Verify that other indices were NOT updated (only for non-slice(None) cases) - if index_type != "slice_none": - for i in range(num_prims): - if i not in target_indices: - torch.testing.assert_close(updated_data1[i], initial_data1[i], atol=1e-5, rtol=0) - if initial_data2 is not None and updated_data2 is not None: - try: - torch.testing.assert_close(updated_data2[i], initial_data2[i], atol=1e-5, rtol=0) - except AssertionError: - # Account for quaternion sign ambiguity - torch.testing.assert_close(updated_data2[i], -initial_data2[i], atol=1e-5, rtol=0) - - -@pytest.mark.parametrize("device", ["cpu", "cuda"]) -@pytest.mark.parametrize("backend", ["usd", "fabric"]) -def test_indices_single_element(device, backend): - """Test with a single index.""" - _skip_if_backend_unavailable(backend, device) - - stage = sim_utils.get_current_stage() - prim_type = _prim_type_for_backend(backend) - - # Create prims - num_prims = 5 - for i in range(num_prims): - sim_utils.create_prim(f"/World/Object_{i}", prim_type, translation=(float(i), 0.0, 0.0), stage=stage) - - # Create view - view = _create_view("/World/Object_.*", device=device, backend=backend) - - # Test with single index - indices = [3] - positions, orientations = view.get_world_poses(indices=indices) - - # Verify shapes - assert positions.shape == (1, 3) - assert orientations.shape == (1, 4) - - # Set pose for single index - new_position = torch.tensor([[100.0, 200.0, 300.0]], device=device) - view.set_world_poses(positions=new_position, indices=indices) - - # Verify it was set - retrieved_positions, _ = view.get_world_poses(indices=indices) - torch.testing.assert_close(retrieved_positions, new_position, atol=1e-5, rtol=0) - - -@pytest.mark.parametrize("device", ["cpu", "cuda"]) -@pytest.mark.parametrize("backend", ["usd", "fabric"]) -def test_indices_out_of_order(device, backend): - """Test with indices provided in non-sequential order.""" - _skip_if_backend_unavailable(backend, device) - - stage = sim_utils.get_current_stage() - prim_type = _prim_type_for_backend(backend) + assert torch.all(view.get_visibility()) - # Create prims - num_prims = 10 - for i in range(num_prims): - sim_utils.create_prim(f"/World/Object_{i}", prim_type, translation=(0.0, 0.0, 0.0), stage=stage) - - # Create view - view = _create_view("/World/Object_.*", device=device, backend=backend) - - # Use out-of-order indices - indices = [7, 2, 9, 0, 5] - new_positions = torch.tensor( - [[7.0, 0.0, 0.0], [2.0, 0.0, 0.0], [9.0, 0.0, 0.0], [0.0, 0.0, 0.0], [5.0, 0.0, 0.0]], device=device + view.set_visibility( + torch.tensor([False], dtype=torch.bool, device=device), indices=wp.array([1], dtype=wp.int32, device=device) ) - - # Set poses with out-of-order indices - view.set_world_poses(positions=new_positions, indices=indices) - - # Get all poses - all_positions, _ = view.get_world_poses() - - # Verify each index got the correct value - expected_x_values = [0.0, 0.0, 2.0, 0.0, 0.0, 5.0, 0.0, 7.0, 0.0, 9.0] - for i in range(num_prims): - assert abs(all_positions[i, 0].item() - expected_x_values[i]) < 1e-5 - - -@pytest.mark.parametrize("device", ["cpu", "cuda"]) -@pytest.mark.parametrize("backend", ["usd", "fabric"]) -def test_indices_with_only_positions_or_orientations(device, backend): - """Test indices work correctly when setting only positions or only orientations.""" - _skip_if_backend_unavailable(backend, device) - - stage = sim_utils.get_current_stage() - prim_type = _prim_type_for_backend(backend) - - # Create prims - num_prims = 5 - for i in range(num_prims): - sim_utils.create_prim( - f"/World/Object_{i}", - prim_type, - translation=(0.0, 0.0, 0.0), - orientation=(0.0, 0.0, 0.0, 1.0), - stage=stage, - ) - - # Create view - view = _create_view("/World/Object_.*", device=device, backend=backend) - - # Get initial poses - initial_positions, initial_orientations = view.get_world_poses() - - # Set only positions for specific indices - indices = [1, 3] - new_positions = torch.tensor([[10.0, 0.0, 0.0], [30.0, 0.0, 0.0]], device=device) - view.set_world_poses(positions=new_positions, orientations=None, indices=indices) - - # Get updated poses - updated_positions, updated_orientations = view.get_world_poses() - - # Verify positions updated for indices 1 and 3, others unchanged - torch.testing.assert_close(updated_positions[1], new_positions[0], atol=1e-5, rtol=0) - torch.testing.assert_close(updated_positions[3], new_positions[1], atol=1e-5, rtol=0) - torch.testing.assert_close(updated_positions[0], initial_positions[0], atol=1e-5, rtol=0) - - # Verify all orientations unchanged - try: - torch.testing.assert_close(updated_orientations, initial_orientations, atol=1e-5, rtol=0) - except AssertionError: - torch.testing.assert_close(updated_orientations, -initial_orientations, atol=1e-5, rtol=0) - - # Now set only orientations for different indices - indices2 = [0, 4] - new_orientations = torch.tensor([[0.0, 0.0, 0.7071068, 0.7071068], [0.7071068, 0.0, 0.0, 0.7071068]], device=device) - view.set_world_poses(positions=None, orientations=new_orientations, indices=indices2) - - # Get final poses - final_positions, final_orientations = view.get_world_poses() - - # Verify positions unchanged from previous step - torch.testing.assert_close(final_positions, updated_positions, atol=1e-5, rtol=0) - - # Verify orientations updated for indices 0 and 4 - try: - torch.testing.assert_close(final_orientations[0], new_orientations[0], atol=1e-5, rtol=0) - torch.testing.assert_close(final_orientations[4], new_orientations[1], atol=1e-5, rtol=0) - except AssertionError: - # Account for quaternion sign ambiguity - torch.testing.assert_close(final_orientations[0], -new_orientations[0], atol=1e-5, rtol=0) - torch.testing.assert_close(final_orientations[4], -new_orientations[1], atol=1e-5, rtol=0) + vis = view.get_visibility() + assert vis[0] and not vis[1] and vis[2] @pytest.mark.parametrize("device", ["cpu", "cuda"]) -def test_index_type_none_equivalent_to_all(device): - """Test that indices=None is equivalent to getting/setting all prims.""" +def test_visibility_parent_inheritance(device): + """Making a parent invisible hides all children.""" if device == "cuda" and not torch.cuda.is_available(): pytest.skip("CUDA not available") stage = sim_utils.get_current_stage() + sim_utils.create_prim("/World/Parent", "Xform", stage=stage) + for i in range(4): + sim_utils.create_prim(f"/World/Parent/Child_{i}", "Xform", stage=stage) - # Create prims - num_prims = 6 - for i in range(num_prims): - sim_utils.create_prim(f"/World/Object_{i}", "Xform", translation=(float(i), 0.0, 0.0), stage=stage) - - # Create view - view = XformPrimView("/World/Object_.*", device=device) - - # Get poses with indices=None - pos_none, quat_none = view.get_world_poses(indices=None) - - # Get poses with no argument (default) - pos_default, quat_default = view.get_world_poses() - - # Get poses with slice(None) - pos_slice, quat_slice = view.get_world_poses(indices=slice(None)) # type: ignore[arg-type] - - # All should be equivalent - torch.testing.assert_close(pos_none, pos_default, atol=1e-10, rtol=0) - torch.testing.assert_close(quat_none, quat_default, atol=1e-10, rtol=0) - torch.testing.assert_close(pos_none, pos_slice, atol=1e-10, rtol=0) - torch.testing.assert_close(quat_none, quat_slice, atol=1e-10, rtol=0) - - # Test the same for set operations - new_positions = torch.randn(num_prims, 3, device=device) * 10.0 - new_orientations = torch.tensor([[0.0, 0.0, 0.0, 1.0]] * num_prims, dtype=torch.float32, device=device) - - # Set with indices=None - view.set_world_poses(positions=new_positions, orientations=new_orientations, indices=None) - pos_after_none, quat_after_none = view.get_world_poses() - - # Reset - view.set_world_poses(positions=torch.zeros(num_prims, 3, device=device), indices=None) + parent_view = FrameView("/World/Parent", device=device) + children_view = FrameView("/World/Parent/Child_.*", device=device) - # Set with slice(None) - view.set_world_poses( - positions=new_positions, - orientations=new_orientations, - indices=slice(None), # type: ignore[arg-type] - ) - pos_after_slice, quat_after_slice = view.get_world_poses() + parent_view.set_visibility(torch.tensor([False], dtype=torch.bool, device=device)) + assert not torch.any(children_view.get_visibility()) - # Should be equivalent - torch.testing.assert_close(pos_after_none, pos_after_slice, atol=1e-5, rtol=0) - torch.testing.assert_close(quat_after_none, quat_after_slice, atol=1e-5, rtol=0) + parent_view.set_visibility(torch.tensor([True], dtype=torch.bool, device=device)) + assert torch.all(children_view.get_visibility()) -""" -Tests - Integration. -""" +# ================================================================== +# USD-only: Prim ordering +# ================================================================== @pytest.mark.parametrize("device", ["cpu", "cuda"]) -def test_with_franka_robots(device): - """Test XformPrimView with real Franka robot USD assets.""" +def test_prim_ordering_follows_creation_order(device): + """Prims are returned in USD creation order (DFS), not alphabetical.""" if device == "cuda" and not torch.cuda.is_available(): pytest.skip("CUDA not available") stage = sim_utils.get_current_stage() + num_envs = 3 + for i in range(num_envs): + sim_utils.create_prim(f"/World/Env_{i}/Object_1", "Xform", stage=stage) + sim_utils.create_prim(f"/World/Env_{i}/Object_0", "Xform", stage=stage) + sim_utils.create_prim(f"/World/Env_{i}/Object_A", "Xform", stage=stage) - # Load Franka robot assets - franka_usd_path = f"{ISAAC_NUCLEUS_DIR}/Robots/FrankaRobotics/FrankaPanda/franka.usd" - - # Add two Franka robots to the stage - sim_utils.create_prim("/World/Franka_1", "Xform", usd_path=franka_usd_path, stage=stage) - sim_utils.create_prim("/World/Franka_2", "Xform", usd_path=franka_usd_path, stage=stage) - - # Create view for both Frankas - frankas_view = XformPrimView("/World/Franka_.*", device=device) - - # Verify count - assert frankas_view.count == 2 + view = FrameView("/World/Env_.*/Object_.*", device=device) + expected = [] + for i in range(num_envs): + expected += [f"/World/Env_{i}/Object_1", f"/World/Env_{i}/Object_0", f"/World/Env_{i}/Object_A"] - # Get initial world poses (should be at origin) - initial_positions, initial_orientations = frankas_view.get_world_poses() + assert view.prim_paths == expected - # Verify initial positions are at origin - expected_initial_positions = torch.zeros(2, 3, device=device) - torch.testing.assert_close(initial_positions, expected_initial_positions, atol=1e-5, rtol=0) - # Verify initial orientations are identity - expected_initial_orientations = torch.tensor([[0.0, 0.0, 0.0, 1.0], [0.0, 0.0, 0.0, 1.0]], device=device) - try: - torch.testing.assert_close(initial_orientations, expected_initial_orientations, atol=1e-5, rtol=0) - except AssertionError: - torch.testing.assert_close(initial_orientations, -expected_initial_orientations, atol=1e-5, rtol=0) - - # Set new world poses - new_positions = torch.tensor([[10.0, 10.0, 0.0], [-40.0, -40.0, 0.0]], device=device) - # 90° rotation around Z axis for first, -90° for second - new_orientations = torch.tensor( - [[0.0, 0.0, 0.7071068, 0.7071068], [0.0, 0.0, -0.7071068, 0.7071068]], device=device - ) - - frankas_view.set_world_poses(positions=new_positions, orientations=new_orientations) - - # Get poses back and verify - retrieved_positions, retrieved_orientations = frankas_view.get_world_poses() - - torch.testing.assert_close(retrieved_positions, new_positions, atol=1e-5, rtol=0) - try: - torch.testing.assert_close(retrieved_orientations, new_orientations, atol=1e-5, rtol=0) - except AssertionError: - torch.testing.assert_close(retrieved_orientations, -new_orientations, atol=1e-5, rtol=0) +# ================================================================== +# USD-only: xformOp standardization +# ================================================================== @pytest.mark.parametrize("device", ["cpu", "cuda"]) -def test_with_nested_targets(device): - """Test with nested frame/target structure similar to Isaac Sim tests.""" +def test_standardize_transform_op(device): + """FrameView standardizes a prim with xformOp:transform to translate/orient/scale.""" if device == "cuda" and not torch.cuda.is_available(): pytest.skip("CUDA not available") - stage = sim_utils.get_current_stage() - - # Create frames and targets - for i in range(1, 4): - sim_utils.create_prim(f"/World/Frame_{i}", "Xform", stage=stage) - sim_utils.create_prim(f"/World/Frame_{i}/Target", "Xform", stage=stage) - - # Create views - frames_view = XformPrimView("/World/Frame_.*", device=device) - targets_view = XformPrimView("/World/Frame_.*/Target", device=device) - - assert frames_view.count == 3 - assert targets_view.count == 3 + expected_pos = (3.0, -1.0, 0.5) + matrix = Gf.Matrix4d(1.0) + matrix.SetTranslateOnly(Gf.Vec3d(*expected_pos)) - # Set local poses for frames - frame_translations = torch.tensor([[0.0, 0.0, 0.0], [0.0, 10.0, 5.0], [0.0, 3.0, 5.0]], device=device) - frames_view.set_local_poses(translations=frame_translations) + stage = sim_utils.get_current_stage() + prim = stage.DefinePrim("/World/TransformPrim", "Xform") + UsdGeom.Xformable(prim).AddTransformOp().Set(matrix) - # Set local poses for targets - target_translations = torch.tensor([[0.0, 20.0, 10.0], [0.0, 30.0, 20.0], [0.0, 50.0, 10.0]], device=device) - targets_view.set_local_poses(translations=target_translations) + view = FrameView("/World/TransformPrim", device=device) + assert sim_utils.validate_standard_xform_ops(view.prims[0]) - # Get world poses of targets - world_positions, _ = targets_view.get_world_poses() + ordered_ops = UsdGeom.Xformable(view.prims[0]).GetOrderedXformOps() + op_names = [op.GetOpName() for op in ordered_ops] + assert op_names == ["xformOp:translate", "xformOp:orient", "xformOp:scale"] + assert ordered_ops[0].Get() == Gf.Vec3d(*expected_pos) - # Expected world positions are frame_translation + target_translation - expected_positions = torch.tensor([[0.0, 20.0, 10.0], [0.0, 40.0, 25.0], [0.0, 53.0, 15.0]], device=device) - torch.testing.assert_close(world_positions, expected_positions, atol=1e-5, rtol=0) +# ================================================================== +# USD-only: Nested hierarchy (frame + target) +# ================================================================== @pytest.mark.parametrize("device", ["cpu", "cuda"]) -def test_visibility_with_hierarchy(device): - """Test visibility with parent-child hierarchy and inheritance.""" +def test_nested_hierarchy_world_poses(device): + """World pose of nested child == sum of parent + child translations.""" if device == "cuda" and not torch.cuda.is_available(): pytest.skip("CUDA not available") stage = sim_utils.get_current_stage() + frame_positions = [(0.0, 0.0, 0.0), (0.0, 10.0, 5.0), (0.0, 3.0, 5.0)] + target_positions = [(0.0, 20.0, 10.0), (0.0, 30.0, 20.0), (0.0, 50.0, 10.0)] - # Create parent and children - sim_utils.create_prim("/World/Parent", "Xform", stage=stage) - - num_children = 4 - for i in range(num_children): - sim_utils.create_prim(f"/World/Parent/Child_{i}", "Xform", stage=stage) - - # Create views for both parent and children - parent_view = XformPrimView("/World/Parent", device=device) - children_view = XformPrimView("/World/Parent/Child_.*", device=device) - - # Verify parent and all children are visible initially - parent_visibility = parent_view.get_visibility() - children_visibility = children_view.get_visibility() - assert parent_visibility[0], "Parent should be visible initially" - assert torch.all(children_visibility), "All children should be visible initially" - - # Make some children invisible directly - new_visibility = torch.tensor([True, False, True, False], dtype=torch.bool, device=device) - children_view.set_visibility(new_visibility) - - # Verify the visibility changes - retrieved_visibility = children_view.get_visibility() - torch.testing.assert_close(retrieved_visibility, new_visibility) - - # Make all children visible again - children_view.set_visibility(torch.ones(num_children, dtype=torch.bool, device=device)) - all_visible = children_view.get_visibility() - assert torch.all(all_visible), "All children should be visible again" - - # Now test parent visibility inheritance: - # Make parent invisible - parent_view.set_visibility(torch.tensor([False], dtype=torch.bool, device=device)) - - # Verify parent is invisible - parent_visibility = parent_view.get_visibility() - assert not parent_visibility[0], "Parent should be invisible" + for i in range(3): + sim_utils.create_prim(f"/World/Frame_{i}", "Xform", translation=frame_positions[i], stage=stage) + sim_utils.create_prim(f"/World/Frame_{i}/Target", "Xform", translation=target_positions[i], stage=stage) - # Verify children are also invisible (due to parent being invisible) - children_visibility = children_view.get_visibility() - assert not torch.any(children_visibility), "All children should be invisible when parent is invisible" + frames_view = FrameView("/World/Frame_.*", device=device) + targets_view = FrameView("/World/Frame_.*/Target", device=device) - # Make parent visible again - parent_view.set_visibility(torch.tensor([True], dtype=torch.bool, device=device)) + frames_view.set_local_poses(translations=torch.tensor(frame_positions, device=device)) + targets_view.set_local_poses(translations=torch.tensor(target_positions, device=device)) - # Verify parent is visible - parent_visibility = parent_view.get_visibility() - assert parent_visibility[0], "Parent should be visible again" - - # Verify children are also visible again - children_visibility = children_view.get_visibility() - assert torch.all(children_visibility), "All children should be visible again when parent is visible" + world_pos = targets_view.get_world_poses()[0].torch + expected = torch.tensor( + [[f[j] + t[j] for j in range(3)] for f, t in zip(frame_positions, target_positions)], + device=device, + ) + torch.testing.assert_close(world_pos, expected, atol=1e-5, rtol=0) -""" -Tests - Comparison with Isaac Sim Implementation. -""" +# ================================================================== +# USD-only: Comparison with Isaac Sim +# ================================================================== def test_compare_get_world_poses_with_isaacsim(): """Compare get_world_poses with Isaac Sim's implementation.""" - stage = sim_utils.get_current_stage() - - # Check if Isaac Sim is available if _IsaacSimXformPrimView is None: pytest.skip("Isaac Sim is not available") - # Create prims with various poses + stage = sim_utils.get_current_stage() num_prims = 10 for i in range(num_prims): pos = (i * 2.0, i * 0.5, i * 1.5) - # Vary orientations - if i % 3 == 0: - quat = (0.0, 0.0, 0.0, 1.0) # Identity - elif i % 3 == 1: - quat = (0.0, 0.0, 0.7071068, 0.7071068) # 90 deg around Z - else: - quat = (0.7071068, 0.0, 0.0, 0.7071068) # 90 deg around X + quat = (0.0, 0.0, 0.0, 1.0) if i % 2 == 0 else (0.0, 0.0, 0.7071068, 0.7071068) sim_utils.create_prim(f"/World/Env_{i}/Object", "Xform", translation=pos, orientation=quat, stage=stage) pattern = "/World/Env_.*/Object" - - # Create both views - isaaclab_view = XformPrimView(pattern, device="cpu") + isaaclab_view = FrameView(pattern, device="cpu") isaacsim_view = _IsaacSimXformPrimView(pattern, reset_xform_properties=False) - # Get world poses from both - isaaclab_pos, isaaclab_quat = isaaclab_view.get_world_poses() # xyzw - isaacsim_pos, isaacsim_quat = isaacsim_view.get_world_poses() # wxyz - - # Convert Isaac Sim results to torch tensors if needed + isaaclab_pos = isaaclab_view.get_world_poses()[0].torch + isaacsim_pos, isaacsim_quat = isaacsim_view.get_world_poses() if not isinstance(isaacsim_pos, torch.Tensor): isaacsim_pos = torch.tensor(isaacsim_pos, dtype=torch.float32) - if not isinstance(isaacsim_quat, torch.Tensor): - isaacsim_quat = torch.tensor(isaacsim_quat, dtype=torch.float32).roll(-1, dims=1) - # Compare results torch.testing.assert_close(isaaclab_pos, isaacsim_pos, atol=1e-5, rtol=0) - # Compare quaternions (account for sign ambiguity) - try: - torch.testing.assert_close(isaaclab_quat, isaacsim_quat, atol=1e-5, rtol=0) - except AssertionError: - torch.testing.assert_close(isaaclab_quat, -isaacsim_quat, atol=1e-5, rtol=0) - - -def test_compare_set_world_poses_with_isaacsim(): - """Compare set_world_poses with Isaac Sim's implementation.""" - stage = sim_utils.get_current_stage() - - # Check if Isaac Sim is available - if _IsaacSimXformPrimView is None: - pytest.skip("Isaac Sim is not available") - - # Create prims - num_prims = 8 - for i in range(num_prims): - sim_utils.create_prim(f"/World/Env_{i}/Object", "Xform", translation=(0.0, 0.0, 0.0), stage=stage) - - pattern = "/World/Env_.*/Object" - - # Create both views - isaaclab_view = XformPrimView(pattern, device="cpu") - isaacsim_view = _IsaacSimXformPrimView(pattern, reset_xform_properties=False) - - # Generate new poses - new_positions = torch.randn(num_prims, 3) * 10.0 - new_orientations = torch.tensor([[0.0, 0.0, 0.0, 1.0]] * num_prims, dtype=torch.float32) - - # Set poses using both implementations - isaaclab_view.set_world_poses(new_positions.clone(), new_orientations.clone()) # xyzw - isaacsim_view.set_world_poses(new_positions.clone(), new_orientations.clone().roll(1, dims=1)) # wxyz - - # Get poses back from both - isaaclab_pos, isaaclab_quat = isaaclab_view.get_world_poses() # xyzw - isaacsim_pos, isaacsim_quat = isaacsim_view.get_world_poses() # wxyz - - # Convert Isaac Sim results to torch tensors if needed - if not isinstance(isaacsim_pos, torch.Tensor): - isaacsim_pos = torch.tensor(isaacsim_pos, dtype=torch.float32) - if not isinstance(isaacsim_quat, torch.Tensor): - isaacsim_quat = torch.tensor(isaacsim_quat, dtype=torch.float32).roll(-1, dims=1) - - # Compare results - both implementations should produce the same world poses - torch.testing.assert_close(isaaclab_pos, isaacsim_pos, atol=1e-4, rtol=0) - try: - torch.testing.assert_close(isaaclab_quat, isaacsim_quat, atol=1e-4, rtol=0) - except AssertionError: - torch.testing.assert_close(isaaclab_quat, -isaacsim_quat, atol=1e-4, rtol=0) - - -def test_compare_get_local_poses_with_isaacsim(): - """Compare get_local_poses with Isaac Sim's implementation.""" - stage = sim_utils.get_current_stage() - - # Check if Isaac Sim is available - if _IsaacSimXformPrimView is None: - pytest.skip("Isaac Sim is not available") - - # Create hierarchical prims - num_prims = 5 - for i in range(num_prims): - # Create parent - sim_utils.create_prim(f"/World/Env_{i}", "Xform", translation=(i * 5.0, 0.0, 0.0), stage=stage) - # Create child with local pose - local_pos = (1.0, float(i), 0.0) - local_quat = (0.0, 0.0, 0.0, 1.0) if i % 2 == 0 else (0.0, 0.0, 0.7071068, 0.7071068) - sim_utils.create_prim( - f"/World/Env_{i}/Object", "Xform", translation=local_pos, orientation=local_quat, stage=stage - ) - - pattern = "/World/Env_.*/Object" - - # Create both views - isaaclab_view = XformPrimView(pattern, device="cpu") - isaacsim_view = _IsaacSimXformPrimView(pattern, reset_xform_properties=False) - - # Get local poses from both - isaaclab_trans, isaaclab_quat = isaaclab_view.get_local_poses() - isaacsim_trans, isaacsim_quat = isaacsim_view.get_local_poses() - - # Convert Isaac Sim results to torch tensors if needed - if not isinstance(isaacsim_trans, torch.Tensor): - isaacsim_trans = torch.tensor(isaacsim_trans, dtype=torch.float32) - if not isinstance(isaacsim_quat, torch.Tensor): - isaacsim_quat = torch.tensor(isaacsim_quat, dtype=torch.float32).roll(-1, dims=1) - - # Compare results - torch.testing.assert_close(isaaclab_trans, isaacsim_trans, atol=1e-5, rtol=0) - try: - torch.testing.assert_close(isaaclab_quat, isaacsim_quat, atol=1e-5, rtol=0) - except AssertionError: - torch.testing.assert_close(isaaclab_quat, -isaacsim_quat, atol=1e-5, rtol=0) - - -def test_compare_set_local_poses_with_isaacsim(): - """Compare set_local_poses with Isaac Sim's implementation.""" - stage = sim_utils.get_current_stage() - - # Check if Isaac Sim is available - if _IsaacSimXformPrimView is None: - pytest.skip("Isaac Sim is not available") - - # Create hierarchical prims - num_prims = 6 - for i in range(num_prims): - sim_utils.create_prim(f"/World/Env_{i}", "Xform", translation=(i * 3.0, 0.0, 0.0), stage=stage) - sim_utils.create_prim(f"/World/Env_{i}/Object", "Xform", translation=(0.0, 0.0, 0.0), stage=stage) - - pattern = "/World/Env_.*/Object" - - # Create both views - isaaclab_view = XformPrimView(pattern, device="cpu") - isaacsim_view = _IsaacSimXformPrimView(pattern, reset_xform_properties=False) - - # Generate new local poses - new_translations = torch.randn(num_prims, 3) * 5.0 - new_orientations = torch.tensor( - [[0.0, 0.0, 0.0, 1.0], [0.0, 0.0, 0.7071068, 0.7071068]] * (num_prims // 2), dtype=torch.float32 - ) - # Set local poses using both implementations - isaaclab_view.set_local_poses(new_translations.clone(), new_orientations.clone()) - isaacsim_view.set_local_poses(new_translations.clone(), new_orientations.clone().roll(1, dims=1)) - - # Get local poses back from both - isaaclab_trans, isaaclab_quat = isaaclab_view.get_local_poses() - isaacsim_trans, isaacsim_quat = isaacsim_view.get_local_poses() - - # Convert Isaac Sim results to torch tensors if needed - if not isinstance(isaacsim_trans, torch.Tensor): - isaacsim_trans = torch.tensor(isaacsim_trans, dtype=torch.float32) - if not isinstance(isaacsim_quat, torch.Tensor): - isaacsim_quat = torch.tensor(isaacsim_quat, dtype=torch.float32).roll(-1, dims=1) - - # Compare results - torch.testing.assert_close(isaaclab_trans, isaacsim_trans, atol=1e-4, rtol=0) - try: - torch.testing.assert_close(isaaclab_quat, isaacsim_quat, atol=1e-4, rtol=0) - except AssertionError: - torch.testing.assert_close(isaaclab_quat, -isaacsim_quat, atol=1e-4, rtol=0) - - -""" -Tests - Fabric Operations. -""" - - -@pytest.mark.parametrize("device", ["cpu", "cuda"]) -def test_fabric_initialization(device): - """Test XformPrimView initialization with Fabric enabled.""" - _skip_if_backend_unavailable("fabric", device) - - stage = sim_utils.get_current_stage() - - # Create camera prims (Boundable prims that support Fabric) - num_prims = 5 - for i in range(num_prims): - sim_utils.create_prim(f"/World/Cam_{i}", "Camera", translation=(i * 1.0, 0.0, 1.0), stage=stage) - - # Create view with Fabric enabled - view = _create_view("/World/Cam_.*", device=device, backend="fabric") - - # Verify properties - assert view.count == num_prims - assert view.device == device - assert len(view.prims) == num_prims +# ================================================================== +# USD-only: Franka integration +# ================================================================== @pytest.mark.parametrize("device", ["cpu", "cuda"]) -def test_fabric_usd_consistency(device): - """Test that Fabric round-trip (write→read) is consistent, matching Isaac Sim's design. - - Note: This does NOT test Fabric vs USD reads on initialization, as Fabric is designed - for write-first workflows. Instead, it tests that: - 1. Fabric write→read round-trip works correctly - 2. This matches Isaac Sim's Fabric behavior - """ - _skip_if_backend_unavailable("fabric", device) +def test_with_franka_robots(device): + """Verify FrameView works with real Franka robot USD assets.""" + if device == "cuda" and not torch.cuda.is_available(): + pytest.skip("CUDA not available") stage = sim_utils.get_current_stage() + franka_usd_path = f"{ISAAC_NUCLEUS_DIR}/Robots/FrankaRobotics/FrankaPanda/franka.usd" - # Create prims - num_prims = 5 - for i in range(num_prims): - sim_utils.create_prim( - f"/World/Cam_{i}", - "Camera", - translation=(i * 1.0, 2.0, 3.0), - orientation=(0.0, 0.0, 0.7071068, 0.7071068), - stage=stage, - ) - - # Create Fabric view - view_fabric = _create_view("/World/Cam_.*", device=device, backend="fabric") - - # Test Fabric write→read round-trip (Isaac Sim's intended workflow) - # Initialize Fabric state by WRITING first - init_positions = torch.zeros((num_prims, 3), dtype=torch.float32, device=device) - init_positions[:, 0] = torch.arange(num_prims, dtype=torch.float32, device=device) - init_positions[:, 1] = 2.0 - init_positions[:, 2] = 3.0 - init_orientations = torch.tensor([[0.0, 0.0, 0.7071068, 0.7071068]] * num_prims, dtype=torch.float32, device=device) - - view_fabric.set_world_poses(init_positions, init_orientations) + sim_utils.create_prim("/World/Franka_1", "Xform", usd_path=franka_usd_path, stage=stage) + sim_utils.create_prim("/World/Franka_2", "Xform", usd_path=franka_usd_path, stage=stage) - # Read back from Fabric (should match what we wrote) - pos_fabric, quat_fabric = view_fabric.get_world_poses() - torch.testing.assert_close(pos_fabric, init_positions, atol=1e-4, rtol=0) - torch.testing.assert_close(quat_fabric, init_orientations, atol=1e-4, rtol=0) + view = FrameView("/World/Franka_.*", device=device) + assert view.count == 2 - # Test another round-trip with different values - new_positions = torch.rand((num_prims, 3), dtype=torch.float32, device=device) * 10.0 - new_orientations = torch.tensor([[0.0, 0.0, 0.0, 1.0]] * num_prims, dtype=torch.float32, device=device) + positions = view.get_world_poses()[0].torch + torch.testing.assert_close(positions, torch.zeros(2, 3, device=device), atol=1e-5, rtol=0) - view_fabric.set_world_poses(new_positions, new_orientations) + new_pos = torch.tensor([[10.0, 10.0, 0.0], [-40.0, -40.0, 0.0]], device=device) + new_quat = torch.tensor([[0.0, 0.0, 0.7071068, 0.7071068], [0.0, 0.0, -0.7071068, 0.7071068]], device=device) + view.set_world_poses(positions=new_pos, orientations=new_quat) - # Read back from Fabric (should match) - pos_fabric_after, quat_fabric_after = view_fabric.get_world_poses() - torch.testing.assert_close(pos_fabric_after, new_positions, atol=1e-4, rtol=0) - torch.testing.assert_close(quat_fabric_after, new_orientations, atol=1e-4, rtol=0) + ret_pos = view.get_world_poses()[0].torch + torch.testing.assert_close(ret_pos, new_pos, atol=1e-5, rtol=0) diff --git a/source/isaaclab/test/terrains/check_terrain_importer.py b/source/isaaclab/test/terrains/check_terrain_importer.py index 519f84fc2743..a8229023f90c 100644 --- a/source/isaaclab/test/terrains/check_terrain_importer.py +++ b/source/isaaclab/test/terrains/check_terrain_importer.py @@ -64,10 +64,9 @@ import torch -from isaacsim.core.cloner import GridCloner - import isaaclab.sim as sim_utils import isaaclab.terrains as terrain_gen +from isaaclab import cloner as lab_cloner from isaaclab.sim import SimulationCfg, SimulationContext from isaaclab.terrains.config.rough import ROUGH_TERRAINS_CFG from isaaclab.terrains.terrain_importer import TerrainImporter @@ -86,8 +85,10 @@ def main(): num_balls = 2048 # Create interface to clone the scene - cloner = GridCloner(spacing=2.0, stage=sim.stage) - cloner.define_base_env("/World/envs") + # Create environment clones using Lab's cloner utilities + env_fmt = "/World/envs/env_{}" + env_ids = torch.arange(num_balls, dtype=torch.long, device=sim.device) + env_origins, _ = lab_cloner.grid_transforms(num_balls, spacing=2.0, device=sim.device) # Everything under the namespace "/World/envs/env_0" will be cloned sim_utils.define_prim("/World/envs/env_0") @@ -145,16 +146,15 @@ def main(): mesh_sphere_cfg.func(ball_prim_path, mesh_sphere_cfg, translation=(0.0, 0.0, 0.5)) # Clone the scene - cloner.define_base_env("/World/envs") - envs_prim_paths = cloner.generate_paths("/World/envs/env", num_paths=num_balls) - cloner.clone(source_prim_path="/World/envs/env_0", prim_paths=envs_prim_paths, replicate_physics=True) + envs_prim_paths = [f"/World/envs/env_{i}" for i in range(num_balls)] + lab_cloner.usd_replicate(sim.stage, [env_fmt.format(0)], [env_fmt], env_ids, positions=env_origins) physics_scene_path = sim.cfg.physics.physics_prim_path - cloner.filter_collisions( - physics_scene_path, "/World/collisions", prim_paths=envs_prim_paths, global_paths=["/World/ground"] + lab_cloner.filter_collisions( + sim.stage, physics_scene_path, "/World/collisions", prim_paths=envs_prim_paths, global_paths=["/World/ground"] ) - # Set ball positions over terrain origins using XformPrimView (before simulation starts) - xform_view = sim_utils.XformPrimView("/World/envs/env_.*/ball") + # Set ball positions over terrain origins using FrameView (before simulation starts) + xform_view = sim_utils.FrameView("/World/envs/env_.*/ball") # cache initial state of the balls ball_initial_positions = terrain_importer.env_origins.clone() ball_initial_positions[:, 2] += 5.0 diff --git a/source/isaaclab/test/terrains/test_terrain_importer.py b/source/isaaclab/test/terrains/test_terrain_importer.py index 3951296e978a..5234df4cae51 100644 --- a/source/isaaclab/test/terrains/test_terrain_importer.py +++ b/source/isaaclab/test/terrains/test_terrain_importer.py @@ -20,11 +20,11 @@ import trimesh import warp as wp -from isaacsim.core.cloner import GridCloner -from pxr import Usd, UsdGeom +from pxr import UsdGeom import isaaclab.sim as sim_utils import isaaclab.terrains as terrain_gen +from isaaclab import cloner as lab_cloner from isaaclab.sim import PreviewSurfaceCfg, SimulationContext, build_simulation_context, get_first_matching_child_prim from isaaclab.terrains import TerrainImporter, TerrainImporterCfg from isaaclab.terrains.config.rough import ROUGH_TERRAINS_CFG @@ -34,8 +34,8 @@ @pytest.mark.parametrize("device", ["cuda:0", "cpu"]) @pytest.mark.parametrize("env_spacing", [1.0, 4.325, 8.0]) @pytest.mark.parametrize("num_envs", [1, 4, 125, 379, 1024]) -def test_grid_clone_env_origins(device, env_spacing, num_envs): - """Tests that env origins are consistent when computed using the TerrainImporter and IsaacSim GridCloner.""" +def test_terrain_importer_env_origins(device, env_spacing, num_envs): + """Tests that env origins are consistent when computed using the TerrainImporter and Lab's grid_transforms.""" with build_simulation_context(device=device, auto_add_lighting=True) as sim: sim._app_control_on_stop_handle = None # create terrain importer @@ -50,11 +50,11 @@ def test_grid_clone_env_origins(device, env_spacing, num_envs): # obtain env origins using terrain importer terrain_importer_origins = terrain_importer.env_origins - # obtain env origins using grid cloner - grid_cloner_origins = _obtain_grid_cloner_env_origins(num_envs, env_spacing, stage=sim.stage, device=sim.device) + # obtain env origins using Lab's grid_transforms + lab_grid_origins, _ = lab_cloner.grid_transforms(num_envs, spacing=env_spacing, device=sim.device) # check if the env origins are the same - torch.testing.assert_close(terrain_importer_origins, grid_cloner_origins, rtol=1e-5, atol=1e-5) + torch.testing.assert_close(terrain_importer_origins, lab_grid_origins, rtol=1e-5, atol=1e-5) @pytest.mark.parametrize("device", ["cuda:0", "cpu"]) @@ -240,20 +240,6 @@ def _obtain_collision_mesh(mesh_prim_path: str, mesh_type: Literal["Mesh", "Plan return None -def _obtain_grid_cloner_env_origins(num_envs: int, env_spacing: float, stage: Usd.Stage, device: str) -> torch.Tensor: - """Obtain the env origins generated by IsaacSim GridCloner (grid_cloner.py).""" - # create grid cloner - cloner = GridCloner(spacing=env_spacing, stage=stage) - cloner.define_base_env("/World/envs") - envs_prim_paths = cloner.generate_paths("/World/envs/env", num_paths=num_envs) - # create source prim - stage.DefinePrim("/World/envs/env_0", "Xform") - # clone envs using grid cloner - env_origins = cloner.clone(source_prim_path="/World/envs/env_0", prim_paths=envs_prim_paths, replicate_physics=True) - # return as tensor - return torch.tensor(env_origins, dtype=torch.float32, device=device) - - def _populate_scene(sim: SimulationContext, num_balls: int = 2048, geom_sphere: bool = False): """Create a scene with terrain and randomly spawned balls. @@ -270,9 +256,10 @@ def _populate_scene(sim: SimulationContext, num_balls: int = 2048, geom_sphere: ) terrain_importer = TerrainImporter(terrain_importer_cfg) - # Create interface to clone the scene - cloner = GridCloner(spacing=2.0, stage=sim.stage) - cloner.define_base_env("/World/envs") + # Create environment clones using Lab's cloner utilities + env_fmt = "/World/envs/env_{}" + env_ids = torch.arange(num_balls, dtype=torch.long, device=sim.device) + env_origins, _ = lab_cloner.grid_transforms(num_balls, spacing=2.0, device=sim.device) # Everything under the namespace "/World/envs/env_0" will be cloned sim.stage.DefinePrim("/World/envs/env_0", "Xform") @@ -314,21 +301,16 @@ def _populate_scene(sim: SimulationContext, num_balls: int = 2048, geom_sphere: mesh_sphere_cfg.func(ball_prim_path, mesh_sphere_cfg, translation=(0.0, 0.0, 0.5)) # Clone the scene - cloner.define_base_env("/World/envs") - envs_prim_paths = cloner.generate_paths("/World/envs/env", num_paths=num_balls) - cloner.clone( - source_prim_path="/World/envs/env_0", - prim_paths=envs_prim_paths, - replicate_physics=True, - ) + envs_prim_paths = [f"/World/envs/env_{i}" for i in range(num_balls)] + lab_cloner.usd_replicate(sim.stage, [env_fmt.format(0)], [env_fmt], env_ids, positions=env_origins) physics_scene_path = sim.cfg.physics_prim_path - cloner.filter_collisions( - physics_scene_path, "/World/collisions", prim_paths=envs_prim_paths, global_paths=["/World/ground"] + lab_cloner.filter_collisions( + sim.stage, physics_scene_path, "/World/collisions", prim_paths=envs_prim_paths, global_paths=["/World/ground"] ) # Set ball positions over terrain origins - # Create a view over all the balls using Isaac Lab's XformPrimView - ball_view = sim_utils.XformPrimView("/World/envs/env_.*/ball") + # Create a view over all the balls using Isaac Lab's FrameView + ball_view = sim_utils.FrameView("/World/envs/env_.*/ball") # cache initial state of the balls ball_initial_positions = terrain_importer.env_origins.clone() ball_initial_positions[:, 2] += 5.0 diff --git a/source/isaaclab/test/test_mock_interfaces/test_mock_assets.py b/source/isaaclab/test/test_mock_interfaces/test_mock_assets.py index 61d310e4f20d..a10fe5150ff6 100644 --- a/source/isaaclab/test/test_mock_interfaces/test_mock_assets.py +++ b/source/isaaclab/test/test_mock_interfaces/test_mock_assets.py @@ -55,47 +55,39 @@ def test_joint_state_shapes(self, robot): def test_root_state_shapes(self, robot): """Test root state tensor shapes.""" - import warp as wp - # Link frame - pose is wp.transformf so shape is (4,) but converts to (4, 7) - assert wp.to_torch(robot.data.root_link_pose_w).shape == (4, 7) + assert robot.data.root_link_pose_w.torch.shape == (4, 7) # vel is wp.spatial_vectorf so shape is (4,) but converts to (4, 6) - assert wp.to_torch(robot.data.root_link_vel_w).shape == (4, 6) - assert wp.to_torch(robot.data.root_link_state_w).shape == (4, 13) + assert robot.data.root_link_vel_w.torch.shape == (4, 6) + assert robot.data.root_link_state_w.torch.shape == (4, 13) # Sliced properties - assert wp.to_torch(robot.data.root_link_pos_w).shape == (4, 3) - assert wp.to_torch(robot.data.root_link_quat_w).shape == (4, 4) - assert wp.to_torch(robot.data.root_link_lin_vel_w).shape == (4, 3) - assert wp.to_torch(robot.data.root_link_ang_vel_w).shape == (4, 3) + assert robot.data.root_link_pos_w.torch.shape == (4, 3) + assert robot.data.root_link_quat_w.torch.shape == (4, 4) + assert robot.data.root_link_lin_vel_w.torch.shape == (4, 3) + assert robot.data.root_link_ang_vel_w.torch.shape == (4, 3) def test_body_state_shapes(self, robot): """Test body state tensor shapes.""" - import warp as wp - # body_link_pose_w is wp.transformf so shape is (4, 13) but converts to (4, 13, 7) - assert wp.to_torch(robot.data.body_link_pose_w).shape == (4, 13, 7) + assert robot.data.body_link_pose_w.torch.shape == (4, 13, 7) # body_link_vel_w is wp.spatial_vectorf so shape is (4, 13) but converts to (4, 13, 6) - assert wp.to_torch(robot.data.body_link_vel_w).shape == (4, 13, 6) - assert wp.to_torch(robot.data.body_link_state_w).shape == (4, 13, 13) + assert robot.data.body_link_vel_w.torch.shape == (4, 13, 6) + assert robot.data.body_link_state_w.torch.shape == (4, 13, 13) def test_default_state_shapes(self, robot): """Test default state tensor shapes.""" - import warp as wp - # default_root_pose is wp.transformf so shape is (4,) but converts to (4, 7) - assert wp.to_torch(robot.data.default_root_pose).shape == (4, 7) + assert robot.data.default_root_pose.torch.shape == (4, 7) # default_root_vel is wp.spatial_vectorf so shape is (4,) but converts to (4, 6) - assert wp.to_torch(robot.data.default_root_vel).shape == (4, 6) - assert wp.to_torch(robot.data.default_root_state).shape == (4, 13) + assert robot.data.default_root_vel.torch.shape == (4, 6) + assert robot.data.default_root_state.torch.shape == (4, 13) assert robot.data.default_joint_pos.shape == (4, 12) assert robot.data.default_joint_vel.shape == (4, 12) def test_identity_quaternion_default(self, robot): """Test that default quaternions are identity quaternions.""" - import warp as wp - - quat = wp.to_torch(robot.data.root_link_quat_w) + quat = robot.data.root_link_quat_w.torch # XYZW format: x=y=z=0, w=1 expected = torch.zeros_like(quat) expected[:, 3] = 1.0 # Set w=1 @@ -103,23 +95,19 @@ def test_identity_quaternion_default(self, robot): def test_set_joint_pos(self, robot): """Test setting joint positions.""" - import warp as wp - joint_pos = torch.randn(4, 12) robot.data.set_joint_pos(joint_pos) - assert torch.allclose(wp.to_torch(robot.data.joint_pos), joint_pos) + assert torch.allclose(robot.data.joint_pos.torch, joint_pos) def test_set_mock_data_bulk(self, robot): """Test bulk data setter.""" - import warp as wp - joint_pos = torch.randn(4, 12) joint_vel = torch.randn(4, 12) robot.data.set_mock_data(joint_pos=joint_pos, joint_vel=joint_vel) - assert torch.allclose(wp.to_torch(robot.data.joint_pos), joint_pos) - assert torch.allclose(wp.to_torch(robot.data.joint_vel), joint_vel) + assert torch.allclose(robot.data.joint_pos.torch, joint_pos) + assert torch.allclose(robot.data.joint_vel.torch, joint_vel) def test_find_joints(self): """Test joint finding by regex.""" @@ -163,17 +151,13 @@ def test_find_bodies(self): def test_set_joint_position_target(self, robot): """Test setting joint position targets.""" - import warp as wp - target = torch.randn(4, 12) robot.set_joint_position_target(target) - assert torch.allclose(wp.to_torch(robot.data.joint_pos_target), target) + assert torch.allclose(robot.data.joint_pos_target.torch, target) def test_joint_limits(self, robot): """Test joint limits.""" - import warp as wp - - limits = wp.to_torch(robot.data.joint_pos_limits) + limits = robot.data.joint_pos_limits.torch assert limits.shape == (4, 12, 2) # Default limits should be -inf to inf assert torch.all(limits[..., 0] == float("-inf")) @@ -201,22 +185,18 @@ def test_initialization(self, obj): def test_root_state_shapes(self, obj): """Test root state tensor shapes.""" - import warp as wp - # root_link_pose_w is wp.transformf so shape is (4,) but converts to (4, 7) - assert wp.to_torch(obj.data.root_link_pose_w).shape == (4, 7) + assert obj.data.root_link_pose_w.torch.shape == (4, 7) # root_link_vel_w is wp.spatial_vectorf so shape is (4,) but converts to (4, 6) - assert wp.to_torch(obj.data.root_link_vel_w).shape == (4, 6) - assert wp.to_torch(obj.data.root_link_state_w).shape == (4, 13) + assert obj.data.root_link_vel_w.torch.shape == (4, 6) + assert obj.data.root_link_state_w.torch.shape == (4, 13) def test_body_state_shapes(self, obj): """Test body state tensor shapes (single body).""" - import warp as wp - # body_link_pose_w is wp.transformf so shape is (4, 1) but converts to (4, 1, 7) - assert wp.to_torch(obj.data.body_link_pose_w).shape == (4, 1, 7) + assert obj.data.body_link_pose_w.torch.shape == (4, 1, 7) # body_link_vel_w is wp.spatial_vectorf so shape is (4, 1) but converts to (4, 1, 6) - assert wp.to_torch(obj.data.body_link_vel_w).shape == (4, 1, 6) + assert obj.data.body_link_vel_w.torch.shape == (4, 1, 6) def test_body_properties(self, obj): """Test body property shapes.""" @@ -248,13 +228,11 @@ def test_initialization(self, collection): def test_body_state_shapes(self, collection): """Test body state tensor shapes.""" - import warp as wp - # body_link_pose_w is wp.transformf so shape is (4, 5) but converts to (4, 5, 7) - assert wp.to_torch(collection.data.body_link_pose_w).shape == (4, 5, 7) + assert collection.data.body_link_pose_w.torch.shape == (4, 5, 7) # body_link_vel_w is wp.spatial_vectorf so shape is (4, 5) but converts to (4, 5, 6) - assert wp.to_torch(collection.data.body_link_vel_w).shape == (4, 5, 6) - assert wp.to_torch(collection.data.body_link_state_w).shape == (4, 5, 13) + assert collection.data.body_link_vel_w.torch.shape == (4, 5, 6) + assert collection.data.body_link_state_w.torch.shape == (4, 5, 13) def test_find_bodies_returns_mask(self, collection): """Test that find_bodies returns a mask tensor.""" @@ -301,17 +279,14 @@ def test_create_mock_articulation(self): def test_create_mock_rigid_object(self): """Test rigid object factory function.""" - import warp as wp - obj = create_mock_rigid_object(num_instances=3) assert obj.num_instances == 3 assert obj.num_bodies == 1 # root_link_pose_w is wp.transformf so shape is (3,) but converts to (3, 7) - assert wp.to_torch(obj.data.root_link_pose_w).shape == (3, 7) + assert obj.data.root_link_pose_w.torch.shape == (3, 7) def test_create_mock_rigid_object_collection(self): """Test rigid object collection factory function.""" - import warp as wp collection = create_mock_rigid_object_collection( num_instances=4, @@ -322,7 +297,7 @@ def test_create_mock_rigid_object_collection(self): assert collection.num_bodies == 6 assert collection.body_names == ["obj_0", "obj_1", "obj_2", "obj_3", "obj_4", "obj_5"] # body_link_pose_w is wp.transformf so shape is (4, 6) but converts to (4, 6, 7) - assert wp.to_torch(collection.data.body_link_pose_w).shape == (4, 6, 7) + assert collection.data.body_link_pose_w.torch.shape == (4, 6, 7) # ============================================================================== @@ -349,7 +324,6 @@ def test_basic_build(self): def test_with_default_positions(self): """Test setting default joint positions.""" - import warp as wp default_pos = [0.0, 0.5, -0.5] robot = ( @@ -360,11 +334,10 @@ def test_with_default_positions(self): ) expected = torch.tensor([default_pos, default_pos]) - assert torch.allclose(wp.to_torch(robot.data.joint_pos), expected) + assert torch.allclose(robot.data.joint_pos.torch, expected) def test_with_joint_limits(self): """Test setting joint limits.""" - import warp as wp robot = ( MockArticulationBuilder() @@ -374,6 +347,6 @@ def test_with_joint_limits(self): .build() ) - limits = wp.to_torch(robot.data.joint_pos_limits) + limits = robot.data.joint_pos_limits.torch assert torch.all(limits[..., 0] == -1.0) assert torch.all(limits[..., 1] == 1.0) diff --git a/source/isaaclab/test/test_mock_interfaces/test_mock_data_properties.py b/source/isaaclab/test/test_mock_interfaces/test_mock_data_properties.py index 4411328990af..b68bb8141e1c 100644 --- a/source/isaaclab/test/test_mock_interfaces/test_mock_data_properties.py +++ b/source/isaaclab/test/test_mock_interfaces/test_mock_data_properties.py @@ -7,7 +7,6 @@ import pytest import torch -import warp as wp from isaaclab.test.mock_interfaces.assets import ( MockArticulationData, @@ -18,6 +17,7 @@ MockContactSensorData, MockFrameTransformerData, MockImuData, + MockPvaData, ) # ============================================================================== @@ -26,13 +26,69 @@ class TestMockImuDataProperties: - """Comprehensive tests for all MockImuData properties.""" + """Comprehensive tests for all MockImuData properties. + + MockImuData only provides angular velocity and linear acceleration. + """ @pytest.fixture def data(self): """Create MockImuData fixture.""" return MockImuData(num_instances=4, device="cpu") + @pytest.mark.parametrize( + "property_name,expected_shape", + [ + ("ang_vel_b", (4, 3)), + ("lin_acc_b", (4, 3)), + ], + ) + def test_property_shapes(self, data, property_name, expected_shape): + """Test that all properties return tensors with correct shapes.""" + prop = getattr(data, property_name) + assert prop.torch.shape == expected_shape, f"{property_name} has wrong shape" + + @pytest.mark.parametrize( + "setter_name,property_name,shape", + [ + ("set_ang_vel_b", "ang_vel_b", (4, 3)), + ("set_lin_acc_b", "lin_acc_b", (4, 3)), + ], + ) + def test_setters_update_properties(self, data, setter_name, property_name, shape): + """Test that setters properly update the corresponding properties.""" + + test_value = torch.randn(shape) + setter = getattr(data, setter_name) + setter(test_value) + result = getattr(data, property_name).torch + assert torch.allclose(result, test_value), f"{setter_name} did not update {property_name}" + + def test_bulk_setter(self, data): + """Test that set_mock_data updates multiple properties at once.""" + + ang_vel = torch.randn(4, 3) + lin_acc = torch.randn(4, 3) + + data.set_mock_data(ang_vel_b=ang_vel, lin_acc_b=lin_acc) + + assert torch.allclose(data.ang_vel_b.torch, ang_vel) + assert torch.allclose(data.lin_acc_b.torch, lin_acc) + + +# ============================================================================== +# PVA Data Property Tests +# ============================================================================== + + +class TestMockPvaDataProperties: + """Comprehensive tests for all MockPvaData properties.""" + + @pytest.fixture + def data(self): + """Create MockPvaData fixture.""" + return MockPvaData(num_instances=4, device="cpu") + @pytest.mark.parametrize( "property_name,expected_shape", [ @@ -49,7 +105,7 @@ def data(self): def test_property_shapes(self, data, property_name, expected_shape): """Test that all properties return tensors with correct shapes.""" prop = getattr(data, property_name) - assert wp.to_torch(prop).shape == expected_shape, f"{property_name} has wrong shape" + assert prop.torch.shape == expected_shape, f"{property_name} has wrong shape" @pytest.mark.parametrize( "setter_name,property_name,shape", @@ -65,17 +121,15 @@ def test_property_shapes(self, data, property_name, expected_shape): ) def test_setters_update_properties(self, data, setter_name, property_name, shape): """Test that setters properly update the corresponding properties.""" - import warp as wp test_value = torch.randn(shape) setter = getattr(data, setter_name) setter(test_value) - result = wp.to_torch(getattr(data, property_name)) + result = getattr(data, property_name).torch assert torch.allclose(result, test_value), f"{setter_name} did not update {property_name}" def test_bulk_setter(self, data): """Test that set_mock_data updates multiple properties at once.""" - import warp as wp lin_vel = torch.randn(4, 3) ang_vel = torch.randn(4, 3) @@ -83,23 +137,21 @@ def test_bulk_setter(self, data): data.set_mock_data(lin_vel_b=lin_vel, ang_vel_b=ang_vel, lin_acc_b=lin_acc) - assert torch.allclose(wp.to_torch(data.lin_vel_b), lin_vel) - assert torch.allclose(wp.to_torch(data.ang_vel_b), ang_vel) - assert torch.allclose(wp.to_torch(data.lin_acc_b), lin_acc) + assert torch.allclose(data.lin_vel_b.torch, lin_vel) + assert torch.allclose(data.ang_vel_b.torch, ang_vel) + assert torch.allclose(data.lin_acc_b.torch, lin_acc) def test_default_quaternion_is_identity(self, data): """Test that default quaternion is identity in XYZW format: (x, y, z, w) = (0, 0, 0, 1).""" - import warp as wp - quat = wp.to_torch(data.quat_w) + quat = data.quat_w.torch assert torch.allclose(quat[:, :3], torch.zeros(4, 3)) # xyz=0 assert torch.allclose(quat[:, 3], torch.ones(4)) # w=1 def test_default_gravity_points_down(self, data): """Test that default gravity points in -z direction.""" - import warp as wp - gravity = wp.to_torch(data.projected_gravity_b) + gravity = data.projected_gravity_b.torch expected = torch.tensor([[0, 0, -1]] * 4, dtype=torch.float32) assert torch.allclose(gravity, expected) @@ -170,7 +222,7 @@ def test_optional_property_shapes_with_history(self, data, property_name, expect if property_name == "force_matrix_w_history": assert prop.shape == expected_shape, f"{property_name} has wrong shape" else: - assert wp.to_torch(prop).shape == expected_shape, f"{property_name} has wrong shape" + assert prop.torch.shape == expected_shape, f"{property_name} has wrong shape" def test_optional_properties_none_without_config(self, data_no_history): """Test optional properties are None when not configured.""" @@ -194,12 +246,11 @@ def test_optional_properties_none_without_config(self, data_no_history): ) def test_setters_update_properties(self, data, setter_name, property_name, shape): """Test that setters properly update the corresponding properties.""" - import warp as wp test_value = torch.randn(shape) setter = getattr(data, setter_name) setter(test_value) - result = wp.to_torch(getattr(data, property_name)) + result = getattr(data, property_name).torch assert torch.allclose(result, test_value), f"{setter_name} did not update {property_name}" @@ -238,7 +289,7 @@ def data(self): def test_property_shapes(self, data, property_name, expected_shape): """Test that all properties return tensors with correct shapes.""" prop = getattr(data, property_name) - assert wp.to_torch(prop).shape == expected_shape, f"{property_name} has wrong shape" + assert prop.torch.shape == expected_shape, f"{property_name} has wrong shape" @pytest.mark.parametrize( "setter_name,property_name,shape", @@ -253,12 +304,11 @@ def test_property_shapes(self, data, property_name, expected_shape): ) def test_setters_update_properties(self, data, setter_name, property_name, shape): """Test that setters properly update the corresponding properties.""" - import warp as wp test_value = torch.randn(shape) setter = getattr(data, setter_name) setter(test_value) - result = wp.to_torch(getattr(data, property_name)) + result = getattr(data, property_name).torch assert torch.allclose(result, test_value), f"{setter_name} did not update {property_name}" def test_target_frame_names(self, data): @@ -303,7 +353,7 @@ def data(self): def test_joint_state_shapes(self, data, property_name, expected_shape): """Test joint state properties have correct shapes.""" prop = getattr(data, property_name) - assert wp.to_torch(prop).shape == expected_shape, f"{property_name} has wrong shape" + assert prop.torch.shape == expected_shape, f"{property_name} has wrong shape" # -- Joint Property Shapes -- @pytest.mark.parametrize( @@ -326,7 +376,7 @@ def test_joint_state_shapes(self, data, property_name, expected_shape): def test_joint_property_shapes(self, data, property_name, expected_shape): """Test joint property shapes.""" prop = getattr(data, property_name) - assert wp.to_torch(prop).shape == expected_shape, f"{property_name} has wrong shape" + assert prop.torch.shape == expected_shape, f"{property_name} has wrong shape" # -- Root State Properties -- @pytest.mark.parametrize( @@ -352,7 +402,7 @@ def test_joint_property_shapes(self, data, property_name, expected_shape): def test_root_state_shapes(self, data, property_name, expected_shape): """Test root state properties have correct shapes.""" prop = getattr(data, property_name) - assert wp.to_torch(prop).shape == expected_shape, f"{property_name} has wrong shape" + assert prop.torch.shape == expected_shape, f"{property_name} has wrong shape" # -- Body State Properties -- @pytest.mark.parametrize( @@ -380,7 +430,7 @@ def test_root_state_shapes(self, data, property_name, expected_shape): def test_body_state_shapes(self, data, property_name, expected_shape): """Test body state properties have correct shapes.""" prop = getattr(data, property_name) - assert wp.to_torch(prop).shape == expected_shape, f"{property_name} has wrong shape" + assert prop.torch.shape == expected_shape, f"{property_name} has wrong shape" # -- Body Properties -- @pytest.mark.parametrize( @@ -388,13 +438,12 @@ def test_body_state_shapes(self, data, property_name, expected_shape): [ ("body_mass", (4, 13)), ("body_inertia", (4, 13, 9)), - ("body_incoming_joint_wrench_b", (4, 13, 6)), ], ) def test_body_property_shapes(self, data, property_name, expected_shape): """Test body property shapes.""" prop = getattr(data, property_name) - assert wp.to_torch(prop).shape == expected_shape, f"{property_name} has wrong shape" + assert prop.torch.shape == expected_shape, f"{property_name} has wrong shape" # -- Default State Properties -- @pytest.mark.parametrize( @@ -410,7 +459,7 @@ def test_body_property_shapes(self, data, property_name, expected_shape): def test_default_state_shapes(self, data, property_name, expected_shape): """Test default state properties have correct shapes.""" prop = getattr(data, property_name) - assert wp.to_torch(prop).shape == expected_shape, f"{property_name} has wrong shape" + assert prop.torch.shape == expected_shape, f"{property_name} has wrong shape" # -- Derived Properties -- @pytest.mark.parametrize( @@ -427,7 +476,7 @@ def test_default_state_shapes(self, data, property_name, expected_shape): def test_derived_property_shapes(self, data, property_name, expected_shape): """Test derived properties have correct shapes.""" prop = getattr(data, property_name) - assert wp.to_torch(prop).shape == expected_shape, f"{property_name} has wrong shape" + assert prop.torch.shape == expected_shape, f"{property_name} has wrong shape" # -- Tendon Properties -- @pytest.mark.parametrize( @@ -448,7 +497,7 @@ def test_derived_property_shapes(self, data, property_name, expected_shape): def test_tendon_property_shapes(self, data, property_name, expected_shape): """Test tendon properties have correct shapes.""" prop = getattr(data, property_name) - assert wp.to_torch(prop).shape == expected_shape, f"{property_name} has wrong shape" + assert prop.torch.shape == expected_shape, f"{property_name} has wrong shape" # -- Setter Tests -- @pytest.mark.parametrize( @@ -466,12 +515,11 @@ def test_tendon_property_shapes(self, data, property_name, expected_shape): ) def test_setters_update_properties(self, data, setter_name, property_name, shape): """Test that setters properly update the corresponding properties.""" - import warp as wp test_value = torch.randn(shape) setter = getattr(data, setter_name) setter(test_value) - result = wp.to_torch(getattr(data, property_name)) + result = getattr(data, property_name).torch assert torch.allclose(result, test_value), f"{setter_name} did not update {property_name}" def test_bulk_setter_with_multiple_properties(self, data): @@ -486,9 +534,9 @@ def test_bulk_setter_with_multiple_properties(self, data): root_link_pose_w=root_pose, ) - assert torch.allclose(wp.to_torch(data.joint_pos), joint_pos) - assert torch.allclose(wp.to_torch(data.joint_vel), joint_vel) - assert torch.allclose(wp.to_torch(data.root_link_pose_w), root_pose) + assert torch.allclose(data.joint_pos.torch, joint_pos) + assert torch.allclose(data.joint_vel.torch, joint_vel) + assert torch.allclose(data.root_link_pose_w.torch, root_pose) def test_bulk_setter_unknown_property_raises(self, data): """Test that set_mock_data raises on unknown property.""" @@ -542,7 +590,7 @@ def data(self): def test_property_shapes(self, data, property_name, expected_shape): """Test that all properties return tensors with correct shapes.""" prop = getattr(data, property_name) - assert wp.to_torch(prop).shape == expected_shape, f"{property_name} has wrong shape" + assert prop.torch.shape == expected_shape, f"{property_name} has wrong shape" # ============================================================================== @@ -601,7 +649,7 @@ def data(self): def test_property_shapes(self, data, property_name, expected_shape): """Test that all properties return tensors with correct shapes.""" prop = getattr(data, property_name) - assert wp.to_torch(prop).shape == expected_shape, f"{property_name} has wrong shape" + assert prop.torch.shape == expected_shape, f"{property_name} has wrong shape" # ============================================================================== @@ -615,8 +663,8 @@ class TestDeviceHandling: def test_imu_data_device(self): """Test IMU data tensors are on correct device.""" data = MockImuData(num_instances=2, device="cpu") - assert str(data.pos_w.device) == "cpu" - assert str(data.quat_w.device) == "cpu" + assert str(data.ang_vel_b.device) == "cpu" + assert str(data.lin_acc_b.device) == "cpu" def test_contact_sensor_data_device(self): """Test contact sensor data tensors are on correct device.""" @@ -634,8 +682,8 @@ def test_setter_moves_tensor_to_device(self): data = MockImuData(num_instances=2, device="cpu") # Create tensor on CPU (default) test_tensor = torch.randn(2, 3) - data.set_pos_w(test_tensor) - assert str(data.pos_w.device) == "cpu" + data.set_ang_vel_b(test_tensor) + assert str(data.ang_vel_b.device) == "cpu" # ============================================================================== @@ -646,16 +694,16 @@ def test_setter_moves_tensor_to_device(self): class TestCompositeProperties: """Test that composite properties are correctly composed from components.""" - def test_imu_pose_composition(self): - """Test IMU pose_w is correctly composed from pos_w and quat_w.""" - data = MockImuData(num_instances=2, device="cpu") + def test_pva_pose_composition(self): + """Test PVA pose_w is correctly composed from pos_w and quat_w.""" + data = MockPvaData(num_instances=2, device="cpu") pos = torch.randn(2, 3) quat = torch.tensor([[1, 0, 0, 0], [0.707, 0.707, 0, 0]], dtype=torch.float32) data.set_pos_w(pos) data.set_quat_w(quat) - pose = wp.to_torch(data.pose_w) + pose = data.pose_w.torch assert torch.allclose(pose[:, :3], pos) assert torch.allclose(pose[:, 3:], quat) @@ -668,7 +716,7 @@ def test_articulation_root_state_composition(self): data.set_root_link_pose_w(pose) data.set_root_link_vel_w(vel) - state = wp.to_torch(data.root_link_state_w) + state = data.root_link_state_w.torch assert torch.allclose(state[:, :7], pose) assert torch.allclose(state[:, 7:], vel) @@ -681,7 +729,7 @@ def test_articulation_default_state_composition(self): data.set_default_root_pose(pose) data.set_default_root_vel(vel) - state = wp.to_torch(data.default_root_state) + state = data.default_root_state.torch assert torch.allclose(state[:, :7], pose) assert torch.allclose(state[:, 7:], vel) @@ -723,8 +771,8 @@ def test_root_aliases(self, data, alias, source, expected_shape): """Test root state aliases reference correct properties.""" alias_prop = getattr(data, alias) source_prop = getattr(data, source) - assert wp.to_torch(alias_prop).shape == expected_shape, f"{alias} has wrong shape" - assert torch.allclose(wp.to_torch(alias_prop), wp.to_torch(source_prop)), f"{alias} should equal {source}" + assert alias_prop.torch.shape == expected_shape, f"{alias} has wrong shape" + assert torch.allclose(alias_prop.torch, source_prop.torch), f"{alias} should equal {source}" # -- Body state aliases (without _link_ or _com_ prefix) -- @pytest.mark.parametrize( @@ -746,8 +794,8 @@ def test_body_aliases(self, data, alias, source, expected_shape): """Test body state aliases reference correct properties.""" alias_prop = getattr(data, alias) source_prop = getattr(data, source) - assert wp.to_torch(alias_prop).shape == expected_shape, f"{alias} has wrong shape" - assert torch.allclose(wp.to_torch(alias_prop), wp.to_torch(source_prop)), f"{alias} should equal {source}" + assert alias_prop.torch.shape == expected_shape, f"{alias} has wrong shape" + assert torch.allclose(alias_prop.torch, source_prop.torch), f"{alias} should equal {source}" # -- CoM in body frame -- @pytest.mark.parametrize( @@ -760,7 +808,7 @@ def test_body_aliases(self, data, alias, source, expected_shape): def test_com_body_frame_aliases(self, data, alias, expected_shape): """Test CoM in body frame aliases.""" prop = getattr(data, alias) - assert wp.to_torch(prop).shape == expected_shape, f"{alias} has wrong shape" + assert prop.torch.shape == expected_shape, f"{alias} has wrong shape" # -- Joint property aliases -- @pytest.mark.parametrize( @@ -775,14 +823,14 @@ def test_joint_aliases(self, data, alias, source, expected_shape): """Test joint property aliases.""" alias_prop = getattr(data, alias) source_prop = getattr(data, source) - assert wp.to_torch(alias_prop).shape == expected_shape, f"{alias} has wrong shape" - assert torch.allclose(wp.to_torch(alias_prop), wp.to_torch(source_prop)), f"{alias} should equal {source}" + assert alias_prop.torch.shape == expected_shape, f"{alias} has wrong shape" + assert torch.allclose(alias_prop.torch, source_prop.torch), f"{alias} should equal {source}" # -- Fixed tendon alias -- def test_fixed_tendon_limit_alias(self, data): """Test fixed_tendon_limit is alias for fixed_tendon_pos_limits.""" - assert wp.to_torch(data.fixed_tendon_limit).shape == (4, 2, 2) - assert torch.allclose(wp.to_torch(data.fixed_tendon_limit), wp.to_torch(data.fixed_tendon_pos_limits)) + assert data.fixed_tendon_limit.torch.shape == (4, 2, 2) + assert torch.allclose(data.fixed_tendon_limit.torch, data.fixed_tendon_pos_limits.torch) class TestRigidObjectConvenienceAliases: @@ -820,8 +868,8 @@ def test_aliases(self, data, alias, source, expected_shape): """Test convenience aliases reference correct properties.""" alias_prop = getattr(data, alias) source_prop = getattr(data, source) - assert wp.to_torch(alias_prop).shape == expected_shape, f"{alias} has wrong shape" - assert torch.allclose(wp.to_torch(alias_prop), wp.to_torch(source_prop)), f"{alias} should equal {source}" + assert alias_prop.torch.shape == expected_shape, f"{alias} has wrong shape" + assert torch.allclose(alias_prop.torch, source_prop.torch), f"{alias} should equal {source}" @pytest.mark.parametrize( "alias,expected_shape", @@ -833,7 +881,7 @@ def test_aliases(self, data, alias, source, expected_shape): def test_com_body_frame_aliases(self, data, alias, expected_shape): """Test CoM in body frame aliases.""" prop = getattr(data, alias) - assert wp.to_torch(prop).shape == expected_shape, f"{alias} has wrong shape" + assert prop.torch.shape == expected_shape, f"{alias} has wrong shape" class TestRigidObjectCollectionConvenienceAliases: @@ -850,5 +898,5 @@ def data(self): def test_body_state_w_alias(self, data): """Test body_state_w is alias for body_com_state_w.""" - assert wp.to_torch(data.body_state_w).shape == (4, 5, 13) - assert torch.allclose(wp.to_torch(data.body_state_w), wp.to_torch(data.body_com_state_w)) + assert data.body_state_w.torch.shape == (4, 5, 13) + assert torch.allclose(data.body_state_w.torch, data.body_com_state_w.torch) diff --git a/source/isaaclab/test/test_mock_interfaces/test_mock_sensors.py b/source/isaaclab/test/test_mock_interfaces/test_mock_sensors.py index 04b33cc7f97d..949677f1c398 100644 --- a/source/isaaclab/test/test_mock_interfaces/test_mock_sensors.py +++ b/source/isaaclab/test/test_mock_interfaces/test_mock_sensors.py @@ -13,14 +13,17 @@ import pytest import torch +import warp as wp from isaaclab.test.mock_interfaces.sensors import ( MockContactSensor, MockFrameTransformer, MockImu, + MockPva, create_mock_foot_contact_sensor, create_mock_frame_transformer, create_mock_imu, + create_mock_pva, ) from isaaclab.test.mock_interfaces.utils import MockSensorBuilder @@ -30,7 +33,10 @@ class TestMockImu: - """Tests for MockImu and MockImuData.""" + """Tests for MockImu and MockImuData. + + MockImu only provides angular velocity and linear acceleration. + """ @pytest.fixture def imu(self): @@ -45,65 +51,106 @@ def test_initialization(self, imu): def test_lazy_tensor_initialization(self, imu): """Test that unset properties return zero tensors with correct shapes.""" - import warp as wp + # IMU only has angular velocity and linear acceleration + ang_vel = imu.data.ang_vel_b.torch + assert ang_vel.shape == (4, 3) + assert torch.all(ang_vel == 0) + + lin_acc = imu.data.lin_acc_b.torch + assert lin_acc.shape == (4, 3) + assert torch.all(lin_acc == 0) + + def test_set_mock_data(self, imu): + """Test bulk data setter.""" + ang_vel = torch.randn(4, 3) + lin_acc = torch.randn(4, 3) + + imu.data.set_mock_data(ang_vel_b=ang_vel, lin_acc_b=lin_acc) + + assert torch.allclose(imu.data.ang_vel_b.torch, ang_vel) + assert torch.allclose(imu.data.lin_acc_b.torch, lin_acc) + + def test_per_property_setter(self, imu): + """Test individual property setters.""" + lin_acc = torch.randn(4, 3) + imu.data.set_lin_acc_b(lin_acc) + assert torch.allclose(imu.data.lin_acc_b.torch, lin_acc) + + ang_vel = torch.randn(4, 3) + imu.data.set_ang_vel_b(ang_vel) + assert torch.allclose(imu.data.ang_vel_b.torch, ang_vel) + + +# ============================================================================== +# MockPva Tests +# ============================================================================== + +class TestMockPva: + """Tests for MockPva and MockPvaData.""" + + @pytest.fixture + def pva(self): + """Create a mock PVA fixture.""" + return MockPva(num_instances=4, device="cpu") + + def test_initialization(self, pva): + """Test that MockPva initializes correctly.""" + assert pva.num_instances == 4 + assert pva.device == "cpu" + assert pva.data is not None + + def test_lazy_tensor_initialization(self, pva): + """Test that unset properties return zero tensors with correct shapes.""" # Position - pos = wp.to_torch(imu.data.pos_w) + pos = pva.data.pos_w.torch assert pos.shape == (4, 3) assert torch.all(pos == 0) # Quaternion (should be identity in XYZW format: x=0, y=0, z=0, w=1) - quat = wp.to_torch(imu.data.quat_w) + quat = pva.data.quat_w.torch assert quat.shape == (4, 4) assert torch.all(quat[:, :3] == 0) # xyz components assert torch.all(quat[:, 3] == 1) # w component # Velocities and accelerations - assert imu.data.lin_vel_b.shape == (4, 3) - assert imu.data.ang_vel_b.shape == (4, 3) - assert imu.data.lin_acc_b.shape == (4, 3) - assert imu.data.ang_acc_b.shape == (4, 3) + assert pva.data.lin_vel_b.shape == (4, 3) + assert pva.data.ang_vel_b.shape == (4, 3) + assert pva.data.lin_acc_b.shape == (4, 3) + assert pva.data.ang_acc_b.shape == (4, 3) - def test_projected_gravity_default(self, imu): + def test_projected_gravity_default(self, pva): """Test default gravity direction.""" - import warp as wp - - gravity = wp.to_torch(imu.data.projected_gravity_b) + gravity = pva.data.projected_gravity_b.torch assert gravity.shape == (4, 3) # Default gravity should point down: (0, 0, -1) assert torch.all(gravity[:, 2] == -1) - def test_set_mock_data(self, imu): + def test_set_mock_data(self, pva): """Test bulk data setter.""" - import warp as wp - lin_vel = torch.randn(4, 3) ang_vel = torch.randn(4, 3) - imu.data.set_mock_data(lin_vel_b=lin_vel, ang_vel_b=ang_vel) + pva.data.set_mock_data(lin_vel_b=lin_vel, ang_vel_b=ang_vel) - assert torch.allclose(wp.to_torch(imu.data.lin_vel_b), lin_vel) - assert torch.allclose(wp.to_torch(imu.data.ang_vel_b), ang_vel) + assert torch.allclose(pva.data.lin_vel_b.torch, lin_vel) + assert torch.allclose(pva.data.ang_vel_b.torch, ang_vel) - def test_per_property_setter(self, imu): + def test_per_property_setter(self, pva): """Test individual property setters.""" - import warp as wp - lin_acc = torch.randn(4, 3) - imu.data.set_lin_acc_b(lin_acc) - assert torch.allclose(wp.to_torch(imu.data.lin_acc_b), lin_acc) + pva.data.set_lin_acc_b(lin_acc) + assert torch.allclose(pva.data.lin_acc_b.torch, lin_acc) - def test_pose_composition(self, imu): + def test_pose_composition(self, pva): """Test that pose_w combines pos_w and quat_w correctly.""" - import warp as wp - pos = torch.randn(4, 3) quat = torch.tensor([[0, 0, 0, 1]] * 4, dtype=torch.float32) # XYZW format - imu.data.set_pos_w(pos) - imu.data.set_quat_w(quat) + pva.data.set_pos_w(pos) + pva.data.set_quat_w(quat) - pose = wp.to_torch(imu.data.pose_w) + pose = pva.data.pose_w.torch assert pose.shape == (4, 7) assert torch.allclose(pose[:, :3], pos) assert torch.allclose(pose[:, 3:], quat) @@ -165,7 +212,6 @@ def test_find_bodies(self, sensor): def test_compute_first_contact(self, sensor): """Test first contact computation.""" - import warp as wp # Set contact time to 0.5 for all bodies sensor.data.set_current_contact_time(torch.full((4, 4), 0.5)) @@ -180,7 +226,6 @@ def test_compute_first_contact(self, sensor): def test_compute_first_air(self, sensor): """Test first air computation.""" - import warp as wp sensor.data.set_current_air_time(torch.full((4, 4), 0.2)) @@ -273,7 +318,14 @@ def test_create_mock_imu(self): """Test IMU factory function.""" imu = create_mock_imu(num_instances=4) assert imu.num_instances == 4 - assert imu.data.projected_gravity_b.shape == (4, 3) + assert imu.data.ang_vel_b.shape == (4, 3) + assert imu.data.lin_acc_b.shape == (4, 3) + + def test_create_mock_pva(self): + """Test PVA factory function.""" + pva = create_mock_pva(num_instances=4) + assert pva.num_instances == 4 + assert pva.data.projected_gravity_b.shape == (4, 3) def test_create_mock_foot_contact_sensor(self): """Test foot contact sensor factory function.""" @@ -316,6 +368,11 @@ def test_build_imu_sensor(self): sensor = MockSensorBuilder("imu").with_num_instances(2).build() assert sensor.num_instances == 2 + def test_build_pva_sensor(self): + """Test building a PVA sensor.""" + sensor = MockSensorBuilder("pva").with_num_instances(2).build() + assert sensor.num_instances == 2 + def test_build_frame_transformer(self): """Test building a frame transformer sensor.""" sensor = ( diff --git a/source/isaaclab/test/test_scripts_torcharray_patterns.py b/source/isaaclab/test/test_scripts_torcharray_patterns.py new file mode 100644 index 000000000000..227bbda7be3c --- /dev/null +++ b/source/isaaclab/test/test_scripts_torcharray_patterns.py @@ -0,0 +1,133 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Static scanner ensuring scripts/source do not regress the ProxyArray migration. + +Every public ``.data.`` on an asset or sensor now returns a +:class:`~isaaclab.utils.warp.ProxyArray` (or, for CameraData, a raw +``torch.Tensor``). Legacy conversion or tensor-method callsites on these +properties should migrate to explicit ``.torch`` or ``.warp`` access. These +tests regex-scan user-facing scripts/source files and flag regressions before +they reach users running tutorials or demos. +""" + +from __future__ import annotations + +import re +from pathlib import Path + +import pytest + +# Matches: +# wp.to_torch(.data.) +# where can be , [...], ., .[...], etc. +# Anchored so we don't match tool scripts that document the pattern as prose. +_WP_TO_TORCH_DOT_DATA = re.compile( + r"wp\.to_torch\(\s*" + r"[a-zA-Z_][a-zA-Z_0-9]*" # first name + r"(?:\[[^\]\[]*\]|\.[a-zA-Z_][a-zA-Z_0-9]*)*" # chain of [..] or .name + r"\.data\." # .data. + r"[a-zA-Z_][a-zA-Z_0-9]*" # field + r"\s*\)" +) + +# Matches: +# wp.to_torch(_data.) +# Catches the aliased pattern like ``object_data: RigidObjectData = ...`` followed +# by ``wp.to_torch(object_data.root_pos_w)``. +_WP_TO_TORCH_NAME_DATA = re.compile( + r"wp\.to_torch\(\s*" + r"[a-zA-Z_][a-zA-Z_0-9]*_data\." + r"[a-zA-Z_][a-zA-Z_0-9]*" + r"\s*\)" +) + +# Matches: +# .data..clone() +# .data.[...].clone() +# .data..assign(...) +# These are tensor/wp.array instance methods that ProxyArray intentionally does +# not forward. ``data.output[...]`` is camera data and remains torch-native. +_PROXYARRAY_DIRECT_METHOD_DOT_DATA = re.compile( + r"\.data\." + r"(?!_)" # ignore private backing buffers such as data._sim_bind_... + r"(?!output\b)" # camera output dict is torch-native + r"[a-zA-Z_][a-zA-Z_0-9]*" + r"(?:\[[^\]\[]*\])?" + r"\.(?:clone|assign)\s*\(" +) + +# scripts/tools/wrap_warp_to_torch.py is the migration utility and documents +# the old pattern inside strings. Exclude it from the scan. +_EXCLUDE = {"tools/wrap_warp_to_torch.py"} +_EXCLUDE_PREFIXES = ("source/isaaclab_contrib/",) + + +def _repo_root() -> Path: + # this test lives at source/isaaclab/test/test_scripts_torcharray_patterns.py + # parents[0]=test, [1]=isaaclab, [2]=source, [3]=repo root + return Path(__file__).resolve().parents[3] + + +def _scripts_files() -> list[Path]: + scripts = _repo_root() / "scripts" + return sorted(p for p in scripts.rglob("*.py") if "__pycache__" not in p.parts) + + +def _source_and_scripts_files() -> list[Path]: + roots = [_repo_root() / "scripts", _repo_root() / "source"] + return sorted(p for root in roots for p in root.rglob("*.py") if "__pycache__" not in p.parts) + + +@pytest.mark.parametrize("path", _scripts_files(), ids=lambda p: str(p.relative_to(_repo_root()))) +def test_no_wp_to_torch_on_torcharray_data(path: Path) -> None: + """No ``wp.to_torch(.data.)`` / ``wp.to_torch(_data.)`` in scripts/. + + Post-migration, ``.data.`` returns a ``ProxyArray`` + (or ``torch.Tensor`` for CameraData). The temporary ``wp.to_torch`` + shim is deprecated, so use the ``.torch`` accessor instead (or omit + the wrap entirely for torch-native fields). + """ + rel = path.relative_to(_repo_root()).as_posix() + if any(rel.endswith(suffix) for suffix in _EXCLUDE): + pytest.skip(f"{rel} is excluded from the ProxyArray hygiene scan") + if rel.startswith(_EXCLUDE_PREFIXES): + pytest.skip(f"{rel} is outside the ProxyArray migration scan scope") + + text = path.read_text(encoding="utf-8") + + offenders: list[str] = [] + for i, line in enumerate(text.splitlines(), start=1): + if _WP_TO_TORCH_DOT_DATA.search(line) or _WP_TO_TORCH_NAME_DATA.search(line): + offenders.append(f"{rel}:{i}: {line.rstrip()}") + + if offenders: + pytest.fail( + "Found wp.to_torch(...) calls on a migrated ProxyArray data accessor. " + "Use .torch instead of wp.to_torch(...) (see isaaclab 4.6.15 CHANGELOG).\n" + "\n".join(offenders) + ) + + +@pytest.mark.parametrize("path", _source_and_scripts_files(), ids=lambda p: str(p.relative_to(_repo_root()))) +def test_no_direct_proxyarray_data_methods(path: Path) -> None: + """No direct tensor/wp.array methods on migrated ``.data.`` accessors.""" + rel = path.relative_to(_repo_root()).as_posix() + if any(rel.endswith(suffix) for suffix in _EXCLUDE): + pytest.skip(f"{rel} is excluded from the ProxyArray hygiene scan") + if rel.startswith(_EXCLUDE_PREFIXES): + pytest.skip(f"{rel} is outside the ProxyArray migration scan scope") + + text = path.read_text(encoding="utf-8") + + offenders: list[str] = [] + for i, line in enumerate(text.splitlines(), start=1): + if _PROXYARRAY_DIRECT_METHOD_DOT_DATA.search(line): + offenders.append(f"{rel}:{i}: {line.rstrip()}") + + if offenders: + pytest.fail( + "Found direct tensor/wp.array methods on migrated ProxyArray data accessors. " + "Use .torch.clone() for tensor copies or .warp.assign(...) for warp writes.\n" + "\n".join(offenders) + ) diff --git a/source/isaaclab/test/utils/test_configclass.py b/source/isaaclab/test/utils/test_configclass.py index 716c834cc3e1..60f77367e066 100644 --- a/source/isaaclab/test/utils/test_configclass.py +++ b/source/isaaclab/test/utils/test_configclass.py @@ -1145,3 +1145,66 @@ class ChildCfg(ParentCfg): assert _field_module_dir(child, "class_type") == "some_package.sub_package" # extra should resolve to the child's module dir assert _field_module_dir(child, "extra") == "test_some_feature" + + +# ============================================================================= +# Tests: checked_apply +# ============================================================================= + + +def test_checked_apply_forwards_all_fields(): + """checked_apply forwards every declared field on src onto target.""" + from dataclasses import dataclass as plain_dataclass + + from isaaclab.utils import checked_apply + + @configclass + class WrapperCfg: + gap: float = 0.01 + margin: float = 0.0 + + @plain_dataclass + class UpstreamLike: + gap: float = 99.0 + margin: float = 99.0 + unrelated: str = "keep me" + + src = WrapperCfg(margin=0.005) + target = UpstreamLike() + checked_apply(src, target) + + assert target.gap == 0.01 + assert target.margin == 0.005 + # fields not declared on src are not touched + assert target.unrelated == "keep me" + + +def test_checked_apply_raises_on_missing_target_field(): + """checked_apply fails loudly when target lacks a declared field.""" + from dataclasses import dataclass as plain_dataclass + + from isaaclab.utils import checked_apply + + @configclass + class WrapperCfg: + margin: float = 0.01 + renamed_in_upstream: float = 0.0 + + @plain_dataclass + class UpstreamMissingField: + margin: float = 0.0 + # 'renamed_in_upstream' was renamed/removed upstream + + with pytest.raises(AttributeError, match="renamed_in_upstream"): + checked_apply(WrapperCfg(), UpstreamMissingField()) + + +def test_checked_apply_rejects_non_dataclass_src(): + """checked_apply requires src to be a dataclass.""" + from isaaclab.utils import checked_apply + + class NotADataclass: + margin = 0.01 + + with pytest.raises(TypeError, match="must be a dataclass"): + checked_apply(NotADataclass(), object()) diff --git a/source/isaaclab/test/utils/test_string.py b/source/isaaclab/test/utils/test_string.py index ce443dec705b..22f51ab6f483 100644 --- a/source/isaaclab/test/utils/test_string.py +++ b/source/isaaclab/test/utils/test_string.py @@ -19,6 +19,7 @@ import pytest import isaaclab.utils.string as string_utils +from isaaclab.utils.string import _resolve_matching_names_impl def test_resolvable_string_metadata_is_non_eager(): @@ -251,3 +252,22 @@ def test_resolve_matching_names_values_with_basic_strings_and_preserved_order(): query_names = {"a|c": 1, "b": 0, "f": 2} with pytest.raises(ValueError): _ = string_utils.resolve_matching_names_values(query_names, target_names, preserve_order=True) + + +def test_clear_resolve_matching_names_cache(): + """Clearing the cache discards previously cached entries.""" + target_names = ["a", "b", "c"] + # Populate the cache + string_utils.resolve_matching_names("a", target_names) + info_before = _resolve_matching_names_impl.cache_info() + assert info_before.currsize > 0 + + # Clear the cache + string_utils.clear_resolve_matching_names_cache() + info_after = _resolve_matching_names_impl.cache_info() + assert info_after.currsize == 0 + + # Results are still correct after clearing + idx, names = string_utils.resolve_matching_names("a", target_names) + assert idx == [0] + assert names == ["a"] diff --git a/source/isaaclab/test/utils/test_wrench_composer.py b/source/isaaclab/test/utils/test_wrench_composer.py index 9b7c4aecaf15..cffa927c802b 100644 --- a/source/isaaclab/test/utils/test_wrench_composer.py +++ b/source/isaaclab/test/utils/test_wrench_composer.py @@ -131,11 +131,13 @@ def test_wrench_composer_add_force(device: str, num_envs: int, num_bodies: int): ) forces = wp.from_numpy(forces_np, dtype=wp.vec3f, device=device) # Add forces to wrench composer - wrench_composer.add_forces_and_torques(forces=forces, body_ids=body_ids, env_ids=env_ids) + wrench_composer.add_forces_and_torques_index(forces=forces, body_ids=body_ids, env_ids=env_ids) # Add forces to hand-calculated composed force hand_calculated_composed_force_np[env_ids_np[:, None], body_ids_np[None, :], :] += forces_np + # Compose to body frame before checking output + wrench_composer.compose_to_body_frame() # Get composed force from wrench composer - composed_force_np = wrench_composer.composed_force.numpy() + composed_force_np = wrench_composer.out_force_b.warp.numpy() assert np.allclose(composed_force_np, hand_calculated_composed_force_np, atol=1, rtol=1e-7) @@ -168,18 +170,20 @@ def test_wrench_composer_add_torque(device: str, num_envs: int, num_bodies: int) ) torques = wp.from_numpy(torques_np, dtype=wp.vec3f, device=device) # Add torques to wrench composer - wrench_composer.add_forces_and_torques(torques=torques, body_ids=body_ids, env_ids=env_ids) + wrench_composer.add_forces_and_torques_index(torques=torques, body_ids=body_ids, env_ids=env_ids) # Add torques to hand-calculated composed torque hand_calculated_composed_torque_np[env_ids_np[:, None], body_ids_np[None, :], :] += torques_np + # Compose to body frame before checking output + wrench_composer.compose_to_body_frame() # Get composed torque from wrench composer - composed_torque_np = wrench_composer.composed_torque.numpy() + composed_torque_np = wrench_composer.out_torque_b.warp.numpy() assert np.allclose(composed_torque_np, hand_calculated_composed_torque_np, atol=1, rtol=1e-7) @pytest.mark.parametrize("device", ["cuda:0", "cpu"]) @pytest.mark.parametrize("num_envs", [1, 10, 100, 1000]) @pytest.mark.parametrize("num_bodies", [1, 3, 5, 10]) -def test_add_forces_at_positons(device: str, num_envs: int, num_bodies: int): +def test_add_forces_at_positions(device: str, num_envs: int, num_bodies: int): """Test adding forces at local positions (offset from link frame).""" rng = np.random.default_rng(seed=2) @@ -214,7 +218,7 @@ def test_add_forces_at_positons(device: str, num_envs: int, num_bodies: int): forces = wp.from_numpy(forces_np, dtype=wp.vec3f, device=device) positions = wp.from_numpy(positions_np, dtype=wp.vec3f, device=device) # Add forces at positions to wrench composer - wrench_composer.add_forces_and_torques( + wrench_composer.add_forces_and_torques_index( forces=forces, positions=positions, body_ids=body_ids, env_ids=env_ids ) # Add forces to hand-calculated composed force @@ -225,11 +229,13 @@ def test_add_forces_at_positons(device: str, num_envs: int, num_bodies: int): for j in range(num_bodies_np): hand_calculated_composed_torque_np[env_ids_np[i], body_ids_np[j], :] += torques_from_forces[i, j, :] + # Compose to body frame before checking output + wrench_composer.compose_to_body_frame() # Get composed force from wrench composer - composed_force_np = wrench_composer.composed_force.numpy() + composed_force_np = wrench_composer.out_force_b.warp.numpy() assert np.allclose(composed_force_np, hand_calculated_composed_force_np, atol=1, rtol=1e-7) # Get composed torque from wrench composer - composed_torque_np = wrench_composer.composed_torque.numpy() + composed_torque_np = wrench_composer.out_torque_b.warp.numpy() assert np.allclose(composed_torque_np, hand_calculated_composed_torque_np, atol=1, rtol=1e-7) @@ -267,13 +273,15 @@ def test_add_torques_at_position(device: str, num_envs: int, num_bodies: int): torques = wp.from_numpy(torques_np, dtype=wp.vec3f, device=device) positions = wp.from_numpy(positions_np, dtype=wp.vec3f, device=device) # Add torques at positions to wrench composer - wrench_composer.add_forces_and_torques( + wrench_composer.add_forces_and_torques_index( torques=torques, positions=positions, body_ids=body_ids, env_ids=env_ids ) # Add torques to hand-calculated composed torque hand_calculated_composed_torque_np[env_ids_np[:, None], body_ids_np[None, :], :] += torques_np + # Compose to body frame before checking output + wrench_composer.compose_to_body_frame() # Get composed torque from wrench composer - composed_torque_np = wrench_composer.composed_torque.numpy() + composed_torque_np = wrench_composer.out_torque_b.warp.numpy() assert np.allclose(composed_torque_np, hand_calculated_composed_torque_np, atol=1, rtol=1e-7) @@ -319,7 +327,7 @@ def test_add_forces_and_torques_at_position(device: str, num_envs: int, num_bodi torques = wp.from_numpy(torques_np, dtype=wp.vec3f, device=device) positions = wp.from_numpy(positions_np, dtype=wp.vec3f, device=device) # Add forces and torques at positions to wrench composer - wrench_composer.add_forces_and_torques( + wrench_composer.add_forces_and_torques_index( forces=forces, torques=torques, positions=positions, body_ids=body_ids, env_ids=env_ids ) # Add forces to hand-calculated composed force @@ -330,11 +338,13 @@ def test_add_forces_and_torques_at_position(device: str, num_envs: int, num_bodi for j in range(num_bodies_np): hand_calculated_composed_torque_np[env_ids_np[i], body_ids_np[j], :] += torques_from_forces[i, j, :] hand_calculated_composed_torque_np[env_ids_np[:, None], body_ids_np[None, :], :] += torques_np + # Compose to body frame before checking output + wrench_composer.compose_to_body_frame() # Get composed force from wrench composer - composed_force_np = wrench_composer.composed_force.numpy() + composed_force_np = wrench_composer.out_force_b.warp.numpy() assert np.allclose(composed_force_np, hand_calculated_composed_force_np, atol=1, rtol=1e-7) # Get composed torque from wrench composer - composed_torque_np = wrench_composer.composed_torque.numpy() + composed_torque_np = wrench_composer.out_torque_b.warp.numpy() assert np.allclose(composed_torque_np, hand_calculated_composed_torque_np, atol=1, rtol=1e-7) @@ -368,14 +378,18 @@ def test_wrench_composer_reset(device: str, num_envs: int, num_bodies: int): forces = wp.from_numpy(forces_np, dtype=wp.vec3f, device=device) torques = wp.from_numpy(torques_np, dtype=wp.vec3f, device=device) # Add forces and torques to wrench composer - wrench_composer.add_forces_and_torques(forces=forces, torques=torques, body_ids=body_ids, env_ids=env_ids) + wrench_composer.add_forces_and_torques_index(forces=forces, torques=torques, body_ids=body_ids, env_ids=env_ids) # Reset wrench composer wrench_composer.reset() - # Get composed force and torque from wrench composer - composed_force_np = wrench_composer.composed_force.numpy() - composed_torque_np = wrench_composer.composed_torque.numpy() - assert np.allclose(composed_force_np, np.zeros((num_envs, num_bodies, 3)), atol=1, rtol=1e-7) - assert np.allclose(composed_torque_np, np.zeros((num_envs, num_bodies, 3)), atol=1, rtol=1e-7) + # Check all 7 buffers are zero (5 input + 2 output) + zeros = np.zeros((num_envs, num_bodies, 3), dtype=np.float32) + assert np.allclose(wrench_composer.global_force_w.numpy(), zeros, atol=1, rtol=1e-7) + assert np.allclose(wrench_composer.global_torque_w.numpy(), zeros, atol=1, rtol=1e-7) + assert np.allclose(wrench_composer.global_force_at_com_w.numpy(), zeros, atol=1, rtol=1e-7) + assert np.allclose(wrench_composer.local_force_b.numpy(), zeros, atol=1, rtol=1e-7) + assert np.allclose(wrench_composer.local_torque_b.numpy(), zeros, atol=1, rtol=1e-7) + assert np.allclose(wrench_composer.out_force_b.warp.numpy(), zeros, atol=1, rtol=1e-7) + assert np.allclose(wrench_composer.out_torque_b.warp.numpy(), zeros, atol=1, rtol=1e-7) # ============================================================================ @@ -404,13 +418,22 @@ def test_global_forces_with_rotation(device: str, num_envs: int, num_bodies: int forces_global = wp.from_numpy(forces_global_np, dtype=wp.vec3f, device=device) # Apply global forces - wrench_composer.add_forces_and_torques(forces=forces_global, is_global=True) + wrench_composer.add_forces_and_torques_index(forces=forces_global, is_global=True) # Compute expected local forces by rotating global forces by inverse quaternion expected_forces_local = quat_rotate_inv_np(link_quat_np, forces_global_np) + # Check raw global buffer has the global forces + global_force_np = wrench_composer.global_force_at_com_w.numpy() + assert np.allclose(global_force_np, forces_global_np, atol=1e-4, rtol=1e-5), ( + f"Global force buffer mismatch.\nExpected:\n{forces_global_np}\nGot:\n{global_force_np}" + ) + + # Compose to body frame before checking output + wrench_composer.compose_to_body_frame() + # Verify - composed_force_np = wrench_composer.composed_force.numpy() + composed_force_np = wrench_composer.out_force_b.warp.numpy() assert np.allclose(composed_force_np, expected_forces_local, atol=1e-4, rtol=1e-5), ( f"Global force rotation failed.\nExpected:\n{expected_forces_local}\nGot:\n{composed_force_np}" ) @@ -437,13 +460,22 @@ def test_global_torques_with_rotation(device: str, num_envs: int, num_bodies: in torques_global = wp.from_numpy(torques_global_np, dtype=wp.vec3f, device=device) # Apply global torques - wrench_composer.add_forces_and_torques(torques=torques_global, is_global=True) + wrench_composer.add_forces_and_torques_index(torques=torques_global, is_global=True) # Compute expected local torques expected_torques_local = quat_rotate_inv_np(link_quat_np, torques_global_np) + # Check raw global buffer has the global torques + global_torque_np = wrench_composer.global_torque_w.numpy() + assert np.allclose(global_torque_np, torques_global_np, atol=1e-4, rtol=1e-5), ( + f"Global torque buffer mismatch.\nExpected:\n{torques_global_np}\nGot:\n{global_torque_np}" + ) + + # Compose to body frame before checking output + wrench_composer.compose_to_body_frame() + # Verify - composed_torque_np = wrench_composer.composed_torque.numpy() + composed_torque_np = wrench_composer.out_torque_b.warp.numpy() assert np.allclose(composed_torque_np, expected_torques_local, atol=1e-4, rtol=1e-5), ( f"Global torque rotation failed.\nExpected:\n{expected_torques_local}\nGot:\n{composed_torque_np}" ) @@ -474,32 +506,40 @@ def test_global_forces_at_global_position(device: str, num_envs: int, num_bodies positions_global = wp.from_numpy(positions_global_np, dtype=wp.vec3f, device=device) # Apply global forces at global positions - wrench_composer.add_forces_and_torques(forces=forces_global, positions=positions_global, is_global=True) + wrench_composer.add_forces_and_torques_index(forces=forces_global, positions=positions_global, is_global=True) # Compute expected results: # 1. Force in local frame = quat_rotate_inv(link_quat, global_force) expected_forces_local = quat_rotate_inv_np(link_quat_np, forces_global_np) - # 2. Position offset in local frame = global_position - link_position (then used for torque) + # 2. Torque about CoM in world frame = cross(P_global - link_pos, F_global) + # Then rotate to body frame position_offset_global = positions_global_np - link_pos_np - - # 3. Torque = skew(position_offset_global) @ force_global, then rotate to local expected_torques_local = np.zeros((num_envs, num_bodies, 3), dtype=np.float32) for i in range(num_envs): for j in range(num_bodies): - pos_offset = position_offset_global[i, j] # global frame offset - force_local = expected_forces_local[i, j] # local frame force - # skew(pos_offset) @ force_local - expected_torques_local[i, j] = np.cross(pos_offset, force_local) + torque_w = np.cross(position_offset_global[i, j], forces_global_np[i, j]) + expected_torques_local[i, j] = quat_rotate_inv_np( + link_quat_np[i : i + 1, j : j + 1], torque_w.reshape(1, 1, 3) + )[0, 0] + + # Check raw global force buffer has the global forces + global_force_np = wrench_composer.global_force_w.numpy() + assert np.allclose(global_force_np, forces_global_np, atol=1e-4, rtol=1e-5), ( + f"Global force buffer mismatch.\nExpected:\n{forces_global_np}\nGot:\n{global_force_np}" + ) + + # Compose to body frame before checking output + wrench_composer.compose_to_body_frame() # Verify forces - composed_force_np = wrench_composer.composed_force.numpy() + composed_force_np = wrench_composer.out_force_b.warp.numpy() assert np.allclose(composed_force_np, expected_forces_local, atol=1e-3, rtol=1e-4), ( f"Global force at position failed.\nExpected forces:\n{expected_forces_local}\nGot:\n{composed_force_np}" ) # Verify torques - composed_torque_np = wrench_composer.composed_torque.numpy() + composed_torque_np = wrench_composer.out_torque_b.warp.numpy() assert np.allclose(composed_torque_np, expected_torques_local, atol=1e-3, rtol=1e-4), ( f"Global force at position failed.\nExpected torques:\n{expected_torques_local}\nGot:\n{composed_torque_np}" ) @@ -525,20 +565,24 @@ def test_local_vs_global_identity_quaternion(device: str): torques = wp.from_numpy(torques_np, dtype=wp.vec3f, device=device) # Apply as local - wrench_composer_local.add_forces_and_torques(forces=forces, torques=torques, is_global=False) + wrench_composer_local.add_forces_and_torques_index(forces=forces, torques=torques, is_global=False) # Apply as global (should be same with identity quaternion) - wrench_composer_global.add_forces_and_torques(forces=forces, torques=torques, is_global=True) + wrench_composer_global.add_forces_and_torques_index(forces=forces, torques=torques, is_global=True) + + # Compose to body frame before checking output + wrench_composer_local.compose_to_body_frame() + wrench_composer_global.compose_to_body_frame() # Results should be identical assert np.allclose( - wrench_composer_local.composed_force.numpy(), - wrench_composer_global.composed_force.numpy(), + wrench_composer_local.out_force_b.warp.numpy(), + wrench_composer_global.out_force_b.warp.numpy(), atol=1e-6, ) assert np.allclose( - wrench_composer_local.composed_torque.numpy(), - wrench_composer_global.composed_torque.numpy(), + wrench_composer_local.out_torque_b.warp.numpy(), + wrench_composer_global.out_torque_b.warp.numpy(), atol=1e-6, ) @@ -561,13 +605,16 @@ def test_90_degree_rotation_global_force(device: str): force_global = np.array([[[1.0, 0.0, 0.0]]], dtype=np.float32) force_wp = wp.from_numpy(force_global, dtype=wp.vec3f, device=device) - wrench_composer.add_forces_and_torques(forces=force_wp, is_global=True) + wrench_composer.add_forces_and_torques_index(forces=force_wp, is_global=True) # Expected: After inverse rotation (rotate by -90° around Z), X becomes -Y # Actually, inverse rotation of +90° around Z applied to (1,0,0) gives (0,-1,0) expected_force_local = np.array([[[0.0, -1.0, 0.0]]], dtype=np.float32) - composed_force_np = wrench_composer.composed_force.numpy() + # Compose to body frame before checking output + wrench_composer.compose_to_body_frame() + + composed_force_np = wrench_composer.out_force_b.warp.numpy() assert np.allclose(composed_force_np, expected_force_local, atol=1e-5), ( f"90-degree rotation test failed.\nExpected:\n{expected_force_local}\nGot:\n{composed_force_np}" ) @@ -594,16 +641,25 @@ def test_composition_mixed_local_and_global(device: str): forces_global = wp.from_numpy(forces_global_np, dtype=wp.vec3f, device=device) # Add local forces first - wrench_composer.add_forces_and_torques(forces=forces_local, is_global=False) + wrench_composer.add_forces_and_torques_index(forces=forces_local, is_global=False) # Add global forces - wrench_composer.add_forces_and_torques(forces=forces_global, is_global=True) + wrench_composer.add_forces_and_torques_index(forces=forces_global, is_global=True) # Expected: local forces stay as-is, global forces get rotated, then sum global_forces_in_local = quat_rotate_inv_np(link_quat_np, forces_global_np) expected_total = forces_local_np + global_forces_in_local - composed_force_np = wrench_composer.composed_force.numpy() + # Check raw buffer properties + local_force_np = wrench_composer.local_force_b.numpy() + assert np.allclose(local_force_np, forces_local_np, atol=1e-4, rtol=1e-5) + global_force_at_com_np = wrench_composer.global_force_at_com_w.numpy() + assert np.allclose(global_force_at_com_np, forces_global_np, atol=1e-4, rtol=1e-5) + + # Compose to body frame before checking output + wrench_composer.compose_to_body_frame() + + composed_force_np = wrench_composer.out_force_b.warp.numpy() assert np.allclose(composed_force_np, expected_total, atol=1e-4, rtol=1e-5), ( f"Mixed local/global composition failed.\nExpected:\n{expected_total}\nGot:\n{composed_force_np}" ) @@ -633,15 +689,22 @@ def test_local_forces_at_local_position(device: str, num_envs: int, num_bodies: positions_local = wp.from_numpy(positions_local_np, dtype=wp.vec3f, device=device) # Apply local forces at local positions - wrench_composer.add_forces_and_torques(forces=forces_local, positions=positions_local, is_global=False) + wrench_composer.add_forces_and_torques_index(forces=forces_local, positions=positions_local, is_global=False) # Expected: forces stay as-is, torque = cross(position, force) expected_forces = forces_local_np expected_torques = np.cross(positions_local_np, forces_local_np) + # Check raw local buffer + local_force_np = wrench_composer.local_force_b.numpy() + assert np.allclose(local_force_np, expected_forces, atol=1e-4, rtol=1e-5) + + # Compose to body frame before checking output + wrench_composer.compose_to_body_frame() + # Verify - composed_force_np = wrench_composer.composed_force.numpy() - composed_torque_np = wrench_composer.composed_torque.numpy() + composed_force_np = wrench_composer.out_force_b.warp.numpy() + composed_torque_np = wrench_composer.out_torque_b.warp.numpy() assert np.allclose(composed_force_np, expected_forces, atol=1e-4, rtol=1e-5) assert np.allclose(composed_torque_np, expected_torques, atol=1e-4, rtol=1e-5) @@ -670,14 +733,973 @@ def test_global_force_at_link_origin_no_torque(device: str): positions_at_link = wp.from_numpy(link_pos_np, dtype=wp.vec3f, device=device) # Apply global forces at link origin - wrench_composer.add_forces_and_torques(forces=forces_global, positions=positions_at_link, is_global=True) + wrench_composer.add_forces_and_torques_index(forces=forces_global, positions=positions_at_link, is_global=True) # Expected: force rotated to local, torque = 0 (since position offset is zero) expected_forces = quat_rotate_inv_np(link_quat_np, forces_global_np) expected_torques = np.zeros((num_envs, num_bodies, 3), dtype=np.float32) - composed_force_np = wrench_composer.composed_force.numpy() - composed_torque_np = wrench_composer.composed_torque.numpy() + # Check raw global force buffer + global_force_np = wrench_composer.global_force_w.numpy() + assert np.allclose(global_force_np, forces_global_np, atol=1e-4, rtol=1e-5) + + # Compose to body frame before checking output + wrench_composer.compose_to_body_frame() + + composed_force_np = wrench_composer.out_force_b.warp.numpy() + composed_torque_np = wrench_composer.out_torque_b.warp.numpy() assert np.allclose(composed_force_np, expected_forces, atol=1e-4, rtol=1e-5) assert np.allclose(composed_torque_np, expected_torques, atol=1e-4, rtol=1e-5) + + +# ============================================================================ +# add_raw_buffers_from Tests +# ============================================================================ + + +@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) +@pytest.mark.parametrize("num_envs", [1, 10, 100]) +@pytest.mark.parametrize("num_bodies", [1, 3, 5]) +def test_add_raw_buffers_from(device: str, num_envs: int, num_bodies: int): + """Test that add_raw_buffers_from merges all five input buffers correctly.""" + rng = np.random.default_rng(seed=20) + + # Create two composers with random link poses + link_pos_np = rng.uniform(-10.0, 10.0, (num_envs, num_bodies, 3)).astype(np.float32) + link_quat_np = random_unit_quaternion_np(rng, (num_envs, num_bodies)) + link_pos_torch = torch.from_numpy(link_pos_np) + link_quat_torch = torch.from_numpy(link_quat_np) + + mock_a = create_mock_asset(num_envs, num_bodies, device, link_pos=link_pos_torch, link_quat=link_quat_torch) + mock_b = create_mock_asset(num_envs, num_bodies, device, link_pos=link_pos_torch, link_quat=link_quat_torch) + + composer_a = WrenchComposer(mock_a) + composer_b = WrenchComposer(mock_b) + + # Populate composer_a with local forces at positions + forces_local_a_np = rng.uniform(-50.0, 50.0, (num_envs, num_bodies, 3)).astype(np.float32) + positions_local_a_np = rng.uniform(-5.0, 5.0, (num_envs, num_bodies, 3)).astype(np.float32) + composer_a.add_forces_and_torques_index( + forces=wp.from_numpy(forces_local_a_np, dtype=wp.vec3f, device=device), + positions=wp.from_numpy(positions_local_a_np, dtype=wp.vec3f, device=device), + is_global=False, + ) + + # Populate composer_b with global forces at global positions + forces_global_b_np = rng.uniform(-50.0, 50.0, (num_envs, num_bodies, 3)).astype(np.float32) + positions_global_b_np = rng.uniform(-5.0, 5.0, (num_envs, num_bodies, 3)).astype(np.float32) + composer_b.add_forces_and_torques_index( + forces=wp.from_numpy(forces_global_b_np, dtype=wp.vec3f, device=device), + positions=wp.from_numpy(positions_global_b_np, dtype=wp.vec3f, device=device), + is_global=True, + ) + + # Merge b into a + composer_a.add_raw_buffers_from(composer_b) + + # Build a reference composer that receives both calls directly + mock_ref = create_mock_asset(num_envs, num_bodies, device, link_pos=link_pos_torch, link_quat=link_quat_torch) + composer_ref = WrenchComposer(mock_ref) + composer_ref.add_forces_and_torques_index( + forces=wp.from_numpy(forces_local_a_np, dtype=wp.vec3f, device=device), + positions=wp.from_numpy(positions_local_a_np, dtype=wp.vec3f, device=device), + is_global=False, + ) + composer_ref.add_forces_and_torques_index( + forces=wp.from_numpy(forces_global_b_np, dtype=wp.vec3f, device=device), + positions=wp.from_numpy(positions_global_b_np, dtype=wp.vec3f, device=device), + is_global=True, + ) + + # Compose both and compare + composer_a.compose_to_body_frame() + composer_ref.compose_to_body_frame() + + assert np.allclose( + composer_a.out_force_b.warp.numpy(), composer_ref.out_force_b.warp.numpy(), atol=1e-4, rtol=1e-5 + ), "add_raw_buffers_from force mismatch vs direct accumulation" + assert np.allclose( + composer_a.out_torque_b.warp.numpy(), composer_ref.out_torque_b.warp.numpy(), atol=1e-4, rtol=1e-5 + ), "add_raw_buffers_from torque mismatch vs direct accumulation" + + +@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) +def test_add_raw_buffers_from_inactive_is_noop(device: str): + """Test that add_raw_buffers_from is a no-op when the source composer is inactive.""" + num_envs, num_bodies = 4, 2 + rng = np.random.default_rng(seed=21) + + mock_a = create_mock_asset(num_envs, num_bodies, device) + mock_b = create_mock_asset(num_envs, num_bodies, device) + composer_a = WrenchComposer(mock_a) + composer_b = WrenchComposer(mock_b) + + # Populate composer_a with some forces + forces_np = rng.uniform(-50.0, 50.0, (num_envs, num_bodies, 3)).astype(np.float32) + composer_a.add_forces_and_torques_index( + forces=wp.from_numpy(forces_np, dtype=wp.vec3f, device=device), + ) + + # composer_b is inactive (never written to) + assert not composer_b.active + + # Snapshot composer_a's local buffer before merge + local_force_before = composer_a.local_force_b.numpy().copy() + + # Merge inactive composer_b into composer_a -- should be a no-op + composer_a.add_raw_buffers_from(composer_b) + + assert np.allclose(composer_a.local_force_b.numpy(), local_force_before, atol=1e-7) + + +# ============================================================================ +# Mask-based API Tests +# ============================================================================ + + +@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) +@pytest.mark.parametrize("num_envs", [1, 10, 100]) +@pytest.mark.parametrize("num_bodies", [1, 3, 5]) +def test_add_forces_mask(device: str, num_envs: int, num_bodies: int): + """Test that add_forces_and_torques_mask produces the same result as the index variant.""" + rng = np.random.default_rng(seed=30) + + for _ in range(5): + # Random subset selection + env_select = rng.choice([True, False], size=num_envs, replace=True) + body_select = rng.choice([True, False], size=num_bodies, replace=True) + # Ensure at least one env and body are selected + env_select[0] = True + body_select[0] = True + + env_ids_np = np.where(env_select)[0].astype(np.int32) + body_ids_np = np.where(body_select)[0].astype(np.int32) + env_mask_np = env_select.astype(np.bool_) + body_mask_np = body_select.astype(np.bool_) + + # Random forces for the full grid (mask variant takes full-sized arrays) + forces_full_np = rng.uniform(-100.0, 100.0, (num_envs, num_bodies, 3)).astype(np.float32) + + # Index-based composer + mock_idx = create_mock_asset(num_envs, num_bodies, device) + composer_idx = WrenchComposer(mock_idx) + # Extract the subset for index API + forces_subset_np = forces_full_np[env_ids_np[:, None], body_ids_np[None, :], :] + composer_idx.add_forces_and_torques_index( + forces=wp.from_numpy(forces_subset_np, dtype=wp.vec3f, device=device), + env_ids=wp.from_numpy(env_ids_np, dtype=wp.int32, device=device), + body_ids=wp.from_numpy(body_ids_np, dtype=wp.int32, device=device), + ) + + # Mask-based composer + mock_mask = create_mock_asset(num_envs, num_bodies, device) + composer_mask = WrenchComposer(mock_mask) + composer_mask.add_forces_and_torques_mask( + forces=wp.from_numpy(forces_full_np, dtype=wp.vec3f, device=device), + env_mask=wp.from_numpy(env_mask_np, dtype=wp.bool, device=device), + body_mask=wp.from_numpy(body_mask_np, dtype=wp.bool, device=device), + ) + + # Compose both + composer_idx.compose_to_body_frame() + composer_mask.compose_to_body_frame() + + assert np.allclose( + composer_idx.out_force_b.warp.numpy(), composer_mask.out_force_b.warp.numpy(), atol=1e-4, rtol=1e-5 + ), f"Mask vs index force mismatch (envs={num_envs}, bodies={num_bodies})" + assert np.allclose( + composer_idx.out_torque_b.warp.numpy(), composer_mask.out_torque_b.warp.numpy(), atol=1e-4, rtol=1e-5 + ), f"Mask vs index torque mismatch (envs={num_envs}, bodies={num_bodies})" + + +@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) +@pytest.mark.parametrize("num_envs", [1, 10, 100]) +@pytest.mark.parametrize("num_bodies", [1, 3, 5]) +def test_add_forces_mask_global(device: str, num_envs: int, num_bodies: int): + """Test mask-based API with global forces and positions.""" + rng = np.random.default_rng(seed=31) + + # Random link poses + link_pos_np = rng.uniform(-10.0, 10.0, (num_envs, num_bodies, 3)).astype(np.float32) + link_quat_np = random_unit_quaternion_np(rng, (num_envs, num_bodies)) + link_pos_torch = torch.from_numpy(link_pos_np) + link_quat_torch = torch.from_numpy(link_quat_np) + + # Select all envs and bodies to keep comparison simple + forces_np = rng.uniform(-100.0, 100.0, (num_envs, num_bodies, 3)).astype(np.float32) + positions_np = rng.uniform(-10.0, 10.0, (num_envs, num_bodies, 3)).astype(np.float32) + + # Index-based + mock_idx = create_mock_asset(num_envs, num_bodies, device, link_pos=link_pos_torch, link_quat=link_quat_torch) + composer_idx = WrenchComposer(mock_idx) + composer_idx.add_forces_and_torques_index( + forces=wp.from_numpy(forces_np, dtype=wp.vec3f, device=device), + positions=wp.from_numpy(positions_np, dtype=wp.vec3f, device=device), + is_global=True, + ) + + # Mask-based (all-True masks) + mock_mask = create_mock_asset(num_envs, num_bodies, device, link_pos=link_pos_torch, link_quat=link_quat_torch) + composer_mask = WrenchComposer(mock_mask) + env_mask = wp.from_numpy(np.ones(num_envs, dtype=np.bool_), dtype=wp.bool, device=device) + body_mask = wp.from_numpy(np.ones(num_bodies, dtype=np.bool_), dtype=wp.bool, device=device) + composer_mask.add_forces_and_torques_mask( + forces=wp.from_numpy(forces_np, dtype=wp.vec3f, device=device), + positions=wp.from_numpy(positions_np, dtype=wp.vec3f, device=device), + env_mask=env_mask, + body_mask=body_mask, + is_global=True, + ) + + composer_idx.compose_to_body_frame() + composer_mask.compose_to_body_frame() + + assert np.allclose( + composer_idx.out_force_b.warp.numpy(), composer_mask.out_force_b.warp.numpy(), atol=1e-4, rtol=1e-5 + ), "Mask vs index global force mismatch" + assert np.allclose( + composer_idx.out_torque_b.warp.numpy(), composer_mask.out_torque_b.warp.numpy(), atol=1e-4, rtol=1e-5 + ), "Mask vs index global torque mismatch" + + +# ============================================================================ +# set_forces_and_torques_index Tests +# ============================================================================ + + +@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) +def test_set_forces_overwrites_previous_add(device: str): + """Test that set_forces_and_torques_index clears previously accumulated values.""" + num_envs, num_bodies = 4, 2 + rng = np.random.default_rng(seed=40) + + mock_asset = create_mock_asset(num_envs, num_bodies, device) + composer = WrenchComposer(mock_asset) + + # First accumulate some forces via add + forces_a_np = rng.uniform(-100.0, 100.0, (num_envs, num_bodies, 3)).astype(np.float32) + composer.add_forces_and_torques_index( + forces=wp.from_numpy(forces_a_np, dtype=wp.vec3f, device=device), + ) + + # Now set new forces -- should replace, not accumulate + forces_b_np = rng.uniform(-100.0, 100.0, (num_envs, num_bodies, 3)).astype(np.float32) + composer.set_forces_and_torques_index( + forces=wp.from_numpy(forces_b_np, dtype=wp.vec3f, device=device), + ) + + composer.compose_to_body_frame() + + # Output should match forces_b only (forces_a should be gone) + assert np.allclose(composer.out_force_b.warp.numpy(), forces_b_np, atol=1e-4, rtol=1e-5), ( + "set_forces did not clear previous add" + ) + + +@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) +def test_set_forces_clears_targeted_envs_only(device: str): + """Test that set_forces_and_torques_index clears only the targeted environments.""" + num_envs, num_bodies = 4, 3 + rng = np.random.default_rng(seed=41) + + mock_asset = create_mock_asset(num_envs, num_bodies, device) + composer = WrenchComposer(mock_asset) + + # Add global forces at positions (populates global_force_w and global_torque_w) + forces_global_np = rng.uniform(-50.0, 50.0, (num_envs, num_bodies, 3)).astype(np.float32) + positions_np = rng.uniform(-5.0, 5.0, (num_envs, num_bodies, 3)).astype(np.float32) + composer.add_forces_and_torques_index( + forces=wp.from_numpy(forces_global_np, dtype=wp.vec3f, device=device), + positions=wp.from_numpy(positions_np, dtype=wp.vec3f, device=device), + is_global=True, + ) + + # Also add local torques (populates local_torque_b) + torques_local_np = rng.uniform(-50.0, 50.0, (num_envs, num_bodies, 3)).astype(np.float32) + composer.add_forces_and_torques_index( + torques=wp.from_numpy(torques_local_np, dtype=wp.vec3f, device=device), + is_global=False, + ) + + # Now set local forces for envs [0, 2] -- should clear only envs 0, 2 + env_ids_np = np.array([0, 2], dtype=np.int32) + kept_env_ids = np.array([1, 3], dtype=np.int32) + forces_new_np = rng.uniform(-50.0, 50.0, (2, num_bodies, 3)).astype(np.float32) + composer.set_forces_and_torques_index( + forces=wp.from_numpy(forces_new_np, dtype=wp.vec3f, device=device), + env_ids=wp.from_numpy(env_ids_np, dtype=wp.int32, device=device), + is_global=False, + ) + + zeros = np.zeros((num_bodies, 3), dtype=np.float32) + + # Targeted envs [0, 2]: all buffers cleared, then local_force_b written + for eid in env_ids_np: + assert np.allclose(composer.global_force_w.numpy()[eid], zeros, atol=1e-7), ( + f"global_force_w not cleared for targeted env {eid}" + ) + assert np.allclose(composer.global_torque_w.numpy()[eid], zeros, atol=1e-7), ( + f"global_torque_w not cleared for targeted env {eid}" + ) + assert np.allclose(composer.local_torque_b.numpy()[eid], zeros, atol=1e-7), ( + f"local_torque_b not cleared for targeted env {eid}" + ) + + # Non-targeted envs [1, 3]: should retain original values + for eid in kept_env_ids: + assert np.allclose(composer.global_force_w.numpy()[eid], forces_global_np[eid], atol=1e-4, rtol=1e-5), ( + f"global_force_w changed for non-targeted env {eid}" + ) + assert np.allclose(composer.local_torque_b.numpy()[eid], torques_local_np[eid], atol=1e-4, rtol=1e-5), ( + f"local_torque_b changed for non-targeted env {eid}" + ) + + # local_force_b should have new values at env_ids [0, 2], zeros at [1, 3] + expected_local_force = np.zeros((num_envs, num_bodies, 3), dtype=np.float32) + expected_local_force[env_ids_np] = forces_new_np + assert np.allclose(composer.local_force_b.numpy(), expected_local_force, atol=1e-4, rtol=1e-5), ( + "local_force_b has wrong values after set" + ) + + +# ============================================================================ +# Partial Reset Tests +# ============================================================================ + + +@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) +def test_partial_reset_zeros_only_specified_envs(device: str): + """Test that partial reset zeros only the specified environments and leaves others intact.""" + num_envs, num_bodies = 8, 3 + rng = np.random.default_rng(seed=50) + + mock_asset = create_mock_asset(num_envs, num_bodies, device) + composer = WrenchComposer(mock_asset) + + # Populate all envs with local forces + forces_np = rng.uniform(-100.0, 100.0, (num_envs, num_bodies, 3)).astype(np.float32) + composer.add_forces_and_torques_index( + forces=wp.from_numpy(forces_np, dtype=wp.vec3f, device=device), + ) + + # Also add global forces to populate more buffers + forces_global_np = rng.uniform(-100.0, 100.0, (num_envs, num_bodies, 3)).astype(np.float32) + composer.add_forces_and_torques_index( + forces=wp.from_numpy(forces_global_np, dtype=wp.vec3f, device=device), + is_global=True, + ) + + # Partial reset: only envs [1, 3, 5] + reset_env_ids = np.array([1, 3, 5], dtype=np.int32) + kept_env_ids = np.array([0, 2, 4, 6, 7], dtype=np.int32) + composer.reset(env_ids=wp.from_numpy(reset_env_ids, dtype=wp.int32, device=device)) + + # Reset envs should be zeroed across all input buffers + zeros = np.zeros((num_bodies, 3), dtype=np.float32) + local_force = composer.local_force_b.numpy() + global_force_at_com = composer.global_force_at_com_w.numpy() + for eid in reset_env_ids: + assert np.allclose(local_force[eid], zeros, atol=1e-7), f"local_force_b not zeroed for env {eid}" + assert np.allclose(global_force_at_com[eid], zeros, atol=1e-7), ( + f"global_force_at_com_w not zeroed for env {eid}" + ) + + # Kept envs should retain their values + for eid in kept_env_ids: + assert np.allclose(local_force[eid], forces_np[eid], atol=1e-4, rtol=1e-5), ( + f"local_force_b changed for non-reset env {eid}" + ) + assert np.allclose(global_force_at_com[eid], forces_global_np[eid], atol=1e-4, rtol=1e-5), ( + f"global_force_at_com_w changed for non-reset env {eid}" + ) + + # Flags: _active should still be True, _dirty should be True + assert composer.active + assert composer._dirty + + +@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) +def test_full_reset_clears_active_flag(device: str): + """Test that full reset (no args) clears the _active flag.""" + num_envs, num_bodies = 4, 2 + + mock_asset = create_mock_asset(num_envs, num_bodies, device) + composer = WrenchComposer(mock_asset) + + forces_np = np.ones((num_envs, num_bodies, 3), dtype=np.float32) + composer.add_forces_and_torques_index( + forces=wp.from_numpy(forces_np, dtype=wp.vec3f, device=device), + ) + assert composer.active + + composer.reset() + assert not composer.active + assert not composer._dirty + + +# ============================================================================ +# Deprecated API Backward-Compatibility Tests +# ============================================================================ + + +@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) +def test_composed_force_emits_deprecation_warning(device: str): + """Test that accessing composed_force emits a DeprecationWarning.""" + num_envs, num_bodies = 2, 1 + + mock_asset = create_mock_asset(num_envs, num_bodies, device) + composer = WrenchComposer(mock_asset) + + forces_np = np.array([[[1.0, 2.0, 3.0]], [[4.0, 5.0, 6.0]]], dtype=np.float32) + composer.add_forces_and_torques_index( + forces=wp.from_numpy(forces_np, dtype=wp.vec3f, device=device), + ) + + with pytest.warns(DeprecationWarning, match="composed_force.*is deprecated"): + result = composer.composed_force + + # Should return the same data as out_force_b + assert np.allclose(result.warp.numpy(), composer.out_force_b.warp.numpy(), atol=1e-7) + + +@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) +def test_composed_torque_emits_deprecation_warning(device: str): + """Test that accessing composed_torque emits a DeprecationWarning.""" + num_envs, num_bodies = 2, 1 + + mock_asset = create_mock_asset(num_envs, num_bodies, device) + composer = WrenchComposer(mock_asset) + + torques_np = np.array([[[1.0, 2.0, 3.0]], [[4.0, 5.0, 6.0]]], dtype=np.float32) + composer.add_forces_and_torques_index( + torques=wp.from_numpy(torques_np, dtype=wp.vec3f, device=device), + ) + + with pytest.warns(DeprecationWarning, match="composed_torque.*is deprecated"): + result = composer.composed_torque + + assert np.allclose(result.warp.numpy(), composer.out_torque_b.warp.numpy(), atol=1e-7) + + +@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) +def test_deprecated_add_forces_and_torques_emits_warning(device: str): + """Test that the deprecated add_forces_and_torques wrapper emits a warning and works.""" + num_envs, num_bodies = 4, 2 + rng = np.random.default_rng(seed=52) + + mock_asset = create_mock_asset(num_envs, num_bodies, device) + composer = WrenchComposer(mock_asset) + + forces_np = rng.uniform(-50.0, 50.0, (num_envs, num_bodies, 3)).astype(np.float32) + + with pytest.warns(DeprecationWarning, match="add_forces_and_torques.*is deprecated"): + composer.add_forces_and_torques( + forces=wp.from_numpy(forces_np, dtype=wp.vec3f, device=device), + ) + + composer.compose_to_body_frame() + assert np.allclose(composer.out_force_b.warp.numpy(), forces_np, atol=1e-4, rtol=1e-5) + + +# ============================================================================ +# set_forces_and_torques_mask Tests +# ============================================================================ + + +@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) +def test_set_forces_mask_overwrites_previous_add(device: str): + """Test that set_forces_and_torques_mask clears previously accumulated values.""" + num_envs, num_bodies = 4, 2 + rng = np.random.default_rng(seed=60) + + mock_asset = create_mock_asset(num_envs, num_bodies, device) + composer = WrenchComposer(mock_asset) + + # Accumulate some forces via add + forces_a_np = rng.uniform(-100.0, 100.0, (num_envs, num_bodies, 3)).astype(np.float32) + composer.add_forces_and_torques_index( + forces=wp.from_numpy(forces_a_np, dtype=wp.vec3f, device=device), + ) + + # Now set new forces via mask -- should replace, not accumulate + forces_b_np = rng.uniform(-100.0, 100.0, (num_envs, num_bodies, 3)).astype(np.float32) + composer.set_forces_and_torques_mask( + forces=wp.from_numpy(forces_b_np, dtype=wp.vec3f, device=device), + ) + + composer.compose_to_body_frame() + + # Output should match forces_b only (forces_a should be gone) + assert np.allclose(composer.out_force_b.warp.numpy(), forces_b_np, atol=1e-4, rtol=1e-5), ( + "set_forces_and_torques_mask did not clear previous add" + ) + + +@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) +def test_set_forces_mask_clears_targeted_envs_only(device: str): + """Test that set_forces_and_torques_mask clears only the masked environments.""" + num_envs, num_bodies = 4, 3 + rng = np.random.default_rng(seed=61) + + mock_asset = create_mock_asset(num_envs, num_bodies, device) + composer = WrenchComposer(mock_asset) + + # Populate global buffers for all envs + forces_global_np = rng.uniform(-50.0, 50.0, (num_envs, num_bodies, 3)).astype(np.float32) + positions_np = rng.uniform(-5.0, 5.0, (num_envs, num_bodies, 3)).astype(np.float32) + composer.add_forces_and_torques_index( + forces=wp.from_numpy(forces_global_np, dtype=wp.vec3f, device=device), + positions=wp.from_numpy(positions_np, dtype=wp.vec3f, device=device), + is_global=True, + ) + + # Also add local torques for all envs + torques_local_np = rng.uniform(-50.0, 50.0, (num_envs, num_bodies, 3)).astype(np.float32) + composer.add_forces_and_torques_index( + torques=wp.from_numpy(torques_local_np, dtype=wp.vec3f, device=device), + is_global=False, + ) + + # Set local forces via mask for envs [0, 2] -- should clear only masked envs + env_mask_np = np.array([True, False, True, False], dtype=np.bool_) + body_mask_np = np.array([True, True, False], dtype=np.bool_) + forces_new_np = rng.uniform(-50.0, 50.0, (num_envs, num_bodies, 3)).astype(np.float32) + composer.set_forces_and_torques_mask( + forces=wp.from_numpy(forces_new_np, dtype=wp.vec3f, device=device), + env_mask=wp.from_numpy(env_mask_np, dtype=wp.bool, device=device), + body_mask=wp.from_numpy(body_mask_np, dtype=wp.bool, device=device), + is_global=False, + ) + + zeros = np.zeros((num_bodies, 3), dtype=np.float32) + + # Masked envs [0, 2]: all buffers cleared by reset, then local_force_b written where body_mask is True + for eid in [0, 2]: + assert np.allclose(composer.global_force_w.numpy()[eid], zeros, atol=1e-7), ( + f"global_force_w not cleared for masked env {eid}" + ) + assert np.allclose(composer.global_torque_w.numpy()[eid], zeros, atol=1e-7), ( + f"global_torque_w not cleared for masked env {eid}" + ) + assert np.allclose(composer.local_torque_b.numpy()[eid], zeros, atol=1e-7), ( + f"local_torque_b not cleared for masked env {eid}" + ) + + # Non-masked envs [1, 3]: should retain original values + for eid in [1, 3]: + assert np.allclose(composer.global_force_w.numpy()[eid], forces_global_np[eid], atol=1e-4, rtol=1e-5), ( + f"global_force_w changed for non-masked env {eid}" + ) + assert np.allclose(composer.local_torque_b.numpy()[eid], torques_local_np[eid], atol=1e-4, rtol=1e-5), ( + f"local_torque_b changed for non-masked env {eid}" + ) + + # local_force_b should have new values where both masks are True, zeros for masked envs otherwise + expected_local_force = np.zeros((num_envs, num_bodies, 3), dtype=np.float32) + for e in range(num_envs): + for b in range(num_bodies): + if env_mask_np[e] and body_mask_np[b]: + expected_local_force[e, b] = forces_new_np[e, b] + assert np.allclose(composer.local_force_b.numpy(), expected_local_force, atol=1e-4, rtol=1e-5), ( + "local_force_b has wrong values after mask set" + ) + + +@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) +def test_set_forces_mask_matches_set_forces_index(device: str): + """Test that set_forces_and_torques_mask produces the same result as the index variant.""" + num_envs, num_bodies = 6, 3 + rng = np.random.default_rng(seed=62) + + # Random link poses + link_pos_np = rng.uniform(-10.0, 10.0, (num_envs, num_bodies, 3)).astype(np.float32) + link_quat_np = random_unit_quaternion_np(rng, (num_envs, num_bodies)) + link_pos_torch = torch.from_numpy(link_pos_np) + link_quat_torch = torch.from_numpy(link_quat_np) + + # Use all envs/bodies to compare + forces_np = rng.uniform(-100.0, 100.0, (num_envs, num_bodies, 3)).astype(np.float32) + positions_np = rng.uniform(-10.0, 10.0, (num_envs, num_bodies, 3)).astype(np.float32) + + # Index-based + mock_idx = create_mock_asset(num_envs, num_bodies, device, link_pos=link_pos_torch, link_quat=link_quat_torch) + composer_idx = WrenchComposer(mock_idx) + composer_idx.set_forces_and_torques_index( + forces=wp.from_numpy(forces_np, dtype=wp.vec3f, device=device), + positions=wp.from_numpy(positions_np, dtype=wp.vec3f, device=device), + is_global=True, + ) + + # Mask-based (all-True) + mock_mask = create_mock_asset(num_envs, num_bodies, device, link_pos=link_pos_torch, link_quat=link_quat_torch) + composer_mask = WrenchComposer(mock_mask) + composer_mask.set_forces_and_torques_mask( + forces=wp.from_numpy(forces_np, dtype=wp.vec3f, device=device), + positions=wp.from_numpy(positions_np, dtype=wp.vec3f, device=device), + is_global=True, + ) + + composer_idx.compose_to_body_frame() + composer_mask.compose_to_body_frame() + + assert np.allclose( + composer_idx.out_force_b.warp.numpy(), composer_mask.out_force_b.warp.numpy(), atol=1e-4, rtol=1e-5 + ), "set mask vs index force mismatch" + assert np.allclose( + composer_idx.out_torque_b.warp.numpy(), composer_mask.out_torque_b.warp.numpy(), atol=1e-4, rtol=1e-5 + ), "set mask vs index torque mismatch" + + +# ============================================================================ +# Lazy Composition (_ensure_composed) Tests +# ============================================================================ + + +@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) +def test_out_force_b_triggers_lazy_composition(device: str): + """Test that accessing out_force_b without explicit compose_to_body_frame still returns correct results.""" + num_envs, num_bodies = 4, 2 + rng = np.random.default_rng(seed=70) + + link_quat_np = random_unit_quaternion_np(rng, (num_envs, num_bodies)) + link_quat_torch = torch.from_numpy(link_quat_np) + + mock_asset = create_mock_asset(num_envs, num_bodies, device, link_quat=link_quat_torch) + composer = WrenchComposer(mock_asset) + + forces_global_np = rng.uniform(-100.0, 100.0, (num_envs, num_bodies, 3)).astype(np.float32) + composer.add_forces_and_torques_index( + forces=wp.from_numpy(forces_global_np, dtype=wp.vec3f, device=device), + is_global=True, + ) + + # Do NOT call compose_to_body_frame -- rely on lazy composition + expected_forces_local = quat_rotate_inv_np(link_quat_np, forces_global_np) + composed_force_np = composer.out_force_b.warp.numpy() + + assert np.allclose(composed_force_np, expected_forces_local, atol=1e-4, rtol=1e-5), ( + "Lazy composition via out_force_b failed" + ) + + +@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) +def test_out_torque_b_triggers_lazy_composition(device: str): + """Test that accessing out_torque_b without explicit compose_to_body_frame still returns correct results.""" + num_envs, num_bodies = 4, 2 + rng = np.random.default_rng(seed=71) + + link_quat_np = random_unit_quaternion_np(rng, (num_envs, num_bodies)) + link_quat_torch = torch.from_numpy(link_quat_np) + + mock_asset = create_mock_asset(num_envs, num_bodies, device, link_quat=link_quat_torch) + composer = WrenchComposer(mock_asset) + + torques_global_np = rng.uniform(-100.0, 100.0, (num_envs, num_bodies, 3)).astype(np.float32) + composer.add_forces_and_torques_index( + torques=wp.from_numpy(torques_global_np, dtype=wp.vec3f, device=device), + is_global=True, + ) + + # Do NOT call compose_to_body_frame -- rely on lazy composition + expected_torques_local = quat_rotate_inv_np(link_quat_np, torques_global_np) + composed_torque_np = composer.out_torque_b.warp.numpy() + + assert np.allclose(composed_torque_np, expected_torques_local, atol=1e-4, rtol=1e-5), ( + "Lazy composition via out_torque_b failed" + ) + + +@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) +def test_lazy_composition_tracks_dirty_flag(device: str): + """Test that the dirty flag is correctly managed through add/compose/add cycles.""" + num_envs, num_bodies = 2, 1 + + mock_asset = create_mock_asset(num_envs, num_bodies, device) + composer = WrenchComposer(mock_asset) + + # Initially clean + assert not composer._dirty + + # After add, dirty + forces_np = np.ones((num_envs, num_bodies, 3), dtype=np.float32) + composer.add_forces_and_torques_index( + forces=wp.from_numpy(forces_np, dtype=wp.vec3f, device=device), + ) + assert composer._dirty + + # After accessing out_force_b, clean (lazy compose happened) + _ = composer.out_force_b + assert not composer._dirty + + # After another add, dirty again + composer.add_forces_and_torques_index( + forces=wp.from_numpy(forces_np, dtype=wp.vec3f, device=device), + ) + assert composer._dirty + + # Accessing out_torque_b also triggers composition + _ = composer.out_torque_b + assert not composer._dirty + + # Verify accumulated result (2x forces) + expected = 2.0 * forces_np + assert np.allclose(composer.out_force_b.warp.numpy(), expected, atol=1e-4, rtol=1e-5) + + +@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) +def test_compose_is_idempotent(device: str): + """Calling compose_to_body_frame twice without intervening writes produces the same result.""" + rng = np.random.default_rng(seed=456) + num_envs, num_bodies = 4, 3 + + # Non-trivial link pose so the rotation path is exercised + link_pos_np = rng.uniform(-2, 2, (num_envs, num_bodies, 3)).astype(np.float32) + link_quat_np = rng.standard_normal((num_envs, num_bodies, 4)).astype(np.float32) + link_quat_np /= np.linalg.norm(link_quat_np, axis=-1, keepdims=True) + + mock_asset = create_mock_asset( + num_envs, + num_bodies, + device, + link_pos=torch.from_numpy(link_pos_np), + link_quat=torch.from_numpy(link_quat_np), + ) + composer = WrenchComposer(mock_asset) + + # Add global forces with positions (exercises cross-product torque path) + forces_np = rng.uniform(-5, 5, (num_envs, num_bodies, 3)).astype(np.float32) + positions_np = rng.uniform(-1, 1, (num_envs, num_bodies, 3)).astype(np.float32) + torques_np = rng.uniform(-3, 3, (num_envs, num_bodies, 3)).astype(np.float32) + + composer.add_forces_and_torques_index( + forces=wp.from_numpy(forces_np, dtype=wp.vec3f, device=device), + torques=wp.from_numpy(torques_np, dtype=wp.vec3f, device=device), + positions=wp.from_numpy(positions_np, dtype=wp.vec3f, device=device), + is_global=True, + ) + + # First compose + composer.compose_to_body_frame() + force_first = composer.out_force_b.warp.numpy().copy() + torque_first = composer.out_torque_b.warp.numpy().copy() + + # Second compose (no writes in between) + composer.compose_to_body_frame() + force_second = composer.out_force_b.warp.numpy() + torque_second = composer.out_torque_b.warp.numpy() + + np.testing.assert_array_equal(force_first, force_second) + np.testing.assert_array_equal(torque_first, torque_second) + + +# ============================================================================ +# CoM Offset from Link Origin Tests +# ============================================================================ + + +@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) +def test_global_force_with_com_offset(device: str): + """Test that torque correction uses CoM position, not link position, when they differ.""" + num_envs, num_bodies = 2, 1 + + # Link at origin, CoM offset by [1, 0, 0] + link_pos_np = np.zeros((num_envs, num_bodies, 3), dtype=np.float32) + link_quat_np = np.zeros((num_envs, num_bodies, 4), dtype=np.float32) + link_quat_np[..., 3] = 1.0 # identity quaternion (xyzw) + + com_pos_np = np.zeros((num_envs, num_bodies, 3), dtype=np.float32) + com_pos_np[..., 0] = 1.0 # CoM at [1, 0, 0] + + mock_asset = create_mock_asset( + num_envs, + num_bodies, + device, + link_pos=torch.from_numpy(link_pos_np), + link_quat=torch.from_numpy(link_quat_np), + ) + # Set CoM pose separately (pos=[1,0,0], quat=identity) + com_pose = torch.cat([torch.from_numpy(com_pos_np), torch.from_numpy(link_quat_np)], dim=-1) + mock_asset.data.set_body_com_pose_w(com_pose) + + composer = WrenchComposer(mock_asset) + + # Apply global force [0, 0, 10] at position [0, 0, 0] (world origin) + forces_np = np.zeros((num_envs, num_bodies, 3), dtype=np.float32) + forces_np[..., 2] = 10.0 + positions_np = np.zeros((num_envs, num_bodies, 3), dtype=np.float32) + + composer.add_forces_and_torques_index( + forces=wp.from_numpy(forces_np, dtype=wp.vec3f, device=device), + positions=wp.from_numpy(positions_np, dtype=wp.vec3f, device=device), + is_global=True, + ) + + composer.compose_to_body_frame() + + # With identity quaternion: + # torque_w = cross(P, F) - cross(com, F) = cross([0,0,0], [0,0,10]) - cross([1,0,0], [0,0,10]) + # = [0,0,0] - [0*10-0*0, 0*0-1*10, 1*0-0*0] = [0,0,0] - [0, -10, 0] = [0, 10, 0] + # In body frame (identity rotation): [0, 10, 0] + expected_torque = np.zeros((num_envs, num_bodies, 3), dtype=np.float32) + expected_torque[..., 1] = 10.0 + + actual_torque = composer.out_torque_b.warp.numpy() + assert np.allclose(actual_torque, expected_torque, atol=1e-4, rtol=1e-5), ( + f"CoM offset torque correction failed.\nExpected:\n{expected_torque}\nGot:\n{actual_torque}" + ) + + # Force should be unchanged (identity rotation) + assert np.allclose(composer.out_force_b.warp.numpy(), forces_np, atol=1e-4, rtol=1e-5) + + +@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) +def test_global_force_at_com_no_torque_with_com_offset(device: str): + """Test that a global force at CoM position produces zero torque even with CoM offset.""" + num_envs, num_bodies = 2, 1 + + # Link at origin, CoM offset by [2, 3, 0] + link_pos_np = np.zeros((num_envs, num_bodies, 3), dtype=np.float32) + link_quat_np = np.zeros((num_envs, num_bodies, 4), dtype=np.float32) + link_quat_np[..., 3] = 1.0 + + com_pos_np = np.zeros((num_envs, num_bodies, 3), dtype=np.float32) + com_pos_np[..., 0] = 2.0 + com_pos_np[..., 1] = 3.0 + + mock_asset = create_mock_asset( + num_envs, + num_bodies, + device, + link_pos=torch.from_numpy(link_pos_np), + link_quat=torch.from_numpy(link_quat_np), + ) + com_pose = torch.cat([torch.from_numpy(com_pos_np), torch.from_numpy(link_quat_np)], dim=-1) + mock_asset.data.set_body_com_pose_w(com_pose) + + composer = WrenchComposer(mock_asset) + + # Apply global force at the CoM position + forces_np = np.zeros((num_envs, num_bodies, 3), dtype=np.float32) + forces_np[..., 2] = 50.0 + positions_np = com_pos_np.copy() + + composer.add_forces_and_torques_index( + forces=wp.from_numpy(forces_np, dtype=wp.vec3f, device=device), + positions=wp.from_numpy(positions_np, dtype=wp.vec3f, device=device), + is_global=True, + ) + + composer.compose_to_body_frame() + + # Torque = cross(com, F) - cross(com, F) = 0 + expected_torque = np.zeros((num_envs, num_bodies, 3), dtype=np.float32) + assert np.allclose(composer.out_torque_b.warp.numpy(), expected_torque, atol=1e-4, rtol=1e-5), ( + "Force at CoM should produce zero torque regardless of CoM offset" + ) + + +@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) +def test_com_offset_with_rotation(device: str): + """Test torque correction with both CoM offset and non-identity rotation.""" + num_envs, num_bodies = 1, 1 + rng = np.random.default_rng(seed=73) + + # Random rotation + link_quat_np = random_unit_quaternion_np(rng, (num_envs, num_bodies)) + link_pos_np = rng.uniform(-5.0, 5.0, (num_envs, num_bodies, 3)).astype(np.float32) + + # CoM offset from link + com_offset_np = rng.uniform(0.5, 2.0, (num_envs, num_bodies, 3)).astype(np.float32) + com_pos_np = link_pos_np + com_offset_np # simple world-frame offset for test clarity + + mock_asset = create_mock_asset( + num_envs, + num_bodies, + device, + link_pos=torch.from_numpy(link_pos_np), + link_quat=torch.from_numpy(link_quat_np), + ) + com_pose = torch.cat([torch.from_numpy(com_pos_np), torch.from_numpy(link_quat_np)], dim=-1) + mock_asset.data.set_body_com_pose_w(com_pose) + + composer = WrenchComposer(mock_asset) + + # Apply global force at a random world position + forces_np = rng.uniform(-100.0, 100.0, (num_envs, num_bodies, 3)).astype(np.float32) + positions_np = rng.uniform(-10.0, 10.0, (num_envs, num_bodies, 3)).astype(np.float32) + + composer.add_forces_and_torques_index( + forces=wp.from_numpy(forces_np, dtype=wp.vec3f, device=device), + positions=wp.from_numpy(positions_np, dtype=wp.vec3f, device=device), + is_global=True, + ) + + composer.compose_to_body_frame() + + # Expected: torque_w = cross(P, F) - cross(com, F) = cross(P - com, F) + lever_arm = positions_np - com_pos_np + torque_w = np.cross(lever_arm, forces_np) + expected_torque_b = quat_rotate_inv_np(link_quat_np, torque_w) + expected_force_b = quat_rotate_inv_np(link_quat_np, forces_np) + + assert np.allclose(composer.out_force_b.warp.numpy(), expected_force_b, atol=1e-3, rtol=1e-4), ( + "Force mismatch with CoM offset + rotation" + ) + assert np.allclose(composer.out_torque_b.warp.numpy(), expected_torque_b, atol=1e-3, rtol=1e-4), ( + f"Torque mismatch with CoM offset + rotation.\n" + f"Expected:\n{expected_torque_b}\nGot:\n{composer.out_torque_b.warp.numpy()}" + ) + + +# ============================================================================ +# Deprecated set_forces_and_torques Tests +# ============================================================================ + + +@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) +def test_deprecated_set_forces_and_torques_emits_warning(device: str): + """Test that the deprecated set_forces_and_torques wrapper emits a warning and works.""" + num_envs, num_bodies = 4, 2 + rng = np.random.default_rng(seed=80) + + mock_asset = create_mock_asset(num_envs, num_bodies, device) + composer = WrenchComposer(mock_asset) + + forces_np = rng.uniform(-50.0, 50.0, (num_envs, num_bodies, 3)).astype(np.float32) + + with pytest.warns(DeprecationWarning, match="set_forces_and_torques.*is deprecated"): + composer.set_forces_and_torques( + forces=wp.from_numpy(forces_np, dtype=wp.vec3f, device=device), + ) + + composer.compose_to_body_frame() + assert np.allclose(composer.out_force_b.warp.numpy(), forces_np, atol=1e-4, rtol=1e-5) + + +@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) +def test_deprecated_set_forces_and_torques_clears_previous(device: str): + """Test that deprecated set_forces_and_torques actually replaces previous values.""" + num_envs, num_bodies = 4, 2 + rng = np.random.default_rng(seed=81) + + mock_asset = create_mock_asset(num_envs, num_bodies, device) + composer = WrenchComposer(mock_asset) + + # First add some forces + forces_a_np = rng.uniform(-50.0, 50.0, (num_envs, num_bodies, 3)).astype(np.float32) + composer.add_forces_and_torques_index( + forces=wp.from_numpy(forces_a_np, dtype=wp.vec3f, device=device), + ) + + # Then set via deprecated method -- should replace + forces_b_np = rng.uniform(-50.0, 50.0, (num_envs, num_bodies, 3)).astype(np.float32) + with pytest.warns(DeprecationWarning): + composer.set_forces_and_torques( + forces=wp.from_numpy(forces_b_np, dtype=wp.vec3f, device=device), + ) + + composer.compose_to_body_frame() + assert np.allclose(composer.out_force_b.warp.numpy(), forces_b_np, atol=1e-4, rtol=1e-5), ( + "Deprecated set_forces_and_torques did not replace previous values" + ) diff --git a/source/isaaclab/test/utils/test_wrench_composer_integration.py b/source/isaaclab/test/utils/test_wrench_composer_integration.py new file mode 100644 index 000000000000..bb195e856030 --- /dev/null +++ b/source/isaaclab/test/utils/test_wrench_composer_integration.py @@ -0,0 +1,817 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Integration tests for wrench composer with rigid objects. + +These tests validate that global forces/torques remain invariant under body rotation +""" + +"""Launch Isaac Sim Simulator first.""" + +from isaaclab.app import AppLauncher + +# launch omniverse app +simulation_app = AppLauncher(headless=True).app + +"""Rest everything follows.""" + +import pytest +import torch +import warp as wp + +import isaaclab.sim as sim_utils +from isaaclab.assets import RigidObject, RigidObjectCfg +from isaaclab.sim import build_simulation_context +from isaaclab.utils.assets import ISAAC_NUCLEUS_DIR + + +def generate_cubes_scene( + num_cubes: int = 1, + height: float = 1.0, + device: str = "cuda:0", +) -> tuple[RigidObject, torch.Tensor]: + """Generate a scene with the provided number of cubes.""" + origins = torch.tensor([(i * 1.0, 0, height) for i in range(num_cubes)]).to(device) + for i, origin in enumerate(origins): + sim_utils.create_prim(f"/World/Table_{i}", "Xform", translation=origin) + + spawn_cfg = sim_utils.UsdFileCfg( + usd_path=f"{ISAAC_NUCLEUS_DIR}/Props/Blocks/DexCube/dex_cube_instanceable.usd", + rigid_props=sim_utils.RigidBodyPropertiesCfg(), + ) + + cube_object_cfg = RigidObjectCfg( + prim_path="/World/Table_.*/Object", + spawn=spawn_cfg, + init_state=RigidObjectCfg.InitialStateCfg(pos=(0.0, 0.0, height)), + ) + cube_object = RigidObject(cfg=cube_object_cfg) + return cube_object, origins + + +N_STEPS = 100 +FORCE_MAGNITUDE = 10.0 +TORQUE_MAGNITUDE = 1.0 + + +@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) +def test_global_force_invariant_under_rotation(device): + """Test that a permanent global force produces the same acceleration before and after body rotation. + + A global +X force is applied. After 100 steps the body is rotated 180deg about Z. + The acceleration (delta_v per phase) should be the same in both phases because the + force is in the global frame and should not rotate with the body. + """ + with build_simulation_context(device=device, gravity_enabled=False, auto_add_lighting=True) as sim: + sim._app_control_on_stop_handle = None + cube_object, _ = generate_cubes_scene(num_cubes=1, device=device) + + sim.reset() + + body_ids, _ = cube_object.find_bodies(".*") + mass = float(wp.to_torch(cube_object.root_view.get_masses())[0]) + com = cube_object.data.body_com_pos_w.torch.clone() + + # Apply permanent global force along +X at CoM + forces = torch.zeros(1, len(body_ids), 3, device=device) + forces[..., 0] = FORCE_MAGNITUDE + torques = torch.zeros(1, len(body_ids), 3, device=device) + + cube_object.permanent_wrench_composer.set_forces_and_torques( + forces=forces, + torques=torques, + positions=com, + body_ids=body_ids, + is_global=True, + ) + + # Phase 1: run N_STEPS + for _ in range(N_STEPS): + cube_object.write_data_to_sim() + sim.step() + cube_object.update(sim.cfg.dt) + + vel_after_phase1 = cube_object.data.root_lin_vel_w.torch[0].clone() + + # Rotate body 180deg about Z (quat wxyz = [0, 0, 0, 1]) while keeping velocity + root_pose = cube_object.data.root_state_w.torch[0, :7].clone().unsqueeze(0) + root_pose[0, 3:7] = torch.tensor([0.0, 0.0, 1.0, 0.0], device=device) # 180deg about Z (xyzw) + cube_object.write_root_pose_to_sim(root_pose) + + # Phase 2: run N_STEPS more + for _ in range(N_STEPS): + cube_object.write_data_to_sim() + sim.step() + cube_object.update(sim.cfg.dt) + + vel_after_phase2 = cube_object.data.root_lin_vel_w.torch[0].clone() + + # Acceleration should be same in both phases: delta_v_phase2 ≈ delta_v_phase1 + delta_v_phase1 = vel_after_phase1[0].item() # vx after phase 1 + delta_v_phase2 = vel_after_phase2[0].item() - vel_after_phase1[0].item() # vx gained in phase 2 + + expected_dv = FORCE_MAGNITUDE / mass * sim.cfg.dt * N_STEPS + + torch.testing.assert_close( + torch.tensor(delta_v_phase1), + torch.tensor(expected_dv), + rtol=0.001, + atol=0.0001, + ) + torch.testing.assert_close( + torch.tensor(delta_v_phase2), + torch.tensor(expected_dv), + rtol=0.001, + atol=0.0001, + ) + + # Y and Z velocity should remain ~0 + assert abs(vel_after_phase2[1].item()) < 0.5, f"Unexpected Y velocity: {vel_after_phase2[1].item()}" + assert abs(vel_after_phase2[2].item()) < 0.5, f"Unexpected Z velocity: {vel_after_phase2[2].item()}" + + +@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) +def test_local_force_follows_rotation(device): + """Test that a permanent local force rotates with the body. + + A local +X force is applied. After 100 steps the body is rotated 180deg about Z. + Since local +X is now world -X, the force should decelerate the body back towards zero velocity. + """ + with build_simulation_context(device=device, gravity_enabled=False, auto_add_lighting=True) as sim: + sim._app_control_on_stop_handle = None + cube_object, _ = generate_cubes_scene(num_cubes=1, device=device) + + sim.reset() + + body_ids, _ = cube_object.find_bodies(".*") + + # Apply permanent local force along body +X + forces = torch.zeros(1, len(body_ids), 3, device=device) + forces[..., 0] = FORCE_MAGNITUDE + torques = torch.zeros(1, len(body_ids), 3, device=device) + + cube_object.permanent_wrench_composer.set_forces_and_torques( + forces=forces, + torques=torques, + body_ids=body_ids, + is_global=False, + ) + + # Phase 1: run N_STEPS — object accelerates along world +X + for _ in range(N_STEPS): + cube_object.write_data_to_sim() + sim.step() + cube_object.update(sim.cfg.dt) + + vel_after_phase1 = cube_object.data.root_lin_vel_w.torch[0].clone() + assert vel_after_phase1[0].item() > 1.0, "Object should be moving in +X" + + # Rotate body 180deg about Z while keeping velocity + root_pose = cube_object.data.root_state_w.torch[0, :7].clone().unsqueeze(0) + root_pose[0, 3:7] = torch.tensor([0.0, 0.0, 1.0, 0.0], device=device) # 180deg about Z (xyzw) + cube_object.write_root_pose_to_sim(root_pose) + + # Phase 2: run N_STEPS — local +X is now world -X, so force decelerates + for _ in range(N_STEPS): + cube_object.write_data_to_sim() + sim.step() + cube_object.update(sim.cfg.dt) + + vel_after_phase2 = cube_object.data.root_lin_vel_w.torch[0].clone() + + # Velocity should be approximately zero: decelerated by the same amount as it accelerated + torch.testing.assert_close( + vel_after_phase2[0], + torch.tensor(0.0, device=device), + atol=0.0001, + rtol=0.001, + ) + + +@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) +def test_global_force_at_offset_generates_torque(device): + """Test that a global force applied at an offset from CoM generates the expected torque. + + A global +X force applied at +1m Y offset from CoM should produce: + - Linear acceleration in +X + - Angular acceleration about -Z (from cross product: (0,1,0) × (10,0,0) = (0,0,-10)) + """ + with build_simulation_context(device=device, gravity_enabled=False, auto_add_lighting=True) as sim: + sim._app_control_on_stop_handle = None + cube_object, _ = generate_cubes_scene(num_cubes=1, device=device) + + sim.reset() + + body_ids, _ = cube_object.find_bodies(".*") + + # Force at offset: +1m in Y from CoM (global frame) + forces = torch.zeros(1, len(body_ids), 3, device=device) + forces[..., 0] = FORCE_MAGNITUDE # +X force + + torques = torch.zeros(1, len(body_ids), 3, device=device) + + # Position offset: CoM position + 1m in Y (global frame) + com_pos = cube_object.data.body_com_pos_w.torch[:, body_ids, :3].clone() + positions = com_pos.clone() + positions[..., 1] += 1.0 # +1m Y offset + + cube_object.permanent_wrench_composer.set_forces_and_torques( + forces=forces, + torques=torques, + positions=positions, + body_ids=body_ids, + is_global=True, + ) + + # Run 50 steps + for _ in range(50): + cube_object.write_data_to_sim() + sim.step() + cube_object.update(sim.cfg.dt) + + lin_vel = cube_object.data.root_lin_vel_w.torch[0] + ang_vel = cube_object.data.root_ang_vel_w.torch[0] + + # Linear velocity in +X should be positive + assert lin_vel[0].item() > 0.1, f"Expected positive X velocity, got {lin_vel[0].item()}" + + # Angular velocity about Z should be negative (cross product: r × F, r=(0,1,0), F=(10,0,0) -> (0,0,-10)) + assert ang_vel[2].item() < -0.1, f"Expected negative Z angular velocity, got {ang_vel[2].item()}" + + +@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) +def test_global_torque_invariant_under_rotation(device): + """Test that a permanent global torque produces the same angular acceleration before and after rotation. + + A global +Z torque is applied. After 100 steps the body is rotated 90deg about X. + The angular acceleration (delta_omega per phase) about Z should be the same in both phases + because the torque is in the global frame. + """ + with build_simulation_context(device=device, gravity_enabled=False, auto_add_lighting=True) as sim: + sim._app_control_on_stop_handle = None + cube_object, _ = generate_cubes_scene(num_cubes=1, device=device) + + sim.reset() + + body_ids, _ = cube_object.find_bodies(".*") + + # Apply permanent global torque about +Z + forces = torch.zeros(1, len(body_ids), 3, device=device) + torques = torch.zeros(1, len(body_ids), 3, device=device) + torques[..., 2] = TORQUE_MAGNITUDE + + cube_object.permanent_wrench_composer.set_forces_and_torques( + forces=forces, + torques=torques, + body_ids=body_ids, + is_global=True, + ) + + # Phase 1: run N_STEPS + for _ in range(N_STEPS): + cube_object.write_data_to_sim() + sim.step() + cube_object.update(sim.cfg.dt) + + omega_z_after_phase1 = cube_object.data.root_ang_vel_w.torch[0, 2].clone().item() + + # Rotate body 90deg about X and zero out velocities so phase 2 starts from rest + # (avoids gyroscopic cross-coupling at high omega) + root_pose = cube_object.data.root_state_w.torch[0, :7].clone().unsqueeze(0) + root_pose[0, 3:7] = torch.tensor([0.7071, 0.0, 0.0, 0.7071], device=device) # 90deg about X (xyzw) + cube_object.write_root_pose_to_sim(root_pose) + cube_object.write_root_velocity_to_sim(torch.zeros(1, 6, device=device)) + + # Phase 2: run N_STEPS from rest with different body orientation + for _ in range(N_STEPS): + cube_object.write_data_to_sim() + sim.step() + cube_object.update(sim.cfg.dt) + + omega_z_after_phase2 = cube_object.data.root_ang_vel_w.torch[0, 2].clone().item() + + # Both phases start from rest — angular acceleration about Z should be the same + torch.testing.assert_close( + torch.tensor(omega_z_after_phase1), + torch.tensor(omega_z_after_phase2), + rtol=0.001, + atol=0.0001, + ) + + +@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) +def test_global_force_torque_after_translation(device): + """Test that global force torque updates dynamically when the body translates. + + Phase 1: Cube at (1,0,0). Global force F=(0,10,0) applied at explicit position (1,0,0). + stored_torque = cross((1,0,0), (0,10,0)) = (0,0,10) + correction = -cross((1,0,0), (0,10,0)) = (0,0,-10) + net torque = 0 → no rotation, only linear acceleration in +Y. + + Phase 2: Teleport cube to origin (0,0,0), zero velocity, don't re-apply force. + stored_torque = (0,0,10) (unchanged in buffer) + correction = -cross((0,0,0), (0,10,0)) = (0,0,0) + net torque = (0,0,10) → rotation about +Z. + """ + with build_simulation_context(device=device, gravity_enabled=False, auto_add_lighting=True) as sim: + sim._app_control_on_stop_handle = None + cube_object, _ = generate_cubes_scene(num_cubes=1, height=1.0, device=device) + + sim.reset() + + body_ids, _ = cube_object.find_bodies(".*") + + # Phase 1 setup: Move cube to (1, 0, 1) and apply force at (1, 0, 1) + root_state = cube_object.data.root_state_w.torch.clone() + root_state[0, 0] = 1.0 # x = 1 + root_state[0, 1] = 0.0 # y = 0 + root_state[0, 2] = 1.0 # z = 1 + root_state[0, 3:7] = torch.tensor([0.0, 0.0, 0.0, 1.0], device=device) # identity quat (xyzw) + root_state[0, 7:] = 0.0 # zero velocity + cube_object.write_root_state_to_sim(root_state) + + # Step once to let the state settle + sim.step() + cube_object.update(sim.cfg.dt) + + # Get current CoM position for the force application point + com_pos = cube_object.data.body_com_pos_w.torch[:, body_ids, :3].clone() + + forces = torch.zeros(1, len(body_ids), 3, device=device) + forces[..., 1] = FORCE_MAGNITUDE # +Y force + torques = torch.zeros(1, len(body_ids), 3, device=device) + + cube_object.permanent_wrench_composer.set_forces_and_torques( + forces=forces, + torques=torques, + positions=com_pos, + body_ids=body_ids, + is_global=True, + ) + + # Phase 1: run 50 steps — force at CoM, expect no rotation + for _ in range(50): + cube_object.write_data_to_sim() + sim.step() + cube_object.update(sim.cfg.dt) + + ang_vel_phase1 = cube_object.data.root_ang_vel_w.torch[0].clone() + lin_vel_phase1 = cube_object.data.root_lin_vel_w.torch[0].clone() + + # Should have linear velocity in +Y + assert lin_vel_phase1[1].item() > 0.1, f"Expected positive Y velocity, got {lin_vel_phase1[1].item()}" + + # Angular velocity should be ~0 (force applied at CoM → no torque) + assert abs(ang_vel_phase1[2].item()) < 0.1, ( + f"Expected ~0 Z angular velocity in phase 1, got {ang_vel_phase1[2].item()}" + ) + + # Phase 2: Teleport cube to origin, zero velocity, don't re-apply force + root_state2 = cube_object.data.root_state_w.torch.clone() + root_state2[0, 0] = 0.0 # x = 0 + root_state2[0, 1] = 0.0 + root_state2[0, 2] = 1.0 # z = 1 + root_state2[0, 3:7] = torch.tensor([0.0, 0.0, 0.0, 1.0], device=device) # identity (xyzw) + root_state2[0, 7:] = 0.0 # zero velocity + cube_object.write_root_state_to_sim(root_state2) + + # Step once to let state settle + sim.step() + cube_object.update(sim.cfg.dt) + + # Phase 2: run 50 steps — body at origin but stored torque = cross((1,0,1), (0,10,0)) = (-10,0,10) + # correction = -cross((0,0,1), (0,10,0)) = -(0,0,0 - but wait, z=1) + # Actually: stored = cross((com_x,com_y,com_z), (0,10,0)) + # After teleport: correction = -cross(new_pos, F), net torque ≠ 0 since positions differ + for _ in range(50): + cube_object.write_data_to_sim() + sim.step() + cube_object.update(sim.cfg.dt) + + ang_vel_phase2 = cube_object.data.root_ang_vel_w.torch[0].clone() + + # The X component of position changed from ~1 to ~0, so torque about Z changes. + # stored_torque_z = com_x * Fy = ~1 * 10 = ~10 + # After teleport, correction_z = -new_x * Fy = ~0 * 10 = ~0 + # net torque_z ≈ 10 → positive Z angular velocity + assert ang_vel_phase2[2].item() > 0.5, ( + f"Expected positive Z angular velocity in phase 2, got {ang_vel_phase2[2].item()}" + ) + + +@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) +def test_global_force_torque_reverses_on_opposite_side(device): + """Test that dynamic correction produces correct torque sign depending on body position. + + Phase 1: Cube at (-1, 0, 1). Global F=(0, 10, 0) at world point P=(0, 0, 1). + net torque_z = cross(P - link_pos, F)_z = cross((1,0,0), (0,10,0))_z = +10 + → positive Z angular velocity + + Phase 2: Teleport cube to (+1, 0, 1), zero velocity, don't re-apply force. + net torque_z = cross(P - link_pos, F)_z = cross((-1,0,0), (0,10,0))_z = -10 + → negative Z angular velocity + """ + with build_simulation_context(device=device, gravity_enabled=False, auto_add_lighting=True) as sim: + sim._app_control_on_stop_handle = None + cube_object, _ = generate_cubes_scene(num_cubes=1, height=1.0, device=device) + + sim.reset() + + body_ids, _ = cube_object.find_bodies(".*") + + # Move cube to (-1, 0, 1) + root_state = cube_object.data.root_state_w.torch.clone() + root_state[0, 0] = -1.0 + root_state[0, 1] = 0.0 + root_state[0, 2] = 1.0 + root_state[0, 3:7] = torch.tensor([0.0, 0.0, 0.0, 1.0], device=device) # identity (xyzw) + root_state[0, 7:] = 0.0 + cube_object.write_root_state_to_sim(root_state) + sim.step() + cube_object.update(sim.cfg.dt) + + # Apply permanent global F=(0, 10, 0) at world point P=(0, 0, 1) + forces = torch.zeros(1, len(body_ids), 3, device=device) + forces[..., 1] = FORCE_MAGNITUDE + torques = torch.zeros(1, len(body_ids), 3, device=device) + positions = torch.zeros(1, len(body_ids), 3, device=device) + positions[..., 2] = 1.0 # P = (0, 0, 1) + + cube_object.permanent_wrench_composer.set_forces_and_torques( + forces=forces, + torques=torques, + positions=positions, + body_ids=body_ids, + is_global=True, + ) + + # Phase 1: run 50 steps — expect positive Z angular velocity + for _ in range(50): + cube_object.write_data_to_sim() + sim.step() + cube_object.update(sim.cfg.dt) + + omega_z_phase1 = cube_object.data.root_ang_vel_w.torch[0, 2].item() + assert omega_z_phase1 > 0.1, f"Phase 1: expected positive omega_z, got {omega_z_phase1}" + + # Phase 2: Teleport cube to (+1, 0, 1), zero velocity + root_state2 = cube_object.data.root_state_w.torch.clone() + root_state2[0, 0] = 1.0 + root_state2[0, 1] = 0.0 + root_state2[0, 2] = 1.0 + root_state2[0, 3:7] = torch.tensor([0.0, 0.0, 0.0, 1.0], device=device) # identity (xyzw) + root_state2[0, 7:] = 0.0 + cube_object.write_root_state_to_sim(root_state2) + sim.step() + cube_object.update(sim.cfg.dt) + + # Phase 2: run 50 steps — expect negative Z angular velocity + for _ in range(50): + cube_object.write_data_to_sim() + sim.step() + cube_object.update(sim.cfg.dt) + + omega_z_phase2 = cube_object.data.root_ang_vel_w.torch[0, 2].item() + assert omega_z_phase2 < -0.1, f"Phase 2: expected negative omega_z, got {omega_z_phase2}" + + +@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) +def test_global_force_no_position_no_torque(device): + """Test that global force without positions produces no torque (applied at CoM). + + A body at (2, 0, 1) with global F=(0, 10, 0) and no positions should experience + only linear acceleration, no rotation. The force is applied at the body's CoM. + """ + with build_simulation_context(device=device, gravity_enabled=False, auto_add_lighting=True) as sim: + sim._app_control_on_stop_handle = None + cube_object, _ = generate_cubes_scene(num_cubes=1, height=1.0, device=device) + + sim.reset() + + body_ids, _ = cube_object.find_bodies(".*") + + # Move cube to (2, 0, 1) + root_state = cube_object.data.root_state_w.torch.clone() + root_state[0, 0] = 2.0 + root_state[0, 1] = 0.0 + root_state[0, 2] = 1.0 + root_state[0, 3:7] = torch.tensor([0.0, 0.0, 0.0, 1.0], device=device) # identity (xyzw) + root_state[0, 7:] = 0.0 + cube_object.write_root_state_to_sim(root_state) + sim.step() + cube_object.update(sim.cfg.dt) + + # Apply global F=(0, 10, 0) WITHOUT positions → force at CoM, no torque + forces = torch.zeros(1, len(body_ids), 3, device=device) + forces[..., 1] = FORCE_MAGNITUDE + torques = torch.zeros(1, len(body_ids), 3, device=device) + + cube_object.permanent_wrench_composer.set_forces_and_torques( + forces=forces, + torques=torques, + body_ids=body_ids, + is_global=True, + ) + + # Run 50 steps + for _ in range(50): + cube_object.write_data_to_sim() + sim.step() + cube_object.update(sim.cfg.dt) + + omega_z = cube_object.data.root_ang_vel_w.torch[0, 2].item() + # No positions → force at CoM → zero torque → zero angular velocity + assert abs(omega_z) < 0.01, f"Expected ~zero omega_z for force at CoM, got {omega_z}" + + # Should still have linear acceleration in +Y + lin_vel_y = cube_object.data.root_lin_vel_w.torch[0, 1].item() + assert lin_vel_y > 0.1, f"Expected positive Y velocity from applied force, got {lin_vel_y}" + + +@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) +def test_multi_cube_different_torques_from_same_force(device): + """Test kernel indexing across multiple envs with different CoM positions. + + 2 cubes: Cube 0 at (-1, 0, 1), Cube 1 at (+1, 0, 1). + Same global F=(0, 10, 0) at same world point P=(0, 0, 1) to both cubes. + Cube 0: torque_z = cross((1,0,0), (0,10,0))_z = +10 → omega_z > 0 + Cube 1: torque_z = cross((-1,0,0), (0,10,0))_z = -10 → omega_z < 0 + Both have same linear acceleration in +Y. + """ + with build_simulation_context(device=device, gravity_enabled=False, auto_add_lighting=True) as sim: + sim._app_control_on_stop_handle = None + cube_object, _ = generate_cubes_scene(num_cubes=2, height=1.0, device=device) + + sim.reset() + + body_ids, _ = cube_object.find_bodies(".*") + + # Position cubes: Cube 0 at (-1, 0, 1), Cube 1 at (+1, 0, 1) + root_state = cube_object.data.root_state_w.torch.clone() + root_state[0, 0] = -1.0 + root_state[0, 1] = 0.0 + root_state[0, 2] = 1.0 + root_state[0, 3:7] = torch.tensor([0.0, 0.0, 0.0, 1.0], device=device) # identity (xyzw) + root_state[0, 7:] = 0.0 + + root_state[1, 0] = 1.0 + root_state[1, 1] = 0.0 + root_state[1, 2] = 1.0 + root_state[1, 3:7] = torch.tensor([0.0, 0.0, 0.0, 1.0], device=device) # identity (xyzw) + root_state[1, 7:] = 0.0 + cube_object.write_root_state_to_sim(root_state) + sim.step() + cube_object.update(sim.cfg.dt) + + # Apply same global F=(0, 10, 0) at P=(0, 0, 1) to both cubes + forces = torch.zeros(2, len(body_ids), 3, device=device) + forces[..., 1] = FORCE_MAGNITUDE + torques = torch.zeros(2, len(body_ids), 3, device=device) + positions = torch.zeros(2, len(body_ids), 3, device=device) + positions[..., 2] = 1.0 # P = (0, 0, 1) + + cube_object.permanent_wrench_composer.set_forces_and_torques( + forces=forces, + torques=torques, + positions=positions, + body_ids=body_ids, + is_global=True, + ) + + # Run 50 steps + for _ in range(50): + cube_object.write_data_to_sim() + sim.step() + cube_object.update(sim.cfg.dt) + + # Cube 0: omega_z > 0 (force point is to the right of CoM) + omega_z_0 = cube_object.data.root_ang_vel_w.torch[0, 2].item() + assert omega_z_0 > 0.1, f"Cube 0: expected positive omega_z, got {omega_z_0}" + + # Cube 1: omega_z < 0 (force point is to the left of CoM) + omega_z_1 = cube_object.data.root_ang_vel_w.torch[1, 2].item() + assert omega_z_1 < -0.1, f"Cube 1: expected negative omega_z, got {omega_z_1}" + + # Both cubes should have same linear velocity in +Y (same force magnitude) + lin_vel_y_0 = cube_object.data.root_lin_vel_w.torch[0, 1].item() + lin_vel_y_1 = cube_object.data.root_lin_vel_w.torch[1, 1].item() + assert abs(lin_vel_y_0 - lin_vel_y_1) < 0.5, ( + f"Both cubes should have similar Y velocity, got {lin_vel_y_0} and {lin_vel_y_1}" + ) + + +@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) +def test_global_force_torque_far_from_origin(device): + """Test that global force torque correction produces correct physics at large world coordinates. + + Two cubes with identical relative geometry (force offset = (1, 0, 0) from CoM): + Cube 0 at (0, 0, 1) — near origin (reference) + Cube 1 at (2000, 0, 1) — far from origin + + Both get global F=(0, 10, 0) at offset (1, 0, 0) from their respective CoMs. + Expected torque: cross((1,0,0), (0,10,0)) = (0, 0, 10) for both. + + The compose kernel computes cross(P, F) - cross(link_pos, F): + Cube 0: cross((1,0,1), F) - cross((0,0,1), F) — small values, no cancellation + Cube 1: cross((2001,0,1), F) - cross((2000,0,1), F) — large values nearly cancel + + Both cubes should produce the same angular and linear velocities. + """ + with build_simulation_context(device=device, gravity_enabled=False, auto_add_lighting=True) as sim: + sim._app_control_on_stop_handle = None + cube_object, _ = generate_cubes_scene(num_cubes=2, height=1.0, device=device) + + sim.reset() + + body_ids, _ = cube_object.find_bodies(".*") + + # Position cubes: Cube 0 near origin, Cube 1 far from origin + root_state = cube_object.data.root_state_w.torch.clone() + # Cube 0 at (0, 0, 1) + root_state[0, 0] = 0.0 + root_state[0, 1] = 0.0 + root_state[0, 2] = 1.0 + root_state[0, 3:7] = torch.tensor([0.0, 0.0, 0.0, 1.0], device=device) # identity (xyzw) + root_state[0, 7:] = 0.0 + # Cube 1 at (2000, 0, 1) + root_state[1, 0] = 2000.0 + root_state[1, 1] = 0.0 + root_state[1, 2] = 1.0 + root_state[1, 3:7] = torch.tensor([0.0, 0.0, 0.0, 1.0], device=device) # identity (xyzw) + root_state[1, 7:] = 0.0 + cube_object.write_root_state_to_sim(root_state) + sim.step() + cube_object.update(sim.cfg.dt) + + # Apply F=(0, 10, 0) at +1m X offset from each cube's CoM + forces = torch.zeros(2, len(body_ids), 3, device=device) + forces[..., 1] = FORCE_MAGNITUDE # +Y force + torques = torch.zeros(2, len(body_ids), 3, device=device) + + # Positions: each cube's CoM + (1, 0, 0) + com_pos = cube_object.data.body_com_pos_w.torch[:, body_ids, :3].clone() + positions = com_pos.clone() + positions[..., 0] += 1.0 # +1m X offset from CoM + + cube_object.permanent_wrench_composer.set_forces_and_torques( + forces=forces, + torques=torques, + positions=positions, + body_ids=body_ids, + is_global=True, + ) + + # Run 50 steps + for _ in range(50): + cube_object.write_data_to_sim() + sim.step() + cube_object.update(sim.cfg.dt) + + # Both cubes should have positive omega_z (cross((1,0,0), (0,10,0)) = (0,0,10)) + omega_z_0 = cube_object.data.root_ang_vel_w.torch[0, 2].item() + omega_z_1 = cube_object.data.root_ang_vel_w.torch[1, 2].item() + assert omega_z_0 > 0.1, f"Cube 0: expected positive omega_z, got {omega_z_0}" + assert omega_z_1 > 0.1, f"Cube 1: expected positive omega_z, got {omega_z_1}" + + # omega_z values should match within 1% (same relative geometry) + torch.testing.assert_close( + torch.tensor(omega_z_0), + torch.tensor(omega_z_1), + rtol=0.01, + atol=0.0, + msg=lambda msg: ( + f"Angular velocity mismatch between near-origin and far-from-origin cubes:\n" + f" Cube 0 (near): omega_z = {omega_z_0:.6f}\n" + f" Cube 1 (far): omega_z = {omega_z_1:.6f}\n{msg}" + ), + ) + + # Linear velocity in +Y should also match + lin_vel_y_0 = cube_object.data.root_lin_vel_w.torch[0, 1].item() + lin_vel_y_1 = cube_object.data.root_lin_vel_w.torch[1, 1].item() + torch.testing.assert_close( + torch.tensor(lin_vel_y_0), + torch.tensor(lin_vel_y_1), + rtol=0.01, + atol=0.0, + msg=lambda msg: ( + f"Linear velocity mismatch between near-origin and far-from-origin cubes:\n" + f" Cube 0 (near): lin_vel_y = {lin_vel_y_0:.6f}\n" + f" Cube 1 (far): lin_vel_y = {lin_vel_y_1:.6f}\n{msg}" + ), + ) + + +@pytest.mark.parametrize("device", ["cuda:0"]) +def test_global_force_no_position_no_rotation_large_offset(device): + """Test that a global force without positions produces no rotation at large offsets. + + A cube is placed at (2000, 0, 1) and a global force F=(0, 10, 0) is applied + without positions. The cube should accelerate linearly but not rotate. + Before the fix, this would produce torque proportional to 2000 and cause rotation. + """ + with build_simulation_context( + device=device, add_ground_plane=False, auto_add_lighting=True, gravity_enabled=False + ) as sim: + sim._app_control_on_stop_handle = None + cube_object, _ = generate_cubes_scene(num_cubes=1, height=1.0, device=device) + + sim.reset() + + body_ids, _ = cube_object.find_bodies(".*") + + # Place cube at large X offset + root_state = cube_object.data.default_root_state.torch.clone() + root_state[0, 0] = 2000.0 # large X position + root_state[0, 1] = 0.0 + root_state[0, 2] = 1.0 + cube_object.write_root_pose_to_sim(root_state[:, :7]) + cube_object.write_root_velocity_to_sim(root_state[:, 7:]) + cube_object.reset() + + # Apply global force without positions (should go to CoM, no torque) + forces = torch.zeros(cube_object.num_instances, len(body_ids), 3, device=device) + forces[0, :, 1] = 10.0 # F_y = 10 N + + cube_object.permanent_wrench_composer.set_forces_and_torques( + forces=forces, + body_ids=body_ids, + is_global=True, + ) + + # Step simulation + for _ in range(50): + cube_object.write_data_to_sim() + sim.step() + cube_object.update(sim.cfg.dt) + + # Check: angular velocity should be near zero (no rotation) + ang_vel = cube_object.data.root_ang_vel_w.torch[0] + assert torch.allclose(ang_vel, torch.zeros(3, device=device), atol=0.01), ( + f"Expected near-zero angular velocity, got {ang_vel}. " + "Global force without positions should not produce torque." + ) + + # Check: linear velocity in Y should be positive (force is in +Y) + lin_vel = cube_object.data.root_lin_vel_w.torch[0] + assert lin_vel[1] > 0.1, f"Expected positive Y velocity from applied force, got {lin_vel[1]}" + + +@pytest.mark.parametrize("device", ["cuda:0"]) +def test_global_force_at_com_position_no_rotation_large_offset(device): + """Test that a global force with position at CoM produces no rotation at large offsets. + + A cube is placed at (2000, 0, 1) and a global force F=(0, 10, 0) is applied + at the cube's position (i.e., at its CoM). This should produce zero torque, + serving as a control test alongside test_global_force_no_position_no_rotation_large_offset. + """ + with build_simulation_context( + device=device, add_ground_plane=False, auto_add_lighting=True, gravity_enabled=False + ) as sim: + sim._app_control_on_stop_handle = None + cube_object, _ = generate_cubes_scene(num_cubes=1, height=1.0, device=device) + + sim.reset() + + body_ids, _ = cube_object.find_bodies(".*") + + # Place cube at large X offset + root_state = cube_object.data.default_root_state.torch.clone() + root_state[0, 0] = 2000.0 + root_state[0, 1] = 0.0 + root_state[0, 2] = 1.0 + cube_object.write_root_pose_to_sim(root_state[:, :7]) + cube_object.write_root_velocity_to_sim(root_state[:, 7:]) + cube_object.reset() + + # Apply global force AT the cube's position (torque should cancel) + forces = torch.zeros(cube_object.num_instances, len(body_ids), 3, device=device) + forces[0, :, 1] = 10.0 + + positions = torch.zeros(cube_object.num_instances, len(body_ids), 3, device=device) + positions[0, :, 0] = 2000.0 + positions[0, :, 2] = 1.0 + + cube_object.permanent_wrench_composer.set_forces_and_torques( + forces=forces, + positions=positions, + body_ids=body_ids, + is_global=True, + ) + + for _ in range(50): + cube_object.write_data_to_sim() + sim.step() + cube_object.update(sim.cfg.dt) + + # Force at CoM → no rotation + ang_vel = cube_object.data.root_ang_vel_w.torch[0] + assert torch.allclose(ang_vel, torch.zeros(3, device=device), atol=0.01), ( + f"Expected near-zero angular velocity, got {ang_vel}. " + "Global force at CoM position should not produce torque." + ) + + lin_vel = cube_object.data.root_lin_vel_w.torch[0] + assert lin_vel[1] > 0.1, f"Expected positive Y velocity from applied force, got {lin_vel[1]}" diff --git a/source/isaaclab/test/utils/test_wrench_composer_vs_physx.py b/source/isaaclab/test/utils/test_wrench_composer_vs_physx.py new file mode 100644 index 000000000000..8d47b003369c --- /dev/null +++ b/source/isaaclab/test/utils/test_wrench_composer_vs_physx.py @@ -0,0 +1,837 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Integration tests comparing WrenchComposer output vs raw PhysX apply_forces_and_torques_at_position. + +Two identical rigid objects are placed in the same scene. One uses the WrenchComposer path +(set_forces_and_torques → write_data_to_sim → compose → PhysX apply with is_global=False), +the other uses the raw PhysX API directly (apply_forces_and_torques_at_position with matching +is_global flag). After N steps, both objects should have identical velocities. +""" + +"""Launch Isaac Sim Simulator first.""" + +from isaaclab.app import AppLauncher + +# launch omniverse app +simulation_app = AppLauncher(headless=True).app + +"""Rest everything follows.""" + +import math + +import pytest +import torch +import warp as wp + +import isaaclab.sim as sim_utils +from isaaclab.assets import RigidObject, RigidObjectCfg +from isaaclab.sim import build_simulation_context +from isaaclab.utils.assets import ISAAC_NUCLEUS_DIR + + +def generate_dual_cube_scene( + num_cubes: int = 1, + height: float = 1.0, + device: str = "cuda:0", + initial_rot: tuple[float, ...] | None = None, + spacing: float = 2.0, +) -> tuple[RigidObject, RigidObject]: + """Generate a scene with two sets of cubes: one for the composer path, one for raw PhysX. + + Both sets share the same spawn config and initial state (except a Y offset to avoid overlap). + + Args: + num_cubes: Number of cubes per group (environments). + height: Spawn height. + device: Simulation device. + initial_rot: Initial quaternion (x, y, z, w). Defaults to identity. + spacing: Distance between env origins in X. Defaults to 2.0. + + Returns: + Tuple of (cube_composer, cube_raw) RigidObject instances. + """ + if initial_rot is None: + initial_rot = (0.0, 0.0, 0.0, 1.0) # identity in (x,y,z,w) + + y_offset = max(spacing, 3.0) + + # Create Xform prims for both groups + for i in range(num_cubes): + origin_composer = (i * spacing, 0.0, height) + origin_raw = (i * spacing, y_offset, height) # Y offset to avoid overlap + sim_utils.create_prim(f"/World/Composer_{i}", "Xform", translation=origin_composer) + sim_utils.create_prim(f"/World/Raw_{i}", "Xform", translation=origin_raw) + + spawn_cfg = sim_utils.UsdFileCfg( + usd_path=f"{ISAAC_NUCLEUS_DIR}/Props/Blocks/DexCube/dex_cube_instanceable.usd", + rigid_props=sim_utils.RigidBodyPropertiesCfg(), + ) + + cube_composer_cfg = RigidObjectCfg( + prim_path="/World/Composer_.*/Object", + spawn=spawn_cfg, + init_state=RigidObjectCfg.InitialStateCfg(pos=(0.0, 0.0, height), rot=initial_rot), + ) + cube_composer = RigidObject(cfg=cube_composer_cfg) + + cube_raw_cfg = RigidObjectCfg( + prim_path="/World/Raw_.*/Object", + spawn=spawn_cfg, + init_state=RigidObjectCfg.InitialStateCfg(pos=(0.0, y_offset, height), rot=initial_rot), + ) + cube_raw = RigidObject(cfg=cube_raw_cfg) + + return cube_composer, cube_raw + + +N_STEPS = 50 +FORCE_MAGNITUDE = 10.0 +TORQUE_MAGNITUDE = 1.0 +# 45 degrees about Z: (cos(22.5°), 0, 0, sin(22.5°)) +ROT_45_Z = (0.0, 0.0, math.sin(math.pi / 8), math.cos(math.pi / 8)) # 45deg about Z in (x,y,z,w) + + +@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) +def test_composer_vs_physx_local_force(device): + """Baseline: local force at identity orientation. Composer and raw PhysX should match exactly.""" + with build_simulation_context(device=device, gravity_enabled=False, auto_add_lighting=True) as sim: + sim._app_control_on_stop_handle = None + cube_composer, cube_raw = generate_dual_cube_scene(num_cubes=1, device=device) + + sim.reset() + + body_ids, _ = cube_composer.find_bodies(".*") + + # Composer path: local force +X + forces = torch.zeros(1, len(body_ids), 3, device=device) + forces[..., 0] = FORCE_MAGNITUDE + torques = torch.zeros(1, len(body_ids), 3, device=device) + + cube_composer.permanent_wrench_composer.set_forces_and_torques( + forces=forces, + torques=torques, + body_ids=body_ids, + is_global=False, + ) + + # Raw PhysX data (flattened for PhysX view API) + raw_forces = torch.zeros(1, 3, device=device) + raw_forces[:, 0] = FORCE_MAGNITUDE + raw_torques = torch.zeros(1, 3, device=device) + raw_indices = cube_raw._ALL_INDICES + + for _ in range(N_STEPS): + cube_composer.write_data_to_sim() + cube_raw.write_data_to_sim() # no-op (composer inactive) + cube_raw.root_view.apply_forces_and_torques_at_position( + force_data=wp.from_torch(raw_forces.contiguous(), dtype=wp.float32), + torque_data=wp.from_torch(raw_torques.contiguous(), dtype=wp.float32), + position_data=None, + indices=raw_indices, + is_global=False, + ) + sim.step() + cube_composer.update(sim.cfg.dt) + cube_raw.update(sim.cfg.dt) + + # Compare velocities + torch.testing.assert_close( + cube_composer.data.root_lin_vel_w.torch, + cube_raw.data.root_lin_vel_w.torch, + rtol=1e-4, + atol=1e-4, + ) + # Both should have ~zero angular velocity (force at CoM, no torque) + torch.testing.assert_close( + cube_composer.data.root_ang_vel_w.torch, + torch.zeros(1, 3, device=device), + rtol=0.0, + atol=1e-4, + ) + torch.testing.assert_close( + cube_raw.data.root_ang_vel_w.torch, + torch.zeros(1, 3, device=device), + rtol=0.0, + atol=1e-4, + ) + + +@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) +def test_composer_vs_physx_global_force(device): + """Global force with non-identity rotation (45 deg Z). Rotation matters for frame conversion.""" + with build_simulation_context(device=device, gravity_enabled=False, auto_add_lighting=True) as sim: + sim._app_control_on_stop_handle = None + cube_composer, cube_raw = generate_dual_cube_scene(num_cubes=1, device=device, initial_rot=ROT_45_Z) + + sim.reset() + + body_ids, _ = cube_composer.find_bodies(".*") + + # Composer path: global force +X + forces = torch.zeros(1, len(body_ids), 3, device=device) + forces[..., 0] = FORCE_MAGNITUDE + torques = torch.zeros(1, len(body_ids), 3, device=device) + + cube_composer.permanent_wrench_composer.set_forces_and_torques( + forces=forces, + torques=torques, + body_ids=body_ids, + is_global=True, + ) + + # Raw PhysX data + raw_forces = torch.zeros(1, 3, device=device) + raw_forces[:, 0] = FORCE_MAGNITUDE + raw_torques = torch.zeros(1, 3, device=device) + raw_indices = cube_raw._ALL_INDICES + + for _ in range(N_STEPS): + cube_composer.write_data_to_sim() + cube_raw.write_data_to_sim() + cube_raw.root_view.apply_forces_and_torques_at_position( + force_data=wp.from_torch(raw_forces.contiguous(), dtype=wp.float32), + torque_data=wp.from_torch(raw_torques.contiguous(), dtype=wp.float32), + position_data=None, + indices=raw_indices, + is_global=True, + ) + sim.step() + cube_composer.update(sim.cfg.dt) + cube_raw.update(sim.cfg.dt) + + # Linear velocities should match (same global force, same mass) + torch.testing.assert_close( + cube_composer.data.root_lin_vel_w.torch, + cube_raw.data.root_lin_vel_w.torch, + rtol=1e-4, + atol=1e-4, + ) + # Angular velocities should match + torch.testing.assert_close( + cube_composer.data.root_ang_vel_w.torch, + cube_raw.data.root_ang_vel_w.torch, + rtol=1e-4, + atol=1e-4, + ) + # Both should have ~zero angular velocity (force at CoM, no torque) + torch.testing.assert_close( + cube_composer.data.root_ang_vel_w.torch, + torch.zeros(1, 3, device=device), + rtol=0.0, + atol=1e-4, + ) + torch.testing.assert_close( + cube_raw.data.root_ang_vel_w.torch, + torch.zeros(1, 3, device=device), + rtol=0.0, + atol=1e-4, + ) + + +@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) +def test_composer_vs_physx_local_force_at_position(device): + """Local force at a local offset. Both paths should produce identical cross-product torque.""" + with build_simulation_context(device=device, gravity_enabled=False, auto_add_lighting=True) as sim: + sim._app_control_on_stop_handle = None + cube_composer, cube_raw = generate_dual_cube_scene(num_cubes=1, device=device) + + sim.reset() + + body_ids, _ = cube_composer.find_bodies(".*") + + # Local force +X at local offset +0.5m Y + forces = torch.zeros(1, len(body_ids), 3, device=device) + forces[..., 0] = FORCE_MAGNITUDE + torques = torch.zeros(1, len(body_ids), 3, device=device) + positions = torch.zeros(1, len(body_ids), 3, device=device) + positions[..., 1] = 0.5 # +0.5m Y offset in local frame + + cube_composer.permanent_wrench_composer.set_forces_and_torques( + forces=forces, + torques=torques, + positions=positions, + body_ids=body_ids, + is_global=False, + ) + + # Raw PhysX data (local force at local position) + raw_forces = torch.zeros(1, 3, device=device) + raw_forces[:, 0] = FORCE_MAGNITUDE + raw_torques = torch.zeros(1, 3, device=device) + raw_positions = torch.zeros(1, 3, device=device) + raw_positions[:, 1] = 0.5 + raw_indices = cube_raw._ALL_INDICES + + for _ in range(N_STEPS): + cube_composer.write_data_to_sim() + cube_raw.write_data_to_sim() + cube_raw.root_view.apply_forces_and_torques_at_position( + force_data=wp.from_torch(raw_forces.contiguous(), dtype=wp.float32), + torque_data=wp.from_torch(raw_torques.contiguous(), dtype=wp.float32), + position_data=wp.from_torch(raw_positions.contiguous(), dtype=wp.float32), + indices=raw_indices, + is_global=False, + ) + sim.step() + cube_composer.update(sim.cfg.dt) + cube_raw.update(sim.cfg.dt) + + # Both linear and angular velocities should match + torch.testing.assert_close( + cube_composer.data.root_lin_vel_w.torch, + cube_raw.data.root_lin_vel_w.torch, + rtol=1e-4, + atol=1e-4, + ) + torch.testing.assert_close( + cube_composer.data.root_ang_vel_w.torch, + cube_raw.data.root_ang_vel_w.torch, + rtol=1e-4, + atol=1e-4, + ) + + # Sanity: angular velocity should be nonzero (cross-product torque) + assert torch.abs(cube_composer.data.root_ang_vel_w.torch[0, 2]).item() > 0.1, ( + "Expected nonzero Z angular velocity from cross-product torque" + ) + + +@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) +def test_composer_vs_physx_global_force_at_position(device): + """Global force at world position with non-identity rotation. Both rotation AND position correction matter.""" + with build_simulation_context(device=device, gravity_enabled=False, auto_add_lighting=True) as sim: + sim._app_control_on_stop_handle = None + cube_composer, cube_raw = generate_dual_cube_scene(num_cubes=1, device=device, initial_rot=ROT_45_Z) + + sim.reset() + + body_ids, _ = cube_composer.find_bodies(".*") + + # Global force +X + forces = torch.zeros(1, len(body_ids), 3, device=device) + forces[..., 0] = FORCE_MAGNITUDE + torques = torch.zeros(1, len(body_ids), 3, device=device) + + # Position = each cube's link_pos + offset (same offset for both) + offset = torch.zeros(1, len(body_ids), 3, device=device) + offset[..., 1] = 1.0 # +1m Y offset in world frame + + pos_composer = cube_composer.data.body_com_pos_w.torch[:, body_ids, :3].clone() + offset + pos_raw = cube_raw.data.body_com_pos_w.torch[:, body_ids, :3].clone() + offset + + cube_composer.permanent_wrench_composer.set_forces_and_torques( + forces=forces, + torques=torques, + positions=pos_composer, + body_ids=body_ids, + is_global=True, + ) + + # Raw PhysX data + raw_forces = torch.zeros(1, 3, device=device) + raw_forces[:, 0] = FORCE_MAGNITUDE + raw_torques = torch.zeros(1, 3, device=device) + raw_positions = pos_raw.view(-1, 3) + raw_indices = cube_raw._ALL_INDICES + + for _ in range(N_STEPS): + cube_composer.write_data_to_sim() + cube_raw.write_data_to_sim() + cube_raw.root_view.apply_forces_and_torques_at_position( + force_data=wp.from_torch(raw_forces.contiguous(), dtype=wp.float32), + torque_data=wp.from_torch(raw_torques.contiguous(), dtype=wp.float32), + position_data=wp.from_torch(raw_positions.contiguous(), dtype=wp.float32), + indices=raw_indices, + is_global=True, + ) + sim.step() + cube_composer.update(sim.cfg.dt) + cube_raw.update(sim.cfg.dt) + + # Both linear and angular velocities should match + torch.testing.assert_close( + cube_composer.data.root_lin_vel_w.torch, + cube_raw.data.root_lin_vel_w.torch, + rtol=1e-4, + atol=1e-4, + ) + torch.testing.assert_close( + cube_composer.data.root_ang_vel_w.torch, + cube_raw.data.root_ang_vel_w.torch, + rtol=1e-4, + atol=1e-4, + ) + + # Sanity: angular velocity should be nonzero (cross-product torque) + assert torch.abs(cube_composer.data.root_ang_vel_w.torch[0, 2]).item() > 0.1, ( + "Expected nonzero Z angular velocity from positional torque" + ) + + +@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) +def test_composer_vs_physx_local_torque(device): + """Local torque at identity orientation. Should produce matching angular velocity.""" + with build_simulation_context(device=device, gravity_enabled=False, auto_add_lighting=True) as sim: + sim._app_control_on_stop_handle = None + cube_composer, cube_raw = generate_dual_cube_scene(num_cubes=1, device=device) + + sim.reset() + + body_ids, _ = cube_composer.find_bodies(".*") + + # Composer path: local torque about +Z + forces = torch.zeros(1, len(body_ids), 3, device=device) + torques = torch.zeros(1, len(body_ids), 3, device=device) + torques[..., 2] = TORQUE_MAGNITUDE + + cube_composer.permanent_wrench_composer.set_forces_and_torques( + forces=forces, + torques=torques, + body_ids=body_ids, + is_global=False, + ) + + # Raw PhysX data + raw_forces = torch.zeros(1, 3, device=device) + raw_torques = torch.zeros(1, 3, device=device) + raw_torques[:, 2] = TORQUE_MAGNITUDE + raw_indices = cube_raw._ALL_INDICES + + for _ in range(N_STEPS): + cube_composer.write_data_to_sim() + cube_raw.write_data_to_sim() + cube_raw.root_view.apply_forces_and_torques_at_position( + force_data=wp.from_torch(raw_forces.contiguous(), dtype=wp.float32), + torque_data=wp.from_torch(raw_torques.contiguous(), dtype=wp.float32), + position_data=None, + indices=raw_indices, + is_global=False, + ) + sim.step() + cube_composer.update(sim.cfg.dt) + cube_raw.update(sim.cfg.dt) + + # Angular velocities should match + torch.testing.assert_close( + cube_composer.data.root_ang_vel_w.torch, + cube_raw.data.root_ang_vel_w.torch, + rtol=1e-4, + atol=1e-4, + ) + # Linear velocity should be ~zero for both (no force) + torch.testing.assert_close( + cube_composer.data.root_lin_vel_w.torch, + torch.zeros(1, 3, device=device), + rtol=0.0, + atol=1e-4, + ) + torch.testing.assert_close( + cube_raw.data.root_lin_vel_w.torch, + torch.zeros(1, 3, device=device), + rtol=0.0, + atol=1e-4, + ) + + +@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) +def test_composer_vs_physx_global_torque(device): + """Global torque with non-identity rotation (45 deg Z). Composer rotates to body frame internally.""" + with build_simulation_context(device=device, gravity_enabled=False, auto_add_lighting=True) as sim: + sim._app_control_on_stop_handle = None + cube_composer, cube_raw = generate_dual_cube_scene(num_cubes=1, device=device, initial_rot=ROT_45_Z) + + sim.reset() + + body_ids, _ = cube_composer.find_bodies(".*") + + # Composer path: global torque about +Z + forces = torch.zeros(1, len(body_ids), 3, device=device) + torques = torch.zeros(1, len(body_ids), 3, device=device) + torques[..., 2] = TORQUE_MAGNITUDE + + cube_composer.permanent_wrench_composer.set_forces_and_torques( + forces=forces, + torques=torques, + body_ids=body_ids, + is_global=True, + ) + + # Raw PhysX data + raw_forces = torch.zeros(1, 3, device=device) + raw_torques = torch.zeros(1, 3, device=device) + raw_torques[:, 2] = TORQUE_MAGNITUDE + raw_indices = cube_raw._ALL_INDICES + + for _ in range(N_STEPS): + cube_composer.write_data_to_sim() + cube_raw.write_data_to_sim() + cube_raw.root_view.apply_forces_and_torques_at_position( + force_data=wp.from_torch(raw_forces.contiguous(), dtype=wp.float32), + torque_data=wp.from_torch(raw_torques.contiguous(), dtype=wp.float32), + position_data=None, + indices=raw_indices, + is_global=True, + ) + sim.step() + cube_composer.update(sim.cfg.dt) + cube_raw.update(sim.cfg.dt) + + # Angular velocities should match + torch.testing.assert_close( + cube_composer.data.root_ang_vel_w.torch, + cube_raw.data.root_ang_vel_w.torch, + rtol=1e-4, + atol=1e-4, + ) + + +NUM_CUBES_MULTI = 4 + + +@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) +def test_composer_vs_physx_global_force_multi_env(device): + """Global force (no position) with multiple environments. + + Regression: checks that env-indexing and per-body quaternion handling work correctly + when there is more than one environment. + """ + with build_simulation_context(device=device, gravity_enabled=False, auto_add_lighting=True) as sim: + sim._app_control_on_stop_handle = None + cube_composer, cube_raw = generate_dual_cube_scene( + num_cubes=NUM_CUBES_MULTI, device=device, initial_rot=ROT_45_Z + ) + + sim.reset() + + body_ids, _ = cube_composer.find_bodies(".*") + + # Composer path: global force +X for all envs + forces = torch.zeros(NUM_CUBES_MULTI, len(body_ids), 3, device=device) + forces[..., 0] = FORCE_MAGNITUDE + torques = torch.zeros(NUM_CUBES_MULTI, len(body_ids), 3, device=device) + + cube_composer.permanent_wrench_composer.set_forces_and_torques( + forces=forces, + torques=torques, + body_ids=body_ids, + is_global=True, + ) + + # Raw PhysX data (one row per env) + raw_forces = torch.zeros(NUM_CUBES_MULTI, 3, device=device) + raw_forces[:, 0] = FORCE_MAGNITUDE + raw_torques = torch.zeros(NUM_CUBES_MULTI, 3, device=device) + raw_indices = cube_raw._ALL_INDICES + + for _ in range(N_STEPS): + cube_composer.write_data_to_sim() + cube_raw.write_data_to_sim() + cube_raw.root_view.apply_forces_and_torques_at_position( + force_data=wp.from_torch(raw_forces.contiguous(), dtype=wp.float32), + torque_data=wp.from_torch(raw_torques.contiguous(), dtype=wp.float32), + position_data=None, + indices=raw_indices, + is_global=True, + ) + sim.step() + cube_composer.update(sim.cfg.dt) + cube_raw.update(sim.cfg.dt) + + # Linear velocities should match across all envs + torch.testing.assert_close( + cube_composer.data.root_lin_vel_w.torch, + cube_raw.data.root_lin_vel_w.torch, + rtol=1e-4, + atol=1e-4, + ) + # Angular velocities should match + torch.testing.assert_close( + cube_composer.data.root_ang_vel_w.torch, + cube_raw.data.root_ang_vel_w.torch, + rtol=1e-4, + atol=1e-4, + ) + # All envs should have ~zero angular velocity + torch.testing.assert_close( + cube_composer.data.root_ang_vel_w.torch, + torch.zeros(NUM_CUBES_MULTI, 3, device=device), + rtol=0.0, + atol=1e-4, + ) + + +@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) +def test_composer_vs_physx_global_force_with_reset(device): + """Global force (no position) with a mid-simulation reset of half the envs. + + Regression: after reset the permanent wrench is cleared. Re-setting it should + produce correct behavior even though the object state was just reset. + """ + with build_simulation_context(device=device, gravity_enabled=False, auto_add_lighting=True) as sim: + sim._app_control_on_stop_handle = None + cube_composer, cube_raw = generate_dual_cube_scene( + num_cubes=NUM_CUBES_MULTI, device=device, initial_rot=ROT_45_Z, spacing=20.0 + ) + + sim.reset() + + # Capture initial world-frame state (includes env origin offsets) + cube_composer.update(sim.cfg.dt) + cube_raw.update(sim.cfg.dt) + initial_state_composer = torch.cat( + [ + cube_composer.data.root_link_pos_w.torch, + cube_composer.data.root_link_quat_w.torch, + cube_composer.data.root_com_vel_w.torch, + ], + dim=-1, + ).clone() + initial_state_raw = torch.cat( + [ + cube_raw.data.root_link_pos_w.torch, + cube_raw.data.root_link_quat_w.torch, + cube_raw.data.root_com_vel_w.torch, + ], + dim=-1, + ).clone() + + body_ids, _ = cube_composer.find_bodies(".*") + + def apply_global_force(): + """Set the same global +X force on the composer cube.""" + forces = torch.zeros(NUM_CUBES_MULTI, len(body_ids), 3, device=device) + forces[..., 0] = FORCE_MAGNITUDE + torques = torch.zeros(NUM_CUBES_MULTI, len(body_ids), 3, device=device) + cube_composer.permanent_wrench_composer.set_forces_and_torques( + forces=forces, + torques=torques, + body_ids=body_ids, + is_global=True, + ) + + apply_global_force() + + # Raw PhysX data + raw_forces = torch.zeros(NUM_CUBES_MULTI, 3, device=device) + raw_forces[:, 0] = FORCE_MAGNITUDE + raw_torques = torch.zeros(NUM_CUBES_MULTI, 3, device=device) + raw_indices = cube_raw._ALL_INDICES + + # Phase 1: run N_STEPS / 2 + half = N_STEPS // 2 + for _ in range(half): + cube_composer.write_data_to_sim() + cube_raw.write_data_to_sim() + cube_raw.root_view.apply_forces_and_torques_at_position( + force_data=wp.from_torch(raw_forces.contiguous(), dtype=wp.float32), + torque_data=wp.from_torch(raw_torques.contiguous(), dtype=wp.float32), + position_data=None, + indices=raw_indices, + is_global=True, + ) + sim.step() + cube_composer.update(sim.cfg.dt) + cube_raw.update(sim.cfg.dt) + + # Reset first half of envs on both cubes + reset_ids = list(range(NUM_CUBES_MULTI // 2)) + reset_ids_torch = torch.tensor(reset_ids, dtype=torch.long, device=device) + + # Reset root state using captured world-frame initial state (includes env origins) + cube_composer.write_root_state_to_sim(initial_state_composer[reset_ids_torch], env_ids=reset_ids_torch) + cube_raw.write_root_state_to_sim(initial_state_raw[reset_ids_torch], env_ids=reset_ids_torch) + + cube_composer.reset(reset_ids) + cube_raw.reset(reset_ids) + + # Re-apply the force (reset cleared the permanent wrench) + apply_global_force() + + # Phase 2: run N_STEPS / 2 more + for _ in range(half): + cube_composer.write_data_to_sim() + cube_raw.write_data_to_sim() + cube_raw.root_view.apply_forces_and_torques_at_position( + force_data=wp.from_torch(raw_forces.contiguous(), dtype=wp.float32), + torque_data=wp.from_torch(raw_torques.contiguous(), dtype=wp.float32), + position_data=None, + indices=raw_indices, + is_global=True, + ) + sim.step() + cube_composer.update(sim.cfg.dt) + cube_raw.update(sim.cfg.dt) + + # All envs: composer vs raw should match + torch.testing.assert_close( + cube_composer.data.root_lin_vel_w.torch, + cube_raw.data.root_lin_vel_w.torch, + rtol=1e-4, + atol=1e-4, + ) + torch.testing.assert_close( + cube_composer.data.root_ang_vel_w.torch, + cube_raw.data.root_ang_vel_w.torch, + rtol=1e-4, + atol=1e-4, + ) + # All envs should have ~zero angular velocity + torch.testing.assert_close( + cube_composer.data.root_ang_vel_w.torch, + torch.zeros(NUM_CUBES_MULTI, 3, device=device), + rtol=0.0, + atol=1e-4, + ) + + +@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) +def test_composer_vs_physx_payload_scenario(device): + """Mirrors the apply_payload MDP: permanent global downward force at CoM with gravity. + + A constant world-frame downward force (payload weight) is applied via the composer + path vs raw PhysX. The body falls under gravity + payload, contacts the ground, and + orientation changes. The composer does a world->body->world round-trip each step; + this test catches any precision drift from that. + """ + with build_simulation_context(device=device, gravity_enabled=True, auto_add_lighting=True) as sim: + sim._app_control_on_stop_handle = None + cube_composer, cube_raw = generate_dual_cube_scene( + num_cubes=1, height=0.5, device=device, initial_rot=ROT_45_Z, spacing=20.0 + ) + + sim.reset() + cube_composer.update(sim.cfg.dt) + cube_raw.update(sim.cfg.dt) + + # Record initial positions to compare displacements (cubes spawn at different Y) + init_pos_composer = cube_composer.data.root_pos_w.torch.clone() + init_pos_raw = cube_raw.data.root_pos_w.torch.clone() + + body_ids, _ = cube_composer.find_bodies(".*") + + payload_force = 2.0 * 9.81 + forces = torch.zeros(1, len(body_ids), 3, device=device) + forces[..., 2] = -payload_force + torques = torch.zeros(1, len(body_ids), 3, device=device) + + cube_composer.permanent_wrench_composer.set_forces_and_torques( + forces=forces, + torques=torques, + body_ids=body_ids, + is_global=True, + ) + + raw_forces = torch.zeros(1, 3, device=device) + raw_forces[:, 2] = -payload_force + raw_torques = torch.zeros(1, 3, device=device) + raw_indices = cube_raw._ALL_INDICES + + for _ in range(N_STEPS): + cube_composer.write_data_to_sim() + cube_raw.write_data_to_sim() + cube_raw.root_view.apply_forces_and_torques_at_position( + force_data=wp.from_torch(raw_forces.contiguous(), dtype=wp.float32), + torque_data=wp.from_torch(raw_torques.contiguous(), dtype=wp.float32), + position_data=None, + indices=raw_indices, + is_global=True, + ) + sim.step() + cube_composer.update(sim.cfg.dt) + cube_raw.update(sim.cfg.dt) + + # Compare displacements (not absolute positions — cubes have different spawn Y) + disp_composer = cube_composer.data.root_pos_w.torch - init_pos_composer + disp_raw = cube_raw.data.root_pos_w.torch - init_pos_raw + + torch.testing.assert_close(disp_composer, disp_raw, rtol=1e-4, atol=1e-4) + torch.testing.assert_close( + cube_composer.data.root_lin_vel_w.torch, + cube_raw.data.root_lin_vel_w.torch, + rtol=1e-4, + atol=1e-4, + ) + torch.testing.assert_close( + cube_composer.data.root_ang_vel_w.torch, + cube_raw.data.root_ang_vel_w.torch, + rtol=1e-4, + atol=1e-4, + ) + + +@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) +def test_composer_vs_physx_permanent_global_force_at_position_long_run(device): + """Permanent global force at a world-frame offset, run long enough for significant body motion. + + This test catches temporal drift bugs where the stored positional torque diverges from + what PhysX computes each step as the body moves. The force is large enough that the body + translates and rotates significantly over 100 steps, but not so large that it causes + numerical instability. + """ + with build_simulation_context(device=device, gravity_enabled=False, auto_add_lighting=True) as sim: + sim._app_control_on_stop_handle = None + cube_composer, cube_raw = generate_dual_cube_scene(num_cubes=1, device=device, initial_rot=ROT_45_Z) + + sim.reset() + + body_ids, _ = cube_composer.find_bodies(".*") + + # Global force +Z at +1m Y offset from CoM — produces torque around X + forces = torch.zeros(1, len(body_ids), 3, device=device) + forces[..., 2] = FORCE_MAGNITUDE + torques = torch.zeros(1, len(body_ids), 3, device=device) + + offset = torch.zeros(1, len(body_ids), 3, device=device) + offset[..., 1] = 1.0 + + pos_composer = cube_composer.data.body_com_pos_w.torch[:, body_ids, :3].clone() + offset + pos_raw = cube_raw.data.body_com_pos_w.torch[:, body_ids, :3].clone() + offset + + cube_composer.permanent_wrench_composer.set_forces_and_torques( + forces=forces, + torques=torques, + positions=pos_composer, + body_ids=body_ids, + is_global=True, + ) + + raw_forces = torch.zeros(1, 3, device=device) + raw_forces[:, 2] = FORCE_MAGNITUDE + raw_torques = torch.zeros(1, 3, device=device) + raw_positions = pos_raw.view(-1, 3) + raw_indices = cube_raw._ALL_INDICES + + for _ in range(100): + cube_composer.write_data_to_sim() + cube_raw.write_data_to_sim() + cube_raw.root_view.apply_forces_and_torques_at_position( + force_data=wp.from_torch(raw_forces.contiguous(), dtype=wp.float32), + torque_data=wp.from_torch(raw_torques.contiguous(), dtype=wp.float32), + position_data=wp.from_torch(raw_positions.contiguous(), dtype=wp.float32), + indices=raw_indices, + is_global=True, + ) + sim.step() + cube_composer.update(sim.cfg.dt) + cube_raw.update(sim.cfg.dt) + + torch.testing.assert_close( + cube_composer.data.root_lin_vel_w.torch, + cube_raw.data.root_lin_vel_w.torch, + rtol=1e-3, + atol=1e-3, + ) + torch.testing.assert_close( + cube_composer.data.root_ang_vel_w.torch, + cube_raw.data.root_ang_vel_w.torch, + rtol=1e-3, + atol=1e-3, + ) + + # Sanity: angular velocity should be nonzero + assert torch.abs(cube_composer.data.root_ang_vel_w.torch).max().item() > 0.1, ( + "Expected nonzero angular velocity from positional torque over 100 steps" + ) diff --git a/source/isaaclab/test/utils/warp/test_proxy_array.py b/source/isaaclab/test/utils/warp/test_proxy_array.py new file mode 100644 index 000000000000..08bdd4bb916e --- /dev/null +++ b/source/isaaclab/test/utils/warp/test_proxy_array.py @@ -0,0 +1,550 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Tests for the ProxyArray class.""" + +import warnings + +import pytest +import torch +import warp as wp + +wp.config.quiet = True +wp.init() + + +@pytest.fixture(params=["cpu", "cuda:0"]) +def device(request): + """Parametrize tests across CPU and CUDA devices.""" + return request.param + + +class TestProxyArrayBasic: + """Tests for basic ProxyArray functionality.""" + + def test_warp_returns_original(self, device): + """Test that .warp returns the original warp array.""" + from isaaclab.utils.warp.proxy_array import ProxyArray + + arr = wp.zeros(10, dtype=wp.float32, device=device) + ta = ProxyArray(arr) + assert ta.warp is arr + + def test_torch_returns_tensor(self, device): + """Test that .torch returns a torch.Tensor.""" + from isaaclab.utils.warp.proxy_array import ProxyArray + + arr = wp.zeros(10, dtype=wp.float32, device=device) + ta = ProxyArray(arr) + assert isinstance(ta.torch, torch.Tensor) + + def test_torch_is_cached(self, device): + """Test that .torch returns the same tensor object on repeated access.""" + from isaaclab.utils.warp.proxy_array import ProxyArray + + arr = wp.zeros(10, dtype=wp.float32, device=device) + ta = ProxyArray(arr) + t1 = ta.torch + t2 = ta.torch + assert t1 is t2 + + def test_torch_shares_memory(self, device): + """Test that .torch provides a zero-copy view (shares memory with warp).""" + from isaaclab.utils.warp.proxy_array import ProxyArray + + arr = wp.zeros(10, dtype=wp.float32, device=device) + ta = ProxyArray(arr) + t = ta.torch + # Modify the torch tensor + t[0] = 42.0 + # The change should be visible in the warp array + arr_np = arr.numpy() + assert arr_np[0] == 42.0 + + def test_immutable_warp_cannot_be_reassigned(self, device): + """ProxyArray._warp cannot be reassigned; callers must construct a new wrapper.""" + from isaaclab.utils.warp.proxy_array import ProxyArray + + arr = wp.zeros(10, dtype=wp.float32, device=device) + ta = ProxyArray(arr) + + with pytest.raises(AttributeError, match="immutable"): + ta._warp = wp.ones(10, dtype=wp.float32, device=device) + with pytest.raises(AttributeError, match="immutable"): + ta.new_field = 42 # arbitrary attribute writes also blocked + + def test_immutable_allows_internal_torch_cache(self, device): + """Lazy .torch caching still works — only _torch_cache is allowed as a post-init write.""" + from isaaclab.utils.warp.proxy_array import ProxyArray + + arr = wp.zeros(10, dtype=wp.float32, device=device) + ta = ProxyArray(arr) + # First access populates the cache; no exception. + first = ta.torch + # Subsequent accesses return the same cached tensor. + second = ta.torch + assert first is second + + def test_cuda_array_interface(self): + """Test that __cuda_array_interface__ delegates to the underlying warp array.""" + from isaaclab.utils.warp.proxy_array import ProxyArray + + arr = wp.zeros(10, dtype=wp.float32, device="cuda:0") + ta = ProxyArray(arr) + cai = ta.__cuda_array_interface__ + assert isinstance(cai, dict) + assert "data" in cai + assert "shape" in cai + assert cai["shape"] == arr.__cuda_array_interface__["shape"] + + def test_cuda_array_interface_not_on_cpu(self): + """Test that __cuda_array_interface__ raises AttributeError on CPU arrays.""" + from isaaclab.utils.warp.proxy_array import ProxyArray + + arr = wp.zeros(10, dtype=wp.float32, device="cpu") + ta = ProxyArray(arr) + with pytest.raises(AttributeError): + _ = ta.__cuda_array_interface__ + + def test_wp_launch_accepts_proxy_array(self): + """Test that wp.launch() can consume a ProxyArray via __cuda_array_interface__.""" + from isaaclab.utils.warp.proxy_array import ProxyArray + + @wp.kernel + def _add_one(src: wp.array(dtype=wp.float32), dst: wp.array(dtype=wp.float32)): + i = wp.tid() + dst[i] = src[i] + 1.0 + + src = ProxyArray(wp.zeros(5, dtype=wp.float32, device="cuda:0")) + dst = ProxyArray(wp.zeros(5, dtype=wp.float32, device="cuda:0")) + wp.launch(_add_one, dim=5, inputs=[src], outputs=[dst], device="cuda:0") + wp.synchronize_device("cuda:0") + assert dst.torch[0].item() == 1.0 + assert dst.torch[4].item() == 1.0 + + +class TestProxyArrayStructuredTypes: + """Tests for ProxyArray with structured warp types (vec3f, quatf, etc).""" + + def test_vec3f_shape(self, device): + """Test that vec3f arrays produce (N, 3) torch tensors.""" + from isaaclab.utils.warp.proxy_array import ProxyArray + + arr = wp.zeros(8, dtype=wp.vec3f, device=device) + ta = ProxyArray(arr) + assert ta.torch.shape == (8, 3) + + def test_quatf_shape(self, device): + """Test that quatf arrays produce (N, 4) torch tensors.""" + from isaaclab.utils.warp.proxy_array import ProxyArray + + arr = wp.zeros(8, dtype=wp.quatf, device=device) + ta = ProxyArray(arr) + assert ta.torch.shape == (8, 4) + + def test_transformf_shape(self, device): + """Test that transformf arrays produce (N, 7) torch tensors.""" + from isaaclab.utils.warp.proxy_array import ProxyArray + + arr = wp.zeros(8, dtype=wp.transformf, device=device) + ta = ProxyArray(arr) + assert ta.torch.shape == (8, 7) + + def test_spatial_vectorf_shape(self, device): + """Test that spatial_vectorf arrays produce (N, 6) torch tensors.""" + from isaaclab.utils.warp.proxy_array import ProxyArray + + arr = wp.zeros(8, dtype=wp.spatial_vectorf, device=device) + ta = ProxyArray(arr) + assert ta.torch.shape == (8, 6) + + def test_2d_vec3f_shape(self, device): + """Test that 2D vec3f arrays produce (N, M, 3) torch tensors.""" + from isaaclab.utils.warp.proxy_array import ProxyArray + + arr = wp.zeros((4, 5), dtype=wp.vec3f, device=device) + ta = ProxyArray(arr) + assert ta.torch.shape == (4, 5, 3) + + +class TestProxyArrayQuatfTorchAccessWarning: + """Tests for the WARN_ON_TORCH_QUATF_ACCESS opt-in runtime detector.""" + + def test_default_no_warning(self, device, monkeypatch): + """No env var → quatf .torch access is silent.""" + from isaaclab.utils.warp.proxy_array import ProxyArray + + monkeypatch.delenv("WARN_ON_TORCH_QUATF_ACCESS", raising=False) + ta = ProxyArray(wp.zeros(4, dtype=wp.quatf, device=device)) + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter("always") + _ = ta.torch + assert [x for x in w if issubclass(x.category, UserWarning)] == [] + + def test_env_set_warns_on_quatf(self, device, monkeypatch): + """WARN_ON_TORCH_QUATF_ACCESS=1 → quatf .torch read emits a UserWarning at the call site.""" + from isaaclab.utils.warp.proxy_array import ProxyArray + + monkeypatch.setenv("WARN_ON_TORCH_QUATF_ACCESS", "1") + ta = ProxyArray(wp.zeros(4, dtype=wp.quatf, device=device)) + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter("always") + _ = ta.torch # the .torch read on this line is what should be reported + user_warns = [x for x in w if issubclass(x.category, UserWarning)] + assert len(user_warns) == 1 + assert "quatf" in str(user_warns[0].message) + assert "(w, x, y, z)" in str(user_warns[0].message) + assert "(x, y, z, w)" in str(user_warns[0].message) + # stacklevel=2 → the warning's filename is this test file, not proxy_array.py + assert user_warns[0].filename == __file__ + + def test_env_set_does_not_warn_on_non_quatf(self, device, monkeypatch): + """The detector only fires for wp.quatf — float32 / vec3f / transformf are silent.""" + from isaaclab.utils.warp.proxy_array import ProxyArray + + monkeypatch.setenv("WARN_ON_TORCH_QUATF_ACCESS", "1") + for dtype in (wp.float32, wp.vec3f, wp.transformf, wp.spatial_vectorf): + ta = ProxyArray(wp.zeros(4, dtype=dtype, device=device)) + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter("always") + _ = ta.torch + assert [x for x in w if issubclass(x.category, UserWarning)] == [] + + def test_env_zero_does_not_warn(self, device, monkeypatch): + """WARN_ON_TORCH_QUATF_ACCESS=0 → silent (only ``"1"`` enables the detector).""" + from isaaclab.utils.warp.proxy_array import ProxyArray + + monkeypatch.setenv("WARN_ON_TORCH_QUATF_ACCESS", "0") + ta = ProxyArray(wp.zeros(4, dtype=wp.quatf, device=device)) + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter("always") + _ = ta.torch + assert [x for x in w if issubclass(x.category, UserWarning)] == [] + + +class TestProxyArrayConvenienceProperties: + """Tests for convenience properties: shape, dtype, device, len, repr.""" + + def test_shape(self, device): + """Test that .shape returns the warp array shape.""" + from isaaclab.utils.warp.proxy_array import ProxyArray + + arr = wp.zeros((3, 4), dtype=wp.float32, device=device) + ta = ProxyArray(arr) + assert ta.shape == (3, 4) + + def test_dtype(self, device): + """Test that .dtype returns the warp dtype.""" + from isaaclab.utils.warp.proxy_array import ProxyArray + + arr = wp.zeros(10, dtype=wp.float32, device=device) + ta = ProxyArray(arr) + assert ta.dtype == wp.float32 + + def test_device(self, device): + """Test that .device returns the warp device string.""" + from isaaclab.utils.warp.proxy_array import ProxyArray + + arr = wp.zeros(10, dtype=wp.float32, device=device) + ta = ProxyArray(arr) + assert ta.device == arr.device + + def test_len(self, device): + """Test that len() returns the first dimension size.""" + from isaaclab.utils.warp.proxy_array import ProxyArray + + arr = wp.zeros((7, 3), dtype=wp.float32, device=device) + ta = ProxyArray(arr) + assert len(ta) == 7 + + def test_repr(self, device): + """Test that repr() contains ProxyArray and key info.""" + from isaaclab.utils.warp.proxy_array import ProxyArray + + arr = wp.zeros(5, dtype=wp.float32, device=device) + ta = ProxyArray(arr) + r = repr(ta) + assert "ProxyArray" in r + assert "float32" in r + + +class TestProxyArrayDeprecationBridge: + """Tests for the deprecation bridge: __torch_function__, operators.""" + + def setup_method(self): + """Reset the deprecation warning flag before each test.""" + from isaaclab.utils.warp.proxy_array import ProxyArray + + ProxyArray._deprecation_warned = False + + def test_torch_function_works_and_warns(self, device): + """Test that __torch_function__ enables torch ops and emits a deprecation warning.""" + from isaaclab.utils.warp.proxy_array import ProxyArray + + arr = wp.ones(5, dtype=wp.float32, device=device) + ta = ProxyArray(arr) + + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter("always") + result = torch.sum(ta) + assert len(w) == 1 + assert issubclass(w[0].category, DeprecationWarning) + assert isinstance(result, torch.Tensor) + assert result.item() == pytest.approx(5.0) + + def test_torch_cat_works_and_warns(self, device): + """Test that torch.cat works with ProxyArray and emits a deprecation warning.""" + from isaaclab.utils.warp.proxy_array import ProxyArray + + a1 = wp.ones(3, dtype=wp.float32, device=device) + a2 = wp.ones(4, dtype=wp.float32, device=device) + ta1, ta2 = ProxyArray(a1), ProxyArray(a2) + + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter("always") + result = torch.cat([ta1, ta2]) + assert len(w) == 1 + assert issubclass(w[0].category, DeprecationWarning) + assert result.shape == (7,) + + def test_arithmetic_operators_work_and_warn(self, device): + """Test that arithmetic operators work and emit deprecation warnings.""" + from isaaclab.utils.warp.proxy_array import ProxyArray + + arr = wp.ones(5, dtype=wp.float32, device=device) + ta = ProxyArray(arr) + + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter("always") + result = ta + 1.0 + assert len(w) == 1 + assert issubclass(w[0].category, DeprecationWarning) + assert isinstance(result, torch.Tensor) + expected = torch.full((5,), 2.0, device=device) + torch.testing.assert_close(result, expected) + + def test_warns_only_once(self, device): + """Test that the deprecation warning is emitted only once per session.""" + from isaaclab.utils.warp.proxy_array import ProxyArray + + arr = wp.ones(5, dtype=wp.float32, device=device) + ta = ProxyArray(arr) + + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter("always") + _ = ta + 1.0 + _ = ta * 2.0 + _ = ta - 0.5 + # Only one warning despite three operations + assert len(w) == 1 + + def test_tensor_plus_proxy_array(self, device): + """Test that torch.Tensor + ProxyArray works via __torch_function__.""" + from isaaclab.utils.warp.proxy_array import ProxyArray + + arr = wp.ones(5, dtype=wp.float32, device=device) + ta = ProxyArray(arr) + t = torch.ones(5, device=device) * 2.0 + + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter("always") + result = t + ta + assert len(w) == 1 + assert issubclass(w[0].category, DeprecationWarning) + expected = torch.full((5,), 3.0, device=device) + torch.testing.assert_close(result, expected) + + @pytest.mark.parametrize( + "op, scalar, expected", + [ + ("+", 1.0, [2.0, 3.0]), + ("-", 1.0, [0.0, 1.0]), + ("*", 2.0, [2.0, 4.0]), + ("/", 2.0, [0.5, 1.0]), + ("**", 2.0, [1.0, 4.0]), + ], + ) + def test_binary_operators(self, op, scalar, expected): + """Test forward binary operators: +, -, *, /, **.""" + from isaaclab.utils.warp.proxy_array import ProxyArray + + ProxyArray._deprecation_warned = True + ta = ProxyArray(wp.array([1.0, 2.0], dtype=wp.float32, device="cpu")) # noqa: F841 + result = eval(f"ta {op} scalar") # noqa: S307 + assert torch.allclose(result, torch.tensor(expected)) + + @pytest.mark.parametrize( + "op, scalar, expected", + [ + ("+", 1.0, [2.0, 3.0]), + ("-", 1.0, [0.0, -1.0]), + ("*", 2.0, [2.0, 4.0]), + ("/", 2.0, [2.0, 1.0]), + ("**", 2.0, [2.0, 4.0]), + ], + ) + def test_reflected_operators(self, op, scalar, expected): + """Test reflected binary operators: scalar op ProxyArray.""" + from isaaclab.utils.warp.proxy_array import ProxyArray + + ProxyArray._deprecation_warned = True + ta = ProxyArray(wp.array([1.0, 2.0], dtype=wp.float32, device="cpu")) # noqa: F841 + result = eval(f"scalar {op} ta") # noqa: S307 + assert torch.allclose(result, torch.tensor(expected)) + + def test_proxy_array_op_proxy_array(self): + """Test binary operations between two ProxyArray instances.""" + from isaaclab.utils.warp.proxy_array import ProxyArray + + ProxyArray._deprecation_warned = True + ta1 = ProxyArray(wp.array([1.0, 2.0], dtype=wp.float32, device="cpu")) + ta2 = ProxyArray(wp.array([3.0, 4.0], dtype=wp.float32, device="cpu")) + assert torch.allclose(ta1 + ta2, torch.tensor([4.0, 6.0])) + assert torch.allclose(ta1 * ta2, torch.tensor([3.0, 8.0])) + assert torch.allclose(ta2 - ta1, torch.tensor([2.0, 2.0])) + + @pytest.mark.parametrize( + "op, values, expected", + [ + ("-", [1.0, -2.0], [-1.0, 2.0]), + ("+", [1.0, -2.0], [1.0, -2.0]), + ("abs", [-1.0, 2.0], [1.0, 2.0]), + ], + ) + def test_unary_operators(self, op, values, expected): + """Test unary operators: -, +, abs.""" + from isaaclab.utils.warp.proxy_array import ProxyArray + + ProxyArray._deprecation_warned = True + ta = ProxyArray(wp.array(values, dtype=wp.float32, device="cpu")) # noqa: F841 + result = eval(f"{op}(ta)" if op == "abs" else f"{op}ta") # noqa: S307 + assert torch.allclose(result, torch.tensor(expected)) + + @pytest.mark.parametrize( + "op, expected", + [ + ("==", [False, True, False]), + ("!=", [True, False, True]), + ("<", [True, False, False]), + ("<=", [True, True, False]), + (">", [False, False, True]), + (">=", [False, True, True]), + ], + ) + def test_comparison_operators(self, op, expected): + """Test comparison operators: ==, !=, <, <=, >, >=.""" + from isaaclab.utils.warp.proxy_array import ProxyArray + + ProxyArray._deprecation_warned = True + ta = ProxyArray(wp.array([1.0, 2.0, 3.0], dtype=wp.float32, device="cpu")) # noqa: F841 + result = eval(f"ta {op} 2.0") # noqa: S307 + assert result.tolist() == expected + + def test_getitem_1d(self): + """Test 1D indexing via __getitem__.""" + from isaaclab.utils.warp.proxy_array import ProxyArray + + ProxyArray._deprecation_warned = True + ta = ProxyArray(wp.array([10.0, 20.0, 30.0], dtype=wp.float32, device="cpu")) + assert ta[0].item() == 10.0 + assert ta[-1].item() == 30.0 + assert ta[1:].tolist() == [20.0, 30.0] + + def test_getitem_nd(self): + """Test multi-dimensional indexing via __getitem__ with structured types.""" + from isaaclab.utils.warp.proxy_array import ProxyArray + + ProxyArray._deprecation_warned = True + wp_arr = wp.zeros((3, 4), dtype=wp.vec3f, device="cpu") + ta = ProxyArray(wp_arr) + # torch view is (3, 4, 3) + result = ta[:, 0, :] + assert result.shape == (3, 3) + result = ta[0, :, 2] + assert result.shape == (4,) + + def test_setitem_writes_through(self): + """Test __setitem__ writes through to shared warp memory.""" + from isaaclab.utils.warp.proxy_array import ProxyArray + + ProxyArray._deprecation_warned = True + wp_arr = wp.array([1.0, 2.0, 3.0], dtype=wp.float32, device="cpu") + ta = ProxyArray(wp_arr) + ta[0] = 99.0 + assert wp_arr.numpy()[0] == 99.0 + + def test_getitem_warns(self): + """Test __getitem__ emits deprecation warning.""" + from isaaclab.utils.warp.proxy_array import ProxyArray + + ProxyArray._deprecation_warned = False + ta = ProxyArray(wp.array([1.0, 2.0], dtype=wp.float32, device="cpu")) + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter("always") + _ = ta[0] + deprecation_warnings = [x for x in w if issubclass(x.category, DeprecationWarning)] + assert len(deprecation_warnings) == 1 + + +class TestWpToTorchShim: + """Tests for the ``wp.to_torch`` shim installed by ``isaaclab.utils.warp``. + + The shim makes legacy call sites like ``wp.to_torch(asset.data.joint_pos)`` + keep working after the ProxyArray migration, instead of raising + ``AttributeError`` on ``requires_grad`` lookup. + """ + + def test_raw_wp_array_unchanged(self): + """``wp.to_torch(wp.array)`` must still produce a zero-copy torch view.""" + import isaaclab.utils.warp # noqa: F401 # ensure shim is installed + + arr = wp.array([1.0, 2.0, 3.0], dtype=wp.float32, device="cpu") + t = wp.to_torch(arr) + assert isinstance(t, torch.Tensor) + assert t.shape == (3,) + + def test_proxy_array_returns_torch_with_warning(self): + """``wp.to_torch(ProxyArray)`` returns the cached .torch view and warns once.""" + import isaaclab.utils.warp as iw # noqa: F401 # ensure shim is installed + from isaaclab.utils.warp.proxy_array import ProxyArray + + # Reset the module-level one-shot flag so the warning fires in this test. + iw._WP_TO_TORCH_WARNED = False + + arr = wp.array([7.0, 8.0], dtype=wp.float32, device="cpu") + proxy = ProxyArray(arr) + + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + t = wp.to_torch(proxy) + deprecation = [w for w in caught if issubclass(w.category, DeprecationWarning)] + + assert isinstance(t, torch.Tensor) + assert t is proxy.torch, "shim should return the cached .torch view" + assert len(deprecation) == 1 + assert "ProxyArray" in str(deprecation[0].message) + + def test_proxy_array_warning_is_one_shot(self): + """Repeated ``wp.to_torch(ProxyArray)`` calls must not spam warnings.""" + import isaaclab.utils.warp as iw + from isaaclab.utils.warp.proxy_array import ProxyArray + + iw._WP_TO_TORCH_WARNED = True # pretend the warning already fired + + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + wp.to_torch(ProxyArray(wp.zeros(2, dtype=wp.float32, device="cpu"))) + deprecation = [w for w in caught if issubclass(w.category, DeprecationWarning)] + + assert not deprecation, "shim must not re-warn after the first call" + + def test_requires_grad_forwarded_to_raw_wp_array(self): + """The ``requires_grad`` kwarg still reaches the original ``wp.to_torch``.""" + import isaaclab.utils.warp # noqa: F401 + + arr = wp.array([1.0, 2.0], dtype=wp.float32, device="cpu") + t = wp.to_torch(arr, requires_grad=False) + assert isinstance(t, torch.Tensor) + assert t.requires_grad is False diff --git a/source/isaaclab/test/visualizers/test_visualizer.py b/source/isaaclab/test/visualizers/test_visualizer.py index ed1baf9198c1..44d3a89aea16 100644 --- a/source/isaaclab/test/visualizers/test_visualizer.py +++ b/source/isaaclab/test/visualizers/test_visualizer.py @@ -7,6 +7,7 @@ from __future__ import annotations +import importlib.util from types import SimpleNamespace import pytest @@ -61,15 +62,18 @@ def is_running(self) -> bool: def _make_cfg(**kwargs): cfg = { - "env_filter_mode": "none", - "env_filter_ids": [0, 2, 4], - "env_filter_random_n": 2, - "env_filter_seed": 7, + "max_visible_envs": None, + "visible_env_indices": None, + # Default off in tests: contiguous cap-only path matches historical assertions. + "randomly_sample_visible_envs": False, } cfg.update(kwargs) return SimpleNamespace(**cfg) +_HAS_ISAACLAB_VIZ = importlib.util.find_spec("isaaclab_visualizers") is not None + + class _FakeProvider: def __init__(self, num_envs: int = 0, transforms: dict | None = None): self._num_envs = num_envs @@ -82,25 +86,68 @@ def get_camera_transforms(self): return self._transforms -def test_compute_visualized_env_ids_none_mode(): - viz = _DummyVisualizer(_make_cfg(env_filter_mode="none")) +def test_compute_visualized_env_ids_cap_only_returns_none(): + """Cap-only path: :meth:`_compute_visualized_env_ids` is ``None``. + + The cap is applied later by ``resolve_visible_env_indices``. + """ + viz = _DummyVisualizer(_make_cfg(visible_env_indices=None)) viz._scene_data_provider = _FakeProvider(num_envs=8) assert viz._compute_visualized_env_ids() is None -def test_compute_visualized_env_ids_from_ids_filters_out_of_range(): - viz = _DummyVisualizer(_make_cfg(env_filter_mode="env_ids", env_filter_ids=[-1, 0, 3, 99])) +def test_compute_visualized_env_ids_from_visible_indices_filters_out_of_range(): + viz = _DummyVisualizer(_make_cfg(visible_env_indices=[-1, 0, 3, 99])) viz._scene_data_provider = _FakeProvider(num_envs=4) assert viz._compute_visualized_env_ids() == [0, 3] -def test_compute_visualized_env_ids_random_n_is_deterministic(): - cfg = _make_cfg(env_filter_mode="random_n", env_filter_random_n=3, env_filter_seed=123) - viz_a = _DummyVisualizer(cfg) - viz_b = _DummyVisualizer(cfg) - viz_a._scene_data_provider = _FakeProvider(num_envs=10) - viz_b._scene_data_provider = _FakeProvider(num_envs=10) - assert viz_a._compute_visualized_env_ids() == viz_b._compute_visualized_env_ids() +@pytest.mark.skipif(not _HAS_ISAACLAB_VIZ, reason="isaaclab_visualizers not installed") +def test_partial_visualization_cap_only_uses_resolver(): + """With ``visible_env_indices`` unset, :func:`resolve_visible_env_indices` applies ``max_visible_envs``.""" + from isaaclab_visualizers.newton_adapter import resolve_visible_env_indices + + cfg = _make_cfg(max_visible_envs=3, visible_env_indices=None) + viz = _DummyVisualizer(cfg) + viz._scene_data_provider = _FakeProvider(num_envs=10) + assert viz._compute_visualized_env_ids() is None + assert resolve_visible_env_indices(None, cfg.max_visible_envs, 10) == [0, 1, 2] + assert resolve_visible_env_indices(None, 3, 10) == [0, 1, 2] + + +@pytest.mark.skipif(not _HAS_ISAACLAB_VIZ, reason="isaaclab_visualizers not installed") +def test_compute_visualized_env_ids_random_cap_only_sorted_once(): + """Cap-only random mode returns a sorted sample; explicit indices ignore the flag.""" + cfg = _make_cfg(max_visible_envs=3, visible_env_indices=None, randomly_sample_visible_envs=True) + viz = _DummyVisualizer(cfg) + viz._scene_data_provider = _FakeProvider(num_envs=10) + sampled = viz._compute_visualized_env_ids() + assert sampled is not None and len(sampled) == 3 + assert sampled == sorted(sampled) + assert len(set(sampled)) == 3 + assert all(0 <= i < 10 for i in sampled) + + cfg_explicit = _make_cfg( + visible_env_indices=[1, 5], + max_visible_envs=1, + randomly_sample_visible_envs=True, + ) + viz2 = _DummyVisualizer(cfg_explicit) + viz2._scene_data_provider = _FakeProvider(num_envs=10) + assert viz2._compute_visualized_env_ids() == [1, 5] + + +@pytest.mark.skipif(not _HAS_ISAACLAB_VIZ, reason="isaaclab_visualizers not installed") +def test_explicit_visible_env_indices_truncated_by_max_visible_envs(): + """Explicit indices from :meth:`_compute_visualized_env_ids`; ``max_visible_envs`` truncates from the end.""" + from isaaclab_visualizers.newton_adapter import resolve_visible_env_indices + + cfg = _make_cfg(visible_env_indices=[0, 2, 4], max_visible_envs=1) + viz = _DummyVisualizer(cfg) + viz._scene_data_provider = _FakeProvider(num_envs=10) + ids = viz._compute_visualized_env_ids() + assert ids == [0, 2, 4] + assert resolve_visible_env_indices(ids, cfg.max_visible_envs, 10) == [0] def test_resolve_camera_pose_from_usd_path_uses_provider_transforms(): diff --git a/source/isaaclab_assets/changelog.d/.gitkeep b/source/isaaclab_assets/changelog.d/.gitkeep new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/source/isaaclab_assets/config/extension.toml b/source/isaaclab_assets/config/extension.toml index f9cba2e4f4d3..1bf36d627e3e 100644 --- a/source/isaaclab_assets/config/extension.toml +++ b/source/isaaclab_assets/config/extension.toml @@ -1,6 +1,6 @@ [package] # Semantic Versioning is used: https://semver.org/ -version = "0.3.0" +version = "0.3.3" # Description title = "Isaac Lab Assets" diff --git a/source/isaaclab_assets/docs/CHANGELOG.rst b/source/isaaclab_assets/docs/CHANGELOG.rst index f08751773d55..1d676f70a27e 100644 --- a/source/isaaclab_assets/docs/CHANGELOG.rst +++ b/source/isaaclab_assets/docs/CHANGELOG.rst @@ -1,6 +1,34 @@ Changelog --------- +0.3.3 (2026-04-29) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added configuration for Flexiv Rizon 4s with Grav parallel gripper for manipulation tasks. + + +0.3.2 (2026-04-13) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed Cassie failing to load on Newton by enabling + :attr:`~isaaclab.sim.schemas.JointDrivePropertiesCfg.ensure_drives_exist` + in :data:`~isaaclab_assets.robots.cassie.CASSIE_CFG`. + + +0.3.1 (2026-02-17) +~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Configuration for Flexiv Rizon 4s robot used for manipulation tasks. + 0.3.0 (2026-01-30) ~~~~~~~~~~~~~~~~~~~ @@ -9,7 +37,6 @@ Changed * Changed the quaternion ordering to match warp, PhysX, and Newton native XYZW quaternion ordering. - 0.2.4 (2025-11-26) ~~~~~~~~~~~~~~~~~~ diff --git a/source/isaaclab_assets/isaaclab_assets/__init__.pyi b/source/isaaclab_assets/isaaclab_assets/__init__.pyi index 3de7508d21ec..dc69e0b8c71c 100644 --- a/source/isaaclab_assets/isaaclab_assets/__init__.pyi +++ b/source/isaaclab_assets/isaaclab_assets/__init__.pyi @@ -54,6 +54,8 @@ __all__ = [ "UR10_SHORT_SUCTION_CFG", "UR10e_ROBOTIQ_GRIPPER_CFG", "UR10e_ROBOTIQ_2F_85_CFG", + "FLEXIV_RIZON4S_CFG", + "FLEXIV_RIZON4S_GRAV_GRIPPER_CFG", "GELSIGHT_R15_CFG", "GELSIGHT_MINI_CFG", "VELODYNE_VLP_16_RAYCASTER_CFG", @@ -115,5 +117,7 @@ from .robots import ( UR10_SHORT_SUCTION_CFG, UR10e_ROBOTIQ_GRIPPER_CFG, UR10e_ROBOTIQ_2F_85_CFG, + FLEXIV_RIZON4S_CFG, + FLEXIV_RIZON4S_GRAV_GRIPPER_CFG, ) from .sensors import GELSIGHT_R15_CFG, GELSIGHT_MINI_CFG, VELODYNE_VLP_16_RAYCASTER_CFG diff --git a/source/isaaclab_assets/isaaclab_assets/robots/__init__.pyi b/source/isaaclab_assets/isaaclab_assets/robots/__init__.pyi index f66adcf2ab8e..1a91afa213a7 100644 --- a/source/isaaclab_assets/isaaclab_assets/robots/__init__.pyi +++ b/source/isaaclab_assets/isaaclab_assets/robots/__init__.pyi @@ -54,6 +54,8 @@ __all__ = [ "UR10_SHORT_SUCTION_CFG", "UR10e_ROBOTIQ_GRIPPER_CFG", "UR10e_ROBOTIQ_2F_85_CFG", + "FLEXIV_RIZON4S_CFG", + "FLEXIV_RIZON4S_GRAV_GRIPPER_CFG", ] from .agibot import AGIBOT_A2D_CFG @@ -104,3 +106,4 @@ from .universal_robots import ( UR10e_ROBOTIQ_GRIPPER_CFG, UR10e_ROBOTIQ_2F_85_CFG, ) +from .flexiv import FLEXIV_RIZON4S_CFG, FLEXIV_RIZON4S_GRAV_GRIPPER_CFG diff --git a/source/isaaclab_assets/isaaclab_assets/robots/cassie.py b/source/isaaclab_assets/isaaclab_assets/robots/cassie.py index 09e75e241fed..faaefc414164 100644 --- a/source/isaaclab_assets/isaaclab_assets/robots/cassie.py +++ b/source/isaaclab_assets/isaaclab_assets/robots/cassie.py @@ -37,6 +37,7 @@ articulation_props=sim_utils.ArticulationRootPropertiesCfg( enabled_self_collisions=True, solver_position_iteration_count=4, solver_velocity_iteration_count=0 ), + joint_drive_props=sim_utils.JointDrivePropertiesCfg(ensure_drives_exist=True), ), init_state=ArticulationCfg.InitialStateCfg( pos=(0.0, 0.0, 0.9), diff --git a/source/isaaclab_assets/isaaclab_assets/robots/flexiv.py b/source/isaaclab_assets/isaaclab_assets/robots/flexiv.py new file mode 100644 index 000000000000..18adf4312022 --- /dev/null +++ b/source/isaaclab_assets/isaaclab_assets/robots/flexiv.py @@ -0,0 +1,171 @@ +# Copyright (c) 2026-2027, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + + +"""Configuration for the Flexiv Rizon robots. + +The following configurations are available: + +* :obj:`FLEXIV_RIZON4S_CFG`: The Flexiv Rizon 4s arm without a gripper. +* :obj:`FLEXIV_RIZON4S_GRAV_GRIPPER_CFG`: The Flexiv Rizon 4s arm with Grav gripper. + +Reference: https://www.flexiv.com/product/rizon +""" + +import isaaclab.sim as sim_utils +from isaaclab.actuators import ImplicitActuatorCfg +from isaaclab.assets.articulation import ArticulationCfg +from isaaclab.utils.assets import ISAACLAB_NUCLEUS_DIR + +## +# Configuration +## + +FLEXIV_RIZON4S_CFG = ArticulationCfg( + spawn=sim_utils.UsdFileCfg( + usd_path=f"{ISAACLAB_NUCLEUS_DIR}/Robots/Flexiv/Rizon4s/rizon4s.usd", + rigid_props=sim_utils.RigidBodyPropertiesCfg( + disable_gravity=True, + max_depenetration_velocity=5.0, + ), + articulation_props=sim_utils.ArticulationRootPropertiesCfg( + enabled_self_collisions=False, + solver_position_iteration_count=16, + solver_velocity_iteration_count=1, + ), + activate_contact_sensors=False, + ), + init_state=ArticulationCfg.InitialStateCfg( + joint_pos={ + "joint1": 0.0, + "joint2": -0.698, + "joint3": 0.0, + "joint4": 1.571, + "joint5": 0.0, + "joint6": 0.698, + "joint7": 0.0, + }, + pos=(0.0, 0.0, 0.0), + rot=(0.0, 0.0, 0.0, 1.0), + ), + actuators={ + "shoulder": ImplicitActuatorCfg( + joint_names_expr=["joint[1-2]"], + effort_limit_sim=123.0, + velocity_limit_sim=2.094, + stiffness=6000.0, + damping=108.5, + friction=0.0, + armature=0.0, + ), + "elbow": ImplicitActuatorCfg( + joint_names_expr=["joint[3-4]"], + effort_limit_sim=64.0, + velocity_limit_sim=2.443, + stiffness=4200.0, + damping=90.7, + friction=0.0, + armature=0.0, + ), + "wrist": ImplicitActuatorCfg( + joint_names_expr=["joint[5-7]"], + effort_limit_sim=39.0, + velocity_limit_sim=4.887, + stiffness=1500.0, + damping=54.2, + friction=0.0, + armature=0.0, + ), + }, +) +"""Configuration of Flexiv Rizon 4s arm using implicit actuator models.""" + + +FLEXIV_RIZON4S_GRAV_GRIPPER_CFG = ArticulationCfg( + spawn=sim_utils.UsdFileCfg( + usd_path=f"{ISAACLAB_NUCLEUS_DIR}/Robots/Flexiv/Rizon4s/rizon4s_with_grav.usd", + rigid_props=sim_utils.RigidBodyPropertiesCfg( + disable_gravity=False, + max_depenetration_velocity=5.0, + ), + articulation_props=sim_utils.ArticulationRootPropertiesCfg( + enabled_self_collisions=False, + solver_position_iteration_count=16, + solver_velocity_iteration_count=1, + ), + activate_contact_sensors=False, + ), + init_state=ArticulationCfg.InitialStateCfg( + joint_pos={ + "joint1": 0.0, + "joint2": -0.698, + "joint3": 0.0, + "joint4": 1.571, + "joint5": 0.0, + "joint6": 0.698, + "joint7": 0.0, + "finger_joint": 0.0, + "left_outer_finger_joint": 0.0, + "right_outer_finger_joint": 0.0, + }, + pos=(0.0, 0.0, 0.0), + rot=(0.0, 0.0, 0.0, 1.0), + ), + actuators={ + "shoulder": ImplicitActuatorCfg( + joint_names_expr=["joint[1-2]"], + effort_limit_sim=123.0, + velocity_limit_sim=2.094, + stiffness=1320.0, + damping=72.0, + friction=0.0, + armature=0.0, + ), + "elbow": ImplicitActuatorCfg( + joint_names_expr=["joint[3-4]"], + effort_limit_sim=64.0, + velocity_limit_sim=2.443, + stiffness=600.0, + damping=35.0, + friction=0.0, + armature=0.0, + ), + "wrist": ImplicitActuatorCfg( + joint_names_expr=["joint[5-7]"], + effort_limit_sim=39.0, + velocity_limit_sim=4.887, + stiffness=216.0, + damping=29.0, + friction=0.0, + armature=0.0, + ), + "gripper_drive": ImplicitActuatorCfg( + joint_names_expr=["finger_joint"], + effort_limit_sim=200.0, + velocity_limit_sim=0.6, + stiffness=2e3, + damping=1e1, + friction=0.0, + armature=0.0, + ), + "gripper_passive": ImplicitActuatorCfg( + joint_names_expr=[".*_knuckle_joint"], + effort_limit_sim=1.0, + velocity_limit_sim=1.0, + stiffness=0.0, + damping=0.0, + friction=0.0, + armature=0.0, + ), + }, +) +"""Configuration of Flexiv Rizon 4s arm with Grav gripper using implicit actuator models. + +The Grav gripper is a parallel gripper with the following joint configuration: +- finger_joint: Main actuation joint (opened: 45 deg, closed: -8.88 deg) +- *_knuckle_joint: Passive/mimic joints (not directly actuated) + +End effector body: right_finger_tip +""" diff --git a/source/isaaclab_assets/setup.py b/source/isaaclab_assets/setup.py index 862cc5bf6892..1e678c893be3 100644 --- a/source/isaaclab_assets/setup.py +++ b/source/isaaclab_assets/setup.py @@ -26,14 +26,11 @@ keywords=EXTENSION_TOML_DATA["package"]["keywords"], include_package_data=True, package_data={"": ["*.pyi"]}, - python_requires=">=3.10", + python_requires=">=3.12", packages=["isaaclab_assets"], classifiers=[ "Natural Language :: English", - "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", - "Isaac Sim :: 5.0.0", - "Isaac Sim :: 5.1.0", "Isaac Sim :: 6.0.0", ], zip_safe=False, diff --git a/source/isaaclab_contrib/changelog.d/.gitkeep b/source/isaaclab_contrib/changelog.d/.gitkeep new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/source/isaaclab_contrib/docs/README.md b/source/isaaclab_contrib/docs/README.md index 1861b593bd50..346b47e5522c 100644 --- a/source/isaaclab_contrib/docs/README.md +++ b/source/isaaclab_contrib/docs/README.md @@ -256,7 +256,7 @@ The TacSL tactile sensor system includes: ```python import isaaclab.sim as sim_utils -from isaaclab.sensors import TiledCameraCfg +from isaaclab.sensors import CameraCfg from isaaclab_contrib.sensors.tacsl_sensor import VisuoTactileSensorCfg @@ -287,8 +287,8 @@ tactile_sensor_cfg = VisuoTactileSensorCfg( friction_coefficient=2.0, # Surface friction tangential_stiffness=0.1, # Tangential stiffness - # Camera configuration (must match render_cfg dimensions) - camera_cfg=TiledCameraCfg( + # Camera configuration (dimensions must match GELSIGHT_R15_CFG which provides the render_cfg) + camera_cfg=CameraCfg( prim_path="{ENV_REGEX_NS}/Robot/elastomer_tip/cam", height=GELSIGHT_R15_CFG.image_height, width=GELSIGHT_R15_CFG.image_width, diff --git a/source/isaaclab_contrib/isaaclab_contrib/sensors/tacsl_sensor/visuotactile_sensor.py b/source/isaaclab_contrib/isaaclab_contrib/sensors/tacsl_sensor/visuotactile_sensor.py index 576ec4d90af6..720a85223aa6 100644 --- a/source/isaaclab_contrib/isaaclab_contrib/sensors/tacsl_sensor/visuotactile_sensor.py +++ b/source/isaaclab_contrib/isaaclab_contrib/sensors/tacsl_sensor/visuotactile_sensor.py @@ -20,7 +20,7 @@ import isaaclab.sim as sim_utils import isaaclab.utils.math as math_utils from isaaclab.markers import VisualizationMarkers -from isaaclab.sensors.camera import Camera, TiledCamera +from isaaclab.sensors.camera import Camera from isaaclab.sensors.sensor_base import SensorBase from isaaclab.sim import SimulationContext from isaaclab.utils.math import quat_apply, quat_inv @@ -66,7 +66,7 @@ class VisuoTactileSensor(SensorBase): The following requirements must be satisfied for proper sensor operation: **Camera Tactile Imaging** - If ``enable_camera_tactile=True``, a valid ``camera_cfg`` (TiledCameraCfg) must be + If ``enable_camera_tactile=True``, a valid ``camera_cfg`` (CameraCfg) must be provided with appropriate camera parameters. **Force Field Computation** @@ -98,7 +98,7 @@ def __init__(self, cfg: VisuoTactileSensorCfg): self._data: VisuoTactileSensorData = VisuoTactileSensorData() # Camera-based tactile sensing - self._camera_sensor: Camera | TiledCamera | None = None + self._camera_sensor: Camera | None = None self._nominal_tactile: dict | None = None # Force field tactile sensing @@ -262,7 +262,7 @@ def _initialize_camera_tactile(self): self._tactile_rgb_render = GelsightRender(self.cfg.render_cfg, device=self.device) # Create camera sensor - self._camera_sensor = TiledCamera(self.cfg.camera_cfg) + self._camera_sensor = Camera(self.cfg.camera_cfg) # Initialize camera if not self._camera_sensor.is_initialized: diff --git a/source/isaaclab_contrib/isaaclab_contrib/sensors/tacsl_sensor/visuotactile_sensor_cfg.py b/source/isaaclab_contrib/isaaclab_contrib/sensors/tacsl_sensor/visuotactile_sensor_cfg.py index 92ef015a63d6..3eccac3db2a5 100644 --- a/source/isaaclab_contrib/isaaclab_contrib/sensors/tacsl_sensor/visuotactile_sensor_cfg.py +++ b/source/isaaclab_contrib/isaaclab_contrib/sensors/tacsl_sensor/visuotactile_sensor_cfg.py @@ -12,7 +12,7 @@ from isaaclab.markers import VisualizationMarkersCfg from isaaclab.markers.config import VISUO_TACTILE_SENSOR_MARKER_CFG -from isaaclab.sensors import SensorBaseCfg, TiledCameraCfg +from isaaclab.sensors import CameraCfg, SensorBaseCfg from isaaclab.utils import configclass from isaaclab.utils.assets import ISAACLAB_NUCLEUS_DIR @@ -171,7 +171,7 @@ class VisuoTactileSensorCfg(SensorBaseCfg): tangential_stiffness: float = 0.1 """Tangential stiffness for shear forces.""" - camera_cfg: TiledCameraCfg | None = None + camera_cfg: CameraCfg | None = None """Camera configuration for tactile RGB/depth sensing. If None, camera-based sensing will be disabled even if :attr:`enable_camera_tactile` is True. diff --git a/source/isaaclab_contrib/setup.py b/source/isaaclab_contrib/setup.py index d637b00bfdbd..df9e796cf4d6 100644 --- a/source/isaaclab_contrib/setup.py +++ b/source/isaaclab_contrib/setup.py @@ -49,15 +49,13 @@ keywords=EXTENSION_TOML_DATA["package"]["keywords"], include_package_data=True, package_data={"": ["*.pyi"]}, - python_requires=">=3.10", + python_requires=">=3.12", extras_require=EXTRAS_REQUIRE, packages=["isaaclab_contrib"], classifiers=[ "Natural Language :: English", - "Programming Language :: Python :: 3.10", - "Programming Language :: Python :: 3.11", - "Isaac Sim :: 4.5.0", - "Isaac Sim :: 5.0.0", + "Programming Language :: Python :: 3.12", + "Isaac Sim :: 6.0.0", ], zip_safe=False, ) diff --git a/source/isaaclab_contrib/test/sensors/test_visuotactile_sensor.py b/source/isaaclab_contrib/test/sensors/test_visuotactile_sensor.py index 88a2249bafa0..3f5078eec9c4 100644 --- a/source/isaaclab_contrib/test/sensors/test_visuotactile_sensor.py +++ b/source/isaaclab_contrib/test/sensors/test_visuotactile_sensor.py @@ -25,7 +25,7 @@ import isaaclab.sim as sim_utils from isaaclab.assets import Articulation, ArticulationCfg, RigidObject, RigidObjectCfg -from isaaclab.sensors.camera import TiledCameraCfg +from isaaclab.sensors.camera import CameraCfg from isaaclab.terrains.trimesh.utils import make_plane from isaaclab.terrains.utils import create_prim_from_mesh from isaaclab.utils.assets import ISAACLAB_NUCLEUS_DIR @@ -69,7 +69,7 @@ def get_sensor_cfg_by_type(sensor_type: str) -> VisuoTactileSensorCfg: return VisuoTactileSensorCfg( prim_path="/World/Robot/elastomer/tactile_cam", enable_force_field=False, - camera_cfg=TiledCameraCfg( + camera_cfg=CameraCfg( height=320, width=240, prim_path="/World/Robot/elastomer_tip/cam", @@ -89,7 +89,7 @@ def get_sensor_cfg_by_type(sensor_type: str) -> VisuoTactileSensorCfg: debug_vis=False, enable_camera_tactile=True, enable_force_field=True, - camera_cfg=TiledCameraCfg( + camera_cfg=CameraCfg( height=320, width=240, prim_path="/World/Robot/elastomer_tip/cam", @@ -307,7 +307,8 @@ def test_sensor_cam_set_wrong_prim(setup_tactile_cam): sim.reset() robot.update(dt) sensor.update(dt) - assert "Could not find prim with path" in str(excinfo.value) + err_msg = str(excinfo.value) + assert "Could not find prim with path" in err_msg or "does not match the number of environments" in err_msg @pytest.mark.isaacsim_ci diff --git a/source/isaaclab_experimental/changelog.d/.gitkeep b/source/isaaclab_experimental/changelog.d/.gitkeep new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/source/isaaclab_experimental/config/extension.toml b/source/isaaclab_experimental/config/extension.toml index c172c3bee876..9bcfc0753383 100644 --- a/source/isaaclab_experimental/config/extension.toml +++ b/source/isaaclab_experimental/config/extension.toml @@ -1,7 +1,7 @@ [package] # Note: Semantic Versioning is used: https://semver.org/ -version = "0.0.2" +version = "0.0.3" # Description title = "Experimental playground for upcoming IsaacLab features" diff --git a/source/isaaclab_experimental/docs/CHANGELOG.rst b/source/isaaclab_experimental/docs/CHANGELOG.rst index c8bda39e0e91..5f19d1fb8c5a 100644 --- a/source/isaaclab_experimental/docs/CHANGELOG.rst +++ b/source/isaaclab_experimental/docs/CHANGELOG.rst @@ -1,6 +1,30 @@ Changelog --------- +0.0.3 (2026-04-27) +~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Updated the Warp-graphable MDP terms and the Warp inhand-manipulation env to read + asset/sensor data via the explicit :attr:`~isaaclab.utils.warp.ProxyArray.warp` + accessor when the value flows into a ``wp.launch`` call (or a sim-write helper that + forwards to one). Affected modules: + :mod:`isaaclab_experimental.envs.mdp.observations`, + :mod:`isaaclab_experimental.envs.mdp.rewards`, + :mod:`isaaclab_experimental.envs.mdp.terminations`, + :mod:`isaaclab_experimental.envs.mdp.events`, + :mod:`isaaclab_experimental.envs.mdp.actions.joint_actions`, and + :mod:`isaaclab_tasks_experimental.direct.inhand_manipulation.inhand_manipulation_warp_env`. + The previous code relied on ``ProxyArray``'s ``__cuda_array_interface__`` bridge, + which works but is not explicit. No behavior change. +* Replaced ``wp.to_torch(asset.data.joint_pos).shape[1]`` in + :class:`~isaaclab_experimental.managers.ObservationManager` with + ``asset.data.joint_pos.shape[1]`` — :class:`~isaaclab.utils.warp.ProxyArray` forwards + ``shape``, so the round-trip through ``wp.to_torch`` is no longer needed. + + 0.0.2 (2026-03-16) ~~~~~~~~~~~~~~~~~~ diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/__init__.py b/source/isaaclab_experimental/isaaclab_experimental/envs/__init__.py index 81c59dda7d51..fef4091748a9 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/__init__.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/__init__.py @@ -44,8 +44,12 @@ from .direct_rl_env_warp import DirectRLEnvWarp # noqa: F401 from .interactive_scene_warp import InteractiveSceneWarp # noqa: F401 +from .manager_based_env_warp import ManagerBasedEnvWarp # noqa: F401 +from .manager_based_rl_env_warp import ManagerBasedRLEnvWarp # noqa: F401 __all__ = [ "DirectRLEnvWarp", "InteractiveSceneWarp", + "ManagerBasedEnvWarp", + "ManagerBasedRLEnvWarp", ] diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/manager_based_env_warp.py b/source/isaaclab_experimental/isaaclab_experimental/envs/manager_based_env_warp.py new file mode 100644 index 000000000000..8c558b925947 --- /dev/null +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/manager_based_env_warp.py @@ -0,0 +1,737 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Experimental manager-based base environment. + +This is a local copy of :class:`isaaclab.envs.ManagerBasedEnv` placed under +``isaaclab_experimental`` so we can evolve the manager-based workflow for Warp-first +pipelines without depending on (or subclassing) the stable env implementation. + +Behavior is intended to match the stable environment initially. +""" + +# import builtins +import contextlib +import importlib +import logging +import warnings +from collections.abc import Sequence +from copy import deepcopy +from typing import Any + +import torch +import warp as wp + +from isaaclab.envs.common import VecEnvObs +from isaaclab.envs.manager_based_env_cfg import ManagerBasedEnvCfg +from isaaclab.envs.ui import ViewportCameraController +from isaaclab.envs.utils.io_descriptors import export_articulations_data, export_scene_data +from isaaclab.sim import SimulationContext +from isaaclab.sim.utils import use_stage +from isaaclab.ui.widgets import ManagerLiveVisualizer +from isaaclab.utils.seed import configure_seed +from isaaclab.utils.timer import Timer + +from isaaclab_experimental.envs.interactive_scene_warp import InteractiveSceneWarp as InteractiveScene +from isaaclab_experimental.utils.manager_call_switch import ManagerCallMode, ManagerCallSwitch +from isaaclab_experimental.utils.warp import resolve_1d_mask + +# import logger +logger = logging.getLogger(__name__) + + +@wp.kernel +def initialize_rng_state( + # input + seed: wp.int32, + # output + state: wp.array(dtype=wp.uint32), +): + env_id = wp.tid() + state[env_id] = wp.rand_init(seed, wp.int32(env_id)) + + +class ManagerBasedEnvWarp: + """The base environment for the manager-based workflow (experimental fork). + + The implementation mirrors :class:`isaaclab.envs.ManagerBasedEnv` to provide + an isolated base class for experimental Warp-based workflows. + """ + + def __init__(self, cfg: ManagerBasedEnvCfg): + """Initialize the environment. + + Args: + cfg: The configuration object for the environment. + + Raises: + RuntimeError: If a simulation context already exists. The environment must always create one + since it configures the simulation context and controls the simulation. + """ + # check that the config is valid + cfg.validate() + # store inputs to class + self.cfg = cfg + # initialize internal variables + self._is_closed = False + # temporary debug runtime config for manager source/call switching. + cfg_source: dict | str | None = getattr(self.cfg, "manager_call_config", None) + max_modes: dict[str, int] | None = getattr(self.cfg, "manager_call_max_mode", None) + self._manager_call_switch = ManagerCallSwitch(cfg_source, max_modes=max_modes) + self._apply_manager_term_cfg_profile() + + # set the seed for the environment + if self.cfg.seed is not None: + self.cfg.seed = self.seed(self.cfg.seed) + else: + logger.warning("Seed not set for the environment. The environment creation may not be deterministic.") + + # create a simulation context to control the simulator + if SimulationContext.instance() is None: + # the type-annotation is required to avoid a type-checking error + # since it gets confused with Isaac Sim's SimulationContext class + self.sim: SimulationContext = SimulationContext(self.cfg.sim) + else: + # simulation context should only be created before the environment + # when in extension mode + # if not builtins.ISAAC_LAUNCHED_FROM_TERMINAL: + # raise RuntimeError("Simulation context already exists. Cannot create a new one.") + self.sim: SimulationContext = SimulationContext.instance() + + # make sure torch is running on the correct device + if "cuda" in self.device: + torch.cuda.set_device(self.device) + + # print useful information + print("[INFO]: Base environment:") + print(f"\tEnvironment device : {self.device}") + print(f"\tEnvironment seed : {self.cfg.seed}") + print(f"\tPhysics step-size : {self.physics_dt}") + print(f"\tRendering step-size : {self.physics_dt * self.cfg.sim.render_interval}") + print(f"\tEnvironment step-size : {self.step_dt}") + + if self.cfg.sim.render_interval < self.cfg.decimation: + msg = ( + f"The render interval ({self.cfg.sim.render_interval}) is smaller than the decimation " + f"({self.cfg.decimation}). Multiple render calls will happen for each environment step. " + "If this is not intended, set the render interval to be equal to the decimation." + ) + logger.warning(msg) + + # counter for simulation steps + self._sim_step_counter = 0 + + # allocate dictionary to store metrics + self.extras = {} + + # generate scene + with Timer("[INFO]: Time taken for scene creation", "scene_creation"): + # set the stage context for scene creation steps which use the stage + with use_stage(self.sim.stage): + self.scene = InteractiveScene(self.cfg.scene) + # attach_stage_to_usd_context() + print("[INFO]: Scene manager: ", self.scene) + + # Shared per-env Warp RNG state (accessible to all managers/terms via `env`). + # This is a single stream per env (no lookup) and is initialized once when `num_envs` is known. + self.rng_state_wp = wp.zeros((self.num_envs,), dtype=wp.uint32, device=self.device) + seed_val = int(self.cfg.seed) if self.cfg.seed is not None else -1 + wp.launch( + kernel=initialize_rng_state, + dim=self.num_envs, + inputs=[seed_val, self.rng_state_wp], + device=self.device, + ) + + # TODO(jichuanh): this is problematic as warp capture requires stable pointers, + # using different masks for different managers/terms will cause problems. + # Pre-allocated env masks (shared across managers/terms via `env`). + self.ALL_ENV_MASK = wp.ones((self.num_envs,), dtype=wp.bool, device=self.device) + self.ENV_MASK = wp.zeros((self.num_envs,), dtype=wp.bool, device=self.device) + + # Persistent scalar buffer for global env step count (stable pointer for capture). + self._global_env_step_count_wp = wp.zeros((1,), dtype=wp.int32, device=self.device) + + # set up camera viewport controller + # viewport is not available in other rendering modes so the function will throw a warning + # FIXME: This needs to be fixed in the future when we unify the UI functionalities even for + # non-rendering modes. + viz_str = self.sim.get_setting("/isaaclab/visualizer") or "" + available_visualizers = [v.strip() for v in viz_str.split(",") if v.strip()] + if "kit" in available_visualizers and bool(viz_str): + self.viewport_camera_controller = ViewportCameraController(self, self.cfg.viewer) + else: + self.viewport_camera_controller = None + + # create event manager + # note: this is needed here (rather than after simulation play) to allow USD-related randomization events + # that must happen before the simulation starts. Example: randomizing mesh scale + self.event_manager = self._manager_call_switch.resolve_manager_class("EventManager")(self.cfg.events, self) + + # apply USD-related randomization events + if "prestartup" in self.event_manager.available_modes: + self.event_manager.apply(mode="prestartup") + + # play the simulator to activate physics handles + # note: this activates the physics simulation view that exposes TensorAPIs + # note: when started in extension mode, first call sim.reset_async() and then initialize the managers + # if builtins.ISAAC_LAUNCHED_FROM_TERMINAL is False: + print("[INFO]: Starting the simulation. This may take a few seconds. Please wait...") + with Timer("[INFO]: Time taken for simulation start", "simulation_start"): + # since the reset can trigger callbacks which use the stage, + # we need to set the stage context here + with use_stage(self.sim.stage): + self.sim.reset() + # update scene to pre populate data buffers for assets and sensors. + # this is needed for the observation manager to get valid tensors for initialization. + # this shouldn't cause an issue since later on, users do a reset over all the environments so the lazy + # buffers would be reset. + self.scene.update(dt=self.physics_dt) + + # TODO(jichuanh): This is a temporary solution for event_manager only, but it should be general for all managers + # Resolve SceneEntityCfg-dependent term params once before any captured event paths. + if (not self.event_manager._is_scene_entities_resolved) and self.sim.is_playing(): + self.event_manager._resolve_terms_callback(None) + + # add timeline event to load managers + self.load_managers() + + # extend UI elements + # we need to do this here after all the managers are initialized + # this is because they dictate the sensors and commands right now + if self.sim.has_gui and self.cfg.ui_window_class_type is not None: + # setup live visualizers + self.setup_manager_visualizers() + self._window = self.cfg.ui_window_class_type(self, window_name="IsaacLab") + else: + # if no window, then we don't need to store the window + self._window = None + + # initialize observation buffers + self.obs_buf = {} + + # export IO descriptors if requested + if self.cfg.export_io_descriptors: + self.export_IO_descriptors() + + # show deprecation message for rerender_on_reset + if self.cfg.rerender_on_reset: + msg = ( + "\033[93m\033[1m[DEPRECATION WARNING] ManagerBasedEnvCfg.rerender_on_reset is deprecated. Use" + " ManagerBasedEnvCfg.num_rerenders_on_reset instead.\033[0m" + ) + warnings.warn( + msg, + FutureWarning, + stacklevel=2, + ) + if self.cfg.num_rerenders_on_reset == 0: + self.cfg.num_rerenders_on_reset = 1 + + def __del__(self): + """Cleanup for the environment.""" + # Suppress errors during Python shutdown to avoid noisy tracebacks + # Note: contextlib may be None during interpreter shutdown + if contextlib is not None: + with contextlib.suppress(ImportError, AttributeError, TypeError): + self.close() + + """ + Properties. + """ + + @property + def num_envs(self) -> int: + """The number of instances of the environment that are running.""" + return self.scene.num_envs + + @property + def physics_dt(self) -> float: + """The physics time-step (in s). + + This is the lowest time-decimation at which the simulation is happening. + """ + return self.cfg.sim.dt + + @property + def step_dt(self) -> float: + """The environment stepping time-step (in s). + + This is the time-step at which the environment steps forward. + """ + return self.cfg.sim.dt * self.cfg.decimation + + @property + def device(self): + """The device on which the environment is running.""" + return self.sim.device + + @property + def env_origins_wp(self) -> wp.array: + """Scene env origins as a warp ``vec3f`` array. Cached on first access.""" + if not hasattr(self, "_env_origins_wp"): + origins = self.scene.env_origins + if isinstance(origins, wp.array): + self._env_origins_wp = origins + else: + self._env_origins_wp = wp.from_torch(origins, dtype=wp.vec3f) + return self._env_origins_wp + + def resolve_env_mask( + self, + *, + env_ids: Sequence[int] | slice | wp.array | torch.Tensor | None = None, + env_mask: wp.array | torch.Tensor | None = None, + ) -> wp.array: + """Resolve environment ids/mask into a Warp boolean mask of shape ``(num_envs,)``.""" + return resolve_1d_mask( + ids=env_ids, + mask=env_mask, + all_mask=self.ALL_ENV_MASK, + scratch_mask=self.ENV_MASK, + device=self.device, + ) + + @property + def get_IO_descriptors(self): + """Get the IO descriptors for the environment. + + Returns: + A dictionary with keys as the group names and values as the IO descriptors. + """ + return { + "observations": self.observation_manager.get_IO_descriptors, + "actions": self.action_manager.get_IO_descriptors, + "articulations": export_articulations_data(self), + "scene": export_scene_data(self), + } + + def export_IO_descriptors(self, output_dir: str | None = None): + """Export the IO descriptors for the environment. + + Args: + output_dir: The directory to export the IO descriptors to. + """ + import os + + import yaml + + IO_descriptors = self.get_IO_descriptors + + if output_dir is None: + if self.cfg.log_dir is not None: + output_dir = os.path.join(self.cfg.log_dir, "io_descriptors") + else: + raise ValueError( + "Output directory is not set. Please set the log directory using the `log_dir`" + " configuration or provide an explicit output_dir parameter." + ) + + if not os.path.exists(output_dir): + os.makedirs(output_dir, exist_ok=True) + + with open(os.path.join(output_dir, "IO_descriptors.yaml"), "w") as f: + print(f"[INFO]: Exporting IO descriptors to {os.path.join(output_dir, 'IO_descriptors.yaml')}") + yaml.safe_dump(IO_descriptors, f) + + """ + Operations - Setup. + """ + + def load_managers(self): + """Load the managers for the environment. + + This function is responsible for creating the various managers (action, observation, + events, etc.) for the environment. Since the managers require access to physics handles, + they can only be created after the simulator is reset (i.e. played for the first time). + + .. note:: + In case of standalone application (when running simulator from Python), the function is called + automatically when the class is initialized. + + However, in case of extension mode, the user must call this function manually after the simulator + is reset. This is because the simulator is only reset when the user calls + :meth:`SimulationContext.reset_async` and it isn't possible to call async functions in the constructor. + + """ + # prepare the managers + # -- event manager (we print it here to make the logging consistent) + print("[INFO] Event Manager: ", self.event_manager) + # -- recorder manager + self.recorder_manager = self._manager_call_switch.resolve_manager_class("RecorderManager")( + self.cfg.recorders, self + ) + print("[INFO] Recorder Manager: ", self.recorder_manager) + # -- action manager + self.action_manager = self._manager_call_switch.resolve_manager_class("ActionManager")(self.cfg.actions, self) + print("[INFO] Action Manager: ", self.action_manager) + # -- observation manager + self.observation_manager = self._manager_call_switch.resolve_manager_class("ObservationManager")( + self.cfg.observations, self + ) + print("[INFO] Observation Manager:", self.observation_manager) + + # perform events at the start of the simulation + # in-case a child implementation creates other managers, the randomization should happen + # when all the other managers are created + if self.__class__ == ManagerBasedEnvWarp and "startup" in self.event_manager.available_modes: + self.event_manager.apply(mode="startup") + + def setup_manager_visualizers(self): + """Creates live visualizers for manager terms.""" + + self.manager_visualizers = { + "action_manager": ManagerLiveVisualizer(manager=self.action_manager), + "observation_manager": ManagerLiveVisualizer(manager=self.observation_manager), + } + + """ + Operations - MDP. + """ + + def reset( + self, seed: int | None = None, env_ids: Sequence[int] | None = None, options: dict[str, Any] | None = None + ) -> tuple[VecEnvObs, dict]: + """Resets the specified environments and returns observations. + + This function calls the :meth:`_reset_idx` function to reset the specified environments. + However, certain operations, such as procedural terrain generation, that happened during initialization + are not repeated. + + Args: + seed: The seed to use for randomization. Defaults to None, in which case the seed is not set. + env_ids: The environment ids to reset. Defaults to None, in which case all environments are reset. + options: Additional information to specify how the environment is reset. Defaults to None. + + Note: + This argument is used for compatibility with Gymnasium environment definition. + + Returns: + A tuple containing the observations and extras. + """ + if env_ids is None: + env_ids = torch.arange(self.num_envs, dtype=torch.int64, device=self.device) + + # trigger recorder terms for pre-reset calls + self.recorder_manager.record_pre_reset(env_ids) + + # set the seed + if seed is not None: + used_seed = self.seed(seed) + # keep cfg seed in sync for downstream users + self.cfg.seed = used_seed + # re-initialize per-env Warp RNG state without reallocating (stable pointer for capture) + wp.launch( + kernel=initialize_rng_state, + dim=self.num_envs, + inputs=[int(used_seed), self.rng_state_wp], + device=self.device, + ) + + # reset state of scene + self._reset_idx(env_ids) + + # update articulation kinematics + self.scene.write_data_to_sim() + self.sim.forward() + # if sensors are added to the scene, make sure we render to reflect changes in reset + if self.sim.settings.get("/isaaclab/render/rtx_sensors") and self.cfg.num_rerenders_on_reset > 0: + for _ in range(self.cfg.num_rerenders_on_reset): + self.sim.render() + + # trigger recorder terms for post-reset calls + self.recorder_manager.record_post_reset(env_ids) + + # compute observations + self.obs_buf = self.observation_manager.compute(update_history=True) + + # return observations + return self.obs_buf, self.extras + + def reset_to( + self, + state: dict[str, dict[str, dict[str, torch.Tensor]]], + env_ids: Sequence[int] | None, + seed: int | None = None, + is_relative: bool = False, + ): + """Resets specified environments to provided states. + + This function resets the environments to the provided states. The state is a dictionary + containing the state of the scene entities. Please refer to :meth:`InteractiveScene.get_state` + for the format. + + The function is different from the :meth:`reset` function as it resets the environments to specific states, + instead of using the randomization events for resetting the environments. + + Args: + state: The state to reset the specified environments to. Please refer to + :meth:`InteractiveScene.get_state` for the format. + env_ids: The environment ids to reset. Defaults to None, in which case all environments are reset. + seed: The seed to use for randomization. Defaults to None, in which case the seed is not set. + is_relative: If set to True, the state is considered relative to the environment origins. + Defaults to False. + """ + # reset all envs in the scene if env_ids is None + if env_ids is None: + env_ids = torch.arange(self.num_envs, dtype=torch.int64, device=self.device) + + # trigger recorder terms for pre-reset calls + self.recorder_manager.record_pre_reset(env_ids) + + # set the seed + if seed is not None: + self.seed(seed) + + self._reset_idx(env_ids) + + # set the state + self.scene.reset_to(state, env_ids, is_relative=is_relative) + + # update articulation kinematics + self.sim.forward() + + # if sensors are added to the scene, make sure we render to reflect changes in reset + if self.sim.settings.get("/isaaclab/render/rtx_sensors") and self.cfg.num_rerenders_on_reset > 0: + for _ in range(self.cfg.num_rerenders_on_reset): + self.sim.render() + + # trigger recorder terms for post-reset calls + self.recorder_manager.record_post_reset(env_ids) + + # compute observations + self.obs_buf = self.observation_manager.compute(update_history=True) + + # return observations + return self.obs_buf, self.extras + + def step(self, action: torch.Tensor) -> tuple[VecEnvObs, dict]: + """Execute one time-step of the environment's dynamics. + + The environment steps forward at a fixed time-step, while the physics simulation is + decimated at a lower time-step. This is to ensure that the simulation is stable. These two + time-steps can be configured independently using the :attr:`ManagerBasedEnvCfg.decimation` (number of + simulation steps per environment step) and the :attr:`ManagerBasedEnvCfg.sim.dt` (physics time-step) + parameters. Based on these parameters, the environment time-step is computed as the product of the two. + + Args: + action: The actions to apply on the environment. Shape is (num_envs, action_dim). + + Returns: + A tuple containing the observations and extras. + """ + # process actions + action_device = action.to(self.device) + if action_device.dtype != torch.float32: + action_device = action_device.float() + if not action_device.is_contiguous(): + action_device = action_device.contiguous() + action_wp = wp.from_torch(action_device, dtype=wp.float32) + self.action_manager.process_action(action_wp) + + self.recorder_manager.record_pre_step() + + # check if we need to do rendering within the physics loop + # note: checked here once to avoid multiple checks within the loop + is_rendering = bool(self.sim.settings.get("/isaaclab/visualizer")) or self.sim.settings.get( + "/isaaclab/render/rtx_sensors" + ) + + # perform physics stepping + for _ in range(self.cfg.decimation): + self._sim_step_counter += 1 + # set actions into buffers + self.action_manager.apply_action() + # set actions into simulator + self.scene.write_data_to_sim() + # simulate + self.sim.step(render=False) + # render between steps only if the GUI or an RTX sensor needs it + # note: we assume the render interval to be the shortest accepted rendering interval. + # If a camera needs rendering at a faster frequency, this will lead to unexpected behavior. + if self._sim_step_counter % self.cfg.sim.render_interval == 0 and is_rendering: + self.sim.render() + # update buffers at sim dt + self.scene.update(dt=self.physics_dt) + + # post-step: step interval event + if "interval" in self.event_manager.available_modes: + self.event_manager.apply(mode="interval", dt=self.step_dt) + + # -- compute observations + self.obs_buf = self.observation_manager.compute(update_history=True) + self.recorder_manager.record_post_step() + + # return observations and extras + return self.obs_buf, self.extras + + @staticmethod + def seed(seed: int = -1) -> int: + """Set the seed for the environment. + + Args: + seed: The seed for random generator. Defaults to -1. + + Returns: + The seed used for random generator. + """ + # set seed for replicator + try: + import omni.replicator.core as rep + + rep.set_global_seed(seed) + except ModuleNotFoundError: + pass + # set seed for torch and other libraries + return configure_seed(seed) + + def close(self): + """Cleanup for the environment.""" + if not self._is_closed: + # destructor is order-sensitive + del self.viewport_camera_controller + del self.action_manager + del self.observation_manager + del self.event_manager + del self.recorder_manager + del self.scene + + # self.sim.clear_all_callbacks() + self.sim.clear_instance() + + # destroy the window + if self._window is not None: + self._window = None + # update closing status + self._is_closed = True + + """ + Helper functions. + """ + + def _resolve_stable_cfg_counterpart(self) -> ManagerBasedEnvCfg | None: + """Resolve a stable task config counterpart for the current experimental task config. + + The lookup follows a module-name mirror convention: + ``isaaclab_tasks_experimental...`` -> ``isaaclab_tasks...`` with the same config class name. + """ + cfg_cls = self.cfg.__class__ + cfg_module_name = cfg_cls.__module__ + if "isaaclab_tasks_experimental" not in cfg_module_name: + return None + + stable_module_name = cfg_module_name.replace("isaaclab_tasks_experimental", "isaaclab_tasks", 1) + try: + stable_module = importlib.import_module(stable_module_name) + except Exception as exc: + logger.warning( + "Failed to import stable task cfg module '%s' for manager_call_config stable mode: %s", + stable_module_name, + exc, + ) + return None + + stable_cfg_cls = getattr(stable_module, cfg_cls.__name__, None) + if stable_cfg_cls is None: + logger.warning( + "Stable task cfg class '%s' not found in module '%s'.", + cfg_cls.__name__, + stable_module_name, + ) + return None + + try: + return stable_cfg_cls() + except Exception as exc: + logger.warning( + "Failed to instantiate stable task cfg '%s.%s': %s", + stable_module_name, + cfg_cls.__name__, + exc, + ) + return None + + def _apply_manager_term_cfg_profile(self) -> None: + """Align term configs with manager modes for stable manager selections. + + When a manager is configured as STABLE (0), swap its corresponding config subtree + from the stable task counterpart to keep manager-term type/signature compatibility. + """ + manager_to_cfg_attr = { + "ActionManager": "actions", + "ObservationManager": "observations", + "EventManager": "events", + "RecorderManager": "recorders", + "CommandManager": "commands", + "TerminationManager": "terminations", + "RewardManager": "rewards", + "CurriculumManager": "curriculum", + } + + stable_manager_names = [ + manager_name + for manager_name in manager_to_cfg_attr + if self._manager_call_switch.get_mode_for_manager(manager_name) == ManagerCallMode.STABLE + ] + if not stable_manager_names: + return + + stable_cfg = self._resolve_stable_cfg_counterpart() + if stable_cfg is None: + logger.warning( + "Stable managers requested (%s), but no stable cfg counterpart could be resolved." + " Keeping experimental term configs.", + ", ".join(stable_manager_names), + ) + return + + replaced_items: list[str] = [] + for manager_name, cfg_attr in manager_to_cfg_attr.items(): + if self._manager_call_switch.get_mode_for_manager(manager_name) != ManagerCallMode.STABLE: + continue + if not hasattr(self.cfg, cfg_attr) or not hasattr(stable_cfg, cfg_attr): + continue + setattr(self.cfg, cfg_attr, deepcopy(getattr(stable_cfg, cfg_attr))) + replaced_items.append(f"{manager_name} -> cfg.{cfg_attr}") + + if replaced_items: + print("[INFO] Applied stable term config profile for managers:") + for item in replaced_items: + print(f" - {item}") + + def _reset_idx(self, env_ids: Sequence[int]): + """Reset environments based on specified indices. + + Args: + env_ids: List of environment ids which must be reset + """ + # reset the internal buffers of the scene elements + self.scene.reset(env_ids) + + # apply events such as randomization for environments that need a reset + if "reset" in self.event_manager.available_modes: + env_step_count = self._sim_step_counter // self.cfg.decimation + self._global_env_step_count_wp.fill_(env_step_count) + self.event_manager.apply( + mode="reset", env_ids=env_ids, global_env_step_count=self._global_env_step_count_wp + ) + + # iterate over all managers and reset them + # this returns a dictionary of information which is stored in the extras + # note: This is order-sensitive! Certain things need be reset before others. + self.extras["log"] = dict() + env_mask = self.resolve_env_mask(env_ids=env_ids) + # -- observation manager + info = self.observation_manager.reset(env_mask=env_mask) + self.extras["log"].update(info) + # -- action manager + info = self.action_manager.reset(env_mask=env_mask) + self.extras["log"].update(info) + # -- event manager + info = self.event_manager.reset(env_mask=env_mask) + self.extras["log"].update(info) + # -- recorder manager + info = self.recorder_manager.reset(env_ids) + self.extras["log"].update(info) diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/manager_based_rl_env_warp.py b/source/isaaclab_experimental/isaaclab_experimental/envs/manager_based_rl_env_warp.py new file mode 100644 index 000000000000..2e1894e54003 --- /dev/null +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/manager_based_rl_env_warp.py @@ -0,0 +1,616 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Experimental manager-based RL environment (Warp entry point). + +This module provides an experimental fork of the stable manager-based RL environment +so it can diverge (Warp-first / graph-friendly) without inheriting from the stable +`isaaclab.envs.ManagerBasedRLEnv` implementation. +""" + +# needed to import for allowing type-hinting: np.ndarray | None +from __future__ import annotations + +import math +import os +from collections.abc import Sequence +from typing import Any, ClassVar + +import gymnasium as gym +import numpy as np +import torch +import warp as wp + +from isaaclab.envs.common import VecEnvStepReturn +from isaaclab.envs.manager_based_rl_env_cfg import ManagerBasedRLEnvCfg +from isaaclab.managers import CommandManager +from isaaclab.ui.widgets import ManagerLiveVisualizer +from isaaclab.utils.timer import Timer + +from isaaclab_experimental.utils.manager_call_switch import ManagerCallMode +from isaaclab_experimental.utils.torch_utils import clone_obs_buffer + +from .manager_based_env_warp import ManagerBasedEnvWarp + +DEBUG_TIMERS = os.environ.get("DEBUG_TIMERS", "0") == "1" +"""Enable outer step() timer. Set DEBUG_TIMERS=1 env var to enable.""" + +DEBUG_TIMER_STEP = os.environ.get("DEBUG_TIMER_STEP", "0") == "1" +"""Enable step sub-phase timers. Set DEBUG_TIMER_STEP=1 env var to enable.""" + +DEBUG_TIMER_RESET = os.environ.get("DEBUG_TIMER_RESET", "0") == "1" +"""Enable reset sub-phase timers. Set DEBUG_TIMER_RESET=1 env var to enable.""" + + +class ManagerBasedRLEnvWarp(ManagerBasedEnvWarp, gym.Env): + """The superclass for the manager-based workflow reinforcement learning-based environments. + + This class inherits from :class:`ManagerBasedEnv` and implements the core functionality for + reinforcement learning-based environments. It is designed to be used with any RL + library. The class is designed to be used with vectorized environments, i.e., the + environment is expected to be run in parallel with multiple sub-environments. The + number of sub-environments is specified using the ``num_envs``. + + Each observation from the environment is a batch of observations for each sub- + environments. The method :meth:`step` is also expected to receive a batch of actions + for each sub-environment. + + While the environment itself is implemented as a vectorized environment, we do not + inherit from :class:`gym.vector.VectorEnv`. This is mainly because the class adds + various methods (for wait and asynchronous updates) which are not required. + Additionally, each RL library typically has its own definition for a vectorized + environment. Thus, to reduce complexity, we directly use the :class:`gym.Env` over + here and leave it up to library-defined wrappers to take care of wrapping this + environment for their agents. + + Note: + For vectorized environments, it is recommended to **only** call the :meth:`reset` + method once before the first call to :meth:`step`, i.e. after the environment is created. + After that, the :meth:`step` function handles the reset of terminated sub-environments. + This is because the simulator does not support resetting individual sub-environments + in a vectorized environment. + + """ + + is_vector_env: ClassVar[bool] = True + """Whether the environment is a vectorized environment.""" + metadata: ClassVar[dict[str, Any]] = { + "render_modes": [None, "human", "rgb_array"], + # "isaac_sim_version": get_version(), + } + """Metadata for the environment.""" + + cfg: ManagerBasedRLEnvCfg + """Configuration for the environment.""" + + def __init__(self, cfg: ManagerBasedRLEnvCfg, render_mode: str | None = None, **kwargs): + """Initialize the environment. + + Args: + cfg: The configuration for the environment. + render_mode: The render mode for the environment. Defaults to None, which + is similar to ``"human"``. + """ + # -- counter for curriculum + self.common_step_counter = 0 + + # initialize the episode length buffer BEFORE loading the managers to use it in mdp functions. + # Warp array is the source of truth; torch view is zero-copy for += and indexed assignment. + self._episode_length_buf_wp = wp.zeros(cfg.scene.num_envs, dtype=wp.int64, device=cfg.sim.device) + self._episode_length_buf = wp.to_torch(self._episode_length_buf_wp) + + # initialize the base class to setup the scene. + super().__init__(cfg=cfg) + # store the render mode + self.render_mode = render_mode + + # The persistent reset mask needed for warp capture + # The intended use is to copy into this mask whenever capture is needed + # TODO: termination manager provides the same mask, investigate whether this can be replaced. + self.reset_mask_wp = wp.zeros(cfg.scene.num_envs, dtype=wp.bool, device=cfg.sim.device) + + # Persistent action input buffer to keep pointer stable for captured graphs. + self._action_in_wp: wp.array = wp.zeros( + (self.num_envs, self.action_manager.total_action_dim), dtype=wp.float32, device=self.device + ) + + # initialize data and constants + # -- set the framerate of the gym video recorder wrapper so that the playback speed + # of the produced video matches the simulation + self.metadata["render_fps"] = 1 / self.step_dt + self.has_rtx_sensors = self.sim.get_setting("/isaaclab/render/rtx_sensors") + + print("[INFO]: Completed setting up the environment...") + + """ + Properties. + """ + + @property + def episode_length_buf(self) -> torch.Tensor: + """Episode length buffer (torch view of the underlying warp array).""" + return self._episode_length_buf + + @episode_length_buf.setter + def episode_length_buf(self, value: torch.Tensor): + """Copy into the existing buffer to preserve the warp array linkage.""" + self._episode_length_buf[:] = value + + @property + def max_episode_length_s(self) -> float: + """Maximum episode length in seconds.""" + return self.cfg.episode_length_s + + @property + def max_episode_length(self) -> int: + """Maximum episode length in environment steps.""" + return math.ceil(self.max_episode_length_s / self.step_dt) + + """ + Operations - Setup. + """ + + def load_managers(self): + # note: this order is important since observation manager needs to know the command and action managers + # and the reward manager needs to know the termination manager + # -- command manager (stable impl — not routed through ManagerCallSwitch) + self.command_manager = CommandManager(self.cfg.commands, self) + print("[INFO] Command Manager: ", self.command_manager) + + # call the parent class to load the managers for observations and actions. + super().load_managers() + + # prepare the managers + # -- termination manager + self.termination_manager = self._manager_call_switch.resolve_manager_class("TerminationManager")( + self.cfg.terminations, self + ) + print("[INFO] Termination Manager: ", self.termination_manager) + # -- reward manager (experimental fork; Warp-compatible rewards) + self.reward_manager = self._manager_call_switch.resolve_manager_class("RewardManager")(self.cfg.rewards, self) + print("[INFO] Reward Manager: ", self.reward_manager) + # -- curriculum manager + self.curriculum_manager = self._manager_call_switch.resolve_manager_class("CurriculumManager")( + self.cfg.curriculum, self + ) + print("[INFO] Curriculum Manager: ", self.curriculum_manager) + + # setup the action and observation spaces for Gym + self._configure_gym_env_spaces() + + # perform events at the start of the simulation + if "startup" in self.event_manager.available_modes: + self.event_manager.apply(mode="startup") + + def setup_manager_visualizers(self): + """Creates live visualizers for manager terms.""" + + self.manager_visualizers = { + "action_manager": ManagerLiveVisualizer(manager=self.action_manager), + "observation_manager": ManagerLiveVisualizer(manager=self.observation_manager), + "command_manager": ManagerLiveVisualizer(manager=self.command_manager), + "termination_manager": ManagerLiveVisualizer(manager=self.termination_manager), + "reward_manager": ManagerLiveVisualizer(manager=self.reward_manager), + "curriculum_manager": ManagerLiveVisualizer(manager=self.curriculum_manager), + } + + """ + Operations - MDP + """ + + def invalidate_wp_graphs(self) -> None: + """Invalidate all cached Warp graphs. + + Call this if the captured launch topology changes (e.g. different term list, shapes, etc.). + """ + self._manager_call_switch.invalidate_graphs() + + def step_warp_termination_compute(self) -> None: + """Captured stage: compute terminations (env-step frequency).""" + self.reset_buf = self.termination_manager.compute() + self.reset_terminated = self.termination_manager.terminated + self.reset_time_outs = self.termination_manager.time_outs + + @Timer(name="env_step", msg="Step took:", enable=DEBUG_TIMER_STEP, time_unit="us") + def step(self, action: torch.Tensor) -> VecEnvStepReturn: + """Execute one time-step of the environment's dynamics and reset terminated environments. + + Unlike the :class:`ManagerBasedEnv.step` class, the function performs the following operations: + + 1. Process the actions. + 2. Perform physics stepping. + 3. Perform rendering if gui is enabled. + 4. Update the environment counters and compute the rewards and terminations. + 5. Reset the environments that terminated. + 6. Compute the observations. + 7. Return the observations, rewards, resets and extras. + + Args: + action: The actions to apply on the environment. Shape is (num_envs, action_dim). + + Returns: + A tuple containing the observations, rewards, resets (terminated and truncated) and extras. + """ + # process actions + # NOTE: keep a persistent action input buffer for graph pointer stability. + # IMPORTANT: Do NOT re-wrap/replace the `wp.array` used by captured graphs each step. + # Instead, copy the latest actions into the persistent buffer. + with Timer(name="action_preprocess", msg="Action preprocessing took:", enable=DEBUG_TIMER_STEP, time_unit="us"): + if self._action_in_wp is None: + raise RuntimeError("Action buffer not initialized. Call reset() before step().") + action_device = action.to(self.device) + wp.copy(self._action_in_wp, wp.from_torch(action_device, dtype=wp.float32)) + + self._manager_call_switch.call_stage( + stage="ActionManager_process_action", + warp_call={"fn": self.action_manager.process_action, "kwargs": {"action": self._action_in_wp}}, + timer=DEBUG_TIMER_STEP, + ) + + self.recorder_manager.record_pre_step() + + # check if we need to do rendering within the physics loop + # note: checked here once to avoid multiple checks within the loop + is_rendering = self.sim.is_rendering + + # perform physics stepping + for _ in range(self.cfg.decimation): + self._sim_step_counter += 1 + # set actions into buffers + self._manager_call_switch.call_stage( + stage="ActionManager_apply_action", + warp_call={"fn": self.action_manager.apply_action}, + timer=DEBUG_TIMER_STEP, + ) + self._manager_call_switch.call_stage( + stage="Scene_write_data_to_sim", + warp_call={"fn": self.scene.write_data_to_sim}, + timer=DEBUG_TIMER_STEP, + ) + + # simulate + with Timer(name="simulate", msg="Newton simulation step took:", enable=DEBUG_TIMER_STEP, time_unit="us"): + self.sim.step(render=False) + self.recorder_manager.record_post_physics_decimation_step() + # render between steps only if the GUI or an RTX sensor needs it + # note: we assume the render interval to be the shortest accepted rendering interval. + # If a camera needs rendering at a faster frequency, this will lead to unexpected behavior. + if self._sim_step_counter % self.cfg.sim.render_interval == 0 and is_rendering: + self.sim.render() + # update buffers at sim dt + with Timer( + name="scene.update", + msg="Scene.update took:", + enable=DEBUG_TIMER_STEP, + time_unit="us", + ): + self.scene.update(dt=self.physics_dt) + + # post-step: + # -- update env counters (used for curriculum generation) + self.episode_length_buf += 1 # step in current episode (per env) + self.common_step_counter += 1 # total step (common for all envs) + + # -- post-processing (termination + reward) as independently configurable stages + self._manager_call_switch.call_stage( + stage="TerminationManager_compute", + warp_call={"fn": self.step_warp_termination_compute}, + timer=DEBUG_TIMER_STEP, + ) + self.reward_buf = self._manager_call_switch.call_stage( + stage="RewardManager_compute", + warp_call={"fn": self.reward_manager.compute, "kwargs": {"dt": float(self.step_dt)}}, + timer=DEBUG_TIMER_STEP, + ) + + if len(self.recorder_manager.active_terms) > 0: + # update observations for recording if needed + self._manager_call_switch.call_stage( + stage="ObservationManager_compute_no_history", + warp_call={"fn": self.observation_manager.compute, "kwargs": {"return_cloned_output": False}}, + timer=DEBUG_TIMER_STEP, + ) + self.recorder_manager.record_post_step() + + # -- reset envs that terminated/timed-out and log the episode information + # NOTE: Interim path (intentional). + # We still compact `reset_buf` into `env_ids` here because several reset-time managers/recorders + # are still `env_ids`-based. Do NOT remove/replace this until mask-based reset is end-to-end. + with Timer( + name="reset_selection", + msg="Reset selection took:", + enable=DEBUG_TIMER_STEP, + time_unit="us", + ): + # Keep the reset-mask handoff fully in Warp when experimental termination buffers exist. + # Stable termination manager path exposes torch-only dones/reset buffers. + termination_manager_mode = self._manager_call_switch.get_mode_for_manager("TerminationManager") + if termination_manager_mode == ManagerCallMode.STABLE: + # copy still needed as mask will be used if manager is set to mode > 0 + wp.copy(self.reset_mask_wp, wp.from_torch(self.reset_buf, dtype=wp.bool)) + else: + wp.copy(self.reset_mask_wp, self.termination_manager.dones_wp) + reset_env_ids = self.reset_buf.nonzero(as_tuple=False).squeeze(-1) + if len(reset_env_ids) > 0: + # trigger recorder terms for pre-reset calls + self.recorder_manager.record_pre_reset(reset_env_ids) + + with Timer( + name="reset_idx", + msg="Reset idx took:", + enable=DEBUG_TIMER_STEP, + time_unit="us", + ): + self._reset_idx(env_ids=reset_env_ids, env_mask=self.reset_mask_wp) + + # if sensors are added to the scene, make sure we render to reflect changes in reset + if self.has_rtx_sensors and self.cfg.num_rerenders_on_reset > 0: + for _ in range(self.cfg.num_rerenders_on_reset): + self.sim.render() + + # trigger recorder terms for post-reset calls + self.recorder_manager.record_post_reset(reset_env_ids) + + # -- update command + self.command_manager.compute(dt=float(self.step_dt)) + + # -- step interval events + if "interval" in self.event_manager.available_modes: + self._manager_call_switch.call_stage( + stage="EventManager_apply_interval", + warp_call={"fn": self.event_manager.apply, "kwargs": {"mode": "interval", "dt": float(self.step_dt)}}, + timer=DEBUG_TIMER_STEP, + ) + + # -- compute observations + # note: done after reset to get the correct observations for reset envs + self.obs_buf = self._manager_call_switch.call_stage( + stage="ObservationManager_compute_update_history", + warp_call={ + "fn": self.observation_manager.compute, + "kwargs": {"update_history": True, "return_cloned_output": False}, + "output": lambda r: clone_obs_buffer(r), + }, + timer=DEBUG_TIMER_STEP, + ) + # return observations, rewards, resets and extras + return self.obs_buf, self.reward_buf, self.reset_terminated, self.reset_time_outs, self.extras + + def render(self, recompute: bool = False) -> np.ndarray | None: + """Run rendering without stepping through the physics. + + By convention, if mode is: + + - **human**: Render to the current display and return nothing. Usually for human consumption. + - **rgb_array**: Return a numpy.ndarray with shape (x, y, 3), representing RGB values for an + x-by-y pixel image, suitable for turning into a video. + + Args: + recompute: Whether to force a render even if the simulator has already rendered the scene. + Defaults to False. + + Returns: + The rendered image as a numpy array if mode is "rgb_array". Otherwise, returns None. + + Raises: + RuntimeError: If mode is set to "rgb_data" and simulation render mode does not support it. + In this case, the simulation render mode must be set to ``RenderMode.PARTIAL_RENDERING`` + or ``RenderMode.FULL_RENDERING``. + NotImplementedError: If an unsupported rendering mode is specified. + """ + # run a rendering step of the simulator + # if we have rtx sensors, we do not need to render again sin + if not self.has_rtx_sensors and not recompute: + self.sim.render() + # decide the rendering mode + if self.render_mode == "human" or self.render_mode is None: + return None + elif self.render_mode == "rgb_array": + # check that if any render could have happened + has_gui = bool(self.sim.get_setting("/isaaclab/has_gui")) + offscreen_render = bool(self.sim.get_setting("/isaaclab/render/offscreen")) + if not (has_gui or offscreen_render): + raise RuntimeError( + f"Cannot render '{self.render_mode}' when the simulation render mode does not support" + " rendering. Please set the simulation render mode to 'PARTIAL_RENDERING' or" + " 'FULL_RENDERING'. If running headless, make sure --enable_cameras is set." + ) + # create the annotator if it does not exist + if not hasattr(self, "_rgb_annotator"): + import omni.replicator.core as rep + + # create render product + self._render_product = rep.create.render_product( + self.cfg.viewer.cam_prim_path, self.cfg.viewer.resolution + ) + # create rgb annotator -- used to read data from the render product + self._rgb_annotator = rep.AnnotatorRegistry.get_annotator("rgb", device="cpu") + self._rgb_annotator.attach([self._render_product]) + # obtain the rgb data + rgb_data = self._rgb_annotator.get_data() + # convert to numpy array + rgb_data = np.frombuffer(rgb_data, dtype=np.uint8).reshape(*rgb_data.shape) + # return the rgb data + # note: initially the renerer is warming up and returns empty data + if rgb_data.size == 0: + return np.zeros((self.cfg.viewer.resolution[1], self.cfg.viewer.resolution[0], 3), dtype=np.uint8) + else: + return rgb_data[:, :, :3] + else: + raise NotImplementedError( + f"Render mode '{self.render_mode}' is not supported. Please use: {self.metadata['render_modes']}." + ) + + def close(self): + if not self._is_closed: + # destructor is order-sensitive + del self.command_manager + del self.reward_manager + del self.termination_manager + del self.curriculum_manager + # call the parent class to close the environment + super().close() + + """ + Helper functions. + """ + + def _configure_gym_env_spaces(self): + """Configure the action and observation spaces for the Gym environment.""" + # observation space (unbounded since we don't impose any limits) + self.single_observation_space = gym.spaces.Dict() + for group_name, group_term_names in self.observation_manager.active_terms.items(): + # extract quantities about the group + has_concatenated_obs = self.observation_manager.group_obs_concatenate[group_name] + group_dim = self.observation_manager.group_obs_dim[group_name] + # check if group is concatenated or not + # if not concatenated, then we need to add each term separately as a dictionary + if has_concatenated_obs: + self.single_observation_space[group_name] = gym.spaces.Box(low=-np.inf, high=np.inf, shape=group_dim) + else: + group_term_cfgs = self.observation_manager._group_obs_term_cfgs[group_name] + term_dict = {} + for term_name, term_dim, term_cfg in zip(group_term_names, group_dim, group_term_cfgs): + low = -np.inf if term_cfg.clip is None else term_cfg.clip[0] + high = np.inf if term_cfg.clip is None else term_cfg.clip[1] + term_dict[term_name] = gym.spaces.Box(low=low, high=high, shape=term_dim) + self.single_observation_space[group_name] = gym.spaces.Dict(term_dict) + # action space (unbounded since we don't impose any limits) + action_dim = sum(self.action_manager.action_term_dim) + self.single_action_space = gym.spaces.Box(low=-np.inf, high=np.inf, shape=(action_dim,)) + + # batch the spaces for vectorized environments + self.observation_space = gym.vector.utils.batch_space(self.single_observation_space, self.num_envs) + self.action_space = gym.vector.utils.batch_space(self.single_action_space, self.num_envs) + + def _reset_idx( + self, + env_ids: Sequence[int] | slice | torch.Tensor, + *, + env_mask: wp.array | None = None, + ): + """Reset environments based on specified indices. + + IMPORTANT: + This function always uses the **TerminationManager-produced Warp env mask** (`self.reset_buf`) to select + which envs to reset. The ids/mask conversion is performed in `step()` before calling this function. + + In other words: + - If `env_mask` is provided, it **must** be `self.reset_buf` (Warp bool mask) + - If `env_mask` is not provided, this function will populate `self.reset_buf` from `env_ids` + - When `env_mask` is provided, `env_ids` **must** correspond to the same mask + + Args: + env_ids: Environment indices to reset. + env_mask: Warp boolean env mask selecting envs to reset. Must be `self.reset_buf`. + If None, uses and populates `self.reset_buf` from `env_ids`. + """ + if env_mask is None: + # Base `reset()` / `reset_to()` call-path provides only `env_ids`. + # Populate the stable TerminationManager-owned mask (`self.reset_buf`) from ids. + env_mask = self.reset_mask_wp + # Use the centralized env-id/mask resolution from the base Warp env, then copy into the + # stable TerminationManager-owned buffer (`self.reset_buf`) used by captured graphs. + resolved_mask = self.resolve_env_mask(env_ids=env_ids) + wp.copy(env_mask, resolved_mask) + + if not isinstance(env_mask, wp.array): + raise TypeError(f"env_mask must be a wp.array (got {type(env_mask)}).") + + # update the curriculum for environments that need a reset + with Timer( + name="curriculum_manager.compute_reset", + msg="CurriculumManager.compute (reset) took:", + enable=DEBUG_TIMER_RESET, + time_unit="us", + ): + self.curriculum_manager.compute(env_ids=env_ids) + + # reset the internal buffers of the scene elements + self._manager_call_switch.call_stage( + stage="Scene_reset", + warp_call={"fn": self.scene.reset, "kwargs": {"env_ids": env_ids, "env_mask": env_mask}}, + timer=DEBUG_TIMER_RESET, + ) + + if "reset" in self.event_manager.available_modes: + self._global_env_step_count_wp.fill_(self._sim_step_counter // self.cfg.decimation) + self._manager_call_switch.call_stage( + stage="EventManager_apply_reset", + warp_call={ + "fn": self.event_manager.apply, + "kwargs": { + "mode": "reset", + "env_mask_wp": env_mask, + "global_env_step_count": self._global_env_step_count_wp, + }, + }, + timer=DEBUG_TIMER_RESET, + ) + + # iterate over all managers and reset them + # this returns a dictionary of information which is stored in the extras + # note: This is order-sensitive! Certain things need be reset before others. + # -- observation manager + action + reward managers + obs_info = self._manager_call_switch.call_stage( + stage="ObservationManager_reset", + warp_call={"fn": self.observation_manager.reset, "kwargs": {"env_mask": env_mask}}, + timer=DEBUG_TIMER_RESET, + ) + action_info = self._manager_call_switch.call_stage( + stage="ActionManager_reset", + warp_call={"fn": self.action_manager.reset, "kwargs": {"env_mask": env_mask}}, + timer=DEBUG_TIMER_RESET, + ) + reward_info = self._manager_call_switch.call_stage( + stage="RewardManager_reset", + warp_call={"fn": self.reward_manager.reset, "kwargs": {"env_mask": env_mask}}, + timer=DEBUG_TIMER_RESET, + ) + + # -- curriculum manager + with Timer( + name="curriculum_manager.reset", + msg="CurriculumManager.reset took:", + enable=DEBUG_TIMER_RESET, + time_unit="us", + ): + curriculum_info = self.curriculum_manager.reset(env_ids=env_ids) + + # -- command + event + termination managers + command_info = self.command_manager.reset(env_ids=env_ids) + event_info = self._manager_call_switch.call_stage( + stage="EventManager_reset", + warp_call={"fn": self.event_manager.reset, "kwargs": {"env_mask": env_mask}}, + stable_call={"fn": self.event_manager.reset, "kwargs": {"env_ids": env_ids}}, + timer=DEBUG_TIMER_RESET, + ) + termination_info = self._manager_call_switch.call_stage( + stage="TerminationManager_reset", + warp_call={"fn": self.termination_manager.reset, "kwargs": {"env_mask": env_mask}}, + stable_call={"fn": self.termination_manager.reset, "kwargs": {"env_ids": env_ids}}, + timer=DEBUG_TIMER_RESET, + ) + + # -- recorder manager + recorder_info = self.recorder_manager.reset(env_ids=env_ids) + + # reset the episode length buffer + self.episode_length_buf[env_ids] = 0 + + # aggregate logging info + log: dict[str, Any] = {} + for info in ( + obs_info, + action_info, + reward_info, + curriculum_info, + command_info, + event_info, + termination_info, + recorder_info, + ): + log.update(info) + self.extras["log"] = log diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp/__init__.py b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp/__init__.py new file mode 100644 index 000000000000..1476dc828798 --- /dev/null +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp/__init__.py @@ -0,0 +1,26 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Experimental MDP terms. + +This package forwards all stable MDP terms from :mod:`isaaclab.envs.mdp`, but overrides reward +functions with Warp-first implementations from :mod:`isaaclab_experimental.envs.mdp.rewards`. +""" + +# Forward stable MDP terms (commands/observations/terminations/etc.) but *exclude* rewards and actions. +# Rewards and actions are provided by this experimental package to keep Warp-first execution. +from isaaclab.envs.mdp.commands import * # noqa: F401, F403 +from isaaclab.envs.mdp.curriculums import * # noqa: F401, F403 +from isaaclab.envs.mdp.events import * # noqa: F401, F403 +from isaaclab.envs.mdp.observations import * # noqa: F401, F403 +from isaaclab.envs.mdp.recorders import * # noqa: F401, F403 +from isaaclab.envs.mdp.terminations import * # noqa: F401, F403 + +# Override terms with experimental implementations. +from .actions import * # noqa: F401, F403 +from .events import * # noqa: F401, F403 +from .observations import * # noqa: F401, F403 +from .rewards import * # noqa: F401, F403 +from .terminations import * # noqa: F401, F403 diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp/actions/__init__.py b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp/actions/__init__.py new file mode 100644 index 000000000000..d295384149d4 --- /dev/null +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp/actions/__init__.py @@ -0,0 +1,13 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Experimental action terms (Warp-first). + +Provides Warp-first action term implementations overriding the stable +:mod:`isaaclab.envs.mdp.actions` module. +""" + +from .actions_cfg import * # noqa: F401, F403 +from .joint_actions import * # noqa: F401, F403 diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp/actions/actions_cfg.py b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp/actions/actions_cfg.py new file mode 100644 index 000000000000..39d5b29c6fdb --- /dev/null +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp/actions/actions_cfg.py @@ -0,0 +1,61 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from dataclasses import MISSING + +from isaaclab.utils import configclass + +from isaaclab_experimental.managers.action_manager import ActionTerm, ActionTermCfg + +from . import joint_actions + +## +# Joint actions. +## + + +@configclass +class JointActionCfg(ActionTermCfg): + """Configuration for the base joint action term. + + See :class:`JointAction` for more details. + """ + + joint_names: list[str] = MISSING + """List of joint names or regex expressions that the action will be mapped to.""" + scale: float | dict[str, float] = 1.0 + """Scale factor for the action (float or dict of regex expressions). Defaults to 1.0.""" + offset: float | dict[str, float] = 0.0 + """Offset factor for the action (float or dict of regex expressions). Defaults to 0.0.""" + preserve_order: bool = False + """Whether to preserve the order of the joint names in the action output. Defaults to False.""" + + +@configclass +class JointPositionActionCfg(JointActionCfg): + """Configuration for the joint position action term. + + See :class:`JointPositionAction` for more details. + """ + + class_type: type[ActionTerm] = joint_actions.JointPositionAction + + use_default_offset: bool = True + """Whether to use default joint positions configured in the articulation asset as offset. + Defaults to True. + + If True, this flag results in overwriting the values of :attr:`offset` to the default joint positions + from the articulation asset. + """ + + +@configclass +class JointEffortActionCfg(JointActionCfg): + """Configuration for the joint effort action term. + + See :class:`JointEffortAction` for more details. + """ + + class_type: type[ActionTerm] = joint_actions.JointEffortAction diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp/actions/joint_actions.py b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp/actions/joint_actions.py new file mode 100644 index 000000000000..f379f66c1900 --- /dev/null +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp/actions/joint_actions.py @@ -0,0 +1,299 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from __future__ import annotations + +import logging +from typing import TYPE_CHECKING + +import numpy as np +import warp as wp + +import isaaclab.utils.string as string_utils +from isaaclab.assets.articulation import Articulation + +from isaaclab_experimental.managers.action_manager import ActionTerm +from isaaclab_experimental.utils.warp import resolve_1d_mask, zero_masked_2d + +if TYPE_CHECKING: + from isaaclab.envs import ManagerBasedEnv + from isaaclab.envs.utils.io_descriptors import GenericActionIODescriptor + + from . import actions_cfg + +# import logger +logger = logging.getLogger(__name__) + + +@wp.kernel +def _process_joint_actions_kernel( + # input + actions: wp.array(dtype=wp.float32, ndim=2), + action_offset: int, + # params + scale: wp.array(dtype=wp.float32), + offset: wp.array(dtype=wp.float32), + clip: wp.array(dtype=wp.float32, ndim=2), + # output + raw_out: wp.array(dtype=wp.float32, ndim=2), + processed_out: wp.array(dtype=wp.float32, ndim=2), +): + env_id, j = wp.tid() + col = action_offset + j + + a = actions[env_id, col] + raw_out[env_id, j] = a + + x = a * scale[j] + offset[j] + low = clip[j, 0] + high = clip[j, 1] + if x < low: + x = low + if x > high: + x = high + processed_out[env_id, j] = x + + +class JointAction(ActionTerm): + r"""Base class for joint actions. + + This action term performs pre-processing of the raw actions using affine transformations (scale and offset). + These transformations can be configured to be applied to a subset of the articulation's joints. + + Mathematically, the action term is defined as: + + .. math:: + + \text{action} = \text{offset} + \text{scaling} \times \text{input action} + + where :math:`\text{action}` is the action that is sent to the articulation's actuated joints, :math:`\text{offset}` + is the offset applied to the input action, :math:`\text{scaling}` is the scaling applied to the input + action, and :math:`\text{input action}` is the input action from the user. + + Based on above, this kind of action transformation ensures that the input and output actions are in the same + units and dimensions. The child classes of this action term can then map the output action to a specific + desired command of the articulation's joints (e.g. position, velocity, etc.). + """ + + cfg: actions_cfg.JointActionCfg + """The configuration of the action term.""" + _asset: Articulation + """The articulation asset on which the action term is applied.""" + _scale: wp.array + """The scaling factor applied to the input action.""" + _offset: wp.array + """The offset applied to the input action.""" + _clip: wp.array + """The clip applied to the input action.""" + _joint_mask: wp.array + """A persistent joint mask for capturable action application.""" + + def __init__(self, cfg: actions_cfg.JointActionCfg, env: ManagerBasedEnv) -> None: + # initialize the action term + super().__init__(cfg, env) + + # resolve the joints over which the action term is applied + self._joint_ids, self._joint_names = self._asset.find_joints( + self.cfg.joint_names, preserve_order=self.cfg.preserve_order + ) + self._num_joints = len(self._joint_ids) + # log the resolved joint names for debugging + logger.info( + f"Resolved joint names for the action term {self.__class__.__name__}:" + f" {self._joint_names} [{self._joint_ids}]" + ) + + # Avoid indexing across all joints for efficiency + if self._num_joints == self._asset.num_joints and not self.cfg.preserve_order: + self._joint_ids = slice(None) + + # FIXME: ArticulationData.resolve_joint_mask is not available on this branch. + # Port resolve_*_mask methods from dev/newton when articulation_data is aligned. + _all_joint_mask = wp.ones((self._asset.num_joints,), dtype=wp.bool, device=self.device) + _scratch_joint_mask = wp.zeros((self._asset.num_joints,), dtype=wp.bool, device=self.device) + self._joint_mask = wp.clone( + resolve_1d_mask( + ids=self._joint_ids, + mask=None, + all_mask=_all_joint_mask, + scratch_mask=_scratch_joint_mask, + device=self.device, + ) + ) + + # create tensors for raw and processed actions (Warp) + self._raw_actions = wp.zeros((self.num_envs, self.action_dim), dtype=wp.float32, device=self.device) + self._processed_actions = wp.zeros_like(self.raw_actions) + # FIXME: dev/newton set_joint_effort_target accepts partial data + joint_mask. Our branch + # has separate _index (partial data) and _mask (full data) variants. Pre-compute joint_ids + # as warp array for the _index variant. + if self._joint_ids == slice(None): + self._joint_ids_wp = None # None means all joints + else: + self._joint_ids_wp = wp.array(list(self._joint_ids), dtype=wp.int32, device=self.device) + + # parse scale + if isinstance(cfg.scale, (float, int)): + self._scale = wp.array([float(cfg.scale)] * self.action_dim, dtype=wp.float32, device=self.device) + elif isinstance(cfg.scale, dict): + scale_per_joint = [1.0] * self.action_dim + # resolve the dictionary config + index_list, _, value_list = string_utils.resolve_matching_names_values(self.cfg.scale, self._joint_names) + for idx, value in zip(index_list, value_list): + scale_per_joint[idx] = float(value) + self._scale = wp.array(scale_per_joint, dtype=wp.float32, device=self.device) + else: + raise ValueError(f"Unsupported scale type: {type(cfg.scale)}. Supported types are float and dict.") + + # parse offset + if isinstance(cfg.offset, (float, int)): + self._offset = wp.array([float(cfg.offset)] * self.action_dim, dtype=wp.float32, device=self.device) + elif isinstance(cfg.offset, dict): + offset_per_joint = [0.0] * self.action_dim + # resolve the dictionary config + index_list, _, value_list = string_utils.resolve_matching_names_values(self.cfg.offset, self._joint_names) + for idx, value in zip(index_list, value_list): + offset_per_joint[idx] = float(value) + self._offset = wp.array(offset_per_joint, dtype=wp.float32, device=self.device) + else: + raise ValueError(f"Unsupported offset type: {type(cfg.offset)}. Supported types are float and dict.") + + # parse clip + clip_low = [-float("inf")] * self.action_dim + clip_high = [float("inf")] * self.action_dim + if self.cfg.clip is not None: + if isinstance(cfg.clip, dict): + index_list, _, value_list = string_utils.resolve_matching_names_values(self.cfg.clip, self._joint_names) + for idx, value in zip(index_list, value_list): + clip_low[idx] = float(value[0]) + clip_high[idx] = float(value[1]) + else: + raise ValueError(f"Unsupported clip type: {type(cfg.clip)}. Supported types are dict.") + + clip_np = np.column_stack([clip_low, clip_high]).astype(np.float32) + self._clip = wp.array(clip_np, dtype=wp.float32, device=self.device) + + """ + Properties. + """ + + @property + def action_dim(self) -> int: + return self._num_joints + + @property + def raw_actions(self) -> wp.array: + return self._raw_actions + + @property + def processed_actions(self) -> wp.array: + return self._processed_actions + + @property + def IO_descriptor(self) -> GenericActionIODescriptor: + """The IO descriptor of the action term. + + This descriptor is used to describe the action term of the joint action. + It adds the following information to the base descriptor: + - joint_names: The names of the joints. + - scale: The scale of the action term. + - offset: The offset of the action term. + - clip: The clip of the action term. + + Returns: + The IO descriptor of the action term. + """ + super().IO_descriptor + self._IO_descriptor.shape = (self.action_dim,) + self._IO_descriptor.dtype = str(self.raw_actions.dtype) + self._IO_descriptor.action_type = "JointAction" + self._IO_descriptor.joint_names = self._joint_names + self._IO_descriptor.scale = self._scale + # This seems to be always [4xNum_joints] IDK why. Need to check. + if isinstance(self._offset, wp.array): + self._IO_descriptor.offset = self._offset.numpy().tolist() + else: + self._IO_descriptor.offset = None + # FIXME: This is not correct. Add list support. + if self.cfg.clip is not None: + if isinstance(self._clip, wp.array): + self._IO_descriptor.clip = self._clip.numpy().tolist() + else: + self._IO_descriptor.clip = None + else: + self._IO_descriptor.clip = None + return self._IO_descriptor + + """ + Operations. + """ + + def process_actions(self, actions: wp.array, action_offset: int = 0): + wp.launch( + kernel=_process_joint_actions_kernel, + dim=(self.num_envs, self.action_dim), + inputs=[ + actions, + int(action_offset), + self._scale, + self._offset, + self._clip, + self._raw_actions, + self._processed_actions, + ], + device=self.device, + ) + + def reset(self, env_mask: wp.array | None = None) -> None: + """Resets the action term (mask-based).""" + if env_mask is None: + self._raw_actions.fill_(0.0) + return + wp.launch( + kernel=zero_masked_2d, + dim=(self.num_envs, self.action_dim), + inputs=[env_mask, self._raw_actions], + device=self.device, + ) + + +class JointPositionAction(JointAction): + """Joint action term that applies the processed actions to the articulation's joints as position commands. + + Warp-first override of :class:`isaaclab.envs.mdp.actions.JointPositionAction`. + """ + + cfg: actions_cfg.JointPositionActionCfg + """The configuration of the action term.""" + + def __init__(self, cfg: actions_cfg.JointPositionActionCfg, env: ManagerBasedEnv): + super().__init__(cfg, env) + # use default joint positions as offset + if cfg.use_default_offset: + defaults_np = self._asset.data.default_joint_pos.warp.numpy() + if isinstance(self._joint_ids, slice): + offset_vals = defaults_np[0, :].tolist() + else: + offset_vals = [float(defaults_np[0, jid]) for jid in self._joint_ids] + self._offset = wp.array(offset_vals, dtype=wp.float32, device=self.device) + + def apply_actions(self): + self._asset.set_joint_position_target_index(target=self.processed_actions, joint_ids=self._joint_ids_wp) + + +class JointEffortAction(JointAction): + """Joint action term that applies the processed actions to the articulation's joints as effort commands.""" + + cfg: actions_cfg.JointEffortActionCfg + """The configuration of the action term.""" + + def __init__(self, cfg: actions_cfg.JointEffortActionCfg, env: ManagerBasedEnv): + super().__init__(cfg, env) + + def apply_actions(self): + # set joint effort targets + # FIXME: dev/newton uses set_joint_effort_target(data, joint_mask=) which accepts + # partial data. Our branch uses the separate _index variant for partial data. + self._asset.set_joint_effort_target_index(target=self.processed_actions, joint_ids=self._joint_ids_wp) diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp/events.py b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp/events.py new file mode 100644 index 000000000000..e1732df0c026 --- /dev/null +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp/events.py @@ -0,0 +1,584 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Warp-first overrides for common event terms. + +These functions are intended to be used with the experimental Warp-first +:class:`isaaclab_experimental.managers.EventManager` (mask-based interval/reset). + +Why this exists: +- Stable event terms (e.g. `isaaclab.envs.mdp.events.reset_joints_by_offset`) often build torch tensors and then + call into Newton articulation writers with partial indices (env_ids/joint_ids). +- On the Newton backend, passing torch tensors triggers expensive torch->warp conversions that currently allocate + full `(num_envs, num_joints)` buffers. + +These Warp-first implementations avoid that by writing directly into the sim-bound Warp state buffers +(`asset.data.joint_pos` / `asset.data.joint_vel`) for the selected envs/joints. + +Notes: +- These terms assume the Newton/Warp backend (Warp arrays are available for joint state and defaults). +- For best performance, pass :class:`isaaclab_experimental.managers.SceneEntityCfg` so `joint_ids_wp` is cached. +""" + +from __future__ import annotations + +import warp as wp + +from isaaclab.assets import Articulation + +from isaaclab_experimental.managers import SceneEntityCfg +from isaaclab_experimental.utils.warp import WarpCapturable + +# --------------------------------------------------------------------------- +# Randomize rigid body center of mass +# --------------------------------------------------------------------------- + + +@wp.kernel +def _randomize_com_kernel( + env_mask: wp.array(dtype=wp.bool), + rng_state: wp.array(dtype=wp.uint32), + body_com_pos_b: wp.array(dtype=wp.vec3f, ndim=2), + body_ids: wp.array(dtype=wp.int32), + com_lo: wp.vec3f, + com_hi: wp.vec3f, +): + """Add random offset to center of mass positions for selected bodies.""" + env_id = wp.tid() + if not env_mask[env_id]: + return + + state = rng_state[env_id] + for k in range(body_ids.shape[0]): + b = body_ids[k] + v = body_com_pos_b[env_id, b] + dx = wp.randf(state, com_lo[0], com_hi[0]) + dy = wp.randf(state, com_lo[1], com_hi[1]) + dz = wp.randf(state, com_lo[2], com_hi[2]) + body_com_pos_b[env_id, b] = wp.vec3f(v[0] + dx, v[1] + dy, v[2] + dz) + rng_state[env_id] = state + + +@WarpCapturable(False, reason="set_coms_mask calls SimulationManager.add_model_change") +def randomize_rigid_body_com( + env, + env_mask: wp.array, + com_range: dict[str, tuple[float, float]], + asset_cfg: SceneEntityCfg = SceneEntityCfg("robot"), +): + """Randomize the center of mass (CoM) of rigid bodies by adding random offsets. + + Warp-first override of :func:`isaaclab.envs.mdp.events.randomize_rigid_body_com`. + Writes directly into the sim-bound ``body_com_pos_b`` buffer, then notifies the solver + via :meth:`set_coms_mask` so it recomputes inertial properties. + """ + asset: Articulation = env.scene[asset_cfg.name] + + fn = randomize_rigid_body_com + if not getattr(fn, "_is_warmed_up", False) or fn._asset_name != asset_cfg.name: + fn._asset_name = asset_cfg.name + r = [com_range.get(key, (0.0, 0.0)) for key in ["x", "y", "z"]] + fn._com_lo = wp.vec3f(r[0][0], r[1][0], r[2][0]) + fn._com_hi = wp.vec3f(r[0][1], r[1][1], r[2][1]) + fn._is_warmed_up = True + + wp.launch( + kernel=_randomize_com_kernel, + dim=env.num_envs, + inputs=[ + env_mask, + env.rng_state_wp, + asset.data.body_com_pos_b.warp, + asset_cfg.body_ids_wp, + fn._com_lo, + fn._com_hi, + ], + device=env.device, + ) + + # Notify the solver that inertial properties changed (COM position affects inertia). + asset.set_coms_mask(coms=asset.data.body_com_pos_b.warp, env_mask=env_mask) + + +# --------------------------------------------------------------------------- +# Apply external force and torque +# --------------------------------------------------------------------------- + + +@wp.kernel +def _apply_external_force_torque_kernel( + env_mask: wp.array(dtype=wp.bool), + rng_state: wp.array(dtype=wp.uint32), + force_out: wp.array(dtype=wp.vec3f, ndim=2), + torque_out: wp.array(dtype=wp.vec3f, ndim=2), + force_lo: float, + force_hi: float, + torque_lo: float, + torque_hi: float, +): + env_id = wp.tid() + if not env_mask[env_id]: + # zero out unmasked envs so they don't accumulate stale forces + for b in range(force_out.shape[1]): + force_out[env_id, b] = wp.vec3f(0.0, 0.0, 0.0) + torque_out[env_id, b] = wp.vec3f(0.0, 0.0, 0.0) + return + + state = rng_state[env_id] + for b in range(force_out.shape[1]): + force_out[env_id, b] = wp.vec3f( + wp.randf(state, force_lo, force_hi), + wp.randf(state, force_lo, force_hi), + wp.randf(state, force_lo, force_hi), + ) + torque_out[env_id, b] = wp.vec3f( + wp.randf(state, torque_lo, torque_hi), + wp.randf(state, torque_lo, torque_hi), + wp.randf(state, torque_lo, torque_hi), + ) + rng_state[env_id] = state + + +def apply_external_force_torque( + env, + env_mask: wp.array, + force_range: tuple[float, float], + torque_range: tuple[float, float], + asset_cfg: SceneEntityCfg = SceneEntityCfg("robot"), +): + """Randomize external forces and torques applied to the asset's bodies. + + Warp-first override of :func:`isaaclab.envs.mdp.events.apply_external_force_torque`. + """ + asset: Articulation = env.scene[asset_cfg.name] + + # First-call: allocate scratch and pre-convert constant arguments. + if not getattr(apply_external_force_torque, "_is_warmed_up", False): + apply_external_force_torque._scratch_forces = wp.zeros( + (env.num_envs, asset.num_bodies), dtype=wp.vec3f, device=env.device + ) + apply_external_force_torque._scratch_torques = wp.zeros( + (env.num_envs, asset.num_bodies), dtype=wp.vec3f, device=env.device + ) + apply_external_force_torque._is_warmed_up = True + + wp.launch( + kernel=_apply_external_force_torque_kernel, + dim=env.num_envs, + inputs=[ + env_mask, + env.rng_state_wp, + apply_external_force_torque._scratch_forces, + apply_external_force_torque._scratch_torques, + force_range[0], + force_range[1], + torque_range[0], + torque_range[1], + ], + device=env.device, + ) + + asset.permanent_wrench_composer.set_forces_and_torques_mask( + forces=apply_external_force_torque._scratch_forces, + torques=apply_external_force_torque._scratch_torques, + env_mask=env_mask, + ) + + +# --------------------------------------------------------------------------- +# Push by velocity +# --------------------------------------------------------------------------- + + +@wp.kernel +def _push_by_setting_velocity_kernel( + env_mask: wp.array(dtype=wp.bool), + rng_state: wp.array(dtype=wp.uint32), + root_vel_w: wp.array(dtype=wp.spatial_vectorf), + vel_out: wp.array(dtype=wp.spatial_vectorf), + lin_lo: wp.vec3f, + lin_hi: wp.vec3f, + ang_lo: wp.vec3f, + ang_hi: wp.vec3f, +): + env_id = wp.tid() + if not env_mask[env_id]: + return + + vel = root_vel_w[env_id] + state = rng_state[env_id] + + vel_out[env_id] = wp.spatial_vectorf( + vel[0] + wp.randf(state, lin_lo[0], lin_hi[0]), + vel[1] + wp.randf(state, lin_lo[1], lin_hi[1]), + vel[2] + wp.randf(state, lin_lo[2], lin_hi[2]), + vel[3] + wp.randf(state, ang_lo[0], ang_hi[0]), + vel[4] + wp.randf(state, ang_lo[1], ang_hi[1]), + vel[5] + wp.randf(state, ang_lo[2], ang_hi[2]), + ) + + rng_state[env_id] = state + + +def push_by_setting_velocity( + env, + env_mask: wp.array, + velocity_range: dict[str, tuple[float, float]], + asset_cfg: SceneEntityCfg = SceneEntityCfg("robot"), +): + """Push the asset by setting the root velocity to a random value within the given ranges. + + Warp-first override of :func:`isaaclab.envs.mdp.events.push_by_setting_velocity`. + """ + asset: Articulation = env.scene[asset_cfg.name] + + # First-call: allocate scratch and pre-parse constant range arguments. + if not getattr(push_by_setting_velocity, "_is_warmed_up", False): + push_by_setting_velocity._scratch_vel = wp.zeros((env.num_envs,), dtype=wp.spatial_vectorf, device=env.device) + r = [velocity_range.get(key, (0.0, 0.0)) for key in ["x", "y", "z", "roll", "pitch", "yaw"]] + push_by_setting_velocity._lin_lo = wp.vec3f(r[0][0], r[1][0], r[2][0]) + push_by_setting_velocity._lin_hi = wp.vec3f(r[0][1], r[1][1], r[2][1]) + push_by_setting_velocity._ang_lo = wp.vec3f(r[3][0], r[4][0], r[5][0]) + push_by_setting_velocity._ang_hi = wp.vec3f(r[3][1], r[4][1], r[5][1]) + push_by_setting_velocity._is_warmed_up = True + + wp.launch( + kernel=_push_by_setting_velocity_kernel, + dim=env.num_envs, + inputs=[ + env_mask, + env.rng_state_wp, + asset.data.root_vel_w.warp, + push_by_setting_velocity._scratch_vel, + push_by_setting_velocity._lin_lo, + push_by_setting_velocity._lin_hi, + push_by_setting_velocity._ang_lo, + push_by_setting_velocity._ang_hi, + ], + device=env.device, + ) + + asset.write_root_velocity_to_sim_mask(root_velocity=push_by_setting_velocity._scratch_vel, env_mask=env_mask) + + +# --------------------------------------------------------------------------- +# Reset root state uniform +# --------------------------------------------------------------------------- + + +@wp.kernel +def _reset_root_state_uniform_kernel( + env_mask: wp.array(dtype=wp.bool), + rng_state: wp.array(dtype=wp.uint32), + default_root_pose: wp.array(dtype=wp.transformf), + default_root_vel: wp.array(dtype=wp.spatial_vectorf), + env_origins: wp.array(dtype=wp.vec3f), + pose_out: wp.array(dtype=wp.transformf), + vel_out: wp.array(dtype=wp.spatial_vectorf), + pos_lo: wp.vec3f, + pos_hi: wp.vec3f, + rot_lo: wp.vec3f, + rot_hi: wp.vec3f, + vel_lin_lo: wp.vec3f, + vel_lin_hi: wp.vec3f, + vel_ang_lo: wp.vec3f, + vel_ang_hi: wp.vec3f, +): + env_id = wp.tid() + if not env_mask[env_id]: + return + + state = rng_state[env_id] + + # --- Pose --- + default_pose = default_root_pose[env_id] + default_pos = wp.transform_get_translation(default_pose) + default_q = wp.transform_get_rotation(default_pose) + origin = env_origins[env_id] + + # position = default + env_origin + random offset + pos = wp.vec3f( + default_pos[0] + origin[0] + wp.randf(state, pos_lo[0], pos_hi[0]), + default_pos[1] + origin[1] + wp.randf(state, pos_lo[1], pos_hi[1]), + default_pos[2] + origin[2] + wp.randf(state, pos_lo[2], pos_hi[2]), + ) + + # orientation = default * delta(euler_xyz) + roll = wp.randf(state, rot_lo[0], rot_hi[0]) + pitch = wp.randf(state, rot_lo[1], rot_hi[1]) + yaw = wp.randf(state, rot_lo[2], rot_hi[2]) + qx = wp.quat_from_axis_angle(wp.vec3f(1.0, 0.0, 0.0), roll) + qy = wp.quat_from_axis_angle(wp.vec3f(0.0, 1.0, 0.0), pitch) + qz = wp.quat_from_axis_angle(wp.vec3f(0.0, 0.0, 1.0), yaw) + # ZYX extrinsic = XYZ intrinsic: delta = qz * qy * qx + delta_q = wp.mul(wp.mul(qz, qy), qx) + final_q = wp.mul(default_q, delta_q) + + pose_out[env_id] = wp.transformf(pos, final_q) + + # --- Velocity --- + default_vel = default_root_vel[env_id] + vel_out[env_id] = wp.spatial_vectorf( + default_vel[0] + wp.randf(state, vel_lin_lo[0], vel_lin_hi[0]), + default_vel[1] + wp.randf(state, vel_lin_lo[1], vel_lin_hi[1]), + default_vel[2] + wp.randf(state, vel_lin_lo[2], vel_lin_hi[2]), + default_vel[3] + wp.randf(state, vel_ang_lo[0], vel_ang_hi[0]), + default_vel[4] + wp.randf(state, vel_ang_lo[1], vel_ang_hi[1]), + default_vel[5] + wp.randf(state, vel_ang_lo[2], vel_ang_hi[2]), + ) + + rng_state[env_id] = state + + +def reset_root_state_uniform( + env, + env_mask: wp.array, + pose_range: dict[str, tuple[float, float]], + velocity_range: dict[str, tuple[float, float]], + asset_cfg: SceneEntityCfg = SceneEntityCfg("robot"), +): + """Reset the asset root state to a random position and velocity uniformly within the given ranges. + + Warp-first override of :func:`isaaclab.envs.mdp.events.reset_root_state_uniform`. + """ + asset: Articulation = env.scene[asset_cfg.name] + + # First-call: allocate scratch and pre-parse range dicts. + if not getattr(reset_root_state_uniform, "_is_warmed_up", False): + reset_root_state_uniform._scratch_pose = wp.zeros((env.num_envs,), dtype=wp.transformf, device=env.device) + reset_root_state_uniform._scratch_vel = wp.zeros((env.num_envs,), dtype=wp.spatial_vectorf, device=env.device) + # Pre-parse pose_range dict + p = [pose_range.get(key, (0.0, 0.0)) for key in ["x", "y", "z", "roll", "pitch", "yaw"]] + reset_root_state_uniform._pos_lo = wp.vec3f(p[0][0], p[1][0], p[2][0]) + reset_root_state_uniform._pos_hi = wp.vec3f(p[0][1], p[1][1], p[2][1]) + reset_root_state_uniform._rot_lo = wp.vec3f(p[3][0], p[4][0], p[5][0]) + reset_root_state_uniform._rot_hi = wp.vec3f(p[3][1], p[4][1], p[5][1]) + # Pre-parse velocity_range dict + v = [velocity_range.get(key, (0.0, 0.0)) for key in ["x", "y", "z", "roll", "pitch", "yaw"]] + reset_root_state_uniform._vel_lin_lo = wp.vec3f(v[0][0], v[1][0], v[2][0]) + reset_root_state_uniform._vel_lin_hi = wp.vec3f(v[0][1], v[1][1], v[2][1]) + reset_root_state_uniform._vel_ang_lo = wp.vec3f(v[3][0], v[4][0], v[5][0]) + reset_root_state_uniform._vel_ang_hi = wp.vec3f(v[3][1], v[4][1], v[5][1]) + reset_root_state_uniform._is_warmed_up = True + + wp.launch( + kernel=_reset_root_state_uniform_kernel, + dim=env.num_envs, + inputs=[ + env_mask, + env.rng_state_wp, + asset.data.default_root_pose.warp, + asset.data.default_root_vel.warp, + env.env_origins_wp, + reset_root_state_uniform._scratch_pose, + reset_root_state_uniform._scratch_vel, + reset_root_state_uniform._pos_lo, + reset_root_state_uniform._pos_hi, + reset_root_state_uniform._rot_lo, + reset_root_state_uniform._rot_hi, + reset_root_state_uniform._vel_lin_lo, + reset_root_state_uniform._vel_lin_hi, + reset_root_state_uniform._vel_ang_lo, + reset_root_state_uniform._vel_ang_hi, + ], + device=env.device, + ) + + asset.write_root_pose_to_sim_mask(root_pose=reset_root_state_uniform._scratch_pose, env_mask=env_mask) + asset.write_root_velocity_to_sim_mask(root_velocity=reset_root_state_uniform._scratch_vel, env_mask=env_mask) + + +# --------------------------------------------------------------------------- +# Reset joints by offset +# --------------------------------------------------------------------------- + + +@wp.kernel +def _reset_joints_by_offset_kernel( + env_mask: wp.array(dtype=wp.bool), + joint_ids: wp.array(dtype=wp.int32), + rng_state: wp.array(dtype=wp.uint32), + default_joint_pos: wp.array(dtype=wp.float32, ndim=2), + default_joint_vel: wp.array(dtype=wp.float32, ndim=2), + joint_pos: wp.array(dtype=wp.float32, ndim=2), + joint_vel: wp.array(dtype=wp.float32, ndim=2), + soft_joint_pos_limits: wp.array(dtype=wp.vec2f, ndim=2), + soft_joint_vel_limits: wp.array(dtype=wp.float32, ndim=2), + pos_lo: float, + pos_hi: float, + vel_lo: float, + vel_hi: float, +): + env_id = wp.tid() + if not env_mask[env_id]: + return + + # 1 thread per env so per-env RNG state updates are race-free. + state = rng_state[env_id] + for joint_i in range(joint_ids.shape[0]): + joint_id = joint_ids[joint_i] + + # offset samples in the provided ranges (Warp RNG state pattern) + pos_off = wp.randf(state, pos_lo, pos_hi) + vel_off = wp.randf(state, vel_lo, vel_hi) + + pos = default_joint_pos[env_id, joint_id] + pos_off + vel = default_joint_vel[env_id, joint_id] + vel_off + + # clamp to soft limits + lim = soft_joint_pos_limits[env_id, joint_id] + pos = wp.clamp(pos, lim.x, lim.y) + vmax = soft_joint_vel_limits[env_id, joint_id] + vel = wp.clamp(vel, -vmax, vmax) + + # write into sim-bound state buffers + joint_pos[env_id, joint_id] = pos + joint_vel[env_id, joint_id] = vel + + rng_state[env_id] = state + + +def reset_joints_by_offset( + env, + env_mask: wp.array, + position_range: tuple[float, float], + velocity_range: tuple[float, float], + asset_cfg: SceneEntityCfg = SceneEntityCfg("robot"), +): + """Warp-first reset of joint state by random offsets around defaults. + + This overrides the stable `isaaclab.envs.mdp.events.reset_joints_by_offset` when importing + via `isaaclab_experimental.envs.mdp`. + """ + asset: Articulation = env.scene[asset_cfg.name] + + # Assume cfg params are already resolved by the manager stack (Warp-first workflow). + if asset_cfg.joint_ids_wp is None: + raise ValueError( + f"reset_joints_by_offset requires an experimental SceneEntityCfg with resolved joint_ids_wp, " + f"but got None for asset '{asset_cfg.name}'. " + "Use isaaclab_experimental.managers.SceneEntityCfg and ensure joint_names are set." + ) + if not hasattr(env, "rng_state_wp") or env.rng_state_wp is None: + raise AttributeError( + "reset_joints_by_offset requires env.rng_state_wp to be initialized. " + "Use ManagerBasedEnvWarp or ManagerBasedRLEnvWarp as the base environment." + ) + + wp.launch( + kernel=_reset_joints_by_offset_kernel, + dim=env.num_envs, + inputs=[ + env_mask, + asset_cfg.joint_ids_wp, + env.rng_state_wp, + asset.data.default_joint_pos.warp, + asset.data.default_joint_vel.warp, + asset.data.joint_pos.warp, + asset.data.joint_vel.warp, + asset.data.soft_joint_pos_limits.warp, + asset.data.soft_joint_vel_limits.warp, + float(position_range[0]), + float(position_range[1]), + float(velocity_range[0]), + float(velocity_range[1]), + ], + device=env.device, + ) + + # Sync derived buffers (_previous_joint_vel, joint_acc) for reset envs. + asset.write_joint_position_to_sim_mask(position=asset.data.joint_pos.warp, env_mask=env_mask) + asset.write_joint_velocity_to_sim_mask(velocity=asset.data.joint_vel.warp, env_mask=env_mask) + + +@wp.kernel +def _reset_joints_by_scale_kernel( + env_mask: wp.array(dtype=wp.bool), + joint_ids: wp.array(dtype=wp.int32), + rng_state: wp.array(dtype=wp.uint32), + default_joint_pos: wp.array(dtype=wp.float32, ndim=2), + default_joint_vel: wp.array(dtype=wp.float32, ndim=2), + joint_pos: wp.array(dtype=wp.float32, ndim=2), + joint_vel: wp.array(dtype=wp.float32, ndim=2), + soft_joint_pos_limits: wp.array(dtype=wp.vec2f, ndim=2), + soft_joint_vel_limits: wp.array(dtype=wp.float32, ndim=2), + pos_lo: float, + pos_hi: float, + vel_lo: float, + vel_hi: float, +): + env_id = wp.tid() + if not env_mask[env_id]: + return + + state = rng_state[env_id] + for joint_i in range(joint_ids.shape[0]): + joint_id = joint_ids[joint_i] + + # scale samples in the provided ranges + pos_scale = wp.randf(state, pos_lo, pos_hi) + vel_scale = wp.randf(state, vel_lo, vel_hi) + + pos = default_joint_pos[env_id, joint_id] * pos_scale + vel = default_joint_vel[env_id, joint_id] * vel_scale + + lim = soft_joint_pos_limits[env_id, joint_id] + pos = wp.clamp(pos, lim.x, lim.y) + vmax = soft_joint_vel_limits[env_id, joint_id] + vel = wp.clamp(vel, -vmax, vmax) + + # write into sim + joint_pos[env_id, joint_id] = pos + joint_vel[env_id, joint_id] = vel + + rng_state[env_id] = state + + +def reset_joints_by_scale( + env, + env_mask: wp.array, + position_range: tuple[float, float], + velocity_range: tuple[float, float], + asset_cfg: SceneEntityCfg = SceneEntityCfg("robot"), +): + """Warp-first reset of joint state by scaling defaults with random factors.""" + asset: Articulation = env.scene[asset_cfg.name] + + if asset_cfg.joint_ids_wp is None: + raise ValueError( + f"reset_joints_by_scale requires an experimental SceneEntityCfg with resolved joint_ids_wp, " + f"but got None for asset '{asset_cfg.name}'. " + "Use isaaclab_experimental.managers.SceneEntityCfg and ensure joint_names are set." + ) + if not hasattr(env, "rng_state_wp") or env.rng_state_wp is None: + raise AttributeError( + "reset_joints_by_scale requires env.rng_state_wp to be initialized. " + "Use ManagerBasedEnvWarp or ManagerBasedRLEnvWarp as the base environment." + ) + + wp.launch( + kernel=_reset_joints_by_scale_kernel, + dim=env.num_envs, + inputs=[ + env_mask, + asset_cfg.joint_ids_wp, + env.rng_state_wp, + asset.data.default_joint_pos.warp, + asset.data.default_joint_vel.warp, + asset.data.joint_pos.warp, + asset.data.joint_vel.warp, + asset.data.soft_joint_pos_limits.warp, + asset.data.soft_joint_vel_limits.warp, + float(position_range[0]), + float(position_range[1]), + float(velocity_range[0]), + float(velocity_range[1]), + ], + device=env.device, + ) + + # Sync derived buffers (_previous_joint_vel, joint_acc) for reset envs. + asset.write_joint_position_to_sim_mask(position=asset.data.joint_pos.warp, env_mask=env_mask) + asset.write_joint_velocity_to_sim_mask(velocity=asset.data.joint_vel.warp, env_mask=env_mask) diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp/observations.py b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp/observations.py new file mode 100644 index 000000000000..5760d1f03e8c --- /dev/null +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp/observations.py @@ -0,0 +1,370 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Warp-first observation terms (experimental). + +All functions in this file follow the Warp-compatible observation signature expected by the +experimental Warp-first observation manager: + +- ``func(env, out, **params) -> None`` + +where ``out`` is a pre-allocated Warp array with float32 dtype and shape ``(num_envs, D)``. +Output dimension ``D`` is inferred from decorator metadata: ``axes`` for root-state terms, +``out_dim`` for body/command/action/time terms, or ``joint_ids`` count for joint terms. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +import torch +import warp as wp +from isaaclab_newton.kernels.state_kernels import ( + body_ang_vel_from_root, + body_lin_vel_from_root, + rotate_vec_to_body_frame, +) + +from isaaclab.assets import Articulation + +from isaaclab_experimental.envs.utils.io_descriptors import ( + generic_io_descriptor_warp, + record_dtype, + record_joint_names, + record_joint_pos_offsets, + record_joint_vel_offsets, + record_shape, +) +from isaaclab_experimental.managers import SceneEntityCfg + +if TYPE_CHECKING: + from isaaclab.envs import ManagerBasedEnv + + +# --------------------------------------------------------------------------- +# Shared kernels +# --------------------------------------------------------------------------- + + +@wp.kernel +def _vec3_to_out3_kernel( + src: wp.array(dtype=wp.vec3f), + out: wp.array(dtype=wp.float32, ndim=2), +): + env_id = wp.tid() + v = src[env_id] + out[env_id, 0] = v[0] + out[env_id, 1] = v[1] + out[env_id, 2] = v[2] + + +@wp.kernel +def _joint_gather_kernel( + src: wp.array(dtype=wp.float32, ndim=2), + joint_ids: wp.array(dtype=wp.int32), + out: wp.array(dtype=wp.float32, ndim=2), +): + env_id, k = wp.tid() + j = joint_ids[k] + out[env_id, k] = src[env_id, j] + + +""" +Root state. +""" + + +@wp.kernel +def _base_pos_z_kernel( + root_pos_w: wp.array(dtype=wp.vec3f), + out: wp.array(dtype=wp.float32, ndim=2), +): + env_id = wp.tid() + out[env_id, 0] = root_pos_w[env_id][2] + + +@generic_io_descriptor_warp( + units="m", axes=["Z"], observation_type="RootState", on_inspect=[record_shape, record_dtype] +) +def base_pos_z(env: ManagerBasedEnv, out, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")) -> None: + """Root height in the simulation world frame.""" + asset: Articulation = env.scene[asset_cfg.name] + wp.launch( + kernel=_base_pos_z_kernel, + dim=env.num_envs, + inputs=[asset.data.root_pos_w.warp, out], + device=env.device, + ) + + +# Inline Tier 1 access: these observations derive body-frame quantities directly from +# root_link_pose_w (transformf) and root_com_vel_w (spatial_vectorf), avoiding the lazy +# TimestampedWarpBuffer properties which are not CUDA-graph-capturable. +# See GRAPH_CAPTURE_MIGRATION.md in isaaclab_newton for background. +# If ArticulationData Tier 2 lazy update is made graph-safe in the future, these can +# revert to reading the pre-computed .data buffers (simpler, avoids redundant rotations). + + +@wp.kernel +def _base_lin_vel_kernel( + root_pose_w: wp.array(dtype=wp.transformf), + root_vel_w: wp.array(dtype=wp.spatial_vectorf), + out: wp.array(dtype=wp.float32, ndim=2), +): + i = wp.tid() + v = body_lin_vel_from_root(root_pose_w[i], root_vel_w[i]) + out[i, 0] = v[0] + out[i, 1] = v[1] + out[i, 2] = v[2] + + +@generic_io_descriptor_warp( + units="m/s", axes=["X", "Y", "Z"], observation_type="RootState", on_inspect=[record_shape, record_dtype] +) +def base_lin_vel(env: ManagerBasedEnv, out, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")) -> None: + """Root linear velocity in the asset's root frame.""" + asset: Articulation = env.scene[asset_cfg.name] + wp.launch( + kernel=_base_lin_vel_kernel, + dim=env.num_envs, + inputs=[asset.data.root_link_pose_w.warp, asset.data.root_com_vel_w.warp, out], + device=env.device, + ) + + +@wp.kernel +def _base_ang_vel_kernel( + root_pose_w: wp.array(dtype=wp.transformf), + root_vel_w: wp.array(dtype=wp.spatial_vectorf), + out: wp.array(dtype=wp.float32, ndim=2), +): + i = wp.tid() + v = body_ang_vel_from_root(root_pose_w[i], root_vel_w[i]) + out[i, 0] = v[0] + out[i, 1] = v[1] + out[i, 2] = v[2] + + +@generic_io_descriptor_warp( + units="rad/s", axes=["X", "Y", "Z"], observation_type="RootState", on_inspect=[record_shape, record_dtype] +) +def base_ang_vel(env: ManagerBasedEnv, out, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")) -> None: + """Root angular velocity in the asset's root frame.""" + asset: Articulation = env.scene[asset_cfg.name] + wp.launch( + kernel=_base_ang_vel_kernel, + dim=env.num_envs, + inputs=[asset.data.root_link_pose_w.warp, asset.data.root_com_vel_w.warp, out], + device=env.device, + ) + + +@wp.kernel +def _projected_gravity_kernel( + root_pose_w: wp.array(dtype=wp.transformf), + gravity_w: wp.array(dtype=wp.vec3f), + out: wp.array(dtype=wp.float32, ndim=2), +): + i = wp.tid() + g = rotate_vec_to_body_frame(gravity_w[0], root_pose_w[i]) + out[i, 0] = g[0] + out[i, 1] = g[1] + out[i, 2] = g[2] + + +@generic_io_descriptor_warp( + units="m/s^2", axes=["X", "Y", "Z"], observation_type="RootState", on_inspect=[record_shape, record_dtype] +) +def projected_gravity(env: ManagerBasedEnv, out, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")) -> None: + """Gravity projection on the asset's root frame.""" + asset: Articulation = env.scene[asset_cfg.name] + wp.launch( + kernel=_projected_gravity_kernel, + dim=env.num_envs, + inputs=[asset.data.root_link_pose_w.warp, asset.data.GRAVITY_VEC_W.warp, out], + device=env.device, + ) + + +""" +Joint state. +""" + + +@generic_io_descriptor_warp( + observation_type="JointState", on_inspect=[record_joint_names, record_dtype, record_shape], units="rad" +) +def joint_pos(env: ManagerBasedEnv, out, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")) -> None: + """The joint positions of the asset.""" + asset: Articulation = env.scene[asset_cfg.name] + joint_ids_wp = getattr(asset_cfg, "joint_ids_wp", None) + if joint_ids_wp is None: + raise RuntimeError( + "SceneEntityCfg.joint_ids_wp is required for subset joint observations in Warp-first observations. " + "Pass `asset_cfg` via term cfg params so it is resolved at manager init." + ) + wp.launch( + kernel=_joint_gather_kernel, + dim=(env.num_envs, out.shape[1]), + inputs=[asset.data.joint_pos.warp, joint_ids_wp, out], + device=env.device, + ) + + +@wp.kernel +def _joint_rel_gather_kernel( + values: wp.array(dtype=wp.float32, ndim=2), + defaults: wp.array(dtype=wp.float32, ndim=2), + joint_ids: wp.array(dtype=wp.int32), + out: wp.array(dtype=wp.float32, ndim=2), +): + env_id, k = wp.tid() + j = joint_ids[k] + out[env_id, k] = values[env_id, j] - defaults[env_id, j] + + +@generic_io_descriptor_warp( + observation_type="JointState", + on_inspect=[record_joint_names, record_dtype, record_shape, record_joint_pos_offsets], + units="rad", +) +def joint_pos_rel(env: ManagerBasedEnv, out, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")) -> None: + """Joint positions relative to defaults. Writes into ``out``.""" + asset: Articulation = env.scene[asset_cfg.name] + + # Subset selection (requires a pre-resolved Warp joint-id list). + joint_ids_wp = getattr(asset_cfg, "joint_ids_wp", None) + if joint_ids_wp is None: + raise RuntimeError( + "SceneEntityCfg.joint_ids_wp is required for subset joint observations in Warp-first observations. " + "Pass `asset_cfg` via term cfg params so it is resolved at manager init." + ) + wp.launch( + kernel=_joint_rel_gather_kernel, + dim=(env.num_envs, out.shape[1]), + inputs=[asset.data.joint_pos.warp, asset.data.default_joint_pos.warp, joint_ids_wp, out], + device=env.device, + ) + + +@wp.kernel +def _joint_pos_limit_normalized_kernel( + joint_pos: wp.array(dtype=wp.float32, ndim=2), + soft_joint_pos_limits: wp.array(dtype=wp.vec2f, ndim=2), + joint_ids: wp.array(dtype=wp.int32), + out: wp.array(dtype=wp.float32, ndim=2), +): + env_id, k = wp.tid() + j = joint_ids[k] + pos = joint_pos[env_id, j] + lim = soft_joint_pos_limits[env_id, j] + lower = lim.x + upper = lim.y + out[env_id, k] = 2.0 * (pos - (lower + upper) * 0.5) / (upper - lower) + + +@generic_io_descriptor_warp(observation_type="JointState", on_inspect=[record_joint_names, record_dtype, record_shape]) +def joint_pos_limit_normalized(env: ManagerBasedEnv, out, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")) -> None: + """The joint positions of the asset normalized with the asset's joint limits.""" + asset: Articulation = env.scene[asset_cfg.name] + joint_ids_wp = getattr(asset_cfg, "joint_ids_wp", None) + if joint_ids_wp is None: + raise RuntimeError( + "SceneEntityCfg.joint_ids_wp is required for subset joint observations in Warp-first observations. " + "Pass `asset_cfg` via term cfg params so it is resolved at manager init." + ) + wp.launch( + kernel=_joint_pos_limit_normalized_kernel, + dim=(env.num_envs, out.shape[1]), + inputs=[asset.data.joint_pos.warp, asset.data.soft_joint_pos_limits.warp, joint_ids_wp, out], + device=env.device, + ) + + +@generic_io_descriptor_warp( + observation_type="JointState", on_inspect=[record_joint_names, record_dtype, record_shape], units="rad/s" +) +def joint_vel(env: ManagerBasedEnv, out, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")) -> None: + """The joint velocities of the asset.""" + asset: Articulation = env.scene[asset_cfg.name] + joint_ids_wp = getattr(asset_cfg, "joint_ids_wp", None) + if joint_ids_wp is None: + raise RuntimeError( + "SceneEntityCfg.joint_ids_wp is required for subset joint observations in Warp-first observations. " + "Pass `asset_cfg` via term cfg params so it is resolved at manager init." + ) + wp.launch( + kernel=_joint_gather_kernel, + dim=(env.num_envs, out.shape[1]), + inputs=[asset.data.joint_vel.warp, joint_ids_wp, out], + device=env.device, + ) + + +@generic_io_descriptor_warp( + observation_type="JointState", + on_inspect=[record_joint_names, record_dtype, record_shape, record_joint_vel_offsets], + units="rad/s", +) +def joint_vel_rel(env: ManagerBasedEnv, out, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")) -> None: + """Joint velocities relative to defaults. Writes into ``out``.""" + asset: Articulation = env.scene[asset_cfg.name] + + # Subset selection (requires a pre-resolved Warp joint-id list). + joint_ids_wp = getattr(asset_cfg, "joint_ids_wp", None) + if joint_ids_wp is None: + raise RuntimeError( + "SceneEntityCfg.joint_ids_wp is required for subset joint observations in Warp-first observations. " + "Pass `asset_cfg` via term cfg params so it is resolved at manager init." + ) + wp.launch( + kernel=_joint_rel_gather_kernel, + dim=(env.num_envs, out.shape[1]), + inputs=[asset.data.joint_vel.warp, asset.data.default_joint_vel.warp, joint_ids_wp, out], + device=env.device, + ) + + +""" +Actions. +""" + + +@generic_io_descriptor_warp(out_dim="action", dtype=torch.float32, observation_type="Action", on_inspect=[record_shape]) +def last_action(env: ManagerBasedEnv, out, action_name: str | None = None) -> None: + """The last input action to the environment.""" + # TODO(warp-migration): Cross-manager access (observation → action). Currently works + # because experimental ActionManager.action is already a warp array. No from_torch needed. + if action_name is not None: + raise NotImplementedError("Named action support is not yet implemented for Warp-first last_action observation.") + wp.copy(out, env.action_manager.action) + + +""" +Commands. +""" + + +@generic_io_descriptor_warp( + out_dim="command", dtype=torch.float32, observation_type="Command", on_inspect=[record_shape] +) +def generated_commands(env: ManagerBasedEnv, out, command_name: str) -> None: + """The generated command from the command manager. Writes into ``out``. + + Warp-first override of :func:`isaaclab.envs.mdp.observations.generated_commands`. + Uses ``wp.from_torch`` to create a zero-copy warp view of the command tensor on first call. + """ + # TODO(warp-migration): Cross-manager access (observation → command). Replace with direct + # warp getter once all managers are guaranteed to be warp-native. + fn = generated_commands + if not getattr(fn, "_is_warmed_up", False) or fn._cmd_name != command_name: + cmd = env.command_manager.get_command(command_name) + if isinstance(cmd, wp.array): + fn._cmd_wp = cmd + else: + fn._cmd_wp = wp.from_torch(cmd) + fn._cmd_name = command_name + fn._is_warmed_up = True + wp.copy(out, fn._cmd_wp) diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp/rewards.py b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp/rewards.py new file mode 100644 index 000000000000..2b98f1f9cc09 --- /dev/null +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp/rewards.py @@ -0,0 +1,490 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Common functions that can be used to enable reward functions (experimental). + +All functions in this file follow the Warp-compatible reward signature expected by +`isaaclab_experimental.managers.RewardManager`: + +- ``func(env, out, **params) -> None`` + +where ``out`` is a pre-allocated Warp array of shape ``(num_envs,)`` with ``float32`` dtype. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +import warp as wp +from isaaclab_newton.kernels.state_kernels import ( + body_ang_vel_from_root, + body_lin_vel_from_root, + rotate_vec_to_body_frame, +) + +from isaaclab.assets import Articulation + +from isaaclab_experimental.managers import SceneEntityCfg + +if TYPE_CHECKING: + from isaaclab.envs import ManagerBasedRLEnv + + +""" +General. +""" + + +@wp.kernel +def _is_alive_kernel(terminated: wp.array(dtype=wp.bool), out: wp.array(dtype=wp.float32)): + i = wp.tid() + out[i] = wp.where(terminated[i], 0.0, 1.0) + + +def is_alive(env: ManagerBasedRLEnv, out: wp.array(dtype=wp.float32)) -> None: + """Reward for being alive. Writes into ``out`` (shape: (num_envs,)).""" + wp.launch( + kernel=_is_alive_kernel, + dim=env.num_envs, + inputs=[env.termination_manager.terminated_wp, out], + device=env.device, + ) + + +@wp.kernel +def _is_terminated_kernel(terminated: wp.array(dtype=wp.bool), out: wp.array(dtype=wp.float32)): + i = wp.tid() + out[i] = wp.where(terminated[i], 1.0, 0.0) + + +def is_terminated(env: ManagerBasedRLEnv, out) -> None: + """Penalize terminated episodes. Writes into ``out``.""" + wp.launch( + kernel=_is_terminated_kernel, + dim=env.num_envs, + inputs=[env.termination_manager.terminated_wp, out], + device=env.device, + ) + + +""" +Root penalties. +""" + + +# Inline Tier 1 access: these rewards derive body-frame quantities directly from +# root_link_pose_w (transformf) and root_com_vel_w (spatial_vectorf), avoiding the lazy +# TimestampedWarpBuffer properties which are not CUDA-graph-capturable. +# See GRAPH_CAPTURE_MIGRATION.md in isaaclab_newton for background. +# If ArticulationData Tier 2 lazy update is made graph-safe in the future, these can +# revert to reading the pre-computed .data buffers (simpler, avoids redundant rotations). + + +@wp.kernel +def _lin_vel_z_l2_kernel( + root_pose_w: wp.array(dtype=wp.transformf), + root_vel_w: wp.array(dtype=wp.spatial_vectorf), + out: wp.array(dtype=wp.float32), +): + i = wp.tid() + vz = body_lin_vel_from_root(root_pose_w[i], root_vel_w[i])[2] + out[i] = vz * vz + + +def lin_vel_z_l2(env: ManagerBasedRLEnv, out, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")) -> None: + """Penalize z-axis base linear velocity using L2 squared kernel.""" + asset: Articulation = env.scene[asset_cfg.name] + wp.launch( + kernel=_lin_vel_z_l2_kernel, + dim=env.num_envs, + inputs=[asset.data.root_link_pose_w.warp, asset.data.root_com_vel_w.warp, out], + device=env.device, + ) + + +@wp.kernel +def _ang_vel_xy_l2_kernel( + root_pose_w: wp.array(dtype=wp.transformf), + root_vel_w: wp.array(dtype=wp.spatial_vectorf), + out: wp.array(dtype=wp.float32), +): + i = wp.tid() + v = body_ang_vel_from_root(root_pose_w[i], root_vel_w[i]) + out[i] = v[0] * v[0] + v[1] * v[1] + + +def ang_vel_xy_l2(env: ManagerBasedRLEnv, out, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")) -> None: + """Penalize xy-axis base angular velocity using L2 squared kernel.""" + asset: Articulation = env.scene[asset_cfg.name] + wp.launch( + kernel=_ang_vel_xy_l2_kernel, + dim=env.num_envs, + inputs=[asset.data.root_link_pose_w.warp, asset.data.root_com_vel_w.warp, out], + device=env.device, + ) + + +@wp.kernel +def _flat_orientation_l2_kernel( + root_pose_w: wp.array(dtype=wp.transformf), + gravity_w: wp.array(dtype=wp.vec3f), + out: wp.array(dtype=wp.float32), +): + i = wp.tid() + g = rotate_vec_to_body_frame(gravity_w[0], root_pose_w[i]) + out[i] = g[0] * g[0] + g[1] * g[1] + + +def flat_orientation_l2(env: ManagerBasedRLEnv, out, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")) -> None: + """Penalize non-flat base orientation using L2 squared kernel.""" + asset: Articulation = env.scene[asset_cfg.name] + wp.launch( + kernel=_flat_orientation_l2_kernel, + dim=env.num_envs, + inputs=[asset.data.root_link_pose_w.warp, asset.data.GRAVITY_VEC_W.warp, out], + device=env.device, + ) + + +""" +Joint penalties. +""" + + +# TODO(warp-migration): Revisit whether 2D kernel + wp.atomic_add is faster than 1D with inner loop +# for the following masked reduction kernels. Profile with typical joint counts (12-30). +@wp.kernel +def _sum_sq_masked_kernel( + x: wp.array(dtype=wp.float32, ndim=2), joint_mask: wp.array(dtype=wp.bool), out: wp.array(dtype=wp.float32) +): + i = wp.tid() + s = float(0.0) + for j in range(x.shape[1]): + if joint_mask[j]: + s += x[i, j] * x[i, j] + out[i] = s + + +def joint_torques_l2(env: ManagerBasedRLEnv, out, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")) -> None: + """Penalize joint torques applied on the articulation using L2 squared kernel.""" + asset: Articulation = env.scene[asset_cfg.name] + wp.launch( + kernel=_sum_sq_masked_kernel, + dim=env.num_envs, + inputs=[asset.data.applied_torque.warp, asset_cfg.joint_mask, out], + device=env.device, + ) + + +# TODO(warp-migration): Revisit 2D kernel + wp.atomic_add vs 1D inner loop. +@wp.kernel +def _sum_abs_masked_kernel( + x: wp.array(dtype=wp.float32, ndim=2), joint_mask: wp.array(dtype=wp.bool), out: wp.array(dtype=wp.float32) +): + i = wp.tid() + s = float(0.0) + for j in range(x.shape[1]): + if joint_mask[j]: + s += wp.abs(x[i, j]) + out[i] = s + + +def joint_vel_l1(env: ManagerBasedRLEnv, out, asset_cfg: SceneEntityCfg) -> None: + """Penalize joint velocities on the articulation using an L1-kernel. Writes into ``out``.""" + asset: Articulation = env.scene[asset_cfg.name] + wp.launch( + kernel=_sum_abs_masked_kernel, + dim=env.num_envs, + inputs=[asset.data.joint_vel.warp, asset_cfg.joint_mask, out], + device=env.device, + ) + + +def joint_vel_l2(env: ManagerBasedRLEnv, out, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")) -> None: + """Penalize joint velocities on the articulation using L2 squared kernel.""" + asset: Articulation = env.scene[asset_cfg.name] + wp.launch( + kernel=_sum_sq_masked_kernel, + dim=env.num_envs, + inputs=[asset.data.joint_vel.warp, asset_cfg.joint_mask, out], + device=env.device, + ) + + +def joint_acc_l2(env: ManagerBasedRLEnv, out, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")) -> None: + """Penalize joint accelerations on the articulation using L2 squared kernel.""" + asset: Articulation = env.scene[asset_cfg.name] + wp.launch( + kernel=_sum_sq_masked_kernel, + dim=env.num_envs, + inputs=[asset.data.joint_acc.warp, asset_cfg.joint_mask, out], + device=env.device, + ) + + +# TODO(warp-migration): Revisit 2D kernel + wp.atomic_add vs 1D inner loop. +@wp.kernel +def _sum_abs_diff_masked_kernel( + a: wp.array(dtype=wp.float32, ndim=2), + b: wp.array(dtype=wp.float32, ndim=2), + joint_mask: wp.array(dtype=wp.bool), + out: wp.array(dtype=wp.float32), +): + i = wp.tid() + s = float(0.0) + for j in range(a.shape[1]): + if joint_mask[j]: + s += wp.abs(a[i, j] - b[i, j]) + out[i] = s + + +def joint_deviation_l1(env: ManagerBasedRLEnv, out, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")) -> None: + """Penalize joint positions that deviate from the default one.""" + asset: Articulation = env.scene[asset_cfg.name] + wp.launch( + kernel=_sum_abs_diff_masked_kernel, + dim=env.num_envs, + inputs=[asset.data.joint_pos.warp, asset.data.default_joint_pos.warp, asset_cfg.joint_mask, out], + device=env.device, + ) + + +# TODO(warp-migration): Revisit 2D kernel + wp.atomic_add vs 1D inner loop. +@wp.kernel +def _joint_pos_limits_kernel( + joint_pos: wp.array(dtype=wp.float32, ndim=2), + soft_joint_pos_limits: wp.array(dtype=wp.vec2f, ndim=2), + joint_mask: wp.array(dtype=wp.bool), + out: wp.array(dtype=wp.float32), +): + i = wp.tid() + s = float(0.0) + for j in range(joint_pos.shape[1]): + if joint_mask[j]: + pos = joint_pos[i, j] + lim = soft_joint_pos_limits[i, j] + lower = lim.x + upper = lim.y + # penalty for exceeding lower limit + below = lower - pos + if below > 0.0: + s += below + # penalty for exceeding upper limit + above = pos - upper + if above > 0.0: + s += above + out[i] = s + + +def joint_pos_limits(env: ManagerBasedRLEnv, out, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")) -> None: + """Penalize joint positions if they cross the soft limits.""" + asset: Articulation = env.scene[asset_cfg.name] + wp.launch( + kernel=_joint_pos_limits_kernel, + dim=env.num_envs, + inputs=[asset.data.joint_pos.warp, asset.data.soft_joint_pos_limits.warp, asset_cfg.joint_mask, out], + device=env.device, + ) + + +""" +Action penalties. +""" + + +# TODO(warp-migration): Revisit 2D kernel + wp.atomic_add vs 1D inner loop. +@wp.kernel +def _sum_sq_diff_2d_kernel( + a: wp.array(dtype=wp.float32, ndim=2), + b: wp.array(dtype=wp.float32, ndim=2), + out: wp.array(dtype=wp.float32), +): + i = wp.tid() + s = float(0.0) + for j in range(a.shape[1]): + d = a[i, j] - b[i, j] + s += d * d + out[i] = s + + +def action_rate_l2(env: ManagerBasedRLEnv, out) -> None: + """Penalize the rate of change of the actions using L2 squared kernel.""" + wp.launch( + kernel=_sum_sq_diff_2d_kernel, + dim=env.num_envs, + inputs=[env.action_manager.action, env.action_manager.prev_action, out], + device=env.device, + ) + + +# TODO(warp-migration): Revisit 2D kernel + wp.atomic_add vs 1D inner loop. +@wp.kernel +def _sum_sq_2d_kernel(x: wp.array(dtype=wp.float32, ndim=2), out: wp.array(dtype=wp.float32)): + i = wp.tid() + s = float(0.0) + for j in range(x.shape[1]): + s += x[i, j] * x[i, j] + out[i] = s + + +def action_l2(env: ManagerBasedRLEnv, out) -> None: + """Penalize the actions using L2 squared kernel.""" + wp.launch( + kernel=_sum_sq_2d_kernel, + dim=env.num_envs, + inputs=[env.action_manager.action, out], + device=env.device, + ) + + +""" +Contact sensor. +""" + + +@wp.kernel +def _undesired_contacts_kernel( + forces: wp.array(dtype=wp.vec3f, ndim=3), + body_ids: wp.array(dtype=wp.int32), + threshold: float, + out: wp.array(dtype=wp.float32), +): + """Count bodies where max-over-history contact force norm exceeds threshold.""" + i = wp.tid() + count = float(0.0) + for k in range(body_ids.shape[0]): + b = body_ids[k] + max_force = float(0.0) + for h in range(forces.shape[1]): + f = forces[i, h, b] + norm = wp.sqrt(f[0] * f[0] + f[1] * f[1] + f[2] * f[2]) + if norm > max_force: + max_force = norm + if max_force > threshold: + count += 1.0 + out[i] = count + + +def undesired_contacts(env: ManagerBasedRLEnv, out, threshold: float, sensor_cfg: SceneEntityCfg) -> None: + """Penalize undesired contacts as the number of violations above a threshold. Writes into ``out``. + + Warp-first override of :func:`isaaclab.envs.mdp.rewards.undesired_contacts`. + """ + contact_sensor = env.scene.sensors[sensor_cfg.name] + wp.launch( + kernel=_undesired_contacts_kernel, + dim=env.num_envs, + inputs=[contact_sensor.data.net_forces_w_history.warp, sensor_cfg.body_ids_wp, threshold, out], + device=env.device, + ) + + +""" +Velocity-tracking rewards. +""" + + +@wp.kernel +def _track_lin_vel_xy_exp_kernel( + root_pose_w: wp.array(dtype=wp.transformf), + root_vel_w: wp.array(dtype=wp.spatial_vectorf), + command: wp.array(dtype=wp.float32, ndim=2), + std_sq_inv: float, + out: wp.array(dtype=wp.float32), +): + i = wp.tid() + v = body_lin_vel_from_root(root_pose_w[i], root_vel_w[i]) + dx = command[i, 0] - v[0] + dy = command[i, 1] - v[1] + error = dx * dx + dy * dy + out[i] = wp.exp(-error * std_sq_inv) + + +def track_lin_vel_xy_exp( + env: ManagerBasedRLEnv, + out, + std: float, + command_name: str, + asset_cfg: SceneEntityCfg = SceneEntityCfg("robot"), +) -> None: + """Reward tracking of linear velocity commands (xy axes) using exponential kernel. Writes into ``out``. + + Warp-first override of :func:`isaaclab.envs.mdp.rewards.track_lin_vel_xy_exp`. + """ + asset: Articulation = env.scene[asset_cfg.name] + # cache the warp view of the command tensor on first call (zero-copy) + # TODO(warp-migration): Cross-manager access (reward → command). Replace with direct + # warp getter once all managers are guaranteed to be warp-native. + if not getattr(track_lin_vel_xy_exp, "_is_warmed_up", False) or track_lin_vel_xy_exp._cmd_name != command_name: + cmd = env.command_manager.get_command(command_name) + if isinstance(cmd, wp.array): + track_lin_vel_xy_exp._cmd_wp = cmd + else: + track_lin_vel_xy_exp._cmd_wp = wp.from_torch(cmd) + track_lin_vel_xy_exp._cmd_name = command_name + track_lin_vel_xy_exp._is_warmed_up = True + wp.launch( + kernel=_track_lin_vel_xy_exp_kernel, + dim=env.num_envs, + inputs=[ + asset.data.root_link_pose_w.warp, + asset.data.root_com_vel_w.warp, + track_lin_vel_xy_exp._cmd_wp, + 1.0 / (std * std), + out, + ], + device=env.device, + ) + + +@wp.kernel +def _track_ang_vel_z_exp_kernel( + root_pose_w: wp.array(dtype=wp.transformf), + root_vel_w: wp.array(dtype=wp.spatial_vectorf), + command: wp.array(dtype=wp.float32, ndim=2), + cmd_col: int, + std_sq_inv: float, + out: wp.array(dtype=wp.float32), +): + i = wp.tid() + dz = command[i, cmd_col] - body_ang_vel_from_root(root_pose_w[i], root_vel_w[i])[2] + out[i] = wp.exp(-dz * dz * std_sq_inv) + + +def track_ang_vel_z_exp( + env: ManagerBasedRLEnv, + out, + std: float, + command_name: str, + asset_cfg: SceneEntityCfg = SceneEntityCfg("robot"), +) -> None: + """Reward tracking of angular velocity commands (yaw) using exponential kernel. Writes into ``out``. + + Warp-first override of :func:`isaaclab.envs.mdp.rewards.track_ang_vel_z_exp`. + """ + asset: Articulation = env.scene[asset_cfg.name] + # TODO(warp-migration): Cross-manager access (reward → command). Replace with direct + # warp getter once all managers are guaranteed to be warp-native. + if not getattr(track_ang_vel_z_exp, "_is_warmed_up", False) or track_ang_vel_z_exp._cmd_name != command_name: + cmd = env.command_manager.get_command(command_name) + if isinstance(cmd, wp.array): + track_ang_vel_z_exp._cmd_wp = cmd + else: + track_ang_vel_z_exp._cmd_wp = wp.from_torch(cmd) + track_ang_vel_z_exp._cmd_name = command_name + track_ang_vel_z_exp._is_warmed_up = True + wp.launch( + kernel=_track_ang_vel_z_exp_kernel, + dim=env.num_envs, + inputs=[ + asset.data.root_link_pose_w.warp, + asset.data.root_com_vel_w.warp, + track_ang_vel_z_exp._cmd_wp, + 2, + 1.0 / (std * std), + out, + ], + device=env.device, + ) diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp/terminations.py b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp/terminations.py new file mode 100644 index 000000000000..7721469e96a4 --- /dev/null +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp/terminations.py @@ -0,0 +1,161 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Common functions that can be used to activate terminations (experimental). + +All functions in this file follow the Warp-compatible termination signature expected by +`isaaclab_experimental.managers.TerminationManager`: + +- ``func(env, out, **params) -> None`` + +where ``out`` is a pre-allocated Warp array of shape ``(num_envs,)`` with boolean dtype. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +import warp as wp + +from isaaclab.assets import Articulation + +from isaaclab_experimental.managers import SceneEntityCfg + +if TYPE_CHECKING: + from isaaclab.envs import ManagerBasedRLEnv + + +""" +MDP terminations. +""" + + +@wp.kernel +def _time_out_kernel( + episode_length: wp.array(dtype=wp.int64), max_episode_length: wp.int64, out: wp.array(dtype=wp.bool) +): + i = wp.tid() + out[i] = episode_length[i] >= max_episode_length + + +def time_out(env: ManagerBasedRLEnv, out) -> None: + """Terminate the episode when episode length exceeds the maximum episode length.""" + wp.launch( + kernel=_time_out_kernel, + dim=env.num_envs, + inputs=[env._episode_length_buf_wp, env.max_episode_length, out], + device=env.device, + ) + + +""" +Root terminations. +""" + + +@wp.kernel +def _root_height_below_min_kernel( + root_pos_w: wp.array(dtype=wp.vec3f), + minimum_height: float, + out: wp.array(dtype=wp.bool), +): + i = wp.tid() + out[i] = root_pos_w[i][2] < minimum_height + + +def root_height_below_minimum( + env: ManagerBasedRLEnv, out, minimum_height: float, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot") +) -> None: + """Terminate when the asset's root height is below the minimum height.""" + asset: Articulation = env.scene[asset_cfg.name] + wp.launch( + kernel=_root_height_below_min_kernel, + dim=env.num_envs, + inputs=[asset.data.root_pos_w.warp, minimum_height, out], + device=env.device, + ) + + +""" +Joint terminations. +""" + + +@wp.kernel +def _joint_pos_out_of_manual_limit_kernel( + joint_pos: wp.array(dtype=wp.float32, ndim=2), + joint_mask: wp.array(dtype=wp.bool), + lower: float, + upper: float, + out: wp.array(dtype=wp.bool), +): + """2D kernel (num_envs, num_joints). ``out`` is pre-zeroed; only writes True.""" + i, j = wp.tid() + if joint_mask[j]: + v = joint_pos[i, j] + if v < lower or v > upper: + out[i] = True + + +def joint_pos_out_of_manual_limit( + env: ManagerBasedRLEnv, out, bounds: tuple[float, float], asset_cfg: SceneEntityCfg +) -> None: + """Terminate when joint positions are outside configured bounds. Writes into ``out``.""" + asset: Articulation = env.scene[asset_cfg.name] + if asset_cfg.joint_mask is None: + raise ValueError( + f"joint_pos_out_of_manual_limit requires SceneEntityCfg with resolved joint_mask, " + f"but got None for asset '{asset_cfg.name}'." + ) + if asset.data.joint_pos.warp.shape[1] != asset_cfg.joint_mask.shape[0]: + raise ValueError( + f"joint_mask length ({asset_cfg.joint_mask.shape[0]}) does not match " + f"joint_pos dim ({asset.data.joint_pos.warp.shape[1]}) for asset '{asset_cfg.name}'." + ) + wp.launch( + kernel=_joint_pos_out_of_manual_limit_kernel, + dim=(env.num_envs, asset.data.joint_pos.warp.shape[1]), + inputs=[asset.data.joint_pos.warp, asset_cfg.joint_mask, bounds[0], bounds[1], out], + device=env.device, + ) + + +""" +Contact sensor. +""" + + +@wp.kernel +def _illegal_contact_kernel( + forces: wp.array(dtype=wp.vec3f, ndim=3), + body_ids: wp.array(dtype=wp.int32), + threshold: float, + out: wp.array(dtype=wp.bool), +): + """Terminate when any selected body's max-over-history contact force norm exceeds threshold.""" + i = wp.tid() + violated = bool(False) + for k in range(body_ids.shape[0]): + b = body_ids[k] + for h in range(forces.shape[1]): + f = forces[i, h, b] + norm = wp.sqrt(f[0] * f[0] + f[1] * f[1] + f[2] * f[2]) + if norm > threshold: + violated = True + out[i] = violated + + +def illegal_contact(env: ManagerBasedRLEnv, out, threshold: float, sensor_cfg: SceneEntityCfg) -> None: + """Terminate when the contact force on the sensor exceeds the force threshold. Writes into ``out``. + + Warp-first override of :func:`isaaclab.envs.mdp.terminations.illegal_contact`. + """ + contact_sensor = env.scene.sensors[sensor_cfg.name] + wp.launch( + kernel=_illegal_contact_kernel, + dim=env.num_envs, + inputs=[contact_sensor.data.net_forces_w_history.warp, sensor_cfg.body_ids_wp, threshold, out], + device=env.device, + ) diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/utils/io_descriptors.py b/source/isaaclab_experimental/isaaclab_experimental/envs/utils/io_descriptors.py new file mode 100644 index 000000000000..2b72dae02aa7 --- /dev/null +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/utils/io_descriptors.py @@ -0,0 +1,323 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Warp-first IO descriptor decorator and inspection hooks (experimental). + +This module mirrors the stable :mod:`isaaclab.envs.utils.io_descriptors` but is +designed for Warp-first observation terms whose signature is:: + + func(env, out, **params) -> None + +Key difference from the stable decorator: + During inspection (``inspect=True``), the underlying function is **not called**. + Hooks derive metadata from ``env`` / scene / config objects instead of from a + returned output tensor. ``output`` is passed as ``None`` so that hooks share the + same ``(output, descriptor, **kwargs)`` signature as the stable hooks. + +The :class:`GenericObservationIODescriptor` dataclass is reused from the stable +package so that the resulting descriptor dicts are fully compatible with the +existing export / YAML pipeline. +""" + +from __future__ import annotations + +from collections.abc import Callable +from typing import TYPE_CHECKING, Any, Concatenate, ParamSpec, TypeVar + +import warp as wp + +# Reuse the descriptor dataclass from the stable package. +from isaaclab.envs.utils.io_descriptors import GenericObservationIODescriptor + +if TYPE_CHECKING: + from isaaclab.assets.articulation import Articulation + from isaaclab.envs import ManagerBasedEnv + +import dataclasses +import functools +import inspect + +# These are defined to help with type hinting +P = ParamSpec("P") +R = TypeVar("R") + + +# --------------------------------------------------------------------------- +# Decorator +# --------------------------------------------------------------------------- + + +# Automatically builds a descriptor from the kwargs +def _make_descriptor(**kwargs: Any) -> GenericObservationIODescriptor: + """Split *kwargs* into (known dataclass fields) and (extras).""" + field_names = {f.name for f in dataclasses.fields(GenericObservationIODescriptor)} + known = {k: v for k, v in kwargs.items() if k in field_names} + extras = {k: v for k, v in kwargs.items() if k not in field_names} + + desc = GenericObservationIODescriptor(**known) + # User defined extras are stored in the descriptor under the `extras` field + desc.extras = extras + # ``out_dim`` is kept as a top-level attribute (not in extras) so the + # observation manager can read it without inspecting extras. + desc.out_dim = extras.pop("out_dim", None) + return desc + + +# Decorator factory for Warp-first IO descriptors. +def generic_io_descriptor_warp( + _func: Callable[Concatenate[ManagerBasedEnv, P], R] | None = None, + *, + on_inspect: Callable[..., Any] | list[Callable[..., Any]] | None = None, + **descriptor_kwargs: Any, +) -> Callable[[Callable[Concatenate[ManagerBasedEnv, P], R]], Callable[Concatenate[ManagerBasedEnv, P], R]]: + """IO descriptor decorator for Warp-first observation terms. + + Works like the stable :func:`generic_io_descriptor` but adapted to the + ``func(env, out, **params) -> None`` signature: + + * On **normal calls** the decorator passes through to the wrapped function. + * On **inspection** (``inspect=True`` keyword argument) the wrapped function + is *not* called. Instead, the registered hooks are invoked with the same + ``(output, descriptor, **kwargs)`` contract as the stable hooks, except + ``output`` is always ``None``. + + This decorator can be used in the same ways as the stable decorator: + + 1. With keyword arguments:: + + @generic_io_descriptor_warp(observation_type="JointState", units="rad") + def my_func(env, out, asset_cfg=SceneEntityCfg("robot")) -> None: ... + + 2. With a pre-built descriptor:: + + @generic_io_descriptor_warp(GenericObservationIODescriptor(description="..")) + def my_func(env, out, asset_cfg=SceneEntityCfg("robot")) -> None: ... + + 3. With inspection hooks:: + + @generic_io_descriptor_warp( + observation_type="JointState", + on_inspect=[record_joint_names, record_joint_shape, record_joint_pos_offsets], + units="rad", + ) + def joint_pos_rel(env, out, asset_cfg=SceneEntityCfg("robot")) -> None: ... + + Args: + _func: The function to decorate (or a pre-built descriptor). + on_inspect: Hook(s) called during inspection. + **descriptor_kwargs: Keyword arguments to pass to the descriptor. + + Returns: + A decorator that can be used to decorate a function. + """ + # If the decorator is used with a descriptor, use it as the descriptor. + if _func is not None and isinstance(_func, GenericObservationIODescriptor): + descriptor = _func + _func = None + else: + descriptor = _make_descriptor(**descriptor_kwargs) + + # Ensures the hook is a list + if callable(on_inspect): + inspect_hooks: list[Callable[..., Any]] = [on_inspect] + else: + inspect_hooks: list[Callable[..., Any]] = list(on_inspect or []) # handles None + + def _apply(func: Callable[Concatenate[ManagerBasedEnv, P], R]) -> Callable[Concatenate[ManagerBasedEnv, P], R]: + # Capture the signature of the function + sig = inspect.signature(func) + + @functools.wraps(func) + def wrapper(env: ManagerBasedEnv, *args: P.args, **kwargs: P.kwargs) -> R: + inspect_flag: bool = kwargs.pop("inspect", False) + if inspect_flag: + # Warp-first: do NOT call the function (it requires a pre-allocated + # ``out`` buffer that does not exist at inspection time). + # Use bind_partial (tolerates missing ``out``) and apply_defaults so + # that hooks see resolved default values (e.g. ``asset_cfg``). + bound = sig.bind_partial(env, **kwargs) + bound.apply_defaults() + call_kwargs = { + "output": None, + "descriptor": descriptor, + **bound.arguments, + } + for hook in inspect_hooks: + hook(**call_kwargs) + return # noqa: R502 + return func(env, *args, **kwargs) + + # --- Descriptor bookkeeping --- + descriptor.name = func.__name__ + descriptor.full_path = f"{func.__module__}.{func.__name__}" + # Warp-first terms always operate in float32. + descriptor.dtype = str(descriptor.dtype) if descriptor.dtype is not None else "float32" + # Check if description is set in the descriptor + if descriptor.description is None and func.__doc__: + descriptor.description = " ".join(func.__doc__.split()) + + # Adds the descriptor to the wrapped function as an attribute + wrapper._descriptor = descriptor + wrapper._has_descriptor = True + # Alters the signature of the wrapped function to make it match the original function. + # This allows the wrapped functions to pass the checks in the managers. + wrapper.__signature__ = sig + return wrapper + + # If the decorator is used without parentheses, _func will be the function itself. + if callable(_func): + return _apply(_func) + return _apply + + +# --------------------------------------------------------------------------- +# Inspection hooks +# +# All hooks follow the stable convention: (output, descriptor, **kwargs). +# For Warp-first terms ``output`` is always ``None``; hooks that need shape +# or dtype information must derive it from the scene / config objects in +# **kwargs rather than from the output tensor. +# --------------------------------------------------------------------------- + + +def record_shape(output: wp.array | None, descriptor: GenericObservationIODescriptor, **kwargs) -> None: + """Record the shape of the output buffer. + + When ``output`` is not ``None`` (eager path), shape is read directly. + When ``output`` is ``None`` (Warp-first inspection), shape is derived from: + - ``descriptor.extras["axes"]`` for RootState observations, or + - ``asset_cfg.joint_ids`` for JointState observations. + + BodyState shape cannot be derived without calling the function (the per-body + feature size varies). In that case shape is left unset. + + Args: + output: The pre-allocated output buffer, or ``None`` during inspection. + descriptor: The descriptor to record the shape to. + **kwargs: Additional keyword arguments. + """ + if output is not None: + descriptor.shape = (output.shape[-1],) + return + # --- Warp-first fallback: derive shape without output --- + # 1) From axes metadata (RootState) + axes = descriptor.extras.get("axes") if descriptor.extras else None + if axes: + descriptor.shape = (len(axes),) + return + # 2) From asset_cfg for JointState + if descriptor.observation_type == "JointState": + asset_cfg = kwargs.get("asset_cfg") + if asset_cfg is not None: + asset: Articulation = kwargs["env"].scene[asset_cfg.name] + joint_ids = asset_cfg.joint_ids + if joint_ids == slice(None): + descriptor.shape = (len(asset.joint_names),) + else: + descriptor.shape = (len(joint_ids),) + + +def record_dtype(output: wp.array | None, descriptor: GenericObservationIODescriptor, **kwargs) -> None: + """Record the dtype of the output buffer. + + No-op when ``output`` is ``None`` (the typical case during Warp-first + inspection — dtype is already set to ``"float32"`` by the decorator). + + Args: + output: The pre-allocated output buffer, or ``None`` during inspection. + descriptor: The descriptor to record the dtype to. + **kwargs: Additional keyword arguments. + """ + if output is None: + return + descriptor.dtype = str(output.dtype) + + +def record_joint_shape(output: wp.array | None, descriptor: GenericObservationIODescriptor, **kwargs) -> None: + """Derive the observation shape from the resolved ``joint_ids`` count. + + This is the Warp-first alternative to :func:`record_shape` for joint-based + observations. It ignores ``output`` and reads the shape from the asset + configuration instead. + + Args: + output: Ignored — kept for hook signature compatibility. + descriptor: The descriptor to update. + **kwargs: Must contain ``env`` and ``asset_cfg``. + """ + asset: Articulation = kwargs["env"].scene[kwargs["asset_cfg"].name] + joint_ids = kwargs["asset_cfg"].joint_ids + if joint_ids == slice(None, None, None): + descriptor.shape = (len(asset.joint_names),) + else: + descriptor.shape = (len(joint_ids),) + + +def record_joint_names(output: wp.array | None, descriptor: GenericObservationIODescriptor, **kwargs) -> None: + """Record the joint names selected by ``asset_cfg.joint_ids``. + + Expects the ``asset_cfg`` keyword argument to be set. + + Args: + output: Ignored — kept for hook signature compatibility. + descriptor: The descriptor to record the joint names to. + **kwargs: Additional keyword arguments. + """ + asset: Articulation = kwargs["env"].scene[kwargs["asset_cfg"].name] + joint_ids = kwargs["asset_cfg"].joint_ids + if joint_ids == slice(None, None, None): + joint_ids = list(range(len(asset.joint_names))) + descriptor.joint_names = [asset.joint_names[i] for i in joint_ids] + + +def record_body_names(output: wp.array | None, descriptor: GenericObservationIODescriptor, **kwargs) -> None: + """Record the body names selected by ``asset_cfg.body_ids``. + + Expects the ``asset_cfg`` keyword argument to be set. + + Args: + output: Ignored — kept for hook signature compatibility. + descriptor: The descriptor to record the body names to. + **kwargs: Additional keyword arguments. + """ + asset: Articulation = kwargs["env"].scene[kwargs["asset_cfg"].name] + body_ids = kwargs["asset_cfg"].body_ids + if body_ids == slice(None, None, None): + body_ids = list(range(len(asset.body_names))) + descriptor.body_names = [asset.body_names[i] for i in body_ids] + + +def record_joint_pos_offsets(output: wp.array | None, descriptor: GenericObservationIODescriptor, **kwargs): + """Record the default joint-position offsets (first env instance). + + Expects the ``asset_cfg`` keyword argument to be set. + + Args: + output: Ignored — kept for hook signature compatibility. + descriptor: The descriptor to record the joint position offsets to. + **kwargs: Additional keyword arguments. + """ + asset: Articulation = kwargs["env"].scene[kwargs["asset_cfg"].name] + ids = kwargs["asset_cfg"].joint_ids + # Get the offsets of the joints for the first robot in the scene. + # This assumes that all robots have the same joint offsets. + descriptor.joint_pos_offsets = asset.data.default_joint_pos.torch.clone()[:, ids][0] + + +def record_joint_vel_offsets(output: wp.array | None, descriptor: GenericObservationIODescriptor, **kwargs): + """Record the default joint-velocity offsets (first env instance). + + Expects the ``asset_cfg`` keyword argument to be set. + + Args: + output: Ignored — kept for hook signature compatibility. + descriptor: The descriptor to record the joint velocity offsets to. + **kwargs: Additional keyword arguments. + """ + asset: Articulation = kwargs["env"].scene[kwargs["asset_cfg"].name] + ids = kwargs["asset_cfg"].joint_ids + # Get the offsets of the joints for the first robot in the scene. + # This assumes that all robots have the same joint offsets. + descriptor.joint_vel_offsets = asset.data.default_joint_vel.torch.clone()[:, ids][0] diff --git a/source/isaaclab_experimental/isaaclab_experimental/managers/__init__.py b/source/isaaclab_experimental/isaaclab_experimental/managers/__init__.py new file mode 100644 index 000000000000..b4521b98434a --- /dev/null +++ b/source/isaaclab_experimental/isaaclab_experimental/managers/__init__.py @@ -0,0 +1,24 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Experimental manager implementations. + +This package is intended for experimental forks of manager implementations while +keeping stable task configs and the stable `isaaclab.managers` package intact. +""" + +from isaaclab.managers import * # noqa: F401,F403 + +from .action_manager import ActionManager # noqa: F401 +from .command_manager import CommandManager # noqa: F401 +from .event_manager import EventManager # noqa: F401 + +# Override the stable implementation with the experimental fork. +from .manager_base import ManagerTermBase # noqa: F401 +from .manager_term_cfg import ObservationTermCfg, RewardTermCfg, TerminationTermCfg # noqa: F401 +from .observation_manager import ObservationManager # noqa: F401 +from .reward_manager import RewardManager # noqa: F401 +from .scene_entity_cfg import SceneEntityCfg # noqa: F401 +from .termination_manager import TerminationManager # noqa: F401 diff --git a/source/isaaclab_experimental/isaaclab_experimental/managers/action_manager.py b/source/isaaclab_experimental/isaaclab_experimental/managers/action_manager.py new file mode 100644 index 000000000000..672af82bc8ab --- /dev/null +++ b/source/isaaclab_experimental/isaaclab_experimental/managers/action_manager.py @@ -0,0 +1,492 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Action manager for processing actions sent to the environment.""" + +from __future__ import annotations + +import inspect +import re +import weakref +from abc import abstractmethod +from collections.abc import Sequence +from typing import TYPE_CHECKING, Any + +import torch +import warp as wp +from prettytable import PrettyTable + +from isaaclab.assets import AssetBase +from isaaclab.envs.utils.io_descriptors import GenericActionIODescriptor + +from .manager_base import ManagerBase, ManagerTermBase +from .manager_term_cfg import ActionTermCfg + +if TYPE_CHECKING: + from isaaclab.envs import ManagerBasedEnv + +# Shared kernel – imported from utils to avoid duplication. +from isaaclab_experimental.utils.warp.utils import zero_masked_2d as _zero_masked_2d + + +class ActionTerm(ManagerTermBase): + """Base class for action terms. + + The action term is responsible for processing the raw actions sent to the environment + and applying them to the asset managed by the term. The action term is comprised of two + operations: + + * Processing of actions: This operation is performed once per **environment step** and + is responsible for pre-processing the raw actions sent to the environment. + * Applying actions: This operation is performed once per **simulation step** and is + responsible for applying the processed actions to the asset managed by the term. + """ + + def __init__(self, cfg: ActionTermCfg, env: ManagerBasedEnv): + """Initialize the action term. + + Args: + cfg: The configuration object. + env: The environment instance. + """ + # call the base class constructor + super().__init__(cfg, env) + # parse config to obtain asset to which the term is applied + self._asset: AssetBase = self._env.scene[self.cfg.asset_name] + self._IO_descriptor = GenericActionIODescriptor() + self._export_IO_descriptor = True + + # add handle for debug visualization (this is set to a valid handle inside set_debug_vis) + self._debug_vis_handle = None + # set initial state of debug visualization + self.set_debug_vis(self.cfg.debug_vis) + + def __del__(self): + """Unsubscribe from the callbacks.""" + if self._debug_vis_handle: + self._debug_vis_handle.unsubscribe() + self._debug_vis_handle = None + + """ + Properties. + """ + + @property + @abstractmethod + def action_dim(self) -> int: + """Dimension of the action term.""" + raise NotImplementedError + + @property + @abstractmethod + def raw_actions(self) -> wp.array: + """The input/raw actions sent to the term.""" + raise NotImplementedError + + @property + @abstractmethod + def processed_actions(self) -> wp.array: + """The actions computed by the term after applying any processing.""" + raise NotImplementedError + + @property + def has_debug_vis_implementation(self) -> bool: + """Whether the action term has a debug visualization implemented.""" + # check if function raises NotImplementedError + source_code = inspect.getsource(self._set_debug_vis_impl) + return "NotImplementedError" not in source_code + + @property + def IO_descriptor(self) -> GenericActionIODescriptor: + """The IO descriptor for the action term.""" + self._IO_descriptor.name = re.sub(r"([a-z])([A-Z])", r"\1_\2", self.__class__.__name__).lower() + self._IO_descriptor.full_path = f"{self.__class__.__module__}.{self.__class__.__name__}" + self._IO_descriptor.description = " ".join((self.__class__.__doc__ or "").split()) + self._IO_descriptor.export = self.export_IO_descriptor + return self._IO_descriptor + + @property + def export_IO_descriptor(self) -> bool: + """Whether to export the IO descriptor for the action term.""" + return self._export_IO_descriptor + + """ + Operations. + """ + + def set_debug_vis(self, debug_vis: bool) -> bool: + """Sets whether to visualize the action term data. + Args: + debug_vis: Whether to visualize the action term data. + Returns: + Whether the debug visualization was successfully set. False if the action term does + not support debug visualization. + """ + # check if debug visualization is supported + if not self.has_debug_vis_implementation: + return False + + import omni.kit.app + + # toggle debug visualization objects + self._set_debug_vis_impl(debug_vis) + # toggle debug visualization handles + if debug_vis: + # create a subscriber for the post update event if it doesn't exist + if self._debug_vis_handle is None: + app_interface = omni.kit.app.get_app_interface() + self._debug_vis_handle = app_interface.get_post_update_event_stream().create_subscription_to_pop( + lambda event, obj=weakref.proxy(self): obj._debug_vis_callback(event) + ) + else: + # remove the subscriber if it exists + if self._debug_vis_handle is not None: + self._debug_vis_handle.unsubscribe() + self._debug_vis_handle = None + # return success + return True + + @abstractmethod + def process_actions(self, actions: wp.array, action_offset: int = 0): + """Processes the actions sent to the environment. + + Note: + This function is called once per environment step by the manager. + + Args: + actions: The full action buffer of shape (num_envs, total_action_dim). + action_offset: Column offset into the action buffer for this term. + """ + raise NotImplementedError + + @abstractmethod + def apply_actions(self): + """Applies the actions to the asset managed by the term. + + Note: + This is called at every simulation step by the manager. + """ + raise NotImplementedError + + def _set_debug_vis_impl(self, debug_vis: bool): + """Set debug visualization into visualization objects. + This function is responsible for creating the visualization objects if they don't exist + and input ``debug_vis`` is True. If the visualization objects exist, the function should + set their visibility into the stage. + """ + raise NotImplementedError(f"Debug visualization is not implemented for {self.__class__.__name__}.") + + def _debug_vis_callback(self, event): + """Callback for debug visualization. + This function calls the visualization objects and sets the data to visualize into them. + """ + raise NotImplementedError(f"Debug visualization is not implemented for {self.__class__.__name__}.") + + +class ActionManager(ManagerBase): + """Manager for processing and applying actions for a given world. + + The action manager handles the interpretation and application of user-defined + actions on a given world. It is comprised of different action terms that decide + the dimension of the expected actions. + + The action manager performs operations at two stages: + + * processing of actions: It splits the input actions to each term and performs any + pre-processing needed. This should be called once at every environment step. + * apply actions: This operation typically sets the processed actions into the assets in the + scene (such as robots). It should be called before every simulation step. + """ + + def __init__(self, cfg: object, env: ManagerBasedEnv): + """Initialize the action manager. + + Args: + cfg: The configuration object or dictionary (``dict[str, ActionTermCfg]``). + env: The environment instance. + + Raises: + ValueError: If the configuration is None. + """ + # check if config is None + if cfg is None: + raise ValueError("Action manager configuration is None. Please provide a valid configuration.") + + # call the base class constructor (this prepares the terms) + super().__init__(cfg, env) + # create buffers to store actions (Warp) + self._action = wp.zeros((self.num_envs, self.total_action_dim), dtype=wp.float32, device=self.device) + self._prev_action = wp.zeros((self.num_envs, self.total_action_dim), dtype=wp.float32, device=self.device) + + # torch views + self._action_torch = wp.to_torch(self._action) + self._prev_action_torch = wp.to_torch(self._prev_action) + + # check if any term has debug visualization implemented + self.cfg.debug_vis = False + for term in self._terms.values(): + self.cfg.debug_vis |= term.cfg.debug_vis + + def __str__(self) -> str: + """Returns: A string representation for action manager.""" + msg = f" contains {len(self._term_names)} active terms.\n" + + # create table for term information + table = PrettyTable() + table.title = f"Active Action Terms (shape: {self.total_action_dim})" + table.field_names = ["Index", "Name", "Dimension"] + # set alignment of table columns + table.align["Name"] = "l" + table.align["Dimension"] = "r" + # add info on each term + for index, (name, term) in enumerate(self._terms.items()): + table.add_row([index, name, term.action_dim]) + # convert table to string + msg += table.get_string() + msg += "\n" + + return msg + + """ + Properties. + """ + + @property + def total_action_dim(self) -> int: + """Total dimension of actions.""" + return sum(self.action_term_dim) + + @property + def active_terms(self) -> list[str]: + """Name of active action terms.""" + return self._term_names + + @property + def action_term_dim(self) -> list[int]: + """Shape of each action term.""" + return [term.action_dim for term in self._terms.values()] + + @property + def action(self) -> wp.array: + """The actions sent to the environment. Shape is (num_envs, total_action_dim).""" + return self._action + + @property + def prev_action(self) -> wp.array: + """The previous actions sent to the environment. Shape is (num_envs, total_action_dim).""" + return self._prev_action + + @property + def has_debug_vis_implementation(self) -> bool: + """Whether the command terms have debug visualization implemented.""" + # check if function raises NotImplementedError + has_debug_vis = False + for term in self._terms.values(): + has_debug_vis |= term.has_debug_vis_implementation + return has_debug_vis + + @property + def get_IO_descriptors(self) -> list[dict[str, Any]]: + """Get the IO descriptors for the action manager. + + Returns: + A dictionary with keys as the term names and values as the IO descriptors. + """ + + data = [] + + for term_name, term in self._terms.items(): + try: + data.append(term.IO_descriptor.__dict__.copy()) + except Exception as e: + print(f"Error getting IO descriptor for term '{term_name}': {e}") + + formatted_data = [] + for item in data: + name = item.pop("name") + formatted_item = {"name": name, "extras": item.pop("extras")} + if not item.pop("export"): + continue + for k, v in item.items(): + # Check if v is a tuple and convert to list + if isinstance(v, tuple): + v = list(v) + if k in ["description", "units"]: + formatted_item["extras"][k] = v + else: + formatted_item[k] = v + formatted_data.append(formatted_item) + + return formatted_data + + """ + Operations. + """ + + def get_active_iterable_terms(self, env_idx: int) -> Sequence[tuple[str, Sequence[float]]]: + """Returns the active terms as iterable sequence of tuples. + + The first element of the tuple is the name of the term and the second element is the raw value(s) of the term. + + Args: + env_idx: The specific environment to pull the active terms from. + + Returns: + The active terms. + """ + terms = [] + idx = 0 + # Copy to host for debug/inspection (not on hot path). + for name, term in self._terms.items(): + term_actions = self._action_torch[env_idx, idx : idx + term.action_dim] + terms.append((name, term_actions.tolist())) + idx += term.action_dim + return terms + + def set_debug_vis(self, debug_vis: bool): + """Sets whether to visualize the action data. + Args: + debug_vis: Whether to visualize the action data. + Returns: + Whether the debug visualization was successfully set. False if the action + does not support debug visualization. + """ + for term in self._terms.values(): + term.set_debug_vis(debug_vis) + + def reset( + self, + env_ids: Sequence[int] | torch.Tensor | None = None, + *, + env_mask: wp.array | None = None, + ) -> dict[str, Any]: + """Resets the action history. + + Args: + env_ids: The specific environment indices to reset. + If None, all environments are considered. + env_mask: Boolean Warp mask of shape (num_envs,) indicating which envs to reset. + If provided, takes precedence over ``env_ids``. + + Returns: + An empty dictionary. + """ + # Mask-first path: captured callers must provide env_mask. + if env_mask is None or not isinstance(env_mask, wp.array): + if wp.get_device().is_capturing: + raise RuntimeError( + "ActionManager.reset requires env_mask(wp.array[bool]) during capture. " + "Do not pass env_ids on captured paths." + ) + env_mask = self._env.resolve_env_mask(env_ids=env_ids, env_mask=env_mask) + + # reset the action history + if env_mask is None: + self._prev_action.fill_(0.0) + self._action.fill_(0.0) + else: + wp.launch( + kernel=_zero_masked_2d, + dim=(self.num_envs, self.total_action_dim), + inputs=[env_mask, self._prev_action], + device=self.device, + ) + wp.launch( + kernel=_zero_masked_2d, + dim=(self.num_envs, self.total_action_dim), + inputs=[env_mask, self._action], + device=self.device, + ) + + # reset all action terms + for term in self._terms.values(): + term.reset(env_mask=env_mask) + # nothing to log here + return {} + + def process_action(self, action: wp.array): + """Processes the actions sent to the environment. + + Note: + This function should be called once per environment step. + + Args: + action: The actions to process. Shape is (num_envs, total_action_dim). + """ + # check if action dimension is valid + if self.total_action_dim != action.shape[1]: + raise ValueError(f"Invalid action shape, expected: {self.total_action_dim}, received: {action.shape[1]}.") + + # store the input actions + wp.copy(self._prev_action, self._action) + wp.copy(self._action, action) + + # split the actions and apply to each term + idx = 0 + for term in self._terms.values(): + term.process_actions(self._action, idx) + idx += term.action_dim + + def apply_action(self) -> None: + """Applies the actions to the environment/simulation. + + Note: + This should be called at every simulation step. + """ + for term in self._terms.values(): + term.apply_actions() + + def get_term(self, name: str) -> ActionTerm: + """Returns the action term with the specified name. + + Args: + name: The name of the action term. + + Returns: + The action term with the specified name. + """ + return self._terms[name] + + def serialize(self) -> dict: + """Serialize the action manager configuration. + + Returns: + A dictionary of serialized action term configurations. + """ + return {term_name: term.serialize() for term_name, term in self._terms.items()} + + """ + Helper functions. + """ + + def _prepare_terms(self): + # create buffers to parse and store terms + self._term_names: list[str] = list() + self._terms: dict[str, ActionTerm] = dict() + + # check if config is dict already + if isinstance(self.cfg, dict): + cfg_items = self.cfg.items() + else: + cfg_items = self.cfg.__dict__.items() + # parse action terms from the config + for term_name, term_cfg in cfg_items: + # check if term config is None + if term_cfg is None: + continue + # check valid type + if not isinstance(term_cfg, ActionTermCfg): + raise TypeError( + f"Configuration for the term '{term_name}' is not of type ActionTermCfg." + f" Received: '{type(term_cfg)}'." + ) + # create the action term + term = term_cfg.class_type(term_cfg, self._env) + # sanity check if term is valid type + if not isinstance(term, ActionTerm): + raise TypeError(f"Returned object for the term '{term_name}' is not of type ActionType.") + # add term name and parameters + self._term_names.append(term_name) + self._terms[term_name] = term diff --git a/source/isaaclab_experimental/isaaclab_experimental/managers/command_manager.py b/source/isaaclab_experimental/isaaclab_experimental/managers/command_manager.py new file mode 100644 index 000000000000..8b4e8f83dbe7 --- /dev/null +++ b/source/isaaclab_experimental/isaaclab_experimental/managers/command_manager.py @@ -0,0 +1,599 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Command manager for generating and updating commands.""" + +from __future__ import annotations + +import inspect +import weakref +from abc import abstractmethod +from collections.abc import Sequence +from typing import TYPE_CHECKING + +import torch +import warp as wp +from prettytable import PrettyTable + +from isaaclab_experimental.utils.warp.kernels import compute_reset_scale, count_masked + +from .manager_base import ManagerBase, ManagerTermBase +from .manager_term_cfg import CommandTermCfg + +# import omni.kit.app + + +if TYPE_CHECKING: + from isaaclab.envs import ManagerBasedRLEnv + + +@wp.kernel +def _sum_and_zero_masked( + mask: wp.array(dtype=wp.bool), + scale: wp.array(dtype=wp.float32), + metric: wp.array(dtype=wp.float32), + out_mean: wp.array(dtype=wp.float32), +): + env_id = wp.tid() + if mask[env_id]: + wp.atomic_add(out_mean, 0, metric[env_id] * scale[0]) + metric[env_id] = 0.0 + + +@wp.kernel +def _zero_counter_masked(mask: wp.array(dtype=wp.bool), counter: wp.array(dtype=wp.int32)): + env_id = wp.tid() + if mask[env_id]: + counter[env_id] = 0 + + +@wp.kernel +def _step_time_left_and_build_resample_mask( + time_left: wp.array(dtype=wp.float32), + dt: wp.float32, + out_mask: wp.array(dtype=wp.bool), +): + env_id = wp.tid() + t = time_left[env_id] - dt + time_left[env_id] = t + out_mask[env_id] = t <= wp.float32(0.0) + + +@wp.kernel +def _resample_time_left_and_increment_counter( + mask: wp.array(dtype=wp.bool), + time_left: wp.array(dtype=wp.float32), + counter: wp.array(dtype=wp.int32), + rng_state: wp.array(dtype=wp.uint32), + lower: wp.float32, + upper: wp.float32, +): + env_id = wp.tid() + if mask[env_id]: + s = rng_state[env_id] + time_left[env_id] = wp.randf(s, lower, upper) + rng_state[env_id] = s + counter[env_id] = counter[env_id] + 1 + + +class CommandTerm(ManagerTermBase): + """The base class for implementing a command term. + + A command term is used to generate commands for goal-conditioned tasks. For example, + in the case of a goal-conditioned navigation task, the command term can be used to + generate a target position for the robot to navigate to. + + It implements a resampling mechanism that allows the command to be resampled at a fixed + frequency. The resampling frequency can be specified in the configuration object. + Additionally, it is possible to assign a visualization function to the command term + that can be used to visualize the command in the simulator. + """ + + def __init__(self, cfg: CommandTermCfg, env: ManagerBasedRLEnv): + """Initialize the command generator class. + + Args: + cfg: The configuration parameters for the command generator. + env: The environment object. + """ + super().__init__(cfg, env) + + # create buffers to store the command + # -- metrics that can be used for logging (metric_name -> wp.array(num_envs,)) + self.metrics = dict() + # -- time left before resampling + self.time_left_wp = wp.zeros((self.num_envs,), dtype=wp.float32, device=self.device) + # -- counter for the number of times the command has been resampled within the current episode + self.command_counter_wp = wp.zeros((self.num_envs,), dtype=wp.int32, device=self.device) + + # reset/compute scratch buffers (Warp) + self._reset_count_wp = wp.zeros((1,), dtype=wp.int32, device=self.device) + self._reset_scale_wp = wp.zeros((1,), dtype=wp.float32, device=self.device) + self._resample_mask_wp = wp.zeros((self.num_envs,), dtype=wp.bool, device=self.device) + + # add handle for debug visualization (this is set to a valid handle inside set_debug_vis) + self._debug_vis_handle = None + # set initial state of debug visualization + self.set_debug_vis(self.cfg.debug_vis) + + # pre-allocated reset logging extras (filled during reset) + self._reset_metric_mean_wp: dict[str, wp.array] = {} + self._reset_extras: dict[str, torch.Tensor] = {} + + def __del__(self): + """Unsubscribe from the callbacks.""" + if self._debug_vis_handle: + self._debug_vis_handle.unsubscribe() + self._debug_vis_handle = None + + """ + Properties + """ + + @property + @abstractmethod + def command(self) -> torch.Tensor | wp.array: + """The command tensor. Shape is (num_envs, command_dim).""" + raise NotImplementedError + + @property + def has_debug_vis_implementation(self) -> bool: + """Whether the command generator has a debug visualization implemented.""" + # check if function raises NotImplementedError + source_code = inspect.getsource(self._set_debug_vis_impl) + return "NotImplementedError" not in source_code + + @property + def reset_extras(self) -> dict[str, torch.Tensor]: + """Pre-allocated reset logging extras for this command term.""" + return self._reset_extras + + """ + Operations. + """ + + def set_debug_vis(self, debug_vis: bool) -> bool: + """Sets whether to visualize the command data. + + Args: + debug_vis: Whether to visualize the command data. + + Returns: + Whether the debug visualization was successfully set. False if the command + generator does not support debug visualization. + """ + # check if debug visualization is supported + if not self.has_debug_vis_implementation: + return False + # toggle debug visualization objects + self._set_debug_vis_impl(debug_vis) + # toggle debug visualization handles + if debug_vis: + # only enable debug_vis if omniverse is available + from isaaclab.sim.simulation_context import SimulationContext + + sim_context = SimulationContext.instance() + if not sim_context.has_omniverse_visualizer(): + return False + # create a subscriber for the post update event if it doesn't exist + if self._debug_vis_handle is None: + import omni.kit.app + + app_interface = omni.kit.app.get_app_interface() + self._debug_vis_handle = app_interface.get_post_update_event_stream().create_subscription_to_pop( + lambda event, obj=weakref.proxy(self): obj._debug_vis_callback(event) + ) + else: + # remove the subscriber if it exists + if self._debug_vis_handle is not None: + self._debug_vis_handle.unsubscribe() + self._debug_vis_handle = None + # return success + return True + + def reset( + self, + env_ids: Sequence[int] | torch.Tensor | None = None, + *, + env_mask: wp.array | None = None, + ) -> dict[str, torch.Tensor]: + """Reset the command generator and log metrics. + + This function resets the command counter and resamples the command. It should be called + at the beginning of each episode. + + Args: + env_ids: The specific environment indices to reset. + If None, all environments are considered. + env_mask: Boolean Warp mask of shape (num_envs,) selecting reset environments. + If provided, takes precedence over ``env_ids``. + + Returns: + A dictionary containing the information to log under the "{name}" key. + """ + # Mask-first path: captured callers must provide env_mask. + if env_mask is None or not isinstance(env_mask, wp.array): + if wp.get_device().is_capturing: + raise RuntimeError( + "CommandTerm.reset requires env_mask(wp.array[bool]) during capture. " + "Do not pass env_ids on captured paths." + ) + env_mask = self._env.resolve_env_mask(env_ids=env_ids, env_mask=env_mask) + + # compute selected count and reset scale + self._reset_count_wp.zero_() + self._reset_scale_wp.zero_() + wp.launch(kernel=count_masked, dim=self.num_envs, inputs=[env_mask, self._reset_count_wp], device=self.device) + wp.launch( + kernel=compute_reset_scale, + dim=1, + inputs=[self._reset_count_wp, 1.0, self._reset_scale_wp], + device=self.device, + ) + + # update pre-allocated reset extras and clear selected metric rows + for metric_name, metric_value_wp in self.metrics.items(): + out_mean_wp = self._reset_metric_mean_wp[metric_name] + out_mean_wp.zero_() + wp.launch( + kernel=_sum_and_zero_masked, + dim=self.num_envs, + inputs=[env_mask, self._reset_scale_wp, metric_value_wp, out_mean_wp], + device=self.device, + ) + + # set the command counter to zero + wp.launch( + kernel=_zero_counter_masked, + dim=self.num_envs, + inputs=[env_mask, self.command_counter_wp], + device=self.device, + ) + # resample the command + self._resample(env_mask=env_mask) + + return self._reset_extras + + def _prepare_reset_extras(self): + """Pre-allocate reset logging extras from metric definitions.""" + self._reset_metric_mean_wp = {} + self._reset_extras = {} + for metric_name, metric_value in self.metrics.items(): + if not isinstance(metric_value, wp.array): + raise TypeError( + f"Metric '{metric_name}' must be a wp.array(dtype=wp.float32, shape=(num_envs,)). " + f"Received: {type(metric_value)}" + ) + if metric_value.dtype != wp.float32 or metric_value.ndim != 1: + raise TypeError( + f"Metric '{metric_name}' must be wp.float32 1D. " + f"Received dtype={metric_value.dtype}, ndim={metric_value.ndim}." + ) + if metric_value.shape[0] != self.num_envs: + raise ValueError( + f"Metric '{metric_name}' must have shape ({self.num_envs},), received {metric_value.shape}." + ) + out_mean_wp = wp.zeros((1,), dtype=wp.float32, device=self.device) + self._reset_metric_mean_wp[metric_name] = out_mean_wp + self._reset_extras[metric_name] = wp.to_torch(out_mean_wp)[0] + + def compute(self, dt: float): + """Compute the command. + + Args: + dt: The time step passed since the last call to compute. + """ + # update the metrics based on current state + self._update_metrics() + # reduce the time left before resampling and build resample mask + wp.launch( + kernel=_step_time_left_and_build_resample_mask, + dim=self.num_envs, + inputs=[self.time_left_wp, float(dt), self._resample_mask_wp], + device=self.device, + ) + # resample masked envs + self._resample(env_mask=self._resample_mask_wp) + # update the command + self._update_command() + + """ + Helper functions. + """ + + def _resample(self, env_mask: wp.array): + """Resample the command. + + This function resamples the command and time for which the command is applied for the + specified environment mask. + + Args: + env_mask: The boolean environment mask to resample. + """ + if not isinstance(env_mask, wp.array): + raise TypeError(f"env_mask must be a wp.array (got {type(env_mask)}).") + if env_mask.dtype != wp.bool or env_mask.ndim != 1: + raise TypeError(f"env_mask must be wp.bool 1D (got dtype={env_mask.dtype}, ndim={env_mask.ndim}).") + if self._env.rng_state_wp is None: + raise RuntimeError("Environment rng_state_wp is not initialized.") + + # resample time-left and increment command-counter for masked envs + wp.launch( + kernel=_resample_time_left_and_increment_counter, + dim=self.num_envs, + inputs=[ + env_mask, + self.time_left_wp, + self.command_counter_wp, + self._env.rng_state_wp, + float(self.cfg.resampling_time_range[0]), + float(self.cfg.resampling_time_range[1]), + ], + device=self.device, + ) + # resample command values for masked envs + self._resample_command(env_mask) + + """ + Implementation specific functions. + """ + + @abstractmethod + def _update_metrics(self): + """Update the metrics based on the current state.""" + raise NotImplementedError + + @abstractmethod + def _resample_command(self, env_mask: wp.array): + """Resample the command for the specified masked environments.""" + raise NotImplementedError + + @abstractmethod + def _update_command(self): + """Update the command based on the current state.""" + raise NotImplementedError + + def _set_debug_vis_impl(self, debug_vis: bool): + """Set debug visualization into visualization objects. + + This function is responsible for creating the visualization objects if they don't exist + and input ``debug_vis`` is True. If the visualization objects exist, the function should + set their visibility into the stage. + """ + raise NotImplementedError(f"Debug visualization is not implemented for {self.__class__.__name__}.") + + def _debug_vis_callback(self, event): + """Callback for debug visualization. + + This function calls the visualization objects and sets the data to visualize into them. + """ + raise NotImplementedError(f"Debug visualization is not implemented for {self.__class__.__name__}.") + + +class CommandManager(ManagerBase): + """Manager for generating commands. + + The command manager is used to generate commands for an agent to execute. It makes it convenient to switch + between different command generation strategies within the same environment. For instance, in an environment + consisting of a quadrupedal robot, the command to it could be a velocity command or position command. + By keeping the command generation logic separate from the environment, it is easy to switch between different + command generation strategies. + + The command terms are implemented as classes that inherit from the :class:`CommandTerm` class. + Each command generator term should also have a corresponding configuration class that inherits from the + :class:`CommandTermCfg` class. + """ + + _env: ManagerBasedRLEnv + """The environment instance.""" + + def __init__(self, cfg: object, env: ManagerBasedRLEnv): + """Initialize the command manager. + + Args: + cfg: The configuration object or dictionary (``dict[str, CommandTermCfg]``). + env: The environment instance. + """ + # create buffers to parse and store terms + self._terms: dict[str, CommandTerm] = dict() + + # call the base class constructor (this prepares the terms) + super().__init__(cfg, env) + # store the commands + self._commands = dict() + if self.cfg: + self.cfg.debug_vis = False + for term in self._terms.values(): + self.cfg.debug_vis |= term.cfg.debug_vis + + # reset logging extras (persistent holder for orchestrator aggregation) + self._reset_extras: dict[str, torch.Tensor] = {} + for term_name, term in self._terms.items(): + for metric_name, metric_value in term.reset_extras.items(): + self._reset_extras[f"Metrics/{term_name}/{metric_name}"] = metric_value + + def __str__(self) -> str: + """Returns: A string representation for the command manager.""" + msg = f" contains {len(self._terms.values())} active terms.\n" + + # create table for term information + table = PrettyTable() + table.title = "Active Command Terms" + table.field_names = ["Index", "Name", "Type"] + # set alignment of table columns + table.align["Name"] = "l" + # add info on each term + for index, (name, term) in enumerate(self._terms.items()): + table.add_row([index, name, term.__class__.__name__]) + # convert table to string + msg += table.get_string() + msg += "\n" + + return msg + + """ + Properties. + """ + + @property + def active_terms(self) -> list[str]: + """Name of active command terms.""" + return list(self._terms.keys()) + + @property + def has_debug_vis_implementation(self) -> bool: + """Whether the command terms have debug visualization implemented.""" + # check if function raises NotImplementedError + has_debug_vis = False + for term in self._terms.values(): + has_debug_vis |= term.has_debug_vis_implementation + return has_debug_vis + + @property + def reset_extras(self) -> dict[str, torch.Tensor]: + """Persistent reset logging extras for command terms.""" + return self._reset_extras + + """ + Operations. + """ + + def get_active_iterable_terms(self, env_idx: int) -> Sequence[tuple[str, Sequence[float]]]: + """Returns the active terms as iterable sequence of tuples. + + The first element of the tuple is the name of the term and the second element is the raw value(s) of the term. + + Args: + env_idx: The specific environment to pull the active terms from. + + Returns: + The active terms. + """ + + terms = [] + for name, term in self._terms.items(): + command = term.command + if isinstance(command, wp.array): + command = wp.to_torch(command) + terms.append((name, command[env_idx].cpu().tolist())) + return terms + + def set_debug_vis(self, debug_vis: bool): + """Sets whether to visualize the command data. + + Args: + debug_vis: Whether to visualize the command data. + + Returns: + Whether the debug visualization was successfully set. False if the command + generator does not support debug visualization. + """ + for term in self._terms.values(): + term.set_debug_vis(debug_vis) + + def reset( + self, + env_ids: Sequence[int] | torch.Tensor | None = None, + *, + env_mask: wp.array | None = None, + ) -> dict[str, torch.Tensor]: + """Reset the command terms and log their metrics. + + This function resets the command counter and resamples the command for each term. It should be called + at the beginning of each episode. + + Args: + env_ids: The specific environment indices to reset. + If None, all environments are considered. + env_mask: Boolean Warp mask of shape (num_envs,) selecting reset environments. + If provided, takes precedence over ``env_ids``. + + Returns: + A dictionary containing the information to log under the "Metrics/{term_name}/{metric_name}" key. + """ + # Mask-first path: captured callers must provide env_mask. + if env_mask is None or not isinstance(env_mask, wp.array): + if wp.get_device().is_capturing: + raise RuntimeError( + "CommandManager.reset requires env_mask(wp.array[bool]) during capture. " + "Do not pass env_ids on captured paths." + ) + env_mask = self._env.resolve_env_mask(env_ids=env_ids, env_mask=env_mask) + + for term in self._terms.values(): + # reset the command term + term.reset(env_mask=env_mask) + + return self._reset_extras + + def compute(self, dt: float): + """Updates the commands. + + This function calls each command term managed by the class. + + Args: + dt: The time-step interval of the environment. + + """ + # iterate over all the command terms + for term in self._terms.values(): + # compute term's value + term.compute(dt) + + def get_command(self, name: str) -> torch.Tensor: + """Returns the command for the specified command term. + + Args: + name: The name of the command term. + + Returns: + The command tensor of the specified command term. + """ + command = self._terms[name].command + if isinstance(command, wp.array): + return wp.to_torch(command) + return command + + def get_term(self, name: str) -> CommandTerm: + """Returns the command term with the specified name. + + Args: + name: The name of the command term. + + Returns: + The command term with the specified name. + """ + return self._terms[name] + + """ + Helper functions. + """ + + def _prepare_terms(self): + # check if config is dict already + if isinstance(self.cfg, dict): + cfg_items = self.cfg.items() + else: + cfg_items = self.cfg.__dict__.items() + # iterate over all the terms + for term_name, term_cfg in cfg_items: + # check for non config + if term_cfg is None: + continue + # check for valid config type + if not isinstance(term_cfg, CommandTermCfg): + raise TypeError( + f"Configuration for the term '{term_name}' is not of type CommandTermCfg." + f" Received: '{type(term_cfg)}'." + ) + # create the action term + term = term_cfg.class_type(term_cfg, self._env) + # sanity check if term is valid type + if not isinstance(term, CommandTerm): + raise TypeError(f"Returned object for the term '{term_name}' is not of type CommandType.") + # pre-build reset extras once for capture-friendly reset logging + term._prepare_reset_extras() + # add class to dict + self._terms[term_name] = term diff --git a/source/isaaclab_experimental/isaaclab_experimental/managers/event_manager.py b/source/isaaclab_experimental/isaaclab_experimental/managers/event_manager.py new file mode 100644 index 000000000000..3b36613a2ac9 --- /dev/null +++ b/source/isaaclab_experimental/isaaclab_experimental/managers/event_manager.py @@ -0,0 +1,499 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Event manager for orchestrating operations based on different simulation events (experimental, Warp-first). + +This module mirrors :mod:`isaaclab.managers.event_manager` but removes torch ops from hot paths to enable +CUDA-graph-friendly execution for modes that can be captured (notably ``interval``). + +Key differences from the stable manager: +- ``interval`` and ``reset`` modes are **mask-based** internally and implemented using Warp kernels. +- No ``torch.rand`` / ``nonzero`` / tensor allocations in the ``interval`` apply path. + +Event term signature for Warp-first interval/reset modes: + ``func(env, env_mask_wp, **params) -> None`` + +Other modes (e.g. ``prestartup``, ``startup``) are called using the stable convention: + ``func(env, env_ids, **params) -> None`` +""" + +from __future__ import annotations + +import inspect +import logging +from collections.abc import Sequence + +import torch +import warp as wp +from prettytable import PrettyTable + +from .manager_base import ManagerBase +from .manager_term_cfg import EventTermCfg + +logger = logging.getLogger(__name__) + + +@wp.kernel +def _interval_init_per_env( + time_left: wp.array(dtype=wp.float32), + rng_state: wp.array(dtype=wp.uint32), + lower: wp.float32, + upper: wp.float32, +): + env_id = wp.tid() + s = rng_state[env_id] + time_left[env_id] = wp.randf(s, lower, upper) + rng_state[env_id] = s + + +@wp.kernel +def _interval_init_global( + time_left: wp.array(dtype=wp.float32), + rng_state: wp.array(dtype=wp.uint32), + lower: wp.float32, + upper: wp.float32, +): + # single element + s = rng_state[0] + time_left[0] = wp.randf(s, lower, upper) + rng_state[0] = s + + +@wp.kernel +def _interval_step_per_env( + time_left: wp.array(dtype=wp.float32), + rng_state: wp.array(dtype=wp.uint32), + trigger_mask: wp.array(dtype=wp.bool), + dt: wp.float32, + lower: wp.float32, + upper: wp.float32, +): + env_id = wp.tid() + t = time_left[env_id] - dt + if t < wp.float32(1.0e-6): + trigger_mask[env_id] = True + s = rng_state[env_id] + time_left[env_id] = wp.randf(s, lower, upper) + rng_state[env_id] = s + else: + trigger_mask[env_id] = False + time_left[env_id] = t + + +@wp.kernel +def _interval_step_global( + time_left: wp.array(dtype=wp.float32), + rng_state: wp.array(dtype=wp.uint32), + trigger_flag: wp.array(dtype=wp.bool), + dt: wp.float32, + lower: wp.float32, + upper: wp.float32, +): + t = time_left[0] - dt + if t < wp.float32(1.0e-6): + trigger_flag[0] = True + s = rng_state[0] + time_left[0] = wp.randf(s, lower, upper) + rng_state[0] = s + else: + trigger_flag[0] = False + time_left[0] = t + + +@wp.kernel +def _interval_reset_selected( + env_mask: wp.array(dtype=wp.bool), + time_left: wp.array(dtype=wp.float32), + rng_state: wp.array(dtype=wp.uint32), + lower: wp.float32, + upper: wp.float32, +): + env_id = wp.tid() + if env_mask[env_id]: + s = rng_state[env_id] + time_left[env_id] = wp.randf(s, lower, upper) + rng_state[env_id] = s + + +@wp.kernel +def _seed_global_rng_from_env_rng( + env_rng_state: wp.array(dtype=wp.uint32), + global_rng_state: wp.array(dtype=wp.uint32), +): + global_rng_state[0] = wp.rand_init(wp.int32(env_rng_state[0]), wp.int32(0)) + + +@wp.kernel +def _reset_compute_valid_mask( + in_mask: wp.array(dtype=wp.bool), + last_triggered_step: wp.array(dtype=wp.int32), + triggered_once: wp.array(dtype=wp.bool), + out_mask: wp.array(dtype=wp.bool), + global_step_count_buf: wp.array(dtype=wp.int32), + min_step_count: wp.int32, +): + env_id = wp.tid() + if not in_mask[env_id]: + out_mask[env_id] = False + return + + global_step_count = global_step_count_buf[0] + if min_step_count == wp.int32(0): + out_mask[env_id] = True + last_triggered_step[env_id] = global_step_count + triggered_once[env_id] = True + return + + last = last_triggered_step[env_id] + once = triggered_once[env_id] + steps_since = global_step_count - last + valid = steps_since >= min_step_count + # Trigger at least once at the start (matching stable behavior). + valid = valid or ((last == wp.int32(0)) and (not once)) + out_mask[env_id] = valid + if valid: + last_triggered_step[env_id] = global_step_count + triggered_once[env_id] = True + + +class EventManager(ManagerBase): + """Manager for orchestrating operations based on different simulation events (Warp-first for interval/reset).""" + + def __init__(self, cfg: object, env): + # create buffers to parse and store terms + self._mode_term_names: dict[str, list[str]] = {} + self._mode_term_cfgs: dict[str, list[EventTermCfg]] = {} + self._mode_class_term_cfgs: dict[str, list[EventTermCfg]] = {} + + # Warp buffers for interval/reset modes (populated in _prepare_terms) + self._interval_term_time_left_wp: list[wp.array] = [] + self._interval_term_ranges: list[tuple[float, float]] = [] + self._interval_term_is_global: list[bool] = [] + # Scalar RNG state for global interval timers (allocated lazily if needed). + self._interval_global_rng_state_wp: wp.array | None = None + + self._reset_term_last_triggered_step_wp: list[wp.array] = [] + self._reset_term_triggered_once_wp: list[wp.array] = [] + + super().__init__(cfg, env) + + # persistent scratch mask for per-term interval/reset triggering (must be stable pointer for capture) + self._scratch_term_mask_wp = wp.zeros((self.num_envs,), dtype=wp.bool, device=self.device) + + # scratch scalar flag & broadcast view for global interval triggering (no per-term masks) + self._scratch_interval_trigger_flag_wp = wp.zeros((1,), dtype=wp.bool, device=self.device) + self._scratch_interval_trigger_mask_view_wp = wp.array( + ptr=self._scratch_interval_trigger_flag_wp.ptr, + dtype=wp.bool, + shape=(self.num_envs,), + strides=(0,), + capacity=self._scratch_interval_trigger_flag_wp.capacity, + device=self._scratch_interval_trigger_flag_wp.device, + copy=False, + ) + + def __str__(self) -> str: + msg = f" contains {len(self._mode_term_names)} active terms.\n" + for mode in self._mode_term_names: + table = PrettyTable() + table.title = f"Active Event Terms in Mode: '{mode}'" + if mode == "interval": + table.field_names = ["Index", "Name", "Interval time range (s)"] + table.align["Name"] = "l" + for index, (name, cfg) in enumerate(zip(self._mode_term_names[mode], self._mode_term_cfgs[mode])): + table.add_row([index, name, cfg.interval_range_s]) + else: + table.field_names = ["Index", "Name"] + table.align["Name"] = "l" + for index, name in enumerate(self._mode_term_names[mode]): + table.add_row([index, name]) + msg += table.get_string() + msg += "\n" + return msg + + @property + def active_terms(self) -> dict[str, list[str]]: + return self._mode_term_names + + @property + def available_modes(self) -> list[str]: + return list(self._mode_term_names.keys()) + + def set_term_cfg(self, term_name: str, cfg: EventTermCfg): + term_found = False + for mode, terms in self._mode_term_names.items(): + if term_name in terms: + self._mode_term_cfgs[mode][terms.index(term_name)] = cfg + term_found = True + break + if not term_found: + raise ValueError(f"Event term '{term_name}' not found.") + + def get_term_cfg(self, term_name: str) -> EventTermCfg: + for mode, terms in self._mode_term_names.items(): + if term_name in terms: + return self._mode_term_cfgs[mode][terms.index(term_name)] + raise ValueError(f"Event term '{term_name}' not found.") + + def reset( + self, + env_ids: Sequence[int] | slice | torch.Tensor | wp.array | None = None, + *, + env_mask: wp.array | torch.Tensor | None = None, + ) -> dict[str, float]: + # Mask-first path: captured callers must provide env_mask. + if env_mask is None or not isinstance(env_mask, wp.array): + # Keep all id->mask resolution strictly outside capture. + if wp.get_device().is_capturing: + raise RuntimeError( + "EventManager.reset requires env_mask(wp.array[bool]) during capture. " + "Do not pass env_ids on captured paths." + ) + env_mask = self._env.resolve_env_mask(env_ids=env_ids, env_mask=env_mask) + + # reset class terms (mask-based) + for mode_cfg in self._mode_class_term_cfgs.values(): + for term_cfg in mode_cfg: + term_cfg.func.reset(env_mask=env_mask) + + # reset interval timers for non-global interval events + if "interval" in self._mode_term_cfgs: + for i, term_cfg in enumerate(self._mode_term_cfgs["interval"]): + if term_cfg.is_global_time: + continue + lower, upper = self._interval_term_ranges[i] + wp.launch( + kernel=_interval_reset_selected, + dim=self.num_envs, + inputs=[ + env_mask, + self._interval_term_time_left_wp[i], + self._env.rng_state_wp, + float(lower), + float(upper), + ], + device=self.device, + ) + return {} + + def apply( + self, + mode: str, + env_ids: Sequence[int] | slice | torch.Tensor | wp.array | None = None, + dt: float | None = None, + global_env_step_count: wp.array | None = None, + *, + env_mask_wp: wp.array | None = None, + ): + if mode not in self._mode_term_names: + logger.warning(f"Event mode '{mode}' is not defined. Skipping event.") + return + + # SceneEntityCfg-dependent term params should be resolved before entering captured event paths. + if not self._is_scene_entities_resolved: + if wp.get_device().is_capturing: + raise RuntimeError( + "EventManager terms are unresolved during CUDA graph capture. " + "Resolve terms before entering captured event paths." + ) + if self._env.sim.is_playing(): + self._resolve_terms_callback(None) + + if mode == "interval": + if dt is None: + raise ValueError(f"Event mode '{mode}' requires the time-step of the environment.") + if env_ids is not None: + raise ValueError( + f"Event mode '{mode}' does not require environment indices. This is an undefined behavior." + ) + self._apply_interval(float(dt)) + return + + # resolve the environment mask + if env_mask_wp is None: + if wp.get_device().is_capturing: + raise ValueError(f"Event mode '{mode}' requires the environment mask to be provided when capturing.") + env_mask_wp = self._env.resolve_env_mask(env_ids=env_ids) + + if mode == "reset": + if global_env_step_count is None: + raise ValueError(f"Event mode '{mode}' requires the total number of environment steps to be provided.") + self._apply_reset(env_mask_wp, global_env_step_count) + return + + # other modes (startup, prestartup, custom) — env_mask forwarded + for term_cfg in self._mode_term_cfgs[mode]: + term_cfg.func(self._env, env_mask_wp, **term_cfg.params) + + def _apply_interval(self, dt: float) -> None: + if self._env.rng_state_wp is None: + raise RuntimeError("EventManager._apply_interval: env.rng_state_wp is not initialized.") + + # iterate over all the interval terms (fixed list; captured graph-friendly) + for i, term_cfg in enumerate(self._mode_term_cfgs["interval"]): + lower, upper = self._interval_term_ranges[i] + if self._interval_term_is_global[i]: + if self._interval_global_rng_state_wp is None: + raise RuntimeError( + "EventManager._apply_interval: _interval_global_rng_state_wp is not initialized." + ) + # update scalar time_left and scalar flag (mask is a broadcast view of the flag) + wp.launch( + kernel=_interval_step_global, + dim=1, + inputs=[ + self._interval_term_time_left_wp[i], + self._interval_global_rng_state_wp, + self._scratch_interval_trigger_flag_wp, + float(dt), + float(lower), + float(upper), + ], + device=self.device, + ) + term_cfg.func(self._env, self._scratch_interval_trigger_mask_view_wp, **term_cfg.params) + else: + wp.launch( + kernel=_interval_step_per_env, + dim=self.num_envs, + inputs=[ + self._interval_term_time_left_wp[i], + self._env.rng_state_wp, + self._scratch_term_mask_wp, + float(dt), + float(lower), + float(upper), + ], + device=self.device, + ) + term_cfg.func(self._env, self._scratch_term_mask_wp, **term_cfg.params) + + def _apply_reset(self, env_mask_wp: wp.array, global_env_step_count_wp: wp.array) -> None: + if self._scratch_term_mask_wp is None: + raise RuntimeError("EventManager._apply_reset: _scratch_term_mask_wp is not initialized.") + + # iterate over all the reset terms + for index, term_cfg in enumerate(self._mode_term_cfgs["reset"]): + min_step_count = int(term_cfg.min_step_count_between_reset) + wp.launch( + kernel=_reset_compute_valid_mask, + dim=self.num_envs, + inputs=[ + env_mask_wp, + self._reset_term_last_triggered_step_wp[index], + self._reset_term_triggered_once_wp[index], + self._scratch_term_mask_wp, + global_env_step_count_wp, + int(min_step_count), + ], + device=self.device, + ) + term_cfg.func(self._env, self._scratch_term_mask_wp, **term_cfg.params) + + def _prepare_terms(self): + # check if config is dict already + if isinstance(self.cfg, dict): + cfg_items = self.cfg.items() + else: + cfg_items = self.cfg.__dict__.items() + + # iterate over all the terms + for term_name, term_cfg in cfg_items: + if term_cfg is None: + continue + if not isinstance(term_cfg, EventTermCfg): + raise TypeError( + f"Configuration for the term '{term_name}' is not of type EventTermCfg. Received:" + f" '{type(term_cfg)}'." + ) + + if term_cfg.mode != "reset" and term_cfg.min_step_count_between_reset != 0: + logger.warning( + f"Event term '{term_name}' has 'min_step_count_between_reset' set to a non-zero value" + " but the mode is not 'reset'. Ignoring the 'min_step_count_between_reset' value." + ) + + # resolve common parameters + self._resolve_common_term_cfg(term_name, term_cfg, min_argc=2) + + # check if mode is pre-startup and scene replication is enabled + if term_cfg.mode == "prestartup" and self._env.scene.cfg.replicate_physics: + raise RuntimeError( + "Scene replication is enabled, which may affect USD-level randomization." + " When assets are replicated, their properties are shared across instances," + " potentially leading to unintended behavior." + " For stable USD-level randomization, please disable scene replication" + " by setting 'replicate_physics' to False in 'InteractiveSceneCfg'." + ) + + # for prestartup callable class terms, initialize early (stable behavior) + if inspect.isclass(term_cfg.func) and term_cfg.mode == "prestartup": + logger.info(f"Initializing term '{term_name}' with class '{term_cfg.func.__name__}'.") + term_cfg.func = term_cfg.func(cfg=term_cfg, env=self._env) + + # ensure mode buckets exist + if term_cfg.mode not in self._mode_term_names: + self._mode_term_names[term_cfg.mode] = [] + self._mode_term_cfgs[term_cfg.mode] = [] + self._mode_class_term_cfgs[term_cfg.mode] = [] + # add term name and parameters + self._mode_term_names[term_cfg.mode].append(term_name) + self._mode_term_cfgs[term_cfg.mode].append(term_cfg) + + if inspect.isclass(term_cfg.func): + self._mode_class_term_cfgs[term_cfg.mode].append(term_cfg) + + # per-mode Warp buffers + if term_cfg.mode == "interval": + if term_cfg.interval_range_s is None: + raise ValueError( + f"Event term '{term_name}' has mode 'interval' but 'interval_range_s' is not specified." + ) + lower, upper = term_cfg.interval_range_s + self._interval_term_ranges.append((float(lower), float(upper))) + + if term_cfg.is_global_time: + # allocate and seed scalar global RNG state if needed (avoid consuming env0 RNG stream) + if self._interval_global_rng_state_wp is None: + if self._env.rng_state_wp is None: + raise RuntimeError("EventManager._prepare_terms: env.rng_state_wp is not initialized.") + self._interval_global_rng_state_wp = wp.zeros((1,), dtype=wp.uint32, device=self.device) + wp.launch( + kernel=_seed_global_rng_from_env_rng, + dim=1, + inputs=[self._env.rng_state_wp, self._interval_global_rng_state_wp], + device=self.device, + ) + time_left = wp.zeros((1,), dtype=wp.float32, device=self.device) + wp.launch( + kernel=_interval_init_global, + dim=1, + inputs=[time_left, self._interval_global_rng_state_wp, float(lower), float(upper)], + device=self.device, + ) + self._interval_term_time_left_wp.append(time_left) + self._interval_term_is_global.append(True) + else: + time_left = wp.zeros((self.num_envs,), dtype=wp.float32, device=self.device) + wp.launch( + kernel=_interval_init_per_env, + dim=self.num_envs, + inputs=[time_left, self._env.rng_state_wp, float(lower), float(upper)], + device=self.device, + ) + self._interval_term_time_left_wp.append(time_left) + self._interval_term_is_global.append(False) + + elif term_cfg.mode == "reset": + if term_cfg.min_step_count_between_reset < 0: + raise ValueError( + f"Event term '{term_name}' has mode 'reset' but 'min_step_count_between_reset' is" + f" negative: {term_cfg.min_step_count_between_reset}. Please provide a non-negative value." + ) + # per-env last-trigger bookkeeping (Warp) + self._reset_term_last_triggered_step_wp.append( + wp.zeros((self.num_envs,), dtype=wp.int32, device=self.device) + ) + self._reset_term_triggered_once_wp.append(wp.zeros((self.num_envs,), dtype=wp.bool, device=self.device)) diff --git a/source/isaaclab_experimental/isaaclab_experimental/managers/manager_base.py b/source/isaaclab_experimental/isaaclab_experimental/managers/manager_base.py new file mode 100644 index 000000000000..d40920b23fe9 --- /dev/null +++ b/source/isaaclab_experimental/isaaclab_experimental/managers/manager_base.py @@ -0,0 +1,454 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Base classes for managers (experimental). + +This file is a local copy of :mod:`isaaclab.managers.manager_base` placed under +``isaaclab_experimental`` so it can evolve independently for Warp-first / graph-friendly +pipelines. + +Key differences from the stable version: +- :meth:`ManagerTermBase.reset` is **mask-based** (preferred for capture-friendly subset operations). +""" + +from __future__ import annotations + +import contextlib +import copy +import inspect +import logging +from abc import ABC, abstractmethod +from collections.abc import Sequence +from typing import TYPE_CHECKING, Any + +import warp as wp + +import isaaclab.utils.string as string_utils +from isaaclab.utils import class_to_dict, string_to_callable + +from isaaclab_experimental.utils.warp import is_warp_capturable + +from .manager_term_cfg import ManagerTermBaseCfg +from .scene_entity_cfg import SceneEntityCfg + +# import omni.timeline + + +if TYPE_CHECKING: + from isaaclab.envs import ManagerBasedEnv + +# import logger +logger = logging.getLogger(__name__) + + +class ManagerTermBase(ABC): + """Base class for manager terms. + + Manager term implementations can be functions or classes. If the term is a class, it should + inherit from this base class and implement the required methods. + + Each manager is implemented as a class that inherits from the :class:`ManagerBase` class. Each manager + class should also have a corresponding configuration class that defines the configuration terms for the + manager. Each term should the :class:`ManagerTermBaseCfg` class or its subclass. + + Example pseudo-code for creating a manager: + + .. code-block:: python + + from isaaclab.utils import configclass + from isaaclab.utils.mdp import ManagerBase, ManagerTermBaseCfg + + + @configclass + class MyManagerCfg: + my_term_1: ManagerTermBaseCfg = ManagerTermBaseCfg(...) + my_term_2: ManagerTermBaseCfg = ManagerTermBaseCfg(...) + my_term_3: ManagerTermBaseCfg = ManagerTermBaseCfg(...) + + + # define manager instance + my_manager = ManagerBase(cfg=ManagerCfg(), env=env) + + """ + + def __init__(self, cfg: ManagerTermBaseCfg, env: ManagerBasedEnv): + """Initialize the manager term. + + Args: + cfg: The configuration object. + env: The environment instance. + """ + # store the inputs + self.cfg = cfg + self._env = env + + """ + Properties. + """ + + @property + def num_envs(self) -> int: + """Number of environments.""" + return self._env.num_envs + + @property + def device(self) -> str: + """Device on which to perform computations.""" + return self._env.device + + @property + def __name__(self) -> str: + """Return the name of the class or subclass.""" + return self.__class__.__name__ + + """ + Operations. + """ + + def reset(self, env_mask: wp.array | None = None) -> None: + """Resets the manager term (mask-based). + + Args: + env_mask: Boolean mask of shape (num_envs,) indicating which envs to reset. + If None, all envs are considered. + """ + pass + + def serialize(self) -> dict: + """General serialization call. Includes the configuration dict.""" + return {"cfg": class_to_dict(self.cfg)} + + def __call__(self, *args) -> Any: + """Returns the value of the term required by the manager. + + In case of a class implementation, this function is called by the manager + to get the value of the term. The arguments passed to this function are + the ones specified in the term configuration (see :attr:`ManagerTermBaseCfg.params`). + + .. attention:: + To be consistent with memory-less implementation of terms with functions, it is + recommended to ensure that the returned mutable quantities are cloned before + returning them. For instance, if the term returns a tensor, it is recommended + to ensure that the returned tensor is a clone of the original tensor. This prevents + the manager from storing references to the tensors and altering the original tensors. + + Args: + *args: Variable length argument list. + + Returns: + The value of the term. + """ + raise NotImplementedError("The method '__call__' should be implemented by the subclass.") + + +class ManagerBase(ABC): + """Base class for all managers.""" + + def __init__(self, cfg: object, env: ManagerBasedEnv): + """Initialize the manager. + + This function is responsible for parsing the configuration object and creating the terms. + + If the simulation is not playing, the scene entities are not resolved immediately. + Instead, the resolution is deferred until the simulation starts. This is done to ensure + that the scene entities are resolved even if the manager is created after the simulation + has already started. + + Args: + cfg: The configuration object. If None, the manager is initialized without any terms. + env: The environment instance. + """ + # store the inputs + self.cfg = copy.deepcopy(cfg) + self._env = env + + # flag for whether the scene entities have been resolved + # if sim is playing, we resolve the scene entities directly while preparing the terms + self._is_scene_entities_resolved = self._env.sim.is_playing() + + # if the simulation is not playing, we use callbacks to trigger the resolution of the scene + # entities configuration. this is needed for cases where the manager is created after the simulation + # but before the simulation is playing. + # FIXME: Once Isaac Sim supports storing this information as USD schema, we can remove this + # callback and resolve the scene entities directly inside `_prepare_terms`. + # if not self._env.sim.is_playing(): + # # note: Use weakref on all callbacks to ensure that this object can be deleted when its destructor + # # is called + # # The order is set to 20 to allow asset/sensor initialization to complete before the scene entities + # # are resolved. Those have the order 10. + # timeline_event_stream = omni.timeline.get_timeline_interface().get_timeline_event_stream() + # self._resolve_terms_handle = timeline_event_stream.create_subscription_to_pop_by_type( + # int(omni.timeline.TimelineEventType.PLAY), + # lambda event, obj=weakref.proxy(self): obj._resolve_terms_callback(event), + # order=20, + # ) + # else: + # self._resolve_terms_handle = None + self._resolve_terms_handle = None + + # parse config to create terms information + if self.cfg: + self._prepare_terms() + + def __del__(self): + """Delete the manager.""" + # Suppress errors during Python shutdown + # Note: contextlib may be None during interpreter shutdown + if contextlib is not None: + with contextlib.suppress(ImportError, AttributeError, TypeError): + if getattr(self, "_resolve_terms_handle", None): + self._resolve_terms_handle.unsubscribe() + self._resolve_terms_handle = None + + """ + Properties. + """ + + @property + def num_envs(self) -> int: + """Number of environments.""" + return self._env.num_envs + + @property + def device(self) -> str: + """Device on which to perform computations.""" + return self._env.device + + @property + @abstractmethod + def active_terms(self) -> list[str] | dict[str, list[str]]: + """Name of active terms.""" + raise NotImplementedError + + """ + Operations. + """ + + def reset(self, env_ids: Sequence[int] | None = None, env_mask: wp.array | None = None) -> dict[str, float]: + """Resets the manager and returns logging information for the current time-step. + + Args: + env_ids: The environment ids for which to log data. + Defaults None, which logs data for all environments. + + Returns: + Dictionary containing the logging information. + """ + return {} + + def find_terms(self, name_keys: str | Sequence[str]) -> list[str]: + """Find terms in the manager based on the names. + + This function searches the manager for terms based on the names. The names can be + specified as regular expressions or a list of regular expressions. The search is + performed on the active terms in the manager. + + Please check the :meth:`~isaaclab.utils.string_utils.resolve_matching_names` function for more + information on the name matching. + + Args: + name_keys: A regular expression or a list of regular expressions to match the term names. + + Returns: + A list of term names that match the input keys. + """ + # resolve search keys + if isinstance(self.active_terms, dict): + list_of_strings = [] + for names in self.active_terms.values(): + list_of_strings.extend(names) + else: + list_of_strings = self.active_terms + + # return the matching names + return string_utils.resolve_matching_names(name_keys, list_of_strings)[1] + + def get_active_iterable_terms(self, env_idx: int) -> Sequence[tuple[str, Sequence[float]]]: + """Returns the active terms as iterable sequence of tuples. + + The first element of the tuple is the name of the term and the second element is the raw value(s) of the term. + + Returns: + The active terms. + """ + raise NotImplementedError + + """ + Implementation specific. + """ + + @abstractmethod + def _prepare_terms(self): + """Prepare terms information from the configuration object.""" + raise NotImplementedError + + """ + Internal callbacks. + """ + + def _resolve_terms_callback(self, event): + """Resolve configurations of terms once the simulation starts. + + Please check the :meth:`_process_term_cfg_at_play` method for more information. + """ + # check if scene entities have been resolved + if self._is_scene_entities_resolved: + return + # check if config is dict already + if isinstance(self.cfg, dict): + cfg_items = self.cfg.items() + else: + cfg_items = self.cfg.__dict__.items() + + # iterate over all the terms + for term_name, term_cfg in cfg_items: + # check for non config + if term_cfg is None: + continue + # process attributes at runtime + # these properties are only resolvable once the simulation starts playing + self._process_term_cfg_at_play(term_name, term_cfg) + + # set the flag + self._is_scene_entities_resolved = True + + """ + Internal functions. + """ + + def _resolve_common_term_cfg(self, term_name: str, term_cfg: ManagerTermBaseCfg, min_argc: int = 1): + """Resolve common attributes of the term configuration. + + Usually, called by the :meth:`_prepare_terms` method to resolve common attributes of the term + configuration. These include: + + * Resolving the term function and checking if it is callable. + * Checking if the term function's arguments are matched by the parameters. + * Resolving special attributes of the term configuration like ``asset_cfg``, ``sensor_cfg``, etc. + * Initializing the term if it is a class. + + The last two steps are only possible once the simulation starts playing. + + By default, all term functions are expected to have at least one argument, which is the + environment object. Some other managers may expect functions to take more arguments, for + instance, the environment indices as the second argument. In such cases, the + ``min_argc`` argument can be used to specify the minimum number of arguments + required by the term function to be called correctly by the manager. + + Args: + term_name: The name of the term. + term_cfg: The term configuration. + min_argc: The minimum number of arguments required by the term function to be called correctly + by the manager. + + Raises: + TypeError: If the term configuration is not of type :class:`ManagerTermBaseCfg`. + ValueError: If the scene entity defined in the term configuration does not exist. + AttributeError: If the term function is not callable. + ValueError: If the term function's arguments are not matched by the parameters. + """ + # check if the term is a valid term config + if not isinstance(term_cfg, ManagerTermBaseCfg): + raise TypeError( + f"Configuration for the term '{term_name}' is not of type ManagerTermBaseCfg." + f" Received: '{type(term_cfg)}'." + ) + + # get the corresponding function or functional class + if isinstance(term_cfg.func, str): + term_cfg.func = string_to_callable(term_cfg.func) + # check if function is callable + if not callable(term_cfg.func): + raise AttributeError(f"The term '{term_name}' is not callable. Received: {term_cfg.func}") + + # check if the term is a class of valid type + if inspect.isclass(term_cfg.func): + if not issubclass(term_cfg.func, ManagerTermBase): + raise TypeError( + f"Configuration for the term '{term_name}' is not of type ManagerTermBase." + f" Received: '{type(term_cfg.func)}'." + ) + func_static = term_cfg.func.__call__ + min_argc += 1 # forward by 1 to account for 'self' argument + else: + func_static = term_cfg.func + # check if function is callable + if not callable(func_static): + raise AttributeError(f"The term '{term_name}' is not callable. Received: {term_cfg.func}") + + # Materialize configclass defaults from the function signature into params. + # Without this, defaults live only in the callable signature and never get + # resolved/cached by the manager (e.g. SceneEntityCfg.resolve() is never called). + signature = inspect.signature(func_static) + for param in list(signature.parameters.values())[min_argc:]: + if param.default is inspect.Parameter.empty: + continue + if param.name not in term_cfg.params and hasattr(param.default, "__dataclass_fields__"): + term_cfg.params[param.name] = param.default.copy() + + # check statically if the term's arguments are matched by params + term_params = list(term_cfg.params.keys()) + args = signature.parameters + args_with_defaults = [arg for arg in args if args[arg].default is not inspect.Parameter.empty] + args_without_defaults = [arg for arg in args if args[arg].default is inspect.Parameter.empty] + args = args_without_defaults + args_with_defaults + # ignore first two arguments for env and env_ids + # Think: Check for cases when kwargs are set inside the function? + if len(args) > min_argc: + if set(args[min_argc:]) != set(term_params + args_with_defaults): + raise ValueError( + f"The term '{term_name}' expects mandatory parameters: {args_without_defaults[min_argc:]}" + f" and optional parameters: {args_with_defaults}, but received: {term_params}." + ) + + # register non-capturable terms with the call switch for mode=2 fallback + if not is_warp_capturable(term_cfg.func): + switch = getattr(self._env, "_manager_call_switch", None) + if switch is not None: + switch.register_manager_capturability(type(self).__name__, False) + + # process attributes at runtime + # these properties are only resolvable once the simulation starts playing + if self._env.sim.is_playing(): + self._process_term_cfg_at_play(term_name, term_cfg) + + def _process_term_cfg_at_play(self, term_name: str, term_cfg: ManagerTermBaseCfg): + """Process the term configuration at runtime. + + This function is called when the simulation starts playing. It is used to process the term + configuration at runtime. This includes: + + * Resolving the scene entity configuration for the term. + * Initializing the term if it is a class. + + Since the above steps rely on PhysX to parse over the simulation scene, they are deferred + until the simulation starts playing. + + Args: + term_name: The name of the term. + term_cfg: The term configuration. + """ + for key, value in term_cfg.params.items(): + if isinstance(value, SceneEntityCfg): + # load the entity + try: + value.resolve(self._env.scene) + except ValueError as e: + raise ValueError(f"Error while parsing '{term_name}:{key}'. {e}") + # log the entity for checking later + msg = f"[{term_cfg.__class__.__name__}:{term_name}] Found entity '{value.name}'." + if value.joint_ids is not None: + msg += f"\n\tJoint names: {value.joint_names} [{value.joint_ids}]" + if value.body_ids is not None: + msg += f"\n\tBody names: {value.body_names} [{value.body_ids}]" + # print the information + logger.info(msg) + # store the entity + term_cfg.params[key] = value + + # initialize the term if it is a class + if inspect.isclass(term_cfg.func): + logger.info(f"Initializing term '{term_name}' with class '{term_cfg.func.__name__}'.") + term_cfg.func = term_cfg.func(cfg=term_cfg, env=self._env) diff --git a/source/isaaclab_experimental/isaaclab_experimental/managers/manager_term_cfg.py b/source/isaaclab_experimental/isaaclab_experimental/managers/manager_term_cfg.py new file mode 100644 index 000000000000..3fab3bfc5ffc --- /dev/null +++ b/source/isaaclab_experimental/isaaclab_experimental/managers/manager_term_cfg.py @@ -0,0 +1,94 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Configuration terms for different managers (experimental, Warp-first). + +This module is a passthrough to :mod:`isaaclab.managers.manager_term_cfg` except for +the following term configs which are overridden for Warp-first execution: + +- :class:`ObservationTermCfg` +- :class:`RewardTermCfg` +- :class:`TerminationTermCfg` +""" + +from __future__ import annotations + +from collections.abc import Callable +from dataclasses import MISSING + +from isaaclab.managers.manager_term_cfg import * # noqa: F401,F403 +from isaaclab.managers.manager_term_cfg import ManagerTermBaseCfg as _ManagerTermBaseCfg +from isaaclab.utils import configclass + + +@configclass +class RewardTermCfg(_ManagerTermBaseCfg): + """Configuration for a reward term. + + The function is expected to write the (unweighted) reward values into a + pre-allocated Warp buffer provided by the manager. + + Expected signature: + + - ``func(env, out, **params) -> None`` + + where ``out`` is a Warp array of shape ``(num_envs,)`` with float32 dtype. + """ + + func: Callable[..., None] = MISSING + """The function to be called to fill the pre-allocated reward buffer.""" + + weight: float = MISSING + """The weight of the reward term.""" + + +@configclass +class TerminationTermCfg(_ManagerTermBaseCfg): + """Configuration for a termination term (experimental, Warp-first). + + The function is expected to write termination flags into a pre-allocated Warp buffer. + + Expected signature: + + - ``func(env, out, **params) -> None`` + + where ``out`` is a Warp array of shape ``(num_envs,)`` with boolean dtype. + """ + + func: Callable[..., None] = MISSING + """The function to be called to fill the pre-allocated termination buffer.""" + + time_out: bool = False + """Whether the termination term contributes towards episodic timeouts. Defaults to False.""" + + +@configclass +class ObservationTermCfg(_ManagerTermBaseCfg): + """Configuration for an observation term (experimental, Warp-first). + + The function is expected to write observation values into a pre-allocated Warp buffer provided + by the observation manager. + + Expected signature: + + - ``func(env, out, **params) -> None`` + + where ``out`` is a Warp array of shape ``(num_envs, obs_term_dim)`` with float32 dtype. + + Notes: + - The stable fields (noise/modifiers/history) are kept for config compatibility, but the + experimental Warp-first observation manager may not support all of them initially. + """ + + func: Callable[..., None] = MISSING + """The function to be called to fill the pre-allocated observation buffer.""" + + # Keep stable configuration fields for compatibility with existing task configs. + modifiers: list[ModifierCfg] | None = None # noqa: F405 + noise: NoiseCfg | NoiseModelCfg | None = None # noqa: F405 + clip: tuple[float, float] | None = None + scale: tuple[float, ...] | float | None = None + history_length: int = 0 + flatten_history_dim: bool = True diff --git a/source/isaaclab_experimental/isaaclab_experimental/managers/observation_manager.py b/source/isaaclab_experimental/isaaclab_experimental/managers/observation_manager.py new file mode 100644 index 000000000000..74d0a9a955be --- /dev/null +++ b/source/isaaclab_experimental/isaaclab_experimental/managers/observation_manager.py @@ -0,0 +1,941 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Observation manager for computing observation signals for a given world. + +Observations are organized into groups based on their intended usage. This allows having different observation +groups for different types of learning such as asymmetric actor-critic and student-teacher training. Each +group contains observation terms which contain information about the observation function to call, the noise +corruption model to use, and the sensor to retrieve data from. + +Each observation group should inherit from the :class:`ObservationGroupCfg` class. Within each group, each +observation term should instantiate the :class:`ObservationTermCfg` class. Based on the configuration, the +observations in a group can be concatenated into a single tensor or returned as a dictionary with keys +corresponding to the term's name. + +If the observations in a group are concatenated, the shape of the concatenated tensor is computed based on the +shapes of the individual observation terms. This information is stored in the :attr:`group_obs_dim` dictionary +with keys as the group names and values as the shape of the observation tensor. When the terms in a group are not +concatenated, the attribute stores a list of shapes for each term in the group. + +.. note:: + When the observation terms in a group do not have the same shape, the observation terms cannot be + concatenated. In this case, please set the :attr:`ObservationGroupCfg.concatenate_terms` attribute in the + group configuration to False. + +Observations can also have history. This means a running history is updated per sim step. History can be controlled +per :class:`ObservationTermCfg` (See the :attr:`ObservationTermCfg.history_length` and +:attr:`ObservationTermCfg.flatten_history_dim`). History can also be controlled via :class:`ObservationGroupCfg` +where group configuration overwrites per term configuration if set. History follows an oldest to newest ordering. + +The observation manager can be used to compute observations for all the groups or for a specific group. The +observations are computed by calling the registered functions for each term in the group. The functions are +called in the order of the terms in the group. The functions are expected to return a tensor with shape +(num_envs, ...). + +If a noise model or custom modifier is registered for a term, the function is called to corrupt +the observation. The corruption function is expected to return a tensor with the same shape as the observation. +The observations are clipped and scaled as per the configuration settings. + +Experimental (Warp-first) note: + Observation term functions follow a Warp-first signature and **write** into pre-allocated Warp buffers: + ``func(env, out, **params) -> None``. Post-processing may be implemented via Warp kernels where possible. +""" + +from __future__ import annotations + +import inspect +from collections.abc import Sequence +from typing import TYPE_CHECKING, Any + +import numpy as np +import torch +import warp as wp +from prettytable import PrettyTable + +from isaaclab.utils import class_to_dict + +from isaaclab_experimental.utils import modifiers, noise +from isaaclab_experimental.utils.buffers import CircularBuffer +from isaaclab_experimental.utils.torch_utils import clone_obs_buffer + +from .manager_base import ManagerBase, ManagerTermBase +from .manager_term_cfg import ObservationGroupCfg, ObservationTermCfg + +if TYPE_CHECKING: + from isaaclab.envs import ManagerBasedEnv + + +@wp.kernel +def _apply_clip(out: wp.array(dtype=wp.float32, ndim=2), clip_lo: wp.float32, clip_hi: wp.float32): + env_id = wp.tid() + for j in range(out.shape[1]): + out[env_id, j] = wp.clamp(out[env_id, j], clip_lo, clip_hi) + + +@wp.kernel +def _apply_scale(out: wp.array(dtype=wp.float32, ndim=2), scale: wp.array(dtype=wp.float32)): + env_id = wp.tid() + for j in range(out.shape[1]): + out[env_id, j] = out[env_id, j] * scale[j] + + +def _resolve_scale_vector(value: Any, dim: int, device: str) -> torch.Tensor: + """Resolve scale into a (dim,) float32 tensor (defaults to ones).""" + if value is None: + return torch.ones((dim,), device=device, dtype=torch.float32) + if isinstance(value, torch.Tensor): + t = value.to(device=device, dtype=torch.float32) + if t.numel() == 1: + return t.reshape(1).repeat(dim) + if t.numel() == dim: + return t.reshape(dim) + raise ValueError(f"Expected scale tensor with numel=1 or numel={dim}, got {t.numel()}.") + if isinstance(value, (float, int)): + return torch.full((dim,), float(value), device=device, dtype=torch.float32) + if isinstance(value, (tuple, list)): + if len(value) != dim: + raise ValueError(f"Expected scale length {dim}, got {len(value)}.") + return torch.tensor(value, device=device, dtype=torch.float32) + raise TypeError(f"Unsupported scale type: {type(value)}") + + +class ObservationManager(ManagerBase): + """Manager for computing observation signals for a given world. + + Observations are organized into groups based on their intended usage. This allows having different observation + groups for different types of learning such as asymmetric actor-critic and student-teacher training. Each + group contains observation terms which contain information about the observation function to call, the noise + corruption model to use, and the sensor to retrieve data from. + + Each observation group should inherit from the :class:`ObservationGroupCfg` class. Within each group, each + observation term should instantiate the :class:`ObservationTermCfg` class. Based on the configuration, the + observations in a group can be concatenated into a single tensor or returned as a dictionary with keys + corresponding to the term's name. + + If the observations in a group are concatenated, the shape of the concatenated tensor is computed based on the + shapes of the individual observation terms. This information is stored in the :attr:`group_obs_dim` dictionary + with keys as the group names and values as the shape of the observation tensor. When the terms in a group are not + concatenated, the attribute stores a list of shapes for each term in the group. + + .. note:: + When the observation terms in a group do not have the same shape, the observation terms cannot be + concatenated. In this case, please set the :attr:`ObservationGroupCfg.concatenate_terms` attribute in the + group configuration to False. + + Observations can also have history. This means a running history is updated per sim step. History can be controlled + per :class:`ObservationTermCfg` (See the :attr:`ObservationTermCfg.history_length` and + :attr:`ObservationTermCfg.flatten_history_dim`). History can also be controlled via :class:`ObservationGroupCfg` + where group configuration overwrites per term configuration if set. History follows an oldest to newest ordering. + + The observation manager can be used to compute observations for all the groups or for a specific group. The + observations are computed by calling the registered functions for each term in the group. The functions are + called in the order of the terms in the group. The functions are expected to return a tensor with shape + (num_envs, ...). + + If a noise model or custom modifier is registered for a term, the function is called to corrupt + the observation. The corruption function is expected to return a tensor with the same shape as the observation. + The observations are clipped and scaled as per the configuration settings. + + Experimental (Warp-first) note: + Observation term functions follow a Warp-first signature and **write** into pre-allocated Warp buffers: + ``func(env, out, **params) -> None``. + """ + + def __init__(self, cfg: object, env: ManagerBasedEnv): + """Initialize observation manager. + + Args: + cfg: The configuration object or dictionary (``dict[str, ObservationGroupCfg]``). + env: The environment instance. + + Raises: + ValueError: If the configuration is None. + RuntimeError: If the shapes of the observation terms in a group are not compatible for concatenation + and the :attr:`~ObservationGroupCfg.concatenate_terms` attribute is set to True. + """ + if cfg is None: + raise ValueError("Observation manager configuration is None. Please provide a valid configuration.") + + # call the base class constructor (this will parse the terms config) + super().__init__(cfg, env) + + # compute combined vector for obs group (matches stable semantics) + self._group_obs_dim: dict[str, tuple[int, ...] | list[tuple[int, ...]]] = dict() + for group_name, group_term_dims in self._group_obs_term_dim.items(): + # if terms are concatenated, compute the combined shape into a single tuple + # otherwise, keep the list of shapes as is + if self._group_obs_concatenate[group_name]: + try: + term_dims = torch.stack([torch.tensor(dims, device="cpu") for dims in group_term_dims], dim=0) + if len(term_dims.shape) > 1: + if self._group_obs_concatenate_dim[group_name] >= 0: + dim = self._group_obs_concatenate_dim[group_name] - 1 # account for the batch offset + else: + dim = self._group_obs_concatenate_dim[group_name] + dim_sum = torch.sum(term_dims[:, dim], dim=0) + term_dims[0, dim] = dim_sum + term_dims = term_dims[0] + else: + term_dims = torch.sum(term_dims, dim=0) + self._group_obs_dim[group_name] = tuple(term_dims.tolist()) + except RuntimeError: + raise RuntimeError( + f"Unable to concatenate observation terms in group '{group_name}'." + f" The shapes of the terms are: {group_term_dims}." + " Please ensure that the shapes are compatible for concatenation." + " Otherwise, set 'concatenate_terms' to False in the group configuration." + ) + else: + self._group_obs_dim[group_name] = group_term_dims + + # Stores the latest observations. + self._obs_buffer: dict[str, torch.Tensor | dict[str, torch.Tensor]] | None = None + # Note: Persistent Warp output buffers (`_group_out_wp` / `_group_out_torch`) and per-term post-processing + # buffers are allocated during `_prepare_terms()` since they are per-term/per-group setup. + + def __str__(self) -> str: + """Returns: A string representation for the observation manager.""" + msg = f" contains {len(self._group_obs_term_names)} groups.\n" + + # add info for each group + for group_name, group_dim in self._group_obs_dim.items(): + # create table for term information + table = PrettyTable() + table.title = f"Active Observation Terms in Group: '{group_name}'" + if self._group_obs_concatenate[group_name]: + table.title += f" (shape: {group_dim})" + table.field_names = ["Index", "Name", "Shape"] + # set alignment of table columns + table.align["Name"] = "l" + # add info for each term + obs_terms = zip( + self._group_obs_term_names[group_name], + self._group_obs_term_dim[group_name], + ) + for index, (name, dims) in enumerate(obs_terms): + # resolve inputs to simplify prints + tab_dims = tuple(dims) + # add row + table.add_row([index, name, tab_dims]) + # convert table to string + msg += table.get_string() + msg += "\n" + + return msg + + def get_active_iterable_terms(self, env_idx: int) -> Sequence[tuple[str, Sequence[float]]]: + """Returns the active terms as iterable sequence of tuples. + + The first element of the tuple is the name of the term and the second element is the raw value(s) of the term. + + Args: + env_idx: The specific environment to pull the active terms from. + + Returns: + The active terms. + """ + terms = [] + + if self._obs_buffer is None: + self.compute() + obs_buffer: dict[str, torch.Tensor | dict[str, torch.Tensor]] = self._obs_buffer + + for group_name, _ in self._group_obs_dim.items(): + if not self.group_obs_concatenate[group_name]: + for name, term in obs_buffer[group_name].items(): + terms.append((group_name + "-" + name, term[env_idx].cpu().tolist())) + continue + + idx = 0 + # add info for each term + data = obs_buffer[group_name] + for name, shape in zip( + self._group_obs_term_names[group_name], + self._group_obs_term_dim[group_name], + ): + data_length = np.prod(shape) + term = data[env_idx, idx : idx + data_length] + terms.append((group_name + "-" + name, term.cpu().tolist())) + idx += data_length + + return terms + + """ + Properties. + """ + + @property + def active_terms(self) -> dict[str, list[str]]: + """Name of active observation terms in each group. + + The keys are the group names and the values are the list of observation term names in the group. + """ + return self._group_obs_term_names + + @property + def group_obs_dim(self) -> dict[str, tuple[int, ...] | list[tuple[int, ...]]]: + """Shape of computed observations in each group. + + The key is the group name and the value is the shape of the observation tensor. + If the terms in the group are concatenated, the value is a single tuple representing the + shape of the concatenated observation tensor. Otherwise, the value is a list of tuples, + where each tuple represents the shape of the observation tensor for a term in the group. + """ + return self._group_obs_dim + + @property + def group_obs_term_dim(self) -> dict[str, list[tuple[int, ...]]]: + """Shape of individual observation terms in each group. + + The key is the group name and the value is a list of tuples representing the shape of the observation terms + in the group. The order of the tuples corresponds to the order of the terms in the group. + This matches the order of the terms in the :attr:`active_terms`. + """ + return self._group_obs_term_dim + + @property + def group_obs_concatenate(self) -> dict[str, bool]: + """Whether the observation terms are concatenated in each group or not. + + The key is the group name and the value is a boolean specifying whether the observation terms in the group + are concatenated into a single tensor. If True, the observations are concatenated along the last dimension. + + The values are set based on the :attr:`~ObservationGroupCfg.concatenate_terms` attribute in the group + configuration. + """ + return self._group_obs_concatenate + + @property + def get_IO_descriptors(self, group_names_to_export: list[str] = ["policy"]): + """Get the IO descriptors for the observation manager. + + Returns: + A dictionary with keys as the group names and values as the IO descriptors. + """ + group_data: dict[str, list[dict[str, Any]]] = {} + + # Collect raw descriptor dicts (plus overloads). + for group_name in self._group_obs_term_names: + group_data[group_name] = [] + # check if group name is valid + if group_name not in self._group_obs_term_names: + raise ValueError( + f"Unable to find the group '{group_name}' in the observation manager." + f" Available groups are: {list(self._group_obs_term_names.keys())}" + ) + for term_name, term_cfg in zip( + self._group_obs_term_names[group_name], self._group_obs_term_cfgs[group_name] + ): + func = term_cfg.func + if not getattr(func, "_has_descriptor", False): + continue + try: + # Both stable-style and Warp-first decorated terms support + # the ``inspect=True`` keyword. Warp-first terms (decorated + # with ``generic_io_descriptor_warp``) will NOT execute the + # underlying function; their hooks derive metadata from + # env/config objects instead. + func(self._env, **term_cfg.params, inspect=True) + desc = func._descriptor.__dict__.copy() + overloads = {} + for k in ["modifiers", "clip", "scale", "history_length", "flatten_history_dim"]: + if hasattr(term_cfg, k): + overloads[k] = getattr(term_cfg, k) + desc.update(overloads) + group_data[group_name].append(desc) + except Exception as e: + print(f"Error getting IO descriptor for term '{term_name}' in group '{group_name}': {e}") + + formatted_data: dict[str, list[dict[str, Any]]] = {} + for group_name, data in group_data.items(): + if group_name not in group_names_to_export: + continue + formatted_data[group_name] = [] + for item in data: + name = item.pop("name") + extras = item.pop("extras", {}) + formatted_item = {"name": name, "overloads": {}, "extras": extras} + for k, v in item.items(): + if isinstance(v, tuple): + v = list(v) + if isinstance(v, torch.Tensor): + v = v.detach().cpu().numpy().tolist() + if k in ["scale", "clip", "history_length", "flatten_history_dim"]: + formatted_item["overloads"][k] = v + elif k in ["modifiers", "description", "units"]: + formatted_item["extras"][k] = v + else: + formatted_item[k] = v + formatted_data[group_name].append(formatted_item) + return formatted_data + + """ + Operations. + """ + + def reset( + self, + env_ids: Sequence[int] | torch.Tensor | None = None, + *, + env_mask: wp.array | None = None, + ) -> dict[str, float]: + # Mask-first path: captured callers must provide env_mask. + if env_mask is None or not isinstance(env_mask, wp.array): + # Keep all id->mask resolution strictly outside capture. + if wp.get_device().is_capturing: + raise RuntimeError( + "ObservationManager.reset requires env_mask(wp.array[bool]) during capture. " + "Do not pass env_ids on captured paths." + ) + env_mask = self._env.resolve_env_mask(env_ids=env_ids, env_mask=env_mask) + + # call all terms that are classes + for group_name, group_cfg in self._group_obs_class_term_cfgs.items(): + for term_cfg in group_cfg: + term_cfg.func.reset(env_mask=env_mask) + # reset terms with history + for term_name in self._group_obs_term_names[group_name]: + if term_name in self._group_obs_term_history_buffer[group_name]: + self._group_obs_term_history_buffer[group_name][term_name].reset(env_mask=env_mask) + # call all modifiers/noise models that are classes + for mod in self._group_obs_class_instances: + mod.reset(env_mask=env_mask) + + # nothing to log here + return {} + + def compute( + self, update_history: bool = False, return_cloned_output: bool = True + ) -> dict[str, torch.Tensor | dict[str, torch.Tensor]]: + """Compute the observations per group for all groups. + + The method computes the observations for all the groups handled by the observation manager. + Please check the :meth:`compute_group` on the processing of observations per group. + + Args: + update_history: The boolean indicator without return obs should be appended to observation history. + Default to False, in which case calling compute_group does not modify history. This input is no-ops + if the group's history_length == 0. + return_cloned_output: Whether to return a cloned snapshot of the observation buffer. + Set to False to return the persistent internal buffer by reference. + + Returns: + A dictionary with keys as the group names and values as the computed observations. + The observations are either concatenated into a single tensor or returned as a dictionary + with keys corresponding to the term's name. + """ + # Launch kernels for every group (writes into persistent buffers in-place). + for group_name in self._group_obs_term_names: + self.compute_group(group_name, update_history=update_history) + # Build the obs buffer once (persistent refs to in-place-updated tensors/dicts). + if self._obs_buffer is None: + self._obs_buffer = { + group_name: ( + self._group_out_torch[group_name] + if self._group_use_warp_concat[group_name] + else self._group_obs_dict[group_name] + ) + for group_name in self._group_obs_term_names + } + if return_cloned_output: + return clone_obs_buffer(self._obs_buffer) + return self._obs_buffer + + def compute_group(self, group_name: str, update_history: bool = False) -> torch.Tensor | dict[str, torch.Tensor]: + """Computes the observations for a given group. + + The observations for a given group are computed by calling the registered functions for each + term in the group. The functions are called in the order of the terms in the group. The functions + are expected to return a tensor with shape (num_envs, ...). + + The following steps are performed for each observation term: + + 1. Compute observation term by calling the function + 2. Apply custom modifiers in the order specified in :attr:`ObservationTermCfg.modifiers` + 3. Apply corruption/noise model based on :attr:`ObservationTermCfg.noise` + 4. Apply clipping based on :attr:`ObservationTermCfg.clip` + 5. Apply scaling based on :attr:`ObservationTermCfg.scale` + + We apply noise to the computed term first to maintain the integrity of how noise affects the data + as it truly exists in the real world. If the noise is applied after clipping or scaling, the noise + could be artificially constrained or amplified, which might misrepresent how noise naturally occurs + in the data. + + Args: + group_name: The name of the group for which to compute the observations. Defaults to None, + in which case observations for all the groups are computed and returned. + update_history: The boolean indicator without return obs should be appended to observation group's history. + Default to False, in which case calling compute_group does not modify history. This input is no-ops + if the group's history_length == 0. + + Returns: + Depending on the group's configuration, the tensors for individual observation terms are + concatenated along the last dimension into a single tensor. Otherwise, they are returned as + a dictionary with keys corresponding to the term's name. + + Raises: + ValueError: If input ``group_name`` is not a valid group handled by the manager. + """ + # check if group name is valid + if group_name not in self._group_obs_term_names: + raise ValueError( + f"Unable to find the group '{group_name}' in the observation manager." + f" Available groups are: {list(self._group_obs_term_names.keys())}" + ) + # iterate over all the terms in each group + group_term_names = self._group_obs_term_names[group_name] + + # Persistent per-term obs dict (pre-allocated in _prepare_terms). + group_obs = self._group_obs_dict[group_name] + + # evaluate terms: compute, add noise, clip, scale, custom modifiers + for term_name, term_cfg in zip(group_term_names, self._group_obs_term_cfgs[group_name]): + # compute term's value into pre-allocated Warp output + term_cfg.func(self._env, term_cfg.out_wp, **term_cfg.params) + + # apply custom modifiers (in-place on out_wp) + if term_cfg.modifiers is not None: + for modifier in term_cfg.modifiers: + modifier.func(term_cfg.out_wp, **modifier.params) + + # apply noise (Warp in-place on out_wp) + if isinstance(term_cfg.noise, noise.NoiseCfg): + term_cfg.noise.func(term_cfg.out_wp, term_cfg.noise) + elif isinstance(term_cfg.noise, noise.NoiseModelCfg) and term_cfg.noise.func is not None: + term_cfg.noise.func(term_cfg.out_wp) + + # clip then scale (stable semantics); implementation may use Warp kernels + if term_cfg.clip is not None: + wp.launch( + kernel=_apply_clip, + dim=self.num_envs, + inputs=[term_cfg.out_wp, float(term_cfg.clip[0]), float(term_cfg.clip[1])], + device=self.device, + ) + if term_cfg.scale is not None: + wp.launch( + kernel=_apply_scale, + dim=self.num_envs, + inputs=[term_cfg.out_wp, term_cfg.scale_wp], + device=self.device, + ) + + # TODO(jichuanh): This is not migrated yet. Need revisit. + # Update the history buffer if observation term has history enabled + if term_cfg.history_length > 0: + # circular buffer is not capture safe + if wp.get_device().is_capturing: + raise RuntimeError( + "Observation terms with history (circular buffer) are not CUDA-graph-capture-safe yet. " + "Disable history for observation terms used inside a captured graph, or restructure " + "the graph to exclude history-buffered terms." + ) + circular_buffer = self._group_obs_term_history_buffer[group_name][term_name] + if update_history: + circular_buffer.append(wp.to_torch(term_cfg.out_wp)) + elif circular_buffer._buffer is None: + # because circular buffer only exits after the simulation steps, + # this guards history buffer from corruption by external calls before simulation start + circular_buffer = CircularBuffer( + max_len=circular_buffer.max_length, + batch_size=circular_buffer.batch_size, + device=circular_buffer.device, + ) + self._group_obs_term_history_buffer[group_name][term_name] = circular_buffer + circular_buffer.append(wp.to_torch(term_cfg.out_wp)) + + if term_cfg.flatten_history_dim: + group_obs[term_name] = circular_buffer.buffer.reshape(self._env.num_envs, -1) + else: + group_obs[term_name] = circular_buffer.buffer + + # return persistent output (updated in-place by kernels above) + if self._group_use_warp_concat[group_name]: + return self._group_out_torch[group_name] + return group_obs + + def serialize(self) -> dict: + """Serialize the observation term configurations for all active groups. + + Returns: + A dictionary where each group name maps to its serialized observation term configurations. + """ + output = { + group_name: { + term_name: ( + term_cfg.func.serialize() + if isinstance(term_cfg.func, ManagerTermBase) + else {"cfg": class_to_dict(term_cfg)} + ) + for term_name, term_cfg in zip( + self._group_obs_term_names[group_name], + self._group_obs_term_cfgs[group_name], + ) + } + for group_name in self.active_terms.keys() + } + + return output + + """ + Helper functions. + """ + + def _prepare_terms(self): # noqa: C901 + """Prepares a list of observation terms functions.""" + # create buffers to store information for each observation group + # TODO: Make this more convenient by using data structures. + self._group_obs_term_names: dict[str, list[str]] = dict() + self._group_obs_term_dim: dict[str, list[tuple[int, ...]]] = dict() + self._group_obs_term_cfgs: dict[str, list[ObservationTermCfg]] = dict() + self._group_obs_class_term_cfgs: dict[str, list[ObservationTermCfg]] = dict() + self._group_obs_concatenate: dict[str, bool] = dict() + self._group_obs_concatenate_dim: dict[str, int] = dict() + + self._group_obs_term_history_buffer: dict[str, dict] = dict() + # create a list to store classes instances, e.g., for modifiers and noise models + # we store it as a separate list to only call reset on them and prevent unnecessary calls + self._group_obs_class_instances: list[modifiers.ModifierBase | noise.NoiseModel] = list() + + # Persistent Warp output buffers for concatenated 2D groups (optional fast-path). + # For other cases (non-concat groups, history outputs, non-2D concat dims), we allocate per-term outputs. + self._group_out_wp: dict[str, wp.array] = {} + self._group_out_torch: dict[str, torch.Tensor] = {} + self._group_use_warp_concat: dict[str, bool] = {} + self._group_obs_dict: dict[str, dict[str, torch.Tensor]] = {} + + # make sure the simulation is playing since we compute obs dims which needs asset quantities + if not self._env.sim.is_playing(): + raise RuntimeError( + "Simulation is not playing. Observation manager requires the simulation to be playing" + " to compute observation dimensions. Please start the simulation before using the" + " observation manager." + ) + + # check if config is dict already + if isinstance(self.cfg, dict): + group_cfg_items = self.cfg.items() + else: + group_cfg_items = self.cfg.__dict__.items() + # iterate over all the groups + for group_name, group_cfg in group_cfg_items: + # check for non config + if group_cfg is None: + continue + # check if the term is a curriculum term + if not isinstance(group_cfg, ObservationGroupCfg): + raise TypeError( + f"Observation group '{group_name}' is not of type 'ObservationGroupCfg'." + f" Received: '{type(group_cfg)}'." + ) + # initialize list for the group settings + # group name to list of group term names + self._group_obs_term_names[group_name] = list() + + self._group_obs_term_dim[group_name] = list() + self._group_obs_term_cfgs[group_name] = list() + self._group_obs_class_term_cfgs[group_name] = list() + group_entry_history_buffer: dict[str, CircularBuffer] = dict() + # read common config for the group + self._group_obs_concatenate[group_name] = group_cfg.concatenate_terms + # to account for the batch dimension + self._group_obs_concatenate_dim[group_name] = ( + group_cfg.concatenate_dim + 1 if group_cfg.concatenate_dim >= 0 else group_cfg.concatenate_dim + ) + # check if config is dict already + if isinstance(group_cfg, dict): + term_cfg_items = group_cfg.items() + else: + term_cfg_items = group_cfg.__dict__.items() + # iterate over all the terms in each group + # (we also track raw term dims for Warp output allocation) + group_term_cfgs: list[ObservationTermCfg] = [] + group_term_raw_dims: list[int] = [] + for term_name, term_cfg in term_cfg_items: + # skip non-obs settings + if term_name in [ + "enable_corruption", + "concatenate_terms", + "history_length", + "flatten_history_dim", + "concatenate_dim", + ]: + continue + # check for non config + if term_cfg is None: + continue + if not isinstance(term_cfg, ObservationTermCfg): + raise TypeError( + f"Configuration for the term '{term_name}' is not of type ObservationTermCfg." + f" Received: '{type(term_cfg)}'." + ) + # resolve common terms in the config + # Warp-first signature is (env, out, **params) + self._resolve_common_term_cfg(f"{group_name}/{term_name}", term_cfg, min_argc=2) + + # check noise settings + if not group_cfg.enable_corruption: + term_cfg.noise = None + # check group history params and override terms + if group_cfg.history_length is not None: + term_cfg.history_length = group_cfg.history_length + term_cfg.flatten_history_dim = group_cfg.flatten_history_dim + # add term config to list + self._group_obs_term_names[group_name].append(term_name) + self._group_obs_term_cfgs[group_name].append(term_cfg) + + # infer dimensions (Warp-first: terms write to out; we infer dim from resolved scene info) + term_dim = self._infer_term_dim_scalar(term_cfg) + # Cache the "raw" term output dimension (before history reshaping) for Warp buffer allocation. + # This matches the tensor shape produced directly by the term into `out`: (num_envs, term_dim). + term_cfg._term_dim = int(term_dim) + group_term_cfgs.append(term_cfg) + group_term_raw_dims.append(int(term_dim)) + obs_dims = (self._env.num_envs, term_dim) + + # if scale is set, check if single float or tuple + if term_cfg.scale is not None: + if not isinstance(term_cfg.scale, (float, int, tuple)): + raise TypeError( + f"Scale for observation term '{term_name}' in group '{group_name}'" + f" is not of type float, int or tuple. Received: '{type(term_cfg.scale)}'." + ) + if isinstance(term_cfg.scale, tuple) and len(term_cfg.scale) != obs_dims[1]: + raise ValueError( + f"Scale for observation term '{term_name}' in group '{group_name}'" + f" does not match the dimensions of the observation. Expected: {obs_dims[1]}" + f" but received: {len(term_cfg.scale)}." + ) + + scale_vals = ( + term_cfg.scale if isinstance(term_cfg.scale, tuple) else [float(term_cfg.scale)] * obs_dims[1] + ) + term_cfg.scale_wp = wp.array(scale_vals, dtype=wp.float32, device=self._env.device) + + # prepare modifiers for each observation + if term_cfg.modifiers is not None: + # initialize list of modifiers for term + for mod_cfg in term_cfg.modifiers: + # check if class modifier and initialize with observation size when adding + if isinstance(mod_cfg, modifiers.ModifierCfg): + # to list of modifiers + if inspect.isclass(mod_cfg.func): + if not issubclass(mod_cfg.func, modifiers.ModifierBase): + raise TypeError( + f"Modifier function '{mod_cfg.func}' for observation term '{term_name}'" + f" is not a subclass of 'ModifierBase'. Received: '{type(mod_cfg.func)}'." + ) + mod_cfg.func = mod_cfg.func(cfg=mod_cfg, data_dim=obs_dims, device=self._env.device) + + # add to list of class modifiers + self._group_obs_class_instances.append(mod_cfg.func) + else: + raise TypeError( + f"Modifier configuration '{mod_cfg}' of observation term '{term_name}' is not of" + f" required type ModifierCfg, Received: '{type(mod_cfg)}'" + ) + + # check if function is callable + if not callable(mod_cfg.func): + raise AttributeError( + f"Modifier '{mod_cfg}' of observation term '{term_name}' is not callable." + f" Received: {mod_cfg.func}" + ) + + # check if term's arguments are matched by params + term_params = list(mod_cfg.params.keys()) + args = inspect.signature(mod_cfg.func).parameters + args_with_defaults = [arg for arg in args if args[arg].default is not inspect.Parameter.empty] + args_without_defaults = [arg for arg in args if args[arg].default is inspect.Parameter.empty] + args = args_without_defaults + args_with_defaults + # ignore first argument for data + if len(args) > 1: + if set(args[1:]) != set(term_params + args_with_defaults): + raise ValueError( + f"Modifier '{mod_cfg}' of observation term '{term_name}' expects" + f" mandatory parameters: {args_without_defaults[1:]}" + f" and optional parameters: {args_with_defaults}, but received: {term_params}." + ) + + # prepare noise model classes + if term_cfg.noise is not None and isinstance(term_cfg.noise, noise.NoiseModelCfg): + # plumb the shared per-env RNG state so Warp noise kernels can consume it + term_cfg.noise.rng_state_wp = self._env.rng_state_wp + noise_model_cls = term_cfg.noise.class_type + if not issubclass(noise_model_cls, noise.NoiseModel): + raise TypeError( + f"Class type for observation term '{term_name}' NoiseModelCfg" + f" is not a subclass of 'NoiseModel'. Received: '{type(noise_model_cls)}'." + ) + # initialize func to be the noise model class instance + term_cfg.noise.func = noise_model_cls( + term_cfg.noise, num_envs=self._env.num_envs, device=self._env.device + ) + self._group_obs_class_instances.append(term_cfg.noise.func) + + # create history buffers and calculate history term dimensions + if term_cfg.history_length > 0: + group_entry_history_buffer[term_name] = CircularBuffer( + max_len=term_cfg.history_length, batch_size=self._env.num_envs, device=self._env.device + ) + old_dims = list(obs_dims) + old_dims.insert(1, term_cfg.history_length) + obs_dims = tuple(old_dims) + if term_cfg.flatten_history_dim: + obs_dims = (obs_dims[0], np.prod(obs_dims[1:])) + raise NotImplementedError("History reshaping is not implemented yet for warp.") + + self._group_obs_term_dim[group_name].append(obs_dims[1:]) + + # add term in a separate list if term is a class + if isinstance(term_cfg.func, ManagerTermBase): + self._group_obs_class_term_cfgs[group_name].append(term_cfg) + # call reset (in-case internal state should be reset at init) + term_cfg.func.reset() + + # Allocate persistent outputs for this group. + # - If group is concatenated into a flat 2D vector (N, D) with no history terms, allocate a single group + # buffer and map term outputs to contiguous slices (fast-path). + # - Otherwise allocate per-term outputs. + can_use_group_buffer = ( + self._group_obs_concatenate[group_name] + and self._group_obs_concatenate_dim[group_name] in (1, -1) + and all(cfg.history_length == 0 for cfg in group_term_cfgs) + ) + + if can_use_group_buffer: + total = int(sum(group_term_raw_dims)) + out_wp = wp.zeros((self.num_envs, total), dtype=wp.float32, device=self.device) + self._group_out_wp[group_name] = out_wp + self._group_out_torch[group_name] = wp.to_torch(out_wp) + + base_ptr = out_wp.ptr + row_stride = out_wp.strides[0] + col_stride = out_wp.strides[1] + start = 0 + for term_cfg, d in zip(group_term_cfgs, group_term_raw_dims): + out_view = wp.array( + ptr=base_ptr + start * col_stride, + dtype=wp.float32, + shape=(self.num_envs, int(d)), + strides=(row_stride, col_stride), + device=self.device, + ) + term_cfg.out_wp = out_view + term_cfg.out_torch = wp.to_torch(term_cfg.out_wp) + start += int(d) + else: + for term_cfg, d in zip(group_term_cfgs, group_term_raw_dims): + term_cfg.out_wp = wp.zeros((self.num_envs, int(d)), dtype=wp.float32, device=self.device) + term_cfg.out_torch = wp.to_torch(term_cfg.out_wp) + + # Guard: concat groups must use the Warp fast-path (standard concat dim, no history). + if self._group_obs_concatenate[group_name] and not can_use_group_buffer: + raise ValueError( + f"Observation group '{group_name}' is concatenated but cannot use the Warp" + " fast-path (requires concatenate_dim 0 or -1, and all terms history_length == 0)." + ) + + # Precompute fast-path flag and persistent per-term obs dict. + self._group_use_warp_concat[group_name] = can_use_group_buffer + self._group_obs_dict[group_name] = { + term_name: cfg.out_torch + for term_name, cfg in zip(self._group_obs_term_names[group_name], group_term_cfgs) + } + + # add history buffers for each group + self._group_obs_term_history_buffer[group_name] = group_entry_history_buffer + + def _infer_term_dim_scalar(self, term_cfg: ObservationTermCfg) -> int: + """Infer observation output dimension (D,) using decorator metadata, scene info, or manager state. + + Resolution order: + 1. ``out_dim`` on the function's ``@generic_io_descriptor_warp`` decorator. + 2. ``axes`` on the decorator (e.g. ``axes=["X","Y","Z"]`` → dim 3). + 3. Explicit ``term_dim`` / ``out_dim`` / ``obs_dim`` in ``term_cfg.params`` (legacy). + 4. ``asset_cfg.joint_ids`` count (joint-based observations). + """ + # --- 1-2. Decorator metadata (preferred) --- + func = term_cfg.func + # Check for descriptor on the (possibly wrapped) function first, + # then fall back to unwrapping for class-based terms. + descriptor = getattr(func, "_descriptor", None) + if descriptor is None and hasattr(func, "__wrapped__"): + descriptor = getattr(func.__wrapped__, "_descriptor", None) + if descriptor is not None: + # 1. Explicit out_dim on decorator + out_dim = getattr(descriptor, "out_dim", None) + if out_dim is not None: + return self._resolve_out_dim(out_dim, term_cfg) + # 2. Derive from axes metadata + axes = descriptor.extras.get("axes") if descriptor.extras else None + if axes is not None: + return len(axes) + + # --- 3. Legacy explicit override in params --- + for k in ("term_dim", "out_dim", "obs_dim"): + if k in term_cfg.params: + return int(term_cfg.params[k]) + + # --- 3. Joint-based fallback via asset_cfg --- + asset_cfg = term_cfg.params.get("asset_cfg") + if asset_cfg is None: + raise ValueError( + f"Cannot infer output dimension for observation term '{getattr(func, '__name__', func)}'. " + "Add `out_dim=` to its @generic_io_descriptor_warp decorator." + ) + asset = self._env.scene[asset_cfg.name] + joint_ids_wp = getattr(asset_cfg, "joint_ids_wp", None) + if joint_ids_wp is not None: + return int(joint_ids_wp.shape[0]) + joint_ids = getattr(asset_cfg, "joint_ids", slice(None)) + if isinstance(joint_ids, slice): + return int(getattr(asset, "num_joints", asset.data.joint_pos.torch.shape[1])) + return int(len(joint_ids)) + + def _resolve_out_dim(self, out_dim: int | str, term_cfg: ObservationTermCfg) -> int: + """Resolve an ``out_dim`` value from a decorator into a concrete integer. + + Supports: + - ``int``: returned as-is (fixed dimension). + - ``"joint"``: number of selected joints from ``asset_cfg``. + - ``"body:N"``: ``N`` components per selected body from ``asset_cfg``. + - ``"command"``: query ``command_manager.get_command(name).shape[-1]``. + - ``"action"``: query ``action_manager.action.shape[-1]``. + """ + if isinstance(out_dim, int): + return out_dim + + if out_dim == "joint": + asset_cfg = term_cfg.params.get("asset_cfg") + asset = self._env.scene[asset_cfg.name] + joint_ids_wp = getattr(asset_cfg, "joint_ids_wp", None) + if joint_ids_wp is not None: + return int(joint_ids_wp.shape[0]) + joint_ids = getattr(asset_cfg, "joint_ids", slice(None)) + if isinstance(joint_ids, slice): + return int(getattr(asset, "num_joints", asset.data.joint_pos.warp.shape[1])) + return int(len(joint_ids)) + + if isinstance(out_dim, str) and out_dim.startswith("body:"): + per_body = int(out_dim.split(":")[1]) + asset_cfg = term_cfg.params.get("asset_cfg") + body_ids = getattr(asset_cfg, "body_ids", None) + if body_ids is None or body_ids == slice(None): + asset = self._env.scene[asset_cfg.name] + return per_body * len(asset.body_names) + return per_body * len(body_ids) + + if out_dim == "command": + command_name = term_cfg.params.get("command_name") + cmd = self._env.command_manager.get_command(command_name) + return int(cmd.shape[-1]) + + if out_dim == "action": + action = self._env.action_manager.action + return int(action.shape[-1]) + + raise ValueError(f"Unknown out_dim sentinel: {out_dim!r}") diff --git a/source/isaaclab_experimental/isaaclab_experimental/managers/reward_manager.py b/source/isaaclab_experimental/isaaclab_experimental/managers/reward_manager.py new file mode 100644 index 000000000000..67dcbc055c2f --- /dev/null +++ b/source/isaaclab_experimental/isaaclab_experimental/managers/reward_manager.py @@ -0,0 +1,419 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Reward manager for computing reward signals for a given world. + +This file is a copy of `isaaclab.managers.reward_manager` placed under +`isaaclab_experimental` so it can evolve independently. +""" + +from __future__ import annotations + +from collections.abc import Sequence +from typing import TYPE_CHECKING + +import torch +import warp as wp +from prettytable import PrettyTable + +from isaaclab_experimental.utils.warp.kernels import compute_reset_scale, count_masked + +from .manager_base import ManagerBase, ManagerTermBase +from .manager_term_cfg import RewardTermCfg + +if TYPE_CHECKING: + from isaaclab.envs import ManagerBasedRLEnv + + +@wp.kernel +def _sum_and_zero_masked( + # input + mask: wp.array(dtype=wp.bool), + scale: wp.array(dtype=wp.float32), + # input/output + episode_sums: wp.array(dtype=wp.float32, ndim=2), + # output + out_avg: wp.array(dtype=wp.float32), +): + term_idx, env_id = wp.tid() + if mask[env_id]: + wp.atomic_add(out_avg, term_idx, episode_sums[term_idx, env_id] * scale[0]) + episode_sums[term_idx, env_id] = 0.0 + + +@wp.kernel +def _reward_finalize( + # input + term_outs: wp.array(dtype=wp.float32, ndim=2), + term_weights: wp.array(dtype=wp.float32), + dt: float, + # input/output + reward_buf: wp.array(dtype=wp.float32), + episode_sums: wp.array(dtype=wp.float32, ndim=2), + step_reward: wp.array(dtype=wp.float32, ndim=2), +): + env_id = wp.tid() + + total = wp.float32(0.0) + for term_idx in range(term_outs.shape[0]): + weight = term_weights[term_idx] + if weight != 0.0: + raw = term_outs[term_idx, env_id] + weighted = raw * weight + # store weighted reward rate (matches old: value/dt) + step_reward[env_id, term_idx] = weighted + val = weighted * dt + total += val + episode_sums[term_idx, env_id] += val + + reward_buf[env_id] = total + + +@wp.kernel +def _reward_pre_compute_reset( + # output + reward_buf: wp.array(dtype=wp.float32), + step_reward: wp.array(dtype=wp.float32, ndim=2), + term_outs: wp.array(dtype=wp.float32, ndim=2), +): + """Reset per-step reward buffers. + + Launched with dim = (num_envs,) to reset `reward_buf` and clear the corresponding row in `step_reward`. + This works even when `step_reward.shape[1] == 0` (no terms). + """ + env_id = wp.tid() + reward_buf[env_id] = 0.0 + for term_idx in range(term_outs.shape[0]): + step_reward[env_id, term_idx] = 0.0 + term_outs[term_idx, env_id] = 0.0 + + +class RewardManager(ManagerBase): + """Manager for computing reward signals for a given world. + + The reward manager computes the total reward as a sum of the weighted reward terms. The reward + terms are parsed from a nested config class containing the reward manger's settings and reward + terms configuration. + + The reward terms are parsed from a config class containing the manager's settings and each term's + parameters. Each reward term should instantiate the :class:`RewardTermCfg` class. + + .. note:: + + The reward manager multiplies the reward term's ``weight`` with the time-step interval ``dt`` + of the environment. This is done to ensure that the computed reward terms are balanced with + respect to the chosen time-step interval in the environment. + + """ + + _env: ManagerBasedRLEnv + """The environment instance.""" + + def __init__(self, cfg: object, env: ManagerBasedRLEnv): + """Initialize the reward manager. + + Args: + cfg: The configuration object or dictionary (``dict[str, RewardTermCfg]``). + env: The environment instance. + """ + + # create buffers to parse and store terms + self._term_names: list[str] = list() + self._term_cfgs: list[RewardTermCfg] = list() + self._class_term_cfgs: list[RewardTermCfg] = list() + + # call the base class constructor (this will parse the terms config) + super().__init__(cfg, env) + self._term_name_to_term_idx = {name: i for i, name in enumerate(self._term_names)} + + num_terms = len(self._term_names) + self._num_terms = num_terms + + # persistent term output buffer (raw, unweighted) laid out as (term, env) for contiguous per-term ops + self._term_outs_wp = wp.zeros((num_terms, self.num_envs), dtype=wp.float32, device=self.device) + # per-term output buffers are views into rows of `_term_outs_wp` (Warp) + self._term_out_views_wp: list[wp.array] = [] + if num_terms > 0: + row_stride = self._term_outs_wp.strides[0] + col_stride = self._term_outs_wp.strides[1] + base_ptr = self._term_outs_wp.ptr + for term_idx, term_cfg in enumerate(self._term_cfgs): + out_view = wp.array( + ptr=base_ptr + term_idx * row_stride, + dtype=wp.float32, + shape=(self.num_envs,), + strides=(col_stride,), + device=self.device, + ) + self._term_out_views_wp.append(out_view) + term_cfg.out = out_view + + # prepare extra info to store individual reward term information (warp buffers) + self._episode_sums_wp = wp.zeros((num_terms, self.num_envs), dtype=wp.float32, device=self.device) + self._episode_sum_views_wp: dict[str, wp.array] = {} + if num_terms > 0: + row_stride = self._episode_sums_wp.strides[0] + col_stride = self._episode_sums_wp.strides[1] + base_ptr = self._episode_sums_wp.ptr + for term_idx, term_name in enumerate(self._term_names): + sum_view = wp.array( + ptr=base_ptr + term_idx * row_stride, + dtype=wp.float32, + shape=(self.num_envs,), + strides=(col_stride,), + device=self.device, + ) + self._episode_sum_views_wp[term_name] = sum_view + # per-env reward buffer (Warp) + self._reward_wp = wp.zeros((self.num_envs,), dtype=wp.float32, device=self.device) + + # buffer which stores the current step reward rate for each term for each environment (warp buffer) + self._step_reward_wp = wp.zeros((self.num_envs, num_terms), dtype=wp.float32, device=self.device) + + # per-term weights stored on-device for single-kernel accumulation + self._term_weights_wp = wp.array( + [float(term_cfg.weight) for term_cfg in self._term_cfgs], dtype=wp.float32, device=self.device + ) + + # persistent reset-time logging buffers (warp buffers) + self._episode_sum_avg_wp = wp.zeros((num_terms,), dtype=wp.float32, device=self.device) + self._reset_count_wp = wp.zeros((1,), dtype=wp.int32, device=self.device) + self._reset_scale_wp = wp.zeros((1,), dtype=wp.float32, device=self.device) + + # persistent torch tensor views (helpful for CUDA graph capture) + self._reward_tensor_view = wp.to_torch(self._reward_wp) + self._step_reward_tensor_view = wp.to_torch(self._step_reward_wp) + self._term_weights_tensor_view = wp.to_torch(self._term_weights_wp) + self._episode_sum_avg_tensor_view = wp.to_torch(self._episode_sum_avg_wp) + self._reset_extras = { + "Episode_Reward/" + term_name: self._episode_sum_avg_tensor_view[term_idx] + for term_idx, term_name in enumerate(self._term_names) + } + + def __str__(self) -> str: + """Returns: A string representation for reward manager.""" + msg = f" contains {len(self._term_names)} active terms.\n" + + # create table for term information + table = PrettyTable() + table.title = "Active Reward Terms" + table.field_names = ["Index", "Name", "Weight"] + # set alignment of table columns + table.align["Name"] = "l" + table.align["Weight"] = "r" + # add info on each term + for index, (name, term_cfg) in enumerate(zip(self._term_names, self._term_cfgs)): + table.add_row([index, name, term_cfg.weight]) + # convert table to string + msg += table.get_string() + msg += "\n" + + return msg + + """ + Properties. + """ + + @property + def active_terms(self) -> list[str]: + """Name of active reward terms.""" + return self._term_names + + """ + Operations. + """ + + def reset( + self, + env_ids: Sequence[int] | torch.Tensor | None = None, + *, + env_mask: wp.array | None = None, + ) -> dict[str, torch.Tensor]: + """Computes/reset episodic reward sums for masked envs (capturable core). + + Args: + env_ids: The specific environment indices to reset. + If None, all environments are considered. + env_mask: Boolean Warp mask of shape (num_envs,) selecting reset environments. + If provided, takes precedence over ``env_ids``. + + Returns: + A dictionary containing the information to log under the "Reward/{term_name}" key. + """ + # Mask-first path: captured callers must provide env_mask. + if env_mask is None or not isinstance(env_mask, wp.array): + if wp.get_device().is_capturing: + raise RuntimeError( + "RewardManager.reset requires env_mask(wp.array[bool]) during capture. " + "Do not pass env_ids on captured paths." + ) + env_mask = self._env.resolve_env_mask(env_ids=env_ids, env_mask=env_mask) + + self._episode_sum_avg_wp.zero_() + self._reset_count_wp.zero_() + self._reset_scale_wp.zero_() + + wp.launch(kernel=count_masked, dim=self.num_envs, inputs=[env_mask, self._reset_count_wp], device=self.device) + wp.launch( + kernel=compute_reset_scale, + dim=1, + inputs=[self._reset_count_wp, float(self._env.max_episode_length_s), self._reset_scale_wp], + device=self.device, + ) + + if self._num_terms > 0: + wp.launch( + kernel=_sum_and_zero_masked, + dim=(self._num_terms, self.num_envs), + inputs=[env_mask, self._reset_scale_wp, self._episode_sums_wp, self._episode_sum_avg_wp], + device=self.device, + ) + + # reset all the reward terms + for term_cfg in self._class_term_cfgs: + term_cfg.func.reset(env_mask=env_mask) + + return self._reset_extras + + def compute(self, dt: float) -> torch.Tensor: + """Computes the reward signal as a weighted sum of individual terms. + + This function calls each reward term managed by the class and adds them to compute the net + reward signal. It also updates the episodic sums corresponding to individual reward terms. + + Args: + dt: The time-step interval of the environment. + + Returns: + The net reward signal of shape (num_envs,). + """ + # TODO: Investigate performance diff between two .fill_ and kernel launch + # reset computation (Warp buffers) in a single kernel launch + wp.launch( + kernel=_reward_pre_compute_reset, + dim=self.num_envs, + inputs=[self._reward_wp, self._step_reward_wp, self._term_outs_wp], + device=self.device, + ) + # iterate over all the reward terms (Python loop; per-term math is warp) + for term_cfg in self._term_cfgs: + # skip if weight is zero (kind of a micro-optimization) + if term_cfg.weight == 0.0: + continue + # compute term into the persistent warp buffer (raw, unweighted) + # NOTE: `out` is pre-zeroed every step by `_reward_pre_compute_reset`. + term_cfg.func(self._env, term_cfg.out, **term_cfg.params) + + # update total reward, episodic sums and step rewards in a single kernel launch + wp.launch( + kernel=_reward_finalize, + dim=self.num_envs, + inputs=[ + self._term_outs_wp, + self._term_weights_wp, + float(dt), + self._reward_wp, + self._episode_sums_wp, + self._step_reward_wp, + ], + device=self.device, + ) + + return self._reward_tensor_view + + """ + Operations - Term settings. + """ + + def set_term_cfg(self, term_name: str, cfg: RewardTermCfg): + """Sets the configuration of the specified term into the manager. + + Args: + term_name: The name of the reward term. + cfg: The configuration for the reward term. + + Raises: + ValueError: If the term name is not found. + """ + if term_name not in self._term_names: + raise ValueError(f"Reward term '{term_name}' not found.") + # TODO(jichuanh): it's not guaranteed that the pre-allocated output view is still valid. + # Review this in curriculum manager migration. + # set the configuration (preserve the pre-allocated output view) + term_idx = self._term_names.index(term_name) + cfg.out = self._term_out_views_wp[term_idx] + self._term_cfgs[term_idx] = cfg + # keep on-device weights in sync (call this to update weights used in compute) + self._term_weights_tensor_view[term_idx] = float(cfg.weight) + + def get_term_cfg(self, term_name: str) -> RewardTermCfg: + """Gets the configuration for the specified term. + + Args: + term_name: The name of the reward term. + + Returns: + The configuration of the reward term. + + Raises: + ValueError: If the term name is not found. + """ + if term_name not in self._term_names: + raise ValueError(f"Reward term '{term_name}' not found.") + # return the configuration + return self._term_cfgs[self._term_names.index(term_name)] + + def get_active_iterable_terms(self, env_idx: int) -> Sequence[tuple[str, Sequence[float]]]: + """Returns the active terms as iterable sequence of tuples. + + The first element of the tuple is the name of the term and the second element is the raw value(s) of the term. + + Args: + env_idx: The specific environment to pull the active terms from. + + Returns: + The active terms. + """ + terms = [] + step_reward_torch = self._step_reward_tensor_view + for idx, name in enumerate(self._term_names): + terms.append((name, [step_reward_torch[env_idx, idx].cpu().item()])) + return terms + + """ + Helper functions. + """ + + def _prepare_terms(self): + # check if config is dict already + if isinstance(self.cfg, dict): + cfg_items = self.cfg.items() + else: + cfg_items = self.cfg.__dict__.items() + # iterate over all the terms + for term_name, term_cfg in cfg_items: + # check for non config + if term_cfg is None: + continue + # check for valid config type + if not isinstance(term_cfg, RewardTermCfg): + raise TypeError( + f"Configuration for the term '{term_name}' is not of type RewardTermCfg." + f" Received: '{type(term_cfg)}'." + ) + # check for valid weight type + if not isinstance(term_cfg.weight, (float, int)): + raise TypeError( + f"Weight for the term '{term_name}' is not of type float or int." + f" Received: '{type(term_cfg.weight)}'." + ) + # resolve common parameters + self._resolve_common_term_cfg(term_name, term_cfg, min_argc=2) + # add function to list + self._term_names.append(term_name) + self._term_cfgs.append(term_cfg) + # check if the term is a class + if isinstance(term_cfg.func, ManagerTermBase): + self._class_term_cfgs.append(term_cfg) diff --git a/source/isaaclab_experimental/isaaclab_experimental/managers/scene_entity_cfg.py b/source/isaaclab_experimental/isaaclab_experimental/managers/scene_entity_cfg.py new file mode 100644 index 000000000000..1930f6ce1cb7 --- /dev/null +++ b/source/isaaclab_experimental/isaaclab_experimental/managers/scene_entity_cfg.py @@ -0,0 +1,60 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Experimental fork of :class:`isaaclab.managers.SceneEntityCfg`. + +This adds Warp-only cached selections (e.g. a joint mask) while keeping compatibility +with the stable manager stack (which type-checks against the stable SceneEntityCfg). +""" + +from __future__ import annotations + +import warp as wp + +from isaaclab.assets.articulation.base_articulation import BaseArticulation +from isaaclab.managers.scene_entity_cfg import SceneEntityCfg as _SceneEntityCfg +from isaaclab.scene import InteractiveScene + + +class SceneEntityCfg(_SceneEntityCfg): + """Scene entity configuration with an optional Warp joint mask. + + Notes: + - `joint_mask` is intended for Warp kernels only. + """ + + joint_mask: wp.array | None = None + + """Integer indices of selected joints — used for subset-sized gathers where a boolean mask + cannot provide the mapping from output index k to joint index.""" + joint_ids_wp: wp.array | None = None + + """Integer indices of selected bodies — used for subset-sized body gathers.""" + body_ids_wp: wp.array | None = None + + def resolve(self, scene: InteractiveScene): + # run the stable resolution first (fills joint_ids/body_ids from names/regex) + super().resolve(scene) + + entity = scene[self.name] + + # -- Warp joint mask / ids for articulations + if isinstance(entity, BaseArticulation): + if self.joint_ids == slice(None): + joint_ids_list = list(range(entity.num_joints)) + mask_list = [True] * entity.num_joints + else: + joint_ids_list = list(self.joint_ids) + mask_list = [False] * entity.num_joints + for idx in joint_ids_list: + mask_list[idx] = True + self.joint_mask = wp.array(mask_list, dtype=wp.bool, device=scene.device) + self.joint_ids_wp = wp.array(joint_ids_list, dtype=wp.int32, device=scene.device) + + # -- Warp body ids + if self.body_ids is not None and self.body_ids != slice(None): + self.body_ids_wp = wp.array(list(self.body_ids), dtype=wp.int32, device=scene.device) + elif hasattr(entity, "num_bodies"): + self.body_ids_wp = wp.array(list(range(entity.num_bodies)), dtype=wp.int32, device=scene.device) diff --git a/source/isaaclab_experimental/isaaclab_experimental/managers/termination_manager.py b/source/isaaclab_experimental/isaaclab_experimental/managers/termination_manager.py new file mode 100644 index 000000000000..8a768651b292 --- /dev/null +++ b/source/isaaclab_experimental/isaaclab_experimental/managers/termination_manager.py @@ -0,0 +1,355 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Termination manager for computing done signals for a given world (experimental, Warp-first). + +This file mirrors `isaaclab.managers.termination_manager` but switches to a Warp-first, +CUDA-graph-friendly implementation: + +- Term functions write into pre-allocated Warp buffers (no per-step torch returns). +- All per-env termination buffers are persistent Warp arrays with torch views at the boundary. +- No data-dependent indexing (e.g. `nonzero`) inside `compute()`; subset updates use masks/kernels. +""" + +from __future__ import annotations + +from collections.abc import Sequence +from typing import TYPE_CHECKING + +import torch +import warp as wp +from prettytable import PrettyTable + +from .manager_base import ManagerBase, ManagerTermBase +from .manager_term_cfg import TerminationTermCfg + +if TYPE_CHECKING: + from isaaclab.envs import ManagerBasedRLEnv + + +@wp.kernel +def _termination_pre_compute_reset( + # output + term_dones: wp.array(dtype=wp.bool, ndim=2), + truncated: wp.array(dtype=wp.bool), + terminated: wp.array(dtype=wp.bool), + dones: wp.array(dtype=wp.bool), +): + """Reset per-step termination buffers. + + Launched with dim = (num_envs,) to reset per-env flags and clear the corresponding row in `term_dones`. + This works even when `term_dones.shape[1] == 0` (no terms). + """ + env_id = wp.tid() + truncated[env_id] = False + terminated[env_id] = False + dones[env_id] = False + for term_idx in range(term_dones.shape[1]): + term_dones[env_id, term_idx] = False + + +@wp.kernel +def _termination_finalize( + # input + term_dones: wp.array(dtype=wp.bool, ndim=2), + term_is_time_out: wp.array(dtype=wp.bool), + # output + truncated: wp.array(dtype=wp.bool), + terminated: wp.array(dtype=wp.bool), + dones: wp.array(dtype=wp.bool), + last_episode_dones: wp.array(dtype=wp.bool, ndim=2), +): + """Finalize termination flags and update last-episode term flags (single kernel). + + This kernel: + - reduces `term_dones` into `truncated`, `terminated`, and `dones` + - for envs where `dones=True`, copies the current `term_dones` row into `last_episode_dones` + (matching the stable manager's behavior). + """ + env_id = wp.tid() + + trunc = bool(False) + term = bool(False) + for term_idx in range(term_dones.shape[1]): + v = term_dones[env_id, term_idx] + if v: + if term_is_time_out[term_idx]: + trunc = True + else: + term = True + + done = trunc or term + truncated[env_id] = trunc + terminated[env_id] = term + dones[env_id] = done + + if done: + for term_idx in range(term_dones.shape[1]): + last_episode_dones[env_id, term_idx] = term_dones[env_id, term_idx] + + +# TODO(jichuanh): Look into wp.tile for better performance +@wp.kernel +def _termination_reset_mean_all_2d( + last_episode_dones: wp.array(dtype=wp.bool, ndim=2), + term_done_avg: wp.array(dtype=wp.float32), +): + """Compute mean(done) per term with 2D parallel accumulation.""" + env_id, term_idx = wp.tid() + num_envs = last_episode_dones.shape[0] + if num_envs > 0 and last_episode_dones[env_id, term_idx]: + wp.atomic_add(term_done_avg, term_idx, 1.0 / float(num_envs)) + + +class TerminationManager(ManagerBase): + """Manager for computing done signals for a given world (Warp-first). + + The termination manager computes the termination signal (also called dones) as a combination + of termination terms. Each termination term is a function which takes the environment and a + pre-allocated Warp boolean output buffer and fills it with per-env termination flags. + """ + + _env: ManagerBasedRLEnv + """The environment instance.""" + + def __init__(self, cfg: object, env: ManagerBasedRLEnv): + # create buffers to parse and store terms + self._term_names: list[str] = list() + self._term_cfgs: list[TerminationTermCfg] = list() + self._class_term_cfgs: list[TerminationTermCfg] = list() + + # call the base class constructor (this will parse the terms config) + super().__init__(cfg, env) + + self._term_name_to_term_idx = {name: i for i, name in enumerate(self._term_names)} + + # persistent buffers (Warp) + num_terms = len(self._term_names) + self._term_dones_wp = wp.zeros((self.num_envs, num_terms), dtype=wp.bool, device=self.device) + self._term_done_avg_wp = wp.zeros((num_terms,), dtype=wp.float32, device=self.device) + self._last_episode_dones_wp = wp.zeros((self.num_envs, num_terms), dtype=wp.bool, device=self.device) + self._truncated_wp = wp.zeros((self.num_envs,), dtype=wp.bool, device=self.device) + self._terminated_wp = wp.zeros((self.num_envs,), dtype=wp.bool, device=self.device) + self._dones_wp = wp.zeros((self.num_envs,), dtype=wp.bool, device=self.device) + + # per-term flags indicating if a term is a timeout (Warp) + self._term_is_time_out_wp = wp.array( + [bool(term_cfg.time_out) for term_cfg in self._term_cfgs], dtype=wp.bool, device=self.device + ) + + # per-term output buffers are views into the columns of `_term_dones_wp` (Warp). + # This avoids per-term temporary outputs and a per-term "store" kernel. + # TODO: Investigate performance diff whether it should using row as per env or per term + self._term_out_views_wp: list[wp.array] = [] + if num_terms > 0: + row_stride = self._term_dones_wp.strides[0] + col_stride = self._term_dones_wp.strides[1] + base_ptr = self._term_dones_wp.ptr + for term_idx, term_cfg in enumerate(self._term_cfgs): + out_view = wp.array( + ptr=base_ptr + term_idx * col_stride, + dtype=wp.bool, + shape=(self.num_envs,), + strides=(row_stride,), + device=self.device, + ) + self._term_out_views_wp.append(out_view) + term_cfg.out = out_view + + # torch tensor views (persistent) + self._term_dones_tensor_view = wp.to_torch(self._term_dones_wp) + self._last_episode_dones_tensor_view = wp.to_torch(self._last_episode_dones_wp) + self._truncated_tensor_view = wp.to_torch(self._truncated_wp) + self._terminated_tensor_view = wp.to_torch(self._terminated_wp) + self._dones_tensor_view = wp.to_torch(self._dones_wp) + self._term_done_avg_tensor_view = wp.to_torch(self._term_done_avg_wp) + self._reset_extras = { + "Episode_Termination/" + term_name: self._term_done_avg_tensor_view[term_idx] + for term_idx, term_name in enumerate(self._term_names) + } + + def __str__(self) -> str: + """Returns: A string representation for termination manager.""" + msg = f" contains {len(self._term_names)} active terms.\n" + + # create table for term information + table = PrettyTable() + table.title = "Active Termination Terms" + table.field_names = ["Index", "Name", "Time Out"] + # set alignment of table columns + table.align["Name"] = "l" + # add info on each term + for index, (name, term_cfg) in enumerate(zip(self._term_names, self._term_cfgs)): + table.add_row([index, name, term_cfg.time_out]) + # convert table to string + msg += table.get_string() + msg += "\n" + + return msg + + """ + Properties. + """ + + @property + def active_terms(self) -> list[str]: + """Name of active termination terms.""" + return self._term_names + + @property + def dones(self) -> torch.Tensor: + """The net termination signal. Shape is (num_envs,).""" + return self._dones_tensor_view + + @property + def dones_wp(self) -> wp.array: + """The net termination signal. Shape is (num_envs,).""" + return self._dones_wp + + @property + def time_outs(self) -> torch.Tensor: + """The timeout signal (reaching max episode length). Shape is (num_envs,).""" + return self._truncated_tensor_view + + @property + def time_outs_wp(self) -> wp.array: + """The timeout signal (reaching max episode length). Shape is (num_envs,).""" + return self._truncated_wp + + @property + def terminated(self) -> torch.Tensor: + """The terminated signal (reaching a terminal state). Shape is (num_envs,).""" + return self._terminated_tensor_view + + @property + def terminated_wp(self) -> wp.array: + """The terminated signal (reaching a terminal state). Shape is (num_envs,).""" + return self._terminated_wp + + """ + Operations. + """ + + def reset( + self, + env_ids: Sequence[int] | torch.Tensor | None = None, + *, + env_mask: wp.array | None = None, + ) -> dict[str, torch.Tensor]: + """Reset termination stats and class terms; return pre-allocated extras. + + Args: + env_ids: The specific environment indices to reset. + If None, all environments are considered. + env_mask: Boolean Warp mask of shape (num_envs,) selecting reset environments. + If provided, takes precedence over ``env_ids``. + + Returns: + A dictionary containing the information to log under the "Termination/{term_name}" key. + """ + # Mask-first path: captured callers must provide env_mask. + if env_mask is None or not isinstance(env_mask, wp.array): + if wp.get_device().is_capturing: + raise RuntimeError( + "TerminationManager.reset requires env_mask(wp.array[bool]) during capture. " + "Do not pass env_ids on captured paths." + ) + env_mask = self._env.resolve_env_mask(env_ids=env_ids, env_mask=env_mask) + if len(self._term_names) > 0: + self._term_done_avg_wp.zero_() + wp.launch( + kernel=_termination_reset_mean_all_2d, + dim=(self.num_envs, len(self._term_names)), + inputs=[self._last_episode_dones_wp, self._term_done_avg_wp], + device=self.device, + ) + for term_cfg in self._class_term_cfgs: + term_cfg.func.reset(env_mask=env_mask) + return self._reset_extras + + @property + def episode_termination_extras(self) -> dict[str, torch.Tensor]: + """Pre-allocated reset logging extras for termination terms.""" + return self._reset_extras + + def compute(self) -> torch.Tensor: + """Computes the termination signal as union of individual terms. + + Returns: + The combined termination signal of shape (num_envs,). + """ + # reset computation (Warp buffers) in a single kernel launch + wp.launch( + kernel=_termination_pre_compute_reset, + dim=self.num_envs, + inputs=[self._term_dones_wp, self._truncated_wp, self._terminated_wp, self._dones_wp], + device=self.device, + ) + + # iterate over all the termination terms (fixed list; per-term math is Warp) + for term_cfg in self._term_cfgs: + term_cfg.func(self._env, term_cfg.out, **term_cfg.params) + + # finalize dones and update last-episode term flags (single kernel launch) + wp.launch( + kernel=_termination_finalize, + dim=self.num_envs, + inputs=[ + self._term_dones_wp, + self._term_is_time_out_wp, + self._truncated_wp, + self._terminated_wp, + self._dones_wp, + self._last_episode_dones_wp, + ], + device=self.device, + ) + + return self._dones_tensor_view + + def get_term(self, name: str) -> torch.Tensor: + """Returns the termination term value at current step with the specified name. + + Returns: + The corresponding termination term value. Shape is (num_envs,). + """ + return self._term_dones_tensor_view[:, self._term_name_to_term_idx[name]] + + def get_active_iterable_terms(self, env_idx: int) -> Sequence[tuple[str, Sequence[float]]]: + """Returns the active terms as iterable sequence of tuples for debug/inspection.""" + terms = [] + for i, key in enumerate(self._term_names): + terms.append((key, [self._term_dones_tensor_view[env_idx, i].float().cpu().item()])) + return terms + + """ + Helper functions. + """ + + def _prepare_terms(self): + # check if config is dict already + if isinstance(self.cfg, dict): + cfg_items = self.cfg.items() + else: + cfg_items = self.cfg.__dict__.items() + # iterate over all the terms + for term_name, term_cfg in cfg_items: + # check for non config + if term_cfg is None: + continue + # check for valid config type + if not isinstance(term_cfg, TerminationTermCfg): + raise TypeError( + f"Configuration for the term '{term_name}' is not of type TerminationTermCfg." + f" Received: '{type(term_cfg)}'." + ) + # resolve common parameters (env, out) + self._resolve_common_term_cfg(term_name, term_cfg, min_argc=2) + # add function to list + self._term_names.append(term_name) + self._term_cfgs.append(term_cfg) + # check if the term is a class + if isinstance(term_cfg.func, ManagerTermBase): + self._class_term_cfgs.append(term_cfg) diff --git a/source/isaaclab_experimental/isaaclab_experimental/utils/buffers/__init__.py b/source/isaaclab_experimental/isaaclab_experimental/utils/buffers/__init__.py new file mode 100644 index 000000000000..b26627f06d48 --- /dev/null +++ b/source/isaaclab_experimental/isaaclab_experimental/utils/buffers/__init__.py @@ -0,0 +1,12 @@ +# ########## New ########## +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Sub-module containing experimental buffer overrides.""" + +from isaaclab.utils.buffers import * # noqa: F401,F403 + +# Override with experimental implementation +from .circular_buffer import CircularBuffer # noqa: F401 diff --git a/source/isaaclab_experimental/isaaclab_experimental/utils/buffers/circular_buffer.py b/source/isaaclab_experimental/isaaclab_experimental/utils/buffers/circular_buffer.py new file mode 100644 index 000000000000..b25f91becbca --- /dev/null +++ b/source/isaaclab_experimental/isaaclab_experimental/utils/buffers/circular_buffer.py @@ -0,0 +1,194 @@ +# ########## New ########## +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from collections.abc import Sequence + +import torch +import warp as wp + + +class CircularBuffer: + """Circular buffer for storing a history of batched tensor data. + + This class implements a circular buffer for storing a history of batched tensor data. The buffer is + initialized with a maximum length and a batch size. The data is stored in a circular fashion, and the + data can be retrieved in a LIFO (Last-In-First-Out) fashion. The buffer is designed to be used in + multi-environment settings, where each environment has its own data. + + The shape of the appended data is expected to be (batch_size, ...), where the first dimension is the + batch dimension. Correspondingly, the shape of the ring buffer is (max_len, batch_size, ...). + """ + + def __init__(self, max_len: int, batch_size: int, device: str): + """Initialize the circular buffer. + + Args: + max_len: The maximum length of the circular buffer. The minimum allowed value is 1. + batch_size: The batch dimension of the data. + device: The device used for processing. + + Raises: + ValueError: If the buffer size is less than one. + """ + if max_len < 1: + raise ValueError(f"The buffer size should be greater than zero. However, it is set to {max_len}!") + # set the parameters + self._batch_size = batch_size + self._device = device + self._ALL_INDICES = torch.arange(batch_size, device=device) + + # max length tensor for comparisons + self._max_len = torch.full((batch_size,), max_len, dtype=torch.int, device=device) + # number of data pushes passed since the last call to :meth:`reset` + self._num_pushes = torch.zeros(batch_size, dtype=torch.long, device=device) + # the pointer to the current head of the circular buffer (-1 means not initialized) + self._pointer: int = -1 + # the actual buffer for data storage + # note: this is initialized on the first call to :meth:`append` + self._buffer: torch.Tensor = None # type: ignore + + """ + Properties. + """ + + @property + def batch_size(self) -> int: + """The batch size of the ring buffer.""" + return self._batch_size + + @property + def device(self) -> str: + """The device used for processing.""" + return self._device + + @property + def max_length(self) -> int: + """The maximum length of the ring buffer.""" + return int(self._max_len[0].item()) + + @property + def current_length(self) -> torch.Tensor: + """The current length of the buffer. Shape is (batch_size,). + + Since the buffer is circular, the current length is the minimum of the number of pushes + and the maximum length. + """ + return torch.minimum(self._num_pushes, self._max_len) + + @property + def buffer(self) -> torch.Tensor: + """Complete circular buffer with most recent entry at the end and oldest entry at the beginning. + Returns: + Complete circular buffer with most recent entry at the end and oldest entry at the beginning + of dimension 1. The shape is [batch_size, max_length, data.shape[1:]]. + """ + buf = self._buffer.clone() + buf = torch.roll(buf, shifts=self.max_length - self._pointer - 1, dims=0) + return torch.transpose(buf, dim0=0, dim1=1) + + """ + Operations. + """ + + def reset( + self, + batch_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + *, + env_mask: torch.Tensor | wp.array | None = None, + ): + """Reset the circular buffer at the specified batch indices. + + Args: + batch_ids: Elements to reset in the batch dimension. Default is None, which resets all the batch indices. + env_mask: Boolean mask of shape (batch_size,) selecting elements to reset. + If provided, it takes precedence over ``batch_ids``. + """ + if env_mask is not None: + if isinstance(env_mask, wp.array): + env_mask = wp.to_torch(env_mask) + elif not isinstance(env_mask, torch.Tensor): + raise TypeError(f"Unsupported env_mask type: {type(env_mask)}") + if env_mask.dtype != torch.bool: + env_mask = env_mask.to(dtype=torch.bool) + if str(env_mask.device) != self._device: + env_mask = env_mask.to(self._device) + if env_mask.ndim != 1 or env_mask.shape[0] != self._batch_size: + raise ValueError(f"Expected env_mask shape ({self._batch_size},), received {tuple(env_mask.shape)}.") + batch_ids = env_mask + elif isinstance(batch_ids, wp.array): + batch_ids = wp.to_torch(batch_ids) + + # resolve all indices + if batch_ids is None: + batch_ids = slice(None) + # reset the number of pushes for the specified batch indices + self._num_pushes[batch_ids] = 0 + if self._buffer is not None: + # set buffer at batch_id reset indices to 0.0 so that the buffer() getter + # returns the cleared circular buffer after reset. + self._buffer[:, batch_ids, :] = 0.0 + + def append(self, data: torch.Tensor): + """Append the data to the circular buffer. + + Args: + data: The data to append to the circular buffer. The first dimension should be the batch dimension. + Shape is (batch_size, ...). + + Raises: + ValueError: If the input data has a different batch size than the buffer. + """ + # check the batch size + if data.shape[0] != self.batch_size: + raise ValueError(f"The input data has '{data.shape[0]}' batch size while expecting '{self.batch_size}'") + + # move the data to the device + data = data.to(self._device) + # at the first call, initialize the buffer size + if self._buffer is None: + self._pointer = -1 + self._buffer = torch.empty((self.max_length, *data.shape), dtype=data.dtype, device=self._device) + # move the head to the next slot + self._pointer = (self._pointer + 1) % self.max_length + # add the new data to the last layer + self._buffer[self._pointer] = data + # Check for batches with zero pushes and initialize all values in batch to first append + is_first_push = self._num_pushes == 0 + if torch.any(is_first_push): + self._buffer[:, is_first_push] = data[is_first_push] + # increment number of number of pushes for all batches + self._num_pushes += 1 + + def __getitem__(self, key: torch.Tensor) -> torch.Tensor: + """Retrieve the data from the circular buffer in last-in-first-out (LIFO) fashion. + + If the requested index is larger than the number of pushes since the last call to :meth:`reset`, + the oldest stored data is returned. + + Args: + key: The index to retrieve from the circular buffer. The index should be less than the number of pushes + since the last call to :meth:`reset`. Shape is (batch_size,). + + Returns: + The data from the circular buffer. Shape is (batch_size, ...). + + Raises: + ValueError: If the input key has a different batch size than the buffer. + RuntimeError: If the buffer is empty. + """ + # check the batch size + if len(key) != self.batch_size: + raise ValueError(f"The argument 'key' has length {key.shape[0]}, while expecting {self.batch_size}") + # check if the buffer is empty + if torch.any(self._num_pushes == 0) or self._buffer is None: + raise RuntimeError("Attempting to retrieve data on an empty circular buffer. Please append data first.") + + # admissible lag + valid_keys = torch.minimum(key, self._num_pushes - 1) + # the index in the circular buffer (pointer points to the last+1 index) + index_in_buffer = torch.remainder(self._pointer - valid_keys, self.max_length) + # return output + return self._buffer[index_in_buffer, self._ALL_INDICES] diff --git a/source/isaaclab_experimental/isaaclab_experimental/utils/manager_call_switch.py b/source/isaaclab_experimental/isaaclab_experimental/utils/manager_call_switch.py new file mode 100644 index 000000000000..ad149900af2c --- /dev/null +++ b/source/isaaclab_experimental/isaaclab_experimental/utils/manager_call_switch.py @@ -0,0 +1,262 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Manager call switch for routing manager stage calls through stable/warp/captured paths.""" + +from __future__ import annotations + +import importlib +import json +import os +from enum import IntEnum +from typing import Any + +from isaaclab_experimental.utils.warp_graph_cache import WarpGraphCache + +from isaaclab.utils.timer import Timer + + +class ManagerCallMode(IntEnum): + """Execution mode for manager stage calls. + + * ``STABLE`` (0): Call stable Python manager implementations from :mod:`isaaclab.managers`. + * ``WARP_NOT_CAPTURED`` (1): Call Warp-compatible implementations without CUDA graph capture. + * ``WARP_CAPTURED`` (2): Call Warp implementations with CUDA graph capture/replay. + """ + + STABLE = 0 + WARP_NOT_CAPTURED = 1 + WARP_CAPTURED = 2 + + +class ManagerCallSwitch: + """Per-manager call switch for stable/warp/captured execution. + + Routes each manager stage call through the configured execution path: + stable Python, Warp (eager), or Warp (captured CUDA graph). Optionally + wraps each call in a :class:`Timer` context for profiling. + """ + + DEFAULT_CONFIG: dict[str, int] = {"default": 2} + DEFAULT_KEY = "default" + MANAGER_NAMES: tuple[str, ...] = ( + "ActionManager", + "ObservationManager", + "EventManager", + "RecorderManager", + "CommandManager", + "TerminationManager", + "RewardManager", + "CurriculumManager", + "Scene", + ) + # FIXME: Scene_write_data_to_sim calls articulation._apply_actuator_model which + # uses wp.to_torch + torch indexing -- not capture-safe on this branch. + # Cap Scene stages to WARP_NOT_CAPTURED until the articulation layer is capture-ready. + MAX_MODE_OVERRIDES: dict[str, int] = {"Scene": ManagerCallMode.WARP_NOT_CAPTURED} + + ENV_VAR = "MANAGER_CALL_CONFIG" + """Environment variable name for the JSON config string. + + Example usage:: + + MANAGER_CALL_CONFIG='{"RewardManager": 0, "default": 2}' python train.py ... + """ + + def __init__( + self, + cfg_source: dict | str | None = None, + *, + max_modes: dict[str, int] | None = None, + ): + self._graph_cache = WarpGraphCache() + # Merge caller-supplied max_modes with the class-level MAX_MODE_OVERRIDES. + self._max_modes = dict(self.MAX_MODE_OVERRIDES) + if max_modes is not None: + self._max_modes.update(max_modes) + # Resolve config: prefer explicit cfg_source, fall back to env var. + if cfg_source is None: + cfg_source = os.environ.get(self.ENV_VAR) + self._cfg = self._load_cfg(cfg_source) + print("[INFO] ManagerCallSwitch configuration:") + print(f" - {self.DEFAULT_KEY}: {self._cfg[self.DEFAULT_KEY]}") + for manager_name in self.MANAGER_NAMES: + mode = int(self.get_mode_for_manager(manager_name)) + cap = self._max_modes.get(manager_name) + cap_str = f" (cap={cap})" if cap is not None else "" + print(f" - {manager_name}: {mode}{cap_str}") + + # ------------------------------------------------------------------ + # Graph management + # ------------------------------------------------------------------ + + def invalidate_graphs(self) -> None: + """Invalidate cached capture graphs and their cached return values.""" + self._graph_cache.invalidate() + + # ------------------------------------------------------------------ + # Stage dispatch + # ------------------------------------------------------------------ + + def call_stage( + self, + *, + stage: str, + warp_call: dict[str, Any], + stable_call: dict[str, Any] | None = None, + timer: bool = False, + ) -> Any: + """Run the stage according to configured mode, optionally wrapped in a :class:`Timer`. + + A call spec dict supports the following keys: + + * ``fn`` (required): The callable to invoke. + * ``args`` (optional): Positional arguments tuple. + * ``kwargs`` (optional): Keyword arguments dict. + * ``output`` (optional): A ``Callable[[Any], Any]`` that transforms the raw + return value into the final output. For captured stages the raw value is + ``None``. When omitted, the raw return value is used as-is. + + Args: + stage: Stage identifier in the form ``"ManagerName_function_name"``. + warp_call: Call spec for the warp path (eager or captured). + stable_call: Call spec for the stable (torch) path. Defaults to ``None``. + timer: Whether to wrap execution in a :class:`Timer`. Defaults to ``True`` + (controlled by the global :attr:`Timer.enable` class-level toggle). + Pass a module-level flag like ``TIMER_ENABLED_STEP`` to make timing + conditional on that flag. + + Returns: + The (possibly transformed) return value of the stage. + """ + with Timer(name=stage, msg=f"{stage} took:", enable=timer, time_unit="us"): + return self._dispatch(stage, stable_call, warp_call) + + def _dispatch( + self, + stage: str, + stable_call: dict[str, Any] | None, + warp_call: dict[str, Any], + ) -> Any: + """Select call path based on mode, execute, and apply output.""" + mode = self.get_mode_for_manager(self._manager_name_from_stage(stage)) + if mode == ManagerCallMode.STABLE: + if stable_call is None: + raise ValueError(f"Stage '{stage}' is configured as STABLE (mode=0) but no stable_call was provided.") + call, result = stable_call, self._run_call(stable_call) + elif mode == ManagerCallMode.WARP_CAPTURED: + call, result = warp_call, self._wp_capture_or_launch(stage, warp_call) + else: + call, result = warp_call, self._run_call(warp_call) + + output_fn = call.get("output") + return output_fn(result) if output_fn is not None else result + + # ------------------------------------------------------------------ + # Manager resolution + # ------------------------------------------------------------------ + + def _manager_name_from_stage(self, stage: str) -> str: + if "_" not in stage: + raise ValueError(f"Invalid stage '{stage}'. Expected '{{manager_name}}_{{function_name}}'.") + return stage.split("_", 1)[0] + + def get_mode_for_manager(self, manager_name: str) -> ManagerCallMode: + """Return the resolved execution mode for the given manager. + + Looks up the manager in the config dict, falls back to the default, + then caps by :attr:`_max_modes` (static overrides + dynamic registrations). + """ + default_key = next(iter(self.DEFAULT_CONFIG)) + mode_value = self._cfg.get(manager_name, self._cfg[default_key]) + cap = self._max_modes.get(manager_name) + if cap is not None: + mode_value = min(mode_value, cap) + return ManagerCallMode(mode_value) + + def resolve_manager_class(self, manager_name: str, mode_override: ManagerCallMode | int | None = None) -> type: + """Import and return the manager class for the configured mode.""" + mode = self.get_mode_for_manager(manager_name) if mode_override is None else ManagerCallMode(mode_override) + module_name = "isaaclab.managers" if mode == ManagerCallMode.STABLE else "isaaclab_experimental.managers" + module = importlib.import_module(module_name) + if not hasattr(module, manager_name): + raise AttributeError(f"Manager '{manager_name}' not found in module '{module_name}'.") + return getattr(module, manager_name) + + def register_manager_capturability(self, manager_name: str, capturable: bool) -> None: + """Register that a manager has non-capturable terms, capping its mode. + + Called by :class:`ManagerBase` during term preparation when a term + is decorated with ``@warp_capturable(False)``. + """ + if not capturable: + self._max_modes[manager_name] = min( + self._max_modes.get(manager_name, ManagerCallMode.WARP_CAPTURED), + ManagerCallMode.WARP_NOT_CAPTURED, + ) + + # ------------------------------------------------------------------ + # Internal helpers + # ------------------------------------------------------------------ + + def _run_call(self, call: dict[str, Any]) -> Any: + """Execute a single call spec eagerly.""" + return call["fn"](*call.get("args", ()), **call.get("kwargs", {})) + + def _wp_capture_or_launch(self, stage: str, call: dict[str, Any]) -> Any: + """Capture Warp CUDA graph on first call, then replay. + + Delegates to :class:`WarpGraphCache` which handles warm-up, capture, + caching the return value, and replay. + """ + return self._graph_cache.capture_or_replay( + stage, + call["fn"], + args=call.get("args", ()), + kwargs=call.get("kwargs", {}), + ) + + def _load_cfg(self, cfg_source: dict | str | None) -> dict[str, int]: + if cfg_source is None: + cfg = dict(self.DEFAULT_CONFIG) + elif isinstance(cfg_source, dict): + cfg = dict(cfg_source) + if self.DEFAULT_KEY not in cfg: + cfg[self.DEFAULT_KEY] = self.DEFAULT_CONFIG[self.DEFAULT_KEY] + elif isinstance(cfg_source, str): + if cfg_source.strip() == "": + cfg = dict(self.DEFAULT_CONFIG) + else: + parsed = json.loads(cfg_source) + if not isinstance(parsed, dict): + raise TypeError("manager_call_config must decode to a dict.") + cfg = dict(parsed) + if self.DEFAULT_KEY not in cfg: + cfg[self.DEFAULT_KEY] = self.DEFAULT_CONFIG[self.DEFAULT_KEY] + else: + raise TypeError(f"cfg_source must be a dict, string, or None, got: {type(cfg_source)}") + + # validation + for manager_name, mode_value in cfg.items(): + if not isinstance(mode_value, int): + raise TypeError( + f"manager_call_config value for '{manager_name}' must be int (0/1/2), got: {type(mode_value)}" + ) + try: + ManagerCallMode(mode_value) + except ValueError as exc: + raise ValueError( + f"Invalid manager_call_config value for '{manager_name}': {mode_value}. Expected 0/1/2." + ) from exc + + # Apply max mode caps: bake caps into the resolved config so + # get_mode_for_manager never needs per-call branching. + default_mode = cfg[self.DEFAULT_KEY] + for name, max_mode in self._max_modes.items(): + resolved = cfg.get(name, default_mode) + if resolved > max_mode: + cfg[name] = max_mode + + return cfg diff --git a/source/isaaclab_experimental/isaaclab_experimental/utils/modifiers/__init__.py b/source/isaaclab_experimental/isaaclab_experimental/utils/modifiers/__init__.py new file mode 100644 index 000000000000..3563b166642a --- /dev/null +++ b/source/isaaclab_experimental/isaaclab_experimental/utils/modifiers/__init__.py @@ -0,0 +1,21 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Warp-native modifier implementations (experimental). + +Re-exports stable configs and base classes, then overrides the function-based +modifiers (``scale``, ``bias``, ``clip``) with Warp-native versions that +operate in-place on ``wp.array``. + +Calling convention (matches Warp MDP terms):: + + modifier.func(data_wp, **params) -> None # in-place on wp.array +""" + +from .modifier import bias, clip, scale # noqa: F401 +from .modifier_base import ModifierBase # noqa: F401 + +# Override with Warp-native implementations +from .modifier_cfg import ModifierCfg # noqa: F401 diff --git a/source/isaaclab_experimental/isaaclab_experimental/utils/modifiers/modifier.py b/source/isaaclab_experimental/isaaclab_experimental/utils/modifiers/modifier.py new file mode 100644 index 000000000000..887db5e4ee06 --- /dev/null +++ b/source/isaaclab_experimental/isaaclab_experimental/utils/modifiers/modifier.py @@ -0,0 +1,80 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Warp-native function-based modifiers (experimental). + +Each modifier takes a ``wp.array`` as its first argument and operates **in-place** +via ``wp.launch``. The calling convention mirrors Warp MDP terms:: + + modifier.func(data_wp, **params) -> None +""" + +from __future__ import annotations + +import warp as wp + +# -- scale -------------------------------------------------------------------- + + +@wp.kernel +def _scale_kernel(data: wp.array(dtype=wp.float32, ndim=2), multiplier: wp.float32): + i, j = wp.tid() + data[i, j] = data[i, j] * multiplier + + +def scale(data: wp.array, multiplier: float) -> None: + """Scale all elements of *data* by *multiplier* in-place. + + Warp-native drop-in replacement for :func:`isaaclab.utils.modifiers.scale`. + + Args: + data: The observation buffer to modify. Shape ``(num_envs, D)``. + multiplier: Scalar multiplier. + """ + wp.launch(_scale_kernel, dim=data.shape, inputs=[data, float(multiplier)], device=data.device) + + +# -- bias --------------------------------------------------------------------- + + +@wp.kernel +def _bias_kernel(data: wp.array(dtype=wp.float32, ndim=2), value: wp.float32): + i, j = wp.tid() + data[i, j] = data[i, j] + value + + +def bias(data: wp.array, value: float) -> None: + """Add a uniform *value* to all elements of *data* in-place. + + Warp-native drop-in replacement for :func:`isaaclab.utils.modifiers.bias`. + + Args: + data: The observation buffer to modify. Shape ``(num_envs, D)``. + value: Scalar bias to add. + """ + wp.launch(_bias_kernel, dim=data.shape, inputs=[data, float(value)], device=data.device) + + +# -- clip --------------------------------------------------------------------- + + +@wp.kernel +def _clip_kernel(data: wp.array(dtype=wp.float32, ndim=2), lo: wp.float32, hi: wp.float32): + i, j = wp.tid() + data[i, j] = wp.clamp(data[i, j], lo, hi) + + +def clip(data: wp.array, bounds: tuple[float | None, float | None]) -> None: + """Clamp all elements of *data* to [lo, hi] in-place. + + Warp-native drop-in replacement for :func:`isaaclab.utils.modifiers.clip`. + + Args: + data: The observation buffer to modify. Shape ``(num_envs, D)``. + bounds: ``(min, max)`` tuple. ``None`` means no bound on that side. + """ + lo = float(bounds[0]) if bounds[0] is not None else float(-1e38) + hi = float(bounds[1]) if bounds[1] is not None else float(1e38) + wp.launch(_clip_kernel, dim=data.shape, inputs=[data, lo, hi], device=data.device) diff --git a/source/isaaclab_experimental/isaaclab_experimental/utils/modifiers/modifier_base.py b/source/isaaclab_experimental/isaaclab_experimental/utils/modifiers/modifier_base.py new file mode 100644 index 000000000000..083e1576e891 --- /dev/null +++ b/source/isaaclab_experimental/isaaclab_experimental/utils/modifiers/modifier_base.py @@ -0,0 +1,63 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Warp-native modifier base class (experimental).""" + +from __future__ import annotations + +from abc import ABC, abstractmethod +from typing import TYPE_CHECKING + +import warp as wp + +if TYPE_CHECKING: + from .modifier_cfg import ModifierCfg + + +class ModifierBase(ABC): + """Base class for Warp-native class-based modifiers. + + Experimental fork of :class:`isaaclab.utils.modifiers.ModifierBase` adapted for the + Warp-first calling convention. Subclasses operate **in-place** on ``wp.array`` + buffers and return ``None``. + + A class implementation of a modifier can be used to store state information between + calls. This is useful for modifiers that require stateful operations, such as + rolling averages, delays, or decaying filters. + """ + + def __init__(self, cfg: ModifierCfg, data_dim: tuple[int, ...], device: str) -> None: + """Initializes the modifier class. + + Args: + cfg: Configuration parameters. + data_dim: The dimensions of the data to be modified. First element is the + batch size (number of environments). + device: The device to run the modifier on. + """ + self._cfg = cfg + self._data_dim = data_dim + self._device = device + + @abstractmethod + def reset(self, env_mask: wp.array | None = None): + """Resets the modifier. + + Args: + env_mask: Boolean env mask of shape ``(num_envs,)`` selecting environments + to reset. Defaults to None, in which case all environments are + considered. + """ + raise NotImplementedError + + @abstractmethod + def __call__(self, data: wp.array) -> None: + """Apply the modification in-place. + + Args: + data: The ``wp.array`` buffer to modify. Shape should match the + *data_dim* passed during initialization. + """ + raise NotImplementedError diff --git a/source/isaaclab_experimental/isaaclab_experimental/utils/modifiers/modifier_cfg.py b/source/isaaclab_experimental/isaaclab_experimental/utils/modifiers/modifier_cfg.py new file mode 100644 index 000000000000..7cc22eaee6a9 --- /dev/null +++ b/source/isaaclab_experimental/isaaclab_experimental/utils/modifiers/modifier_cfg.py @@ -0,0 +1,39 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Warp-native modifier configuration (experimental).""" + +from collections.abc import Callable +from dataclasses import MISSING +from typing import Any + +from isaaclab.utils import configclass + + +@configclass +class ModifierCfg: + """Configuration parameters for Warp-native modifiers. + + Experimental fork of :class:`isaaclab.utils.modifiers.ModifierCfg` adapted for the + Warp-first calling convention where modifier functions operate **in-place** on a + ``wp.array`` buffer and return ``None``. + """ + + func: Callable[..., None] = MISSING + """Function or callable class used by modifier. + + The function must take a ``wp.array`` as the first argument and operate on it + **in-place** (no return value). The remaining arguments are specified in the + :attr:`params` attribute. + + It also supports callable classes that implement ``__call__()``. In this case the + class should inherit from :class:`ModifierBase` and implement the required methods. + """ + + params: dict[str, Any] = dict() + """The parameters to be passed to the function or callable class as keyword arguments. + + Defaults to an empty dictionary. + """ diff --git a/source/isaaclab_experimental/isaaclab_experimental/utils/noise/__init__.py b/source/isaaclab_experimental/isaaclab_experimental/utils/noise/__init__.py new file mode 100644 index 000000000000..16aa5ab0733c --- /dev/null +++ b/source/isaaclab_experimental/isaaclab_experimental/utils/noise/__init__.py @@ -0,0 +1,22 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Warp-native noise implementations (experimental). + +Re-exports stable configs and classes, then overrides the function-based +noise models (``constant_noise``, ``uniform_noise``, ``gaussian_noise``) +and their configs with Warp-native versions that operate **in-place** on +``wp.array``. + +Calling convention (matches Warp MDP terms):: + + noise_cfg.func(data_wp, noise_cfg) -> None # in-place on wp.array +""" + +from isaaclab.utils.noise import * # noqa: F401,F403 + +# Override with Warp-native implementations +from .noise_cfg import ConstantNoiseCfg, GaussianNoiseCfg, NoiseCfg, UniformNoiseCfg # noqa: F401 +from .noise_model import NoiseModel, constant_noise, gaussian_noise, uniform_noise # noqa: F401 diff --git a/source/isaaclab_experimental/isaaclab_experimental/utils/noise/noise_cfg.py b/source/isaaclab_experimental/isaaclab_experimental/utils/noise/noise_cfg.py new file mode 100644 index 000000000000..5c7045e65a69 --- /dev/null +++ b/source/isaaclab_experimental/isaaclab_experimental/utils/noise/noise_cfg.py @@ -0,0 +1,72 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Warp-native noise configuration (experimental).""" + +from __future__ import annotations + +from collections.abc import Callable +from dataclasses import MISSING +from typing import Literal + +import warp as wp + +from isaaclab.utils import configclass + +from . import noise_model + + +@configclass +class NoiseCfg: + """Configuration for a Warp-native noise term. + + Experimental fork of :class:`isaaclab.utils.noise.NoiseCfg` adapted for the + Warp-first calling convention where noise functions operate **in-place** on a + ``wp.array`` buffer and return ``None``. + """ + + func: Callable[[wp.array, NoiseCfg], None] = MISSING + """The function to be called for applying the noise. + + The function must take a ``wp.array`` as the first argument and the noise + configuration as the second argument. It operates **in-place** (no return value). + """ + + operation: Literal["add", "scale", "abs"] = "add" + """The operation to apply the noise on the data. Defaults to ``"add"``.""" + + +@configclass +class ConstantNoiseCfg(NoiseCfg): + """Configuration for a constant noise term (Warp-native).""" + + func = noise_model.constant_noise + + bias: float = 0.0 + """The bias to add. Defaults to 0.0.""" + + +@configclass +class UniformNoiseCfg(NoiseCfg): + """Configuration for a uniform noise term (Warp-native).""" + + func = noise_model.uniform_noise + + n_min: float = -1.0 + """The minimum value of the noise. Defaults to -1.0.""" + n_max: float = 1.0 + """The maximum value of the noise. Defaults to 1.0.""" + + +@configclass +class GaussianNoiseCfg(NoiseCfg): + """Configuration for a gaussian noise term (Warp-native).""" + + func = noise_model.gaussian_noise + + mean: float = 0.0 + """The mean of the noise. Defaults to 0.0.""" + std: float = 1.0 + """The standard deviation of the noise. Defaults to 1.0.""" diff --git a/source/isaaclab_experimental/isaaclab_experimental/utils/noise/noise_model.py b/source/isaaclab_experimental/isaaclab_experimental/utils/noise/noise_model.py new file mode 100644 index 000000000000..acba926ea488 --- /dev/null +++ b/source/isaaclab_experimental/isaaclab_experimental/utils/noise/noise_model.py @@ -0,0 +1,200 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Warp-native noise functions and models (experimental). + +Each noise function takes a ``wp.array`` as its first argument and operates **in-place** +via ``wp.launch``. The calling convention mirrors the stable noise interface:: + + noise_cfg.func(data_wp, noise_cfg) -> None + +Random noise kernels (gaussian, uniform) consume the shared per-env Warp RNG state +(``rng_state_wp``) that is set on the config at manager prep time from +``env.rng_state_wp``. See :func:`initialize_rng_state` in +``isaaclab_experimental.envs.manager_based_env_warp`` for the initialization pattern. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +import warp as wp + +if TYPE_CHECKING: + from . import noise_cfg + +## +# Operation mode mapping. +## + +_OPERATION_MAP: dict[str, int] = {"add": 0, "scale": 1, "abs": 2} + +## +# Noise as functions. +## + + +# -- constant ----------------------------------------------------------------- + + +@wp.kernel +def _apply_constant_noise( + out: wp.array(dtype=wp.float32, ndim=2), + bias: wp.float32, + operation: wp.int32, +): + env_id = wp.tid() + for j in range(out.shape[1]): + if operation == 0: + out[env_id, j] = out[env_id, j] + bias + elif operation == 1: + out[env_id, j] = out[env_id, j] * bias + else: + out[env_id, j] = bias + + +def constant_noise(data: wp.array, cfg: noise_cfg.ConstantNoiseCfg) -> None: + """Applies a constant noise bias to a given data set in-place. + + Warp-native drop-in replacement for :func:`isaaclab.utils.noise.constant_noise`. + + Args: + data: The data buffer to modify. Shape ``(num_envs, D)``. + cfg: The configuration parameters for constant noise. + """ + wp.launch( + _apply_constant_noise, + dim=data.shape[0], + inputs=[data, float(cfg.bias), _OPERATION_MAP[cfg.operation]], + device=data.device, + ) + + +# -- uniform ------------------------------------------------------------------ + + +@wp.kernel +def _apply_uniform_noise( + out: wp.array(dtype=wp.float32, ndim=2), + rng_state: wp.array(dtype=wp.uint32), + n_min: wp.float32, + n_max: wp.float32, + operation: wp.int32, +): + env_id = wp.tid() + state = rng_state[env_id] + for j in range(out.shape[1]): + n = wp.randf(state, n_min, n_max) + if operation == 0: + out[env_id, j] = out[env_id, j] + n + elif operation == 1: + out[env_id, j] = out[env_id, j] * n + else: + out[env_id, j] = n + rng_state[env_id] = state + + +def uniform_noise(data: wp.array, cfg: noise_cfg.UniformNoiseCfg) -> None: + """Applies uniform noise to a given data set in-place. + + Warp-native drop-in replacement for :func:`isaaclab.utils.noise.uniform_noise`. + + Args: + data: The data buffer to modify. Shape ``(num_envs, D)``. + cfg: The configuration parameters for uniform noise. + """ + wp.launch( + _apply_uniform_noise, + dim=data.shape[0], + inputs=[data, cfg.rng_state_wp, float(cfg.n_min), float(cfg.n_max), _OPERATION_MAP[cfg.operation]], + device=data.device, + ) + + +# -- gaussian ----------------------------------------------------------------- + + +@wp.kernel +def _apply_gaussian_noise( + out: wp.array(dtype=wp.float32, ndim=2), + rng_state: wp.array(dtype=wp.uint32), + mean: wp.float32, + std: wp.float32, + operation: wp.int32, +): + env_id = wp.tid() + state = rng_state[env_id] + for j in range(out.shape[1]): + n = mean + std * wp.randn(state) + if operation == 0: + out[env_id, j] = out[env_id, j] + n + elif operation == 1: + out[env_id, j] = out[env_id, j] * n + else: + out[env_id, j] = n + rng_state[env_id] = state + + +def gaussian_noise(data: wp.array, cfg: noise_cfg.GaussianNoiseCfg) -> None: + """Applies gaussian noise to a given data set in-place. + + Warp-native drop-in replacement for :func:`isaaclab.utils.noise.gaussian_noise`. + + Args: + data: The data buffer to modify. Shape ``(num_envs, D)``. + cfg: The configuration parameters for gaussian noise. + """ + wp.launch( + _apply_gaussian_noise, + dim=data.shape[0], + inputs=[data, cfg.rng_state_wp, float(cfg.mean), float(cfg.std), _OPERATION_MAP[cfg.operation]], + device=data.device, + ) + + +## +# Noise models as classes. +## + + +class NoiseModel: + """Warp-native base class for noise models. + + Experimental fork of :class:`isaaclab.utils.noise.NoiseModel` adapted for the + Warp-first calling convention where noise is applied **in-place** on ``wp.array``. + """ + + def __init__(self, noise_model_cfg: noise_cfg.NoiseModelCfg, num_envs: int, device: str): + """Initialize the noise model. + + Args: + noise_model_cfg: The noise configuration to use. + num_envs: The number of environments. + device: The device to use for the noise model. + """ + self._noise_model_cfg = noise_model_cfg + self._num_envs = num_envs + self._device = device + + def reset(self, env_mask: wp.array | None = None): + """Reset the noise model. + + This method can be implemented by derived classes to reset the noise model. + This is useful when implementing temporal noise models such as random walk. + + Args: + env_mask: Boolean env mask of shape ``(num_envs,)`` selecting environments + to reset. Defaults to None, in which case all environments are + considered. + """ + pass + + def __call__(self, data: wp.array) -> None: + """Apply the noise to the data in-place. + + Args: + data: The data to apply the noise to. Shape is ``(num_envs, ...)``. + """ + self._noise_model_cfg.noise_cfg.func(data, self._noise_model_cfg.noise_cfg) diff --git a/source/isaaclab_experimental/isaaclab_experimental/utils/torch_utils.py b/source/isaaclab_experimental/isaaclab_experimental/utils/torch_utils.py new file mode 100644 index 000000000000..1e611ec3fef1 --- /dev/null +++ b/source/isaaclab_experimental/isaaclab_experimental/utils/torch_utils.py @@ -0,0 +1,32 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from __future__ import annotations + +import torch + + +def clone_obs_buffer( + obs_buffer: dict[str, torch.Tensor | dict[str, torch.Tensor]], +) -> dict[str, torch.Tensor | dict[str, torch.Tensor]]: + """Clone a nested observation buffer, using :meth:`torch.Tensor.clone` for every leaf tensor. + + This avoids the overhead of :func:`copy.deepcopy` while still producing an independent + snapshot of the buffer (new dict objects + cloned tensor storage). + + Args: + obs_buffer: Observation buffer mapping group names to either a single concatenated + tensor or a dict of per-term tensors. + + Returns: + A new dictionary with the same structure whose tensors are clones of the originals. + """ + result: dict[str, torch.Tensor | dict[str, torch.Tensor]] = {} + for key, value in obs_buffer.items(): + if isinstance(value, torch.Tensor): + result[key] = value.clone() + else: # dict[str, torch.Tensor] + result[key] = {k: v.clone() for k, v in value.items()} + return result diff --git a/source/isaaclab_experimental/isaaclab_experimental/utils/warp/__init__.py b/source/isaaclab_experimental/isaaclab_experimental/utils/warp/__init__.py new file mode 100644 index 000000000000..2d071b823a46 --- /dev/null +++ b/source/isaaclab_experimental/isaaclab_experimental/utils/warp/__init__.py @@ -0,0 +1,16 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Warp utility functions and shared kernels for isaaclab_experimental.""" + +from .kernels import compute_reset_scale, count_masked +from .utils import ( + WarpCapturable, + is_warp_capturable, + resolve_1d_mask, + warp_capturable, + wrap_to_pi, + zero_masked_2d, +) diff --git a/source/isaaclab_experimental/isaaclab_experimental/utils/warp/kernels.py b/source/isaaclab_experimental/isaaclab_experimental/utils/warp/kernels.py new file mode 100644 index 000000000000..8d3f9e65d49a --- /dev/null +++ b/source/isaaclab_experimental/isaaclab_experimental/utils/warp/kernels.py @@ -0,0 +1,45 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Shared Warp kernels used across multiple managers.""" + +from __future__ import annotations + +import warp as wp + + +@wp.kernel +def count_masked( + mask: wp.array(dtype=wp.bool), + out_count: wp.array(dtype=wp.int32), +): + """Count the number of True entries in a boolean mask. + + ``out_count`` must be zeroed before launch. Result is stored in ``out_count[0]``. + Launched with ``dim = num_envs``. + """ + env_id = wp.tid() + if mask[env_id]: + wp.atomic_add(out_count, 0, 1) + + +@wp.kernel +def compute_reset_scale( + reset_count: wp.array(dtype=wp.int32), + divisor: wp.float32, + out_scale: wp.array(dtype=wp.float32), +): + """Compute ``1 / (count * divisor)`` scaling factor from a reset count. + + Pass ``divisor = 1.0`` for plain ``1 / count`` (e.g. command manager). + Pass ``divisor = max_episode_length_s`` for reward-style normalization. + + Launched with ``dim = 1``. + """ + count = reset_count[0] + if count > 0: + out_scale[0] = 1.0 / (wp.float32(count) * divisor) + else: + out_scale[0] = 0.0 diff --git a/source/isaaclab_experimental/isaaclab_experimental/utils/warp/utils.py b/source/isaaclab_experimental/isaaclab_experimental/utils/warp/utils.py new file mode 100644 index 000000000000..a4beb8627ef9 --- /dev/null +++ b/source/isaaclab_experimental/isaaclab_experimental/utils/warp/utils.py @@ -0,0 +1,204 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from __future__ import annotations + +from collections.abc import Sequence + +import torch + +import warp as wp + + +@wp.kernel +def _set_mask_from_ids( + mask: wp.array(dtype=wp.bool), + ids: wp.array(dtype=wp.int32), +): + """Set ``mask[ids[i]] = True`` for each thread *i*.""" + i = wp.tid() + mask[ids[i]] = True + + +def resolve_1d_mask( + *, + ids: Sequence[int] | slice | wp.array | torch.Tensor | None, + mask: wp.array | torch.Tensor | None, + all_mask: wp.array, + scratch_mask: wp.array, + device: str, +) -> wp.array: + """Resolve ids/mask into a warp boolean mask. + + Matches the contract of ``ArticulationData._resolve_1d_mask`` on dev/newton. + Callers must provide pre-allocated ``all_mask`` (all-True) and ``scratch_mask`` + (reusable working buffer). No allocations happen inside this function. + + Args: + ids: Indices to set to ``True``. ``None`` or ``slice(None)`` means all. + mask: Explicit boolean mask. If provided, returned directly (after + torch->warp normalization if needed). Takes precedence over *ids*. + all_mask: Pre-allocated all-True mask of shape ``(size,)``, returned + when both *ids* and *mask* are ``None``. + scratch_mask: Pre-allocated scratch mask of shape ``(size,)``, filled + in-place when *ids* are provided. + device: Warp device string. + + Returns: + A ``wp.array(dtype=wp.bool)`` -- ``mask``, ``all_mask``, or ``scratch_mask``. + """ + # Fast path: explicit mask provided. + if mask is not None: + if isinstance(mask, torch.Tensor): + if mask.dtype != torch.bool: + mask = mask.to(dtype=torch.bool) + if str(mask.device) != device: + mask = mask.to(device) + return wp.from_torch(mask, dtype=wp.bool) + return mask + + # Fast path: all ids. + if ids is None or (isinstance(ids, slice) and ids == slice(None)): + return all_mask + + # Normalize slice into explicit indices. + if isinstance(ids, slice): + start, stop, step = ids.indices(scratch_mask.shape[0]) + ids = list(range(start, stop, step)) + elif not isinstance(ids, (torch.Tensor, wp.array)): + ids = list(ids) + + # Prepare output mask. + scratch_mask.fill_(False) + + # Normalize ids to wp.int32 array and launch kernel. + if isinstance(ids, torch.Tensor): + if ids.numel() == 0: + return scratch_mask + if str(ids.device) != device: + ids = ids.to(device) + if ids.dtype != torch.int32: + ids = ids.to(dtype=torch.int32) + if not ids.is_contiguous(): + ids = ids.contiguous() + ids_wp = wp.from_torch(ids, dtype=wp.int32) + elif isinstance(ids, wp.array): + if ids.shape[0] == 0: + return scratch_mask + ids_wp = ids + else: + if len(ids) == 0: + return scratch_mask + ids_wp = wp.array(ids, dtype=wp.int32, device=device) + + wp.launch(kernel=_set_mask_from_ids, dim=ids_wp.shape[0], inputs=[scratch_mask, ids_wp], device=device) + return scratch_mask + + +def warp_capturable(capturable: bool): + """Annotate an MDP term's CUDA-graph capturability. + + No-wrapper decorator: sets ``_warp_capturable`` directly on the function + and returns it unchanged. Safe to stack with any other decorator in any order. + + By default all MDP terms are assumed capturable (True). Use + ``@warp_capturable(False)`` on terms that call non-capturable external APIs. + """ + + def decorator(func): + func._warp_capturable = capturable + return func + + return decorator + + +def is_warp_capturable(func) -> bool: + """Check if a term function is CUDA-graph-capturable. + + Checks ``_warp_capturable`` on the function and its ``__wrapped__`` target. + Returns True (capturable) by default if no annotation is found. + """ + for f in (func, getattr(func, "__wrapped__", None)): + if f is not None: + val = getattr(f, "_warp_capturable", None) + if val is not None: + return val + return True + + +@wp.func +def wrap_to_pi(angle: float) -> float: + """Wrap input angle (in radians) to the range [-pi, pi].""" + two_pi = 2.0 * wp.pi + wrapped_angle = angle + wp.pi + # NOTE: Use floor-based remainder semantics to match torch's `%` for negative inputs. + wrapped_angle = wrapped_angle - wp.floor(wrapped_angle / two_pi) * two_pi + return wp.where((wrapped_angle == 0) and (angle > 0), wp.pi, wrapped_angle - wp.pi) + + +class WarpCapturable: + """CUDA graph capture safety: decorator, annotation checker, and runtime guard. + + Decorator usage:: + + @WarpCapturable(False) + def reset_root_state_uniform(env, env_mask, ...): + ... + + @WarpCapturable(False, reason="calls write_root_pose_to_sim") + def push_by_setting_velocity(env, env_mask, ...): + ... + + - ``@WarpCapturable(True)`` or no decorator: capturable, returned unwrapped. + - ``@WarpCapturable(False)``: sets ``func._warp_capturable = False``, wraps with + runtime guard that raises if ``wp.get_device().is_capturing`` is ``True``. + """ + + def __init__(self, capturable: bool, *, reason: str | None = None): + self._capturable = capturable + self._reason = reason + + def __call__(self, func): + """Decorate *func* with capture safety annotation and optional runtime guard.""" + import functools + + func._warp_capturable = self._capturable + if self._capturable: + return func + + reason = self._reason + + @functools.wraps(func) + def wrapper(*args, **kwargs): + if wp.get_device().is_capturing: + msg = f"'{func.__qualname__}' is marked @WarpCapturable(False) but called during CUDA graph capture." + if reason: + msg = f"{msg} {reason}" + raise RuntimeError(msg) + return func(*args, **kwargs) + + wrapper._warp_capturable = False + return wrapper + + @staticmethod + def is_capturable(func) -> bool: + """Check capturability annotation. Default: ``True``. + + Checks ``__wrapped__`` for decorated functions to handle stacked decorators. + """ + for f in (func, getattr(func, "__wrapped__", None)): + if f is not None: + val = getattr(f, "_warp_capturable", None) + if val is not None: + return val + return True + + +@wp.kernel +def zero_masked_2d(mask: wp.array(dtype=wp.bool), values: wp.array(dtype=wp.float32, ndim=2)): + """Zero out rows of a 2D float32 array where mask is True.""" + env_id, j = wp.tid() + if mask[env_id]: + values[env_id, j] = 0.0 diff --git a/source/isaaclab_experimental/isaaclab_experimental/utils/warp_graph_cache.py b/source/isaaclab_experimental/isaaclab_experimental/utils/warp_graph_cache.py index d2ac09bd4f70..d446be28d099 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/utils/warp_graph_cache.py +++ b/source/isaaclab_experimental/isaaclab_experimental/utils/warp_graph_cache.py @@ -14,8 +14,12 @@ class WarpGraphCache: """Caches Warp CUDA graphs by stage name: captures on first call, replays after. - On the first call for a given stage, the function is recorded into a CUDA - graph and then **immediately replayed** so the graph is validated right away. + On the very first call for a given stage, an **eager warm-up** run + executes *before* graph capture. This lets one-time initialisation + code (memory allocations, torch dtype casts, ``hasattr`` guards, etc.) + run outside the capture context. Only the steady-state kernel + launches are then recorded into the graph. + The return value from the capture run is cached and returned on every subsequent replay, ensuring captured stages return the same references (e.g. tensor views) as eager stages. @@ -55,13 +59,17 @@ def capture_or_replay( if kwargs is None: kwargs = {} graph = self._graphs.get(stage) - if graph is None: - with wp.ScopedCapture() as capture: - result = fn(*args, **kwargs) - self._graphs[stage] = capture.graph - self._results[stage] = result - wp.capture_launch(self._graphs[stage]) - return self._results[stage] + if graph is not None: + wp.capture_launch(graph) + return self._results[stage] + # Warm-up: run eagerly to flush first-call allocations / hasattr guards. + fn(*args, **kwargs) + # Capture: allocations already done, only wp.launch calls are recorded. + with wp.ScopedCapture() as capture: + result = fn(*args, **kwargs) + self._graphs[stage] = capture.graph + self._results[stage] = result + return result def invalidate(self, stage: str | None = None) -> None: """Drop cached graph(s). If *stage* is ``None``, drop all.""" diff --git a/source/isaaclab_experimental/setup.py b/source/isaaclab_experimental/setup.py index f999fcd026f9..81e8ad2c3c2b 100644 --- a/source/isaaclab_experimental/setup.py +++ b/source/isaaclab_experimental/setup.py @@ -31,14 +31,11 @@ keywords=EXTENSION_TOML_DATA["package"]["keywords"], license="BSD-3-Clause", include_package_data=True, - python_requires=">=3.10", + python_requires=">=3.12", install_requires=INSTALL_REQUIRES, packages=find_packages(), classifiers=[ - "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", - "Isaac Sim :: 5.0.0", - "Isaac Sim :: 5.1.0", "Isaac Sim :: 6.0.0", ], zip_safe=False, diff --git a/source/isaaclab_experimental/test/envs/mdp/parity_helpers.py b/source/isaaclab_experimental/test/envs/mdp/parity_helpers.py new file mode 100644 index 000000000000..9aa219ee4a41 --- /dev/null +++ b/source/isaaclab_experimental/test/envs/mdp/parity_helpers.py @@ -0,0 +1,628 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Shared test utilities for MDP warp-vs-stable parity tests. + +Contains constants, assertion helpers, warp kernel runners, mock classes, +numpy math utilities, and mutation helpers used by the observation, reward, +termination, event, and action parity test files. +""" + +from __future__ import annotations + +import numpy as np +import torch +import warp as wp + +from isaaclab.utils.warp import ProxyArray + +# --------------------------------------------------------------------------- +# Constants (shared across all MDP parity test files) +# --------------------------------------------------------------------------- +NUM_ENVS = 64 +NUM_JOINTS = 12 +NUM_ACTIONS = 6 +DEVICE = "cuda:0" +ATOL = 1e-5 +RTOL = 1e-5 + +# Body/sensor-level defaults shared by observation, reward, and termination tests +NUM_BODIES = 4 +NUM_HISTORY = 3 +CMD_DIM = 3 +BODY_IDS = [0, 2] + +# Gravity direction constant (normalized, same as ArticulationData.GRAVITY_VEC_W) +GRAVITY_DIR_NP = np.array([[0.0, 0.0, -1.0]], dtype=np.float32) + + +# --------------------------------------------------------------------------- +# Numpy math utilities +# --------------------------------------------------------------------------- + + +def quat_rotate_inv_np(q_xyzw: np.ndarray, v: np.ndarray) -> np.ndarray: + """Apply inverse quaternion rotation to vectors (numpy, batch). + + Equivalent to ``wp.quat_rotate_inv`` — rotates *v* by the conjugate of *q*. + + Args: + q_xyzw: (N, 4) quaternion array in [x, y, z, w] order (warp convention). + v: (N, 3) vector array. + + Returns: + (N, 3) rotated vectors in float32. + """ + qv = -q_xyzw[..., :3] # conjugate xyz + qw = q_xyzw[..., 3:4] + t = 2.0 * np.cross(qv, v) + return (v + qw * t + np.cross(qv, t)).astype(np.float32) + + +# --------------------------------------------------------------------------- +# Warp / numpy utilities +# --------------------------------------------------------------------------- + + +def proxy_array(*args, **kwargs) -> ProxyArray: + """Build a :class:`ProxyArray` directly from ``wp.array`` constructor arguments. + + Lets the parity-test mocks read as ``self.joint_pos = proxy_array(np_data, device=...)`` + instead of ``ProxyArray(wp.array(np_data, device=...))``. + """ + return ProxyArray(wp.array(*args, **kwargs)) + + +def copy_np_to_wp(dest: wp.array | ProxyArray, src_np: np.ndarray): + """In-place overwrite of a warp array's contents from numpy (preserves pointer).""" + if isinstance(dest, ProxyArray): + dest = dest.warp + tmp = wp.array(src_np, dtype=dest.dtype, device=str(dest.device)) + wp.copy(dest, tmp) + + +# --------------------------------------------------------------------------- +# Test runner helpers +# --------------------------------------------------------------------------- + + +def run_warp_obs(func, env, shape, device=DEVICE, **kwargs): + """Run a warp observation function and return the result as a torch tensor.""" + out = wp.zeros(shape, dtype=wp.float32, device=device) + func(env, out, **kwargs) + return wp.to_torch(out).clone() + + +def run_warp_obs_captured(func, env, shape, device=DEVICE, **kwargs): + """Run a warp observation function under CUDA graph capture and return the result.""" + out = wp.zeros(shape, dtype=wp.float32, device=device) + func(env, out, **kwargs) # warm-up + with wp.ScopedCapture() as capture: + func(env, out, **kwargs) + wp.capture_launch(capture.graph) + return wp.to_torch(out).clone() + + +def run_warp_rew(func, env, device=DEVICE, **kwargs): + """Run a warp reward function and return the result as a torch tensor.""" + out = wp.zeros((NUM_ENVS,), dtype=wp.float32, device=device) + func(env, out, **kwargs) + return wp.to_torch(out).clone() + + +def run_warp_rew_captured(func, env, device=DEVICE, **kwargs): + """Run a warp reward function under CUDA graph capture.""" + out = wp.zeros((NUM_ENVS,), dtype=wp.float32, device=device) + func(env, out, **kwargs) # warm-up + with wp.ScopedCapture() as capture: + func(env, out, **kwargs) + wp.capture_launch(capture.graph) + return wp.to_torch(out).clone() + + +def run_warp_term(func, env, device=DEVICE, **kwargs): + """Run a warp termination function and return the result as a torch tensor.""" + out = wp.zeros((NUM_ENVS,), dtype=wp.bool, device=device) + func(env, out, **kwargs) + return wp.to_torch(out).clone() + + +def run_warp_term_captured(func, env, device=DEVICE, **kwargs): + """Run a warp termination function under CUDA graph capture.""" + out = wp.zeros((NUM_ENVS,), dtype=wp.bool, device=device) + func(env, out, **kwargs) # warm-up + with wp.ScopedCapture() as capture: + func(env, out, **kwargs) + wp.capture_launch(capture.graph) + return wp.to_torch(out).clone() + + +# --------------------------------------------------------------------------- +# Assertion helpers +# --------------------------------------------------------------------------- + + +def assert_close(actual: torch.Tensor, expected: torch.Tensor, atol: float = ATOL, rtol: float = RTOL): + torch.testing.assert_close(actual, expected, atol=atol, rtol=rtol) + + +def assert_equal(actual: torch.Tensor, expected: torch.Tensor): + assert torch.equal(actual, expected), f"Mismatch:\n actual: {actual}\n expected: {expected}" + + +# --------------------------------------------------------------------------- +# Mock classes (shared across parity test files) +# --------------------------------------------------------------------------- + + +class MockArticulationData: + """Mock articulation data backed by Warp arrays (same storage Newton uses). + + Args: + num_envs: Number of environments. + num_joints: Number of joints. + device: Warp device string. + seed: Random seed for reproducibility. + num_bodies: Number of bodies. When > 0, generates body-level arrays + (body_pose_w, body_lin_acc_w, body_com_pos_b) and multi-body + projected_gravity_b. When 0, projected_gravity_b is root-level + (derived from root quaternion). + """ + + def __init__(self, num_envs=NUM_ENVS, num_joints=NUM_JOINTS, device=DEVICE, seed=42, num_bodies=0): + rng = np.random.RandomState(seed) + + # --- Joint state (float32 2D) --- + self.joint_pos = proxy_array(rng.randn(num_envs, num_joints).astype(np.float32), device=device) + self.joint_vel = proxy_array(rng.randn(num_envs, num_joints).astype(np.float32) * 2.0, device=device) + self.joint_acc = proxy_array(rng.randn(num_envs, num_joints).astype(np.float32) * 0.5, device=device) + self.default_joint_pos = proxy_array(rng.randn(num_envs, num_joints).astype(np.float32) * 0.01, device=device) + self.default_joint_vel = proxy_array(np.zeros((num_envs, num_joints), dtype=np.float32), device=device) + self.applied_torque = proxy_array(rng.randn(num_envs, num_joints).astype(np.float32) * 10.0, device=device) + self.computed_torque = proxy_array(rng.randn(num_envs, num_joints).astype(np.float32) * 10.0, device=device) + + # --- Soft joint limits --- + limits_np = np.zeros((num_envs, num_joints, 2), dtype=np.float32) + limits_np[:, :, 0] = -3.14 + limits_np[:, :, 1] = 3.14 + self.soft_joint_pos_limits = proxy_array(limits_np, dtype=wp.vec2f, device=device) + self.soft_joint_vel_limits = proxy_array(np.full((num_envs, num_joints), 10.0, dtype=np.float32), device=device) + + # --- Root state --- + root_pos_np = rng.randn(num_envs, 3).astype(np.float32) + root_pos_np[:, 2] = np.abs(root_pos_np[:, 2]) + 0.1 # positive heights + self.root_pos_w = proxy_array(root_pos_np, dtype=wp.vec3f, device=device) + + # Unit quaternions + quat_np = rng.randn(num_envs, 4).astype(np.float32) + quat_np /= np.linalg.norm(quat_np, axis=1, keepdims=True) + self.root_quat_w = proxy_array(quat_np, dtype=wp.quatf, device=device) + + # Tier 1 compound: root_link_pose_w (transformf = pos + quat) + pose_np = np.zeros((num_envs, 7), dtype=np.float32) + pose_np[:, :3] = root_pos_np + pose_np[:, 3:] = quat_np + self.root_link_pose_w = proxy_array(pose_np, dtype=wp.transformf, device=device) + + # World-frame velocities + lin_vel_w_np = rng.randn(num_envs, 3).astype(np.float32) + ang_vel_w_np = rng.randn(num_envs, 3).astype(np.float32) + self.root_lin_vel_w = proxy_array(lin_vel_w_np, dtype=wp.vec3f, device=device) + self.root_ang_vel_w = proxy_array(ang_vel_w_np, dtype=wp.vec3f, device=device) + + # Tier 1 compound: root_com_vel_w (spatial_vectorf: top=linear, bottom=angular) + vel_np = np.zeros((num_envs, 6), dtype=np.float32) + vel_np[:, :3] = lin_vel_w_np + vel_np[:, 3:] = ang_vel_w_np + self.root_com_vel_w = proxy_array(vel_np, dtype=wp.spatial_vectorf, device=device) + + # Gravity direction constant (1D array to match kernel signatures) + self.GRAVITY_VEC_W = proxy_array([0.0, 0.0, -1.0], dtype=wp.vec3f, device=device) + + # Derived body-frame quantities (consistent with Tier 1 compounds) + self.root_lin_vel_b = proxy_array(quat_rotate_inv_np(quat_np, lin_vel_w_np), dtype=wp.vec3f, device=device) + self.root_ang_vel_b = proxy_array(quat_rotate_inv_np(quat_np, ang_vel_w_np), dtype=wp.vec3f, device=device) + + # --- projected_gravity_b and body-level data --- + if num_bodies > 0: + # Multi-body projected_gravity_b: (num_envs, num_bodies) vec3f + grav_np = rng.randn(num_envs, num_bodies, 3).astype(np.float32) + grav_np[:, :, 2] = -1.0 + grav_np /= np.linalg.norm(grav_np, axis=2, keepdims=True) + self.projected_gravity_b = proxy_array(grav_np, dtype=wp.vec3f, device=device) + + # body_pose_w: (num_envs, num_bodies) transformf + bpose_np = np.zeros((num_envs, num_bodies, 7), dtype=np.float32) + bpose_np[:, :, :3] = rng.randn(num_envs, num_bodies, 3).astype(np.float32) + bpose_np[:, :, 3:7] = [0.0, 0.0, 0.0, 1.0] + self.body_pose_w = proxy_array(bpose_np, dtype=wp.transformf, device=device) + + # body_lin_acc_w: (num_envs, num_bodies) vec3f + self.body_lin_acc_w = proxy_array( + rng.randn(num_envs, num_bodies, 3).astype(np.float32), dtype=wp.vec3f, device=device + ) + + # body_com_pos_b: (num_envs, num_bodies) vec3f + self.body_com_pos_b = proxy_array( + rng.randn(num_envs, num_bodies, 3).astype(np.float32) * 0.01, dtype=wp.vec3f, device=device + ) + else: + # Root-level projected_gravity_b: (num_envs,) vec3f — derived from root quat + self.projected_gravity_b = proxy_array( + quat_rotate_inv_np(quat_np, np.tile(GRAVITY_DIR_NP, (num_envs, 1))), + dtype=wp.vec3f, + device=device, + ) + + # --- Event-specific data --- + self.root_vel_w = proxy_array( + rng.randn(num_envs, 6).astype(np.float32), dtype=wp.spatial_vectorf, device=device + ) + + default_pose_np = np.zeros((num_envs, 7), dtype=np.float32) + default_pose_np[:, 0:3] = rng.randn(num_envs, 3).astype(np.float32) * 0.1 + default_pose_np[:, 3:7] = [0.0, 0.0, 0.0, 1.0] + self.default_root_pose = proxy_array(default_pose_np, dtype=wp.transformf, device=device) + + self.default_root_vel = proxy_array( + np.zeros((num_envs, 6), dtype=np.float32), dtype=wp.spatial_vectorf, device=device + ) + + def resolve_joint_mask(self, joint_ids=None): + n = self.joint_pos.shape[1] + mask = [False] * n + if joint_ids is None or isinstance(joint_ids, slice): + mask = [True] * n + else: + for j in joint_ids: + mask[j] = True + return wp.array(mask, dtype=wp.bool, device=str(self.joint_pos.device)) + + +class MockWrenchComposer: + """Mock wrench composer with no-op methods.""" + + def set_forces_and_torques_mask(self, *a, **kw): + pass + + +class MockArticulation: + """Mock articulation asset with simulation write stubs. + + Provides both no-op write stubs (for event tests) and tracking write stubs + (for action tests). The ``last_*_target`` attributes record the most recent + values passed to ``set_joint_*_target``, enabling verification in action tests. + """ + + def __init__(self, data: MockArticulationData, num_bodies: int = 1, num_joints: int = NUM_JOINTS): + self.data = data + self.num_bodies = num_bodies + self.num_joints = num_joints + self.device = DEVICE + self._joint_names = [f"joint_{i}" for i in range(num_joints)] + self.permanent_wrench_composer = MockWrenchComposer() + # Tracking attributes for action tests + self.last_pos_target = None + self.last_vel_target = None + self.last_effort_target = None + self.last_joint_mask = None + + # -- Simulation write stubs (no-op, for event tests) -------------------- + + def write_root_velocity_to_sim(self, *a, **kw): + pass + + def write_root_velocity_to_sim_mask(self, *a, **kw): + pass + + def write_root_pose_to_sim(self, *a, **kw): + pass + + def write_root_pose_to_sim_mask(self, *a, **kw): + pass + + def write_joint_state_to_sim(self, *a, **kw): + pass + + def write_joint_position_to_sim_mask(self, *a, **kw): + pass + + def write_joint_velocity_to_sim_mask(self, *a, **kw): + pass + + def set_external_force_and_torque(self, *a, **kw): + pass + + # -- Action write stubs (tracking, for action tests) -------------------- + + def set_joint_position_target(self, target, joint_ids=None, joint_mask=None): + self.last_pos_target = target + self.last_joint_mask = joint_mask + + def set_joint_velocity_target(self, target, joint_ids=None, joint_mask=None): + self.last_vel_target = target + self.last_joint_mask = joint_mask + + def set_joint_effort_target(self, target, joint_ids=None, joint_mask=None): + self.last_effort_target = target + self.last_joint_mask = joint_mask + + def set_joint_position_target_index(self, target, joint_ids=None): + self.last_pos_target = target + + def set_joint_effort_target_index(self, target, joint_ids=None): + self.last_effort_target = target + + # -- Query stubs -------------------------------------------------------- + + def find_joints(self, names, preserve_order=False): + if isinstance(names, list) and names == [".*"]: + return list(range(self.num_joints)), list(self._joint_names) + ids = [] + resolved = [] + for name in names if isinstance(names, list) else [names]: + for i, jn in enumerate(self._joint_names): + if (name in jn or name == jn or name == ".*") and i not in ids: + ids.append(i) + resolved.append(jn) + if not ids: + ids = list(range(self.num_joints)) + resolved = list(self._joint_names) + return ids, resolved + + def find_bodies(self, name): + return [0], [name] + + +class MockScene: + """Mock scene with asset lookup, env origins, and optional sensors.""" + + def __init__(self, assets: dict, env_origins, sensors=None): + self._assets = assets + self.env_origins = env_origins + self.sensors = sensors or {} + self.articulations = dict(assets) + self.rigid_objects = {} + self.num_envs = NUM_ENVS + + def __getitem__(self, name: str): + return self._assets[name] + + +# --------------------------------------------------------------------------- +# Root-state mutation helper +# --------------------------------------------------------------------------- + + +def mutate_root_state(rng: np.random.RandomState, art_data: MockArticulationData, num_envs: int = NUM_ENVS): + """Mutate root-level state arrays in-place (preserves buffer pointers). + + Updates root_pos_w, root_quat_w, root_link_pose_w, root_com_vel_w, + root_lin_vel_w, root_ang_vel_w, root_lin_vel_b, root_ang_vel_b, and + (when 1D) projected_gravity_b — all consistently derived from a fresh + random quaternion and world-frame velocities. + """ + root_pos_np = rng.randn(num_envs, 3).astype(np.float32) + root_pos_np[:, 2] = np.abs(root_pos_np[:, 2]) + 0.05 + copy_np_to_wp(art_data.root_pos_w, root_pos_np) + + quat_np = rng.randn(num_envs, 4).astype(np.float32) + quat_np /= np.linalg.norm(quat_np, axis=1, keepdims=True) + copy_np_to_wp(art_data.root_quat_w, quat_np) + + pose_np = np.zeros((num_envs, 7), dtype=np.float32) + pose_np[:, :3] = root_pos_np + pose_np[:, 3:] = quat_np + copy_np_to_wp(art_data.root_link_pose_w, pose_np) + + lin_vel_w_np = rng.randn(num_envs, 3).astype(np.float32) + ang_vel_w_np = rng.randn(num_envs, 3).astype(np.float32) + copy_np_to_wp(art_data.root_lin_vel_w, lin_vel_w_np) + copy_np_to_wp(art_data.root_ang_vel_w, ang_vel_w_np) + + vel_np = np.zeros((num_envs, 6), dtype=np.float32) + vel_np[:, :3] = lin_vel_w_np + vel_np[:, 3:] = ang_vel_w_np + copy_np_to_wp(art_data.root_com_vel_w, vel_np) + + copy_np_to_wp(art_data.root_lin_vel_b, quat_rotate_inv_np(quat_np, lin_vel_w_np)) + copy_np_to_wp(art_data.root_ang_vel_b, quat_rotate_inv_np(quat_np, ang_vel_w_np)) + + # Root-level projected_gravity_b (1D) is derived from quat. + # Multi-body (2D) is mutated separately by callers. + if art_data.projected_gravity_b.warp.ndim == 1: + copy_np_to_wp( + art_data.projected_gravity_b, + quat_rotate_inv_np(quat_np, np.tile(GRAVITY_DIR_NP, (num_envs, 1))), + ) + + +class MockActionManagerWarp: + """Returns warp arrays (for experimental functions).""" + + def __init__(self, action_wp: wp.array, prev_action_wp: wp.array): + self._action = action_wp + self._prev_action = prev_action_wp + + @property + def action(self) -> wp.array: + return self._action + + @property + def prev_action(self) -> wp.array: + return self._prev_action + + +class MockActionManagerTorch: + """Returns torch tensors (for stable functions).""" + + def __init__(self, action_wp: wp.array, prev_action_wp: wp.array): + self._action = wp.to_torch(action_wp) + self._prev_action = wp.to_torch(prev_action_wp) + + @property + def action(self) -> torch.Tensor: + return self._action + + @property + def prev_action(self) -> torch.Tensor: + return self._prev_action + + +# --------------------------------------------------------------------------- +# Shared mock classes (previously duplicated across test files) +# --------------------------------------------------------------------------- + + +class MockSceneEntityCfg: + """Unified cfg that works for both stable (joint_ids) and experimental (joint_mask / joint_ids_wp).""" + + def __init__(self, name: str, joint_ids: list[int], num_joints: int, device: str): + self.name = name + self.joint_ids = joint_ids + + # Experimental extras + mask = [False] * num_joints + for idx in joint_ids: + mask[idx] = True + self.joint_mask = wp.array(mask, dtype=wp.bool, device=device) + self.joint_ids_wp = wp.array(joint_ids, dtype=wp.int32, device=device) + + +class MockContactSensorData: + """Mock contact sensor data with random force history. + + Stores ``net_forces_w_history`` as a warp ``vec3f`` 3D array of shape + ``(num_envs, num_history, num_bodies)``. Both warp kernels (which read + the warp array directly) and stable functions (which call + ``wp.to_torch``) work with this representation. + """ + + def __init__(self, num_envs=NUM_ENVS, num_history=NUM_HISTORY, num_bodies=NUM_BODIES, device=DEVICE, seed=77): + rng = np.random.RandomState(seed) + self.net_forces_w_history = proxy_array( + rng.randn(num_envs, num_history, num_bodies, 3).astype(np.float32), + dtype=wp.vec3f, + device=device, + ) + + +class MockContactSensor: + """Mock contact sensor wrapping :class:`MockContactSensorData`.""" + + def __init__(self, data: MockContactSensorData, num_bodies: int = NUM_BODIES): + self.data = data + self.num_bodies = num_bodies + + +class MockCommandTerm: + """Mock command term with time_left and command_counter.""" + + def __init__(self, num_envs=NUM_ENVS, device=DEVICE, seed=88): + rng = np.random.RandomState(seed) + self.time_left = torch.tensor(rng.rand(num_envs).astype(np.float32) * 0.05, device=device) + self.command_counter = torch.tensor(rng.randint(0, 3, (num_envs,)), dtype=torch.float32, device=device) + + +class MockCommandManager: + """Mock command manager returning a fixed command tensor and term.""" + + def __init__(self, command_tensor: torch.Tensor, cmd_term: MockCommandTerm): + self._cmd = command_tensor + self._term = cmd_term + + def get_command(self, name: str) -> torch.Tensor: + return self._cmd + + def get_term(self, name: str): + return self._term + + +class MockBodyCfg: + """SceneEntityCfg-like object for body-level reward/termination terms.""" + + def __init__(self, name="robot", body_ids=None): + self.name = name + self.body_ids = body_ids if body_ids is not None else list(BODY_IDS) + + +class MockSensorCfg: + """SceneEntityCfg-like object for contact sensor terms. + + Provides both ``body_ids`` (for stable functions) and ``body_ids_wp`` + (for experimental warp functions). + """ + + def __init__(self, name="contact_sensor", body_ids=None, device=DEVICE): + self.name = name + self.body_ids = body_ids if body_ids is not None else list(BODY_IDS) + self.body_ids_wp = wp.array(self.body_ids, dtype=wp.int32, device=device) + + +class MockTerminationManager: + """Mock termination manager providing both torch and warp terminated buffers.""" + + def __init__(self, num_envs=NUM_ENVS, device=DEVICE): + self.terminated = torch.zeros(num_envs, dtype=torch.bool, device=device) + self.terminated_wp = wp.from_torch(self.terminated) + + +# --------------------------------------------------------------------------- +# Art-data mutation helpers (previously duplicated in obs/rew/term test files) +# --------------------------------------------------------------------------- + + +def mutate_art_data( + art_data: MockArticulationData, + warp_env, + num_envs: int = NUM_ENVS, + num_joints: int = NUM_JOINTS, + num_actions: int = NUM_ACTIONS, + rng_seed: int = 200, +): + """Mutate every data array in-place so captured graphs see fresh values.""" + rng = np.random.RandomState(rng_seed) + + copy_np_to_wp(art_data.joint_pos, rng.randn(num_envs, num_joints).astype(np.float32) * 1.5) + copy_np_to_wp(art_data.joint_vel, rng.randn(num_envs, num_joints).astype(np.float32) * 3.0) + copy_np_to_wp(art_data.joint_acc, rng.randn(num_envs, num_joints).astype(np.float32) * 0.8) + copy_np_to_wp(art_data.default_joint_pos, rng.randn(num_envs, num_joints).astype(np.float32) * 0.02) + copy_np_to_wp(art_data.applied_torque, rng.randn(num_envs, num_joints).astype(np.float32) * 12.0) + copy_np_to_wp(art_data.computed_torque, rng.randn(num_envs, num_joints).astype(np.float32) * 12.0) + + mutate_root_state(rng, art_data, num_envs) + + copy_np_to_wp(warp_env.action_manager._action, rng.randn(num_envs, num_actions).astype(np.float32)) + copy_np_to_wp(warp_env.action_manager._prev_action, rng.randn(num_envs, num_actions).astype(np.float32)) + + warp_env.episode_length_buf[:] = torch.randint(0, 500, (num_envs,), dtype=torch.int64, device=DEVICE) + + wp.synchronize() + + +def mutate_body_data( + art_data: MockArticulationData, + num_envs: int = NUM_ENVS, + num_bodies: int = NUM_BODIES, + rng_seed: int = 200, +): + """Mutate body-level and root-level data in-place so captured graphs see fresh values.""" + rng = np.random.RandomState(rng_seed) + + mutate_root_state(rng, art_data, num_envs) + + grav_np = rng.randn(num_envs, num_bodies, 3).astype(np.float32) + grav_np[:, :, 2] = -1.0 + grav_np /= np.linalg.norm(grav_np, axis=2, keepdims=True) + copy_np_to_wp(art_data.projected_gravity_b, grav_np) + + copy_np_to_wp(art_data.body_lin_acc_w, rng.randn(num_envs, num_bodies, 3).astype(np.float32)) + + pose_np = np.zeros((num_envs, num_bodies, 7), dtype=np.float32) + pose_np[:, :, :3] = rng.randn(num_envs, num_bodies, 3).astype(np.float32) + pose_np[:, :, 3:7] = [0.0, 0.0, 0.0, 1.0] + copy_np_to_wp(art_data.body_pose_w, pose_np) + + wp.synchronize() diff --git a/source/isaaclab_experimental/test/envs/mdp/test_actions_warp_parity.py b/source/isaaclab_experimental/test/envs/mdp/test_actions_warp_parity.py new file mode 100644 index 000000000000..f2db4f64fbe9 --- /dev/null +++ b/source/isaaclab_experimental/test/envs/mdp/test_actions_warp_parity.py @@ -0,0 +1,227 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Parity tests for warp-first action MDP terms.""" + +from __future__ import annotations + +import numpy as np +import pytest +import torch +import warp as wp + +wp.init() +pytestmark = pytest.mark.skipif(not wp.is_cuda_available(), reason="CUDA device required") + +from isaaclab_experimental.envs.mdp.actions import ( + JointEffortAction, + JointEffortActionCfg, + JointPositionAction, + JointPositionActionCfg, +) +from parity_helpers import MockArticulation, MockArticulationData, MockScene, copy_np_to_wp + +NUM_ENVS = 32 +NUM_JOINTS = 6 +NUM_BODIES = 3 +DEVICE = "cuda:0" +ATOL = 1e-5 +RTOL = 1e-5 +JOINT_NAMES = [f"joint_{i}" for i in range(NUM_JOINTS)] + + +# ============================================================================ +# Mock infrastructure +# ============================================================================ + + +class MockEnv: + def __init__(self, asset): + self.scene = MockScene({"robot": asset}, env_origins=None) + self.num_envs = NUM_ENVS + self.device = DEVICE + + +# ============================================================================ +# Fixtures +# ============================================================================ + + +@pytest.fixture() +def art_data(): + data = MockArticulationData(num_envs=NUM_ENVS, num_joints=NUM_JOINTS, num_bodies=NUM_BODIES) + # Override defaults with specific per-joint values for action tests + copy_np_to_wp( + data.default_joint_pos, + np.tile([0.1, 0.2, 0.3, 0.4, 0.5, 0.6], (NUM_ENVS, 1)).astype(np.float32), + ) + # Body quaternion for NonHolonomicAction (identity = [0,0,0,1] in xyzw) + quat_np = np.zeros((NUM_ENVS, NUM_BODIES, 4), dtype=np.float32) + quat_np[:, :, 3] = 1.0 + data.body_quat_w = wp.array(quat_np, dtype=wp.quatf, device=DEVICE) + data._num_joints = NUM_JOINTS + return data + + +@pytest.fixture() +def asset(art_data): + return MockArticulation(art_data, num_bodies=NUM_BODIES, num_joints=NUM_JOINTS) + + +@pytest.fixture() +def env(asset): + return MockEnv(asset) + + +@pytest.fixture() +def actions_wp(): + rng = np.random.RandomState(99) + return wp.array(rng.randn(NUM_ENVS, NUM_JOINTS).astype(np.float32), device=DEVICE) + + +# ============================================================================ +# Helpers +# ============================================================================ + + +def assert_close(actual, expected, atol=ATOL, rtol=RTOL): + if isinstance(actual, wp.array): + actual = wp.to_torch(actual) + if isinstance(expected, wp.array): + expected = wp.to_torch(expected) + torch.testing.assert_close(actual.float(), expected.float(), atol=atol, rtol=rtol) + + +# ============================================================================ +# Joint action tests (JointPosition, JointEffort) +# ============================================================================ + + +class TestJointActions: + """Test JointAction subclasses: process, apply, reset.""" + + def test_joint_effort_process_apply(self, env, asset, actions_wp): + cfg = JointEffortActionCfg(asset_name="robot", joint_names=[".*"]) + term = JointEffortAction(cfg, env) + + term.process_actions(actions_wp, action_offset=0) + term.apply_actions() + + # Processed = raw * scale(1.0) + offset(0.0) = raw + assert_close(term.processed_actions, actions_wp) + assert asset.last_effort_target is not None + + def test_joint_position_default_offset(self, env, asset, art_data, actions_wp): + cfg = JointPositionActionCfg(asset_name="robot", joint_names=[".*"], use_default_offset=True) + term = JointPositionAction(cfg, env) + + term.process_actions(actions_wp, action_offset=0) + term.apply_actions() + + # Processed = raw * 1.0 + default_joint_pos[0] + defaults = art_data.default_joint_pos.torch[0] + raw = wp.to_torch(actions_wp) + expected = raw + defaults.unsqueeze(0) + assert_close(term.processed_actions, expected) + assert asset.last_pos_target is not None + + def test_joint_action_reset(self, env, asset, actions_wp): + cfg = JointEffortActionCfg(asset_name="robot", joint_names=[".*"]) + term = JointEffortAction(cfg, env) + + # Process some actions + term.process_actions(actions_wp, action_offset=0) + assert wp.to_torch(term.raw_actions).abs().sum() > 0 + + # Reset all + term.reset(env_mask=None) + assert_close(term.raw_actions, wp.zeros_like(term.raw_actions)) + + def test_joint_action_reset_masked(self, env, asset, actions_wp): + cfg = JointEffortActionCfg(asset_name="robot", joint_names=[".*"]) + term = JointEffortAction(cfg, env) + + term.process_actions(actions_wp, action_offset=0) + raw_before = wp.to_torch(term.raw_actions).clone() + + # Reset only first half + mask_np = [i < NUM_ENVS // 2 for i in range(NUM_ENVS)] + mask = wp.array(mask_np, dtype=wp.bool, device=DEVICE) + term.reset(env_mask=mask) + + raw_after = wp.to_torch(term.raw_actions) + # First half zeroed + assert_close(raw_after[: NUM_ENVS // 2], torch.zeros(NUM_ENVS // 2, NUM_JOINTS, device=DEVICE)) + # Second half unchanged + assert_close(raw_after[NUM_ENVS // 2 :], raw_before[NUM_ENVS // 2 :]) + + def test_joint_action_with_scale(self, env, asset, actions_wp): + cfg = JointEffortActionCfg(asset_name="robot", joint_names=[".*"], scale=2.5) + term = JointEffortAction(cfg, env) + + term.process_actions(actions_wp, action_offset=0) + + raw = wp.to_torch(actions_wp) + expected = raw * 2.5 + assert_close(term.processed_actions, expected) + + +# ============================================================================ +# Mathematical parity tests: warp processed_actions == raw * scale + offset +# (This is the same formula used by the stable JointAction.process_actions.) +# ============================================================================ + + +class TestJointActionMathParity: + """Verify warp processed_actions match the affine formula raw * scale + offset. + + The stable ``JointAction.process_actions`` computes + ``processed = raw * scale + offset``. These tests verify the warp + implementation produces identical results for various scale/offset + configurations, confirming mathematical parity without needing to + instantiate the stable classes (which require a full env). + """ + + def test_effort_identity(self, env, actions_wp): + """scale=1, offset=0 -> processed == raw.""" + cfg = JointEffortActionCfg(asset_name="robot", joint_names=[".*"]) + term = JointEffortAction(cfg, env) + term.process_actions(actions_wp, action_offset=0) + + raw = wp.to_torch(actions_wp) + expected = raw * 1.0 + 0.0 + assert_close(term.processed_actions, expected) + + def test_effort_with_scale(self, env, actions_wp): + """scale=3.0, offset=0 -> processed == raw * 3.""" + cfg = JointEffortActionCfg(asset_name="robot", joint_names=[".*"], scale=3.0) + term = JointEffortAction(cfg, env) + term.process_actions(actions_wp, action_offset=0) + + raw = wp.to_torch(actions_wp) + expected = raw * 3.0 + assert_close(term.processed_actions, expected) + + def test_position_with_default_offset(self, env, art_data, actions_wp): + """use_default_offset=True -> processed == raw + defaults[0].""" + cfg = JointPositionActionCfg(asset_name="robot", joint_names=[".*"], use_default_offset=True) + term = JointPositionAction(cfg, env) + term.process_actions(actions_wp, action_offset=0) + + raw = wp.to_torch(actions_wp) + defaults = art_data.default_joint_pos.torch[0] + expected = raw * 1.0 + defaults.unsqueeze(0) + assert_close(term.processed_actions, expected) + + def test_position_scale_and_offset(self, env, art_data, actions_wp): + """scale=2, use_default_offset=True -> processed == raw * 2 + defaults[0].""" + cfg = JointPositionActionCfg(asset_name="robot", joint_names=[".*"], scale=2.0, use_default_offset=True) + term = JointPositionAction(cfg, env) + term.process_actions(actions_wp, action_offset=0) + + raw = wp.to_torch(actions_wp) + defaults = art_data.default_joint_pos.torch[0] + expected = raw * 2.0 + defaults.unsqueeze(0) + assert_close(term.processed_actions, expected) diff --git a/source/isaaclab_experimental/test/envs/mdp/test_events_warp_parity.py b/source/isaaclab_experimental/test/envs/mdp/test_events_warp_parity.py new file mode 100644 index 000000000000..24b9eb022665 --- /dev/null +++ b/source/isaaclab_experimental/test/envs/mdp/test_events_warp_parity.py @@ -0,0 +1,340 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Parity tests for warp-first event MDP terms.""" + +from __future__ import annotations + +import numpy as np +import pytest +import torch +import warp as wp + +# Skip entire module if no CUDA device available +wp.init() +pytestmark = pytest.mark.skipif(not wp.is_cuda_available(), reason="CUDA device required") + +import isaaclab_experimental.envs.mdp.events as warp_evt +from parity_helpers import ( + DEVICE, + NUM_ACTIONS, + NUM_ENVS, + NUM_JOINTS, + MockActionManagerTorch, + MockActionManagerWarp, + MockArticulation, + MockArticulationData, + MockScene, + MockSceneEntityCfg, + assert_close, + copy_np_to_wp, +) + +# ============================================================================ +# Fixtures +# ============================================================================ + + +@pytest.fixture(autouse=True) +def _clear_function_caches(): + """Clear first-call caches on warp MDP functions so each test starts fresh. + + Functions that cache warp views via the ``hasattr`` pattern need clearing + between tests to avoid stale references from prior fixtures. + """ + yield + for fn in ( + warp_evt.push_by_setting_velocity, + warp_evt.apply_external_force_torque, + warp_evt.reset_root_state_uniform, + warp_evt.randomize_rigid_body_com, + ): + for attr in list(vars(fn)): + if attr.startswith("_"): + delattr(fn, attr) + + +@pytest.fixture() +def art_data(): + return MockArticulationData(NUM_ENVS, NUM_JOINTS, DEVICE) + + +@pytest.fixture() +def env_origins(): + rng = np.random.RandomState(77) + origins_np = rng.randn(NUM_ENVS, 3).astype(np.float32) + return wp.array(origins_np, dtype=wp.vec3f, device=DEVICE) + + +@pytest.fixture() +def scene(art_data, env_origins): + return MockScene({"robot": MockArticulation(art_data)}, env_origins) + + +@pytest.fixture() +def action_wp(): + rng = np.random.RandomState(99) + a = wp.array(rng.randn(NUM_ENVS, NUM_ACTIONS).astype(np.float32), device=DEVICE) + b = wp.array(rng.randn(NUM_ENVS, NUM_ACTIONS).astype(np.float32), device=DEVICE) + return a, b + + +@pytest.fixture() +def episode_length_buf(): + torch.manual_seed(55) + return torch.randint(0, 500, (NUM_ENVS,), dtype=torch.int64, device=DEVICE) + + +@pytest.fixture() +def warp_env(scene, action_wp, episode_length_buf): + """Env with warp action manager (for experimental functions).""" + + class _Env: + pass + + env = _Env() + env.scene = scene + env.action_manager = MockActionManagerWarp(action_wp[0], action_wp[1]) + env.num_envs = NUM_ENVS + env.device = DEVICE + env.episode_length_buf = episode_length_buf + env.step_dt = 0.02 + env.max_episode_length_s = 10.0 + # RNG state for events (seeded deterministically) + env.rng_state_wp = wp.array(np.arange(NUM_ENVS, dtype=np.uint32) + 42, device=DEVICE) + return env + + +@pytest.fixture() +def stable_env(scene, action_wp, episode_length_buf): + """Env with torch action manager (for stable functions).""" + + class _Env: + pass + + env = _Env() + env.scene = scene + env.action_manager = MockActionManagerTorch(action_wp[0], action_wp[1]) + env.num_envs = NUM_ENVS + env.device = DEVICE + env.episode_length_buf = episode_length_buf + env.step_dt = 0.02 + env.max_episode_length_s = 10.0 + return env + + +@pytest.fixture() +def all_joints_cfg(): + return MockSceneEntityCfg("robot", list(range(NUM_JOINTS)), NUM_JOINTS, DEVICE) + + +# ============================================================================ +# Event parity tests: deterministic (zero-width range) warp vs stable +# ============================================================================ + + +class TestEventParity: + """Verify warp event functions produce the same result as stable torch equivalents. + + Since warp and stable use different RNG implementations, parity is tested using + deterministic (zero-width) ranges where randomness has no effect. Both must + produce ``default + 0`` (offset) or ``default * 1`` (scale), clamped to limits. + """ + + def test_reset_joints_by_offset_parity(self, warp_env, stable_env, art_data, all_joints_cfg): + """Zero-offset: both warp and stable should produce clamped defaults.""" + cfg = all_joints_cfg + mask = wp.array([True] * NUM_ENVS, dtype=wp.bool, device=DEVICE) + + # Set known defaults + new_defaults = np.full((NUM_ENVS, NUM_JOINTS), 0.5, dtype=np.float32) + copy_np_to_wp(art_data.default_joint_pos, new_defaults) + + # Run warp version + warp_evt.reset_joints_by_offset( + warp_env, mask, position_range=(0.0, 0.0), velocity_range=(0.0, 0.0), asset_cfg=cfg + ) + wp.synchronize() + warp_pos = art_data.joint_pos.torch.clone() + warp_vel = art_data.joint_vel.torch.clone() + + # Run stable version (writes via write_joint_position_to_sim_index — which our mock + # does not implement, so we compute the expected result directly) + defaults_t = art_data.default_joint_pos.torch.clone() + limits_t = art_data.soft_joint_pos_limits.torch + vel_limits_t = art_data.soft_joint_vel_limits.torch + expected_pos = defaults_t.clamp(limits_t[..., 0], limits_t[..., 1]) + expected_vel = art_data.default_joint_vel.torch.clone().clamp(-vel_limits_t, vel_limits_t) + + assert_close(warp_pos, expected_pos) + assert_close(warp_vel, expected_vel) + + def test_reset_joints_by_scale_parity(self, warp_env, stable_env, art_data, all_joints_cfg): + """Scale=1.0: both warp and stable should produce clamped defaults.""" + cfg = all_joints_cfg + mask = wp.array([True] * NUM_ENVS, dtype=wp.bool, device=DEVICE) + + # Set known defaults + new_defaults = np.full((NUM_ENVS, NUM_JOINTS), 0.25, dtype=np.float32) + copy_np_to_wp(art_data.default_joint_pos, new_defaults) + + # Run warp version + warp_evt.reset_joints_by_scale( + warp_env, mask, position_range=(1.0, 1.0), velocity_range=(1.0, 1.0), asset_cfg=cfg + ) + wp.synchronize() + warp_pos = art_data.joint_pos.torch.clone() + warp_vel = art_data.joint_vel.torch.clone() + + # Expected: default * 1.0, clamped to limits + defaults_t = art_data.default_joint_pos.torch.clone() + limits_t = art_data.soft_joint_pos_limits.torch + vel_limits_t = art_data.soft_joint_vel_limits.torch + expected_pos = defaults_t.clamp(limits_t[..., 0], limits_t[..., 1]) + expected_vel = art_data.default_joint_vel.torch.clone().clamp(-vel_limits_t, vel_limits_t) + + assert_close(warp_pos, expected_pos) + assert_close(warp_vel, expected_vel) + + +# ============================================================================ +# Event capture-mutate-replay tests (from test_mdp_warp_parity.py) +# ============================================================================ + + +class TestEventCapturedDataMutation: + """Verify event functions are capture-safe and react to mutated input data.""" + + # -- reset_joints_by_offset ------------------------------------------------- + + def test_reset_joints_by_offset(self, warp_env, art_data, all_joints_cfg): + """With zero-width offset, result == defaults. Mutate defaults -> result tracks.""" + cfg = all_joints_cfg + mask = wp.array([True] * NUM_ENVS, dtype=wp.bool, device=DEVICE) + + # Warm-up + warp_evt.reset_joints_by_offset( + warp_env, mask, position_range=(0.0, 0.0), velocity_range=(0.0, 0.0), asset_cfg=cfg + ) + + # Capture + with wp.ScopedCapture() as cap: + warp_evt.reset_joints_by_offset( + warp_env, mask, position_range=(0.0, 0.0), velocity_range=(0.0, 0.0), asset_cfg=cfg + ) + + # Mutate defaults in-place + new_defaults = np.full((NUM_ENVS, NUM_JOINTS), 0.5, dtype=np.float32) + copy_np_to_wp(art_data.default_joint_pos, new_defaults) + + # Replay + wp.capture_launch(cap.graph) + wp.synchronize() + + # With zero offset, joint_pos should equal new defaults (clamped to limits [-3.14, 3.14]) + result = art_data.joint_pos.torch + expected = torch.full((NUM_ENVS, NUM_JOINTS), 0.5, device=DEVICE) + assert_close(result, expected) + + # -- reset_joints_by_scale -------------------------------------------------- + + def test_reset_joints_by_scale(self, warp_env, art_data, all_joints_cfg): + """With scale=1.0, result == defaults. Mutate defaults -> result tracks.""" + cfg = all_joints_cfg + mask = wp.array([True] * NUM_ENVS, dtype=wp.bool, device=DEVICE) + + warp_evt.reset_joints_by_scale( + warp_env, mask, position_range=(1.0, 1.0), velocity_range=(1.0, 1.0), asset_cfg=cfg + ) + with wp.ScopedCapture() as cap: + warp_evt.reset_joints_by_scale( + warp_env, mask, position_range=(1.0, 1.0), velocity_range=(1.0, 1.0), asset_cfg=cfg + ) + + new_defaults = np.full((NUM_ENVS, NUM_JOINTS), 0.25, dtype=np.float32) + copy_np_to_wp(art_data.default_joint_pos, new_defaults) + + wp.capture_launch(cap.graph) + wp.synchronize() + + result = art_data.joint_pos.torch + expected = torch.full((NUM_ENVS, NUM_JOINTS), 0.25, device=DEVICE) + assert_close(result, expected) + + # -- push_by_setting_velocity ----------------------------------------------- + + def test_push_by_setting_velocity(self, warp_env, art_data, all_joints_cfg): + """With zero-width velocity range, scratch == root_vel_w. Mutate root_vel_w -> scratch tracks.""" + mask = wp.array([True] * NUM_ENVS, dtype=wp.bool, device=DEVICE) + zero_range = { + "x": (0.0, 0.0), + "y": (0.0, 0.0), + "z": (0.0, 0.0), + "roll": (0.0, 0.0), + "pitch": (0.0, 0.0), + "yaw": (0.0, 0.0), + } + + warp_evt.push_by_setting_velocity(warp_env, mask, velocity_range=zero_range) + with wp.ScopedCapture() as cap: + warp_evt.push_by_setting_velocity(warp_env, mask, velocity_range=zero_range) + + # Mutate root_vel_w + new_vel = np.tile([1.0, 2.0, 3.0, 0.1, 0.2, 0.3], (NUM_ENVS, 1)).astype(np.float32) + copy_np_to_wp(art_data.root_vel_w, new_vel) + + wp.capture_launch(cap.graph) + wp.synchronize() + + scratch = wp.to_torch(warp_evt.push_by_setting_velocity._scratch_vel) + expected = torch.tensor([1.0, 2.0, 3.0, 0.1, 0.2, 0.3], device=DEVICE).expand(NUM_ENVS, -1) + assert_close(scratch, expected) + + # -- apply_external_force_torque -------------------------------------------- + + def test_apply_external_force_torque(self, warp_env, art_data, all_joints_cfg): + """With zero-width ranges, forces/torques are zero. Non-zero ranges produce non-zero output.""" + mask = wp.array([True] * NUM_ENVS, dtype=wp.bool, device=DEVICE) + + # Zero-range: forces and torques should be zero + warp_evt.apply_external_force_torque(warp_env, mask, force_range=(0.0, 0.0), torque_range=(0.0, 0.0)) + with wp.ScopedCapture() as cap: + warp_evt.apply_external_force_torque(warp_env, mask, force_range=(0.0, 0.0), torque_range=(0.0, 0.0)) + wp.capture_launch(cap.graph) + wp.synchronize() + + forces = wp.to_torch(warp_evt.apply_external_force_torque._scratch_forces) + torques = wp.to_torch(warp_evt.apply_external_force_torque._scratch_torques) + assert_close(forces, torch.zeros_like(forces)) + assert_close(torques, torch.zeros_like(torques)) + + # -- reset_root_state_uniform ----------------------------------------------- + + # -- env_mask selectivity --------------------------------------------------- + + def test_reset_joints_mask_selectivity(self, warp_env, art_data, all_joints_cfg): + """Only masked envs are modified; unmasked envs retain their state.""" + cfg = all_joints_cfg + # Mask: only first half of envs + mask_np = np.array([i < NUM_ENVS // 2 for i in range(NUM_ENVS)]) + mask = wp.array(mask_np, dtype=wp.bool, device=DEVICE) + + # Set joint_pos to a known value + sentinel = np.full((NUM_ENVS, NUM_JOINTS), 999.0, dtype=np.float32) + copy_np_to_wp(art_data.joint_pos, sentinel) + + # Set defaults to 0 + copy_np_to_wp(art_data.default_joint_pos, np.zeros((NUM_ENVS, NUM_JOINTS), dtype=np.float32)) + + warp_evt.reset_joints_by_offset( + warp_env, mask, position_range=(0.0, 0.0), velocity_range=(0.0, 0.0), asset_cfg=cfg + ) + wp.synchronize() + + result = art_data.joint_pos.torch + # Masked envs: reset to 0 (defaults + 0 offset) + assert_close(result[: NUM_ENVS // 2], torch.zeros(NUM_ENVS // 2, NUM_JOINTS, device=DEVICE)) + # Unmasked envs: still 999.0 + assert_close(result[NUM_ENVS // 2 :], torch.full((NUM_ENVS // 2, NUM_JOINTS), 999.0, device=DEVICE)) diff --git a/source/isaaclab_experimental/test/envs/mdp/test_observations_warp_parity.py b/source/isaaclab_experimental/test/envs/mdp/test_observations_warp_parity.py new file mode 100644 index 000000000000..9f1eea23bf8d --- /dev/null +++ b/source/isaaclab_experimental/test/envs/mdp/test_observations_warp_parity.py @@ -0,0 +1,458 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Parity tests for warp-first observation MDP terms.""" + +from __future__ import annotations + +import numpy as np +import pytest +import torch +import warp as wp + +# Skip entire module if no CUDA device available +wp.init() +pytestmark = pytest.mark.skipif(not wp.is_cuda_available(), reason="CUDA device required") + +import isaaclab_experimental.envs.mdp.observations as warp_obs +from parity_helpers import ( + CMD_DIM, + DEVICE, + NUM_ACTIONS, + NUM_BODIES, + NUM_ENVS, + NUM_JOINTS, + MockActionManagerTorch, + MockActionManagerWarp, + MockArticulation, + MockArticulationData, + MockCommandManager, + MockCommandTerm, + MockContactSensor, + MockContactSensorData, + MockScene, + MockSceneEntityCfg, + assert_close, + mutate_art_data, + run_warp_obs, + run_warp_obs_captured, +) + +import isaaclab.envs.mdp.observations as stable_obs + +# ============================================================================ +# Fixtures +# ============================================================================ + + +@pytest.fixture(autouse=True) +def _clear_caches(): + yield + for fn in [warp_obs.generated_commands]: + for attr in list(vars(fn)): + if attr.startswith("_"): + delattr(fn, attr) + + +@pytest.fixture() +def art_data(): + return MockArticulationData(NUM_ENVS, NUM_JOINTS, DEVICE) + + +@pytest.fixture() +def art_data_bodies(): + return MockArticulationData(num_bodies=NUM_BODIES) + + +@pytest.fixture() +def env_origins(): + rng = np.random.RandomState(77) + origins_np = rng.randn(NUM_ENVS, 3).astype(np.float32) + return wp.array(origins_np, dtype=wp.vec3f, device=DEVICE) + + +@pytest.fixture() +def contact_data(): + return MockContactSensorData() + + +@pytest.fixture() +def cmd_tensor(): + rng = np.random.RandomState(99) + return torch.tensor(rng.randn(NUM_ENVS, CMD_DIM).astype(np.float32), device=DEVICE) + + +@pytest.fixture() +def cmd_term(): + return MockCommandTerm() + + +@pytest.fixture() +def scene(art_data, env_origins): + return MockScene({"robot": MockArticulation(art_data)}, env_origins) + + +@pytest.fixture() +def scene_bodies(art_data_bodies, env_origins, contact_data): + art = MockArticulation(art_data_bodies, num_bodies=NUM_BODIES) + sensor = MockContactSensor(contact_data) + return MockScene({"robot": art}, env_origins, sensors={"contact_sensor": sensor}) + + +@pytest.fixture() +def action_wp(): + rng = np.random.RandomState(99) + a = wp.array(rng.randn(NUM_ENVS, NUM_ACTIONS).astype(np.float32), device=DEVICE) + b = wp.array(rng.randn(NUM_ENVS, NUM_ACTIONS).astype(np.float32), device=DEVICE) + return a, b # (action, prev_action) + + +@pytest.fixture() +def episode_length_buf(): + torch.manual_seed(55) + return torch.randint(0, 500, (NUM_ENVS,), dtype=torch.int64, device=DEVICE) + + +@pytest.fixture() +def warp_env(scene, action_wp, episode_length_buf): + """Env with warp action manager (for experimental functions).""" + + class _Env: + pass + + env = _Env() + env.scene = scene + env.action_manager = MockActionManagerWarp(action_wp[0], action_wp[1]) + env.num_envs = NUM_ENVS + env.device = DEVICE + env.episode_length_buf = episode_length_buf + env.step_dt = 0.02 + env.max_episode_length_s = 10.0 + env.rng_state_wp = wp.array(np.arange(NUM_ENVS, dtype=np.uint32) + 42, device=DEVICE) + return env + + +@pytest.fixture() +def stable_env(scene, action_wp, episode_length_buf): + """Env with torch action manager (for stable functions).""" + + class _Env: + pass + + env = _Env() + env.scene = scene + env.action_manager = MockActionManagerTorch(action_wp[0], action_wp[1]) + env.num_envs = NUM_ENVS + env.device = DEVICE + env.episode_length_buf = episode_length_buf + env.step_dt = 0.02 + env.max_episode_length_s = 10.0 + return env + + +@pytest.fixture() +def warp_env_bodies(scene_bodies, action_wp, episode_length_buf, cmd_tensor, cmd_term): + """Env with body-level data and command manager (for new-terms observation tests).""" + + class _Env: + pass + + env = _Env() + env.scene = scene_bodies + env.action_manager = MockActionManagerWarp(action_wp[0], action_wp[1]) + env.command_manager = MockCommandManager(cmd_tensor, cmd_term) + env.num_envs = NUM_ENVS + env.device = DEVICE + env.episode_length_buf = episode_length_buf + env.step_dt = 0.02 + env.max_episode_length = 500 + env.max_episode_length_s = 10.0 + env.rng_state_wp = wp.array(np.arange(NUM_ENVS, dtype=np.uint32) + 42, device=DEVICE) + return env + + +@pytest.fixture() +def stable_env_bodies(scene_bodies, action_wp, episode_length_buf, cmd_tensor, cmd_term): + """Env with body-level data and command manager (for stable new-terms observation tests).""" + + class _Env: + pass + + env = _Env() + env.scene = scene_bodies + env.action_manager = MockActionManagerWarp(action_wp[0], action_wp[1]) + env.command_manager = MockCommandManager(cmd_tensor, cmd_term) + env.num_envs = NUM_ENVS + env.device = DEVICE + env.episode_length_buf = episode_length_buf + env.step_dt = 0.02 + env.max_episode_length = 500 + env.max_episode_length_s = 10.0 + return env + + +@pytest.fixture() +def all_joints_cfg(): + return MockSceneEntityCfg("robot", list(range(NUM_JOINTS)), NUM_JOINTS, DEVICE) + + +@pytest.fixture() +def subset_cfg(): + return MockSceneEntityCfg("robot", [0, 2, 5, 8], NUM_JOINTS, DEVICE) + + +# ============================================================================ +# Observation parity tests (from test_mdp_warp_parity.py) +# ============================================================================ + + +class TestObservationParity: + """Verify experimental observation Warp kernels match stable torch implementations.""" + + # -- Root state observations ------------------------------------------------ + + def test_base_pos_z(self, warp_env, stable_env, all_joints_cfg): + cfg = all_joints_cfg + expected = stable_obs.base_pos_z(stable_env, asset_cfg=cfg) + actual = run_warp_obs(warp_obs.base_pos_z, warp_env, (NUM_ENVS, 1), asset_cfg=cfg) + actual_cap = run_warp_obs_captured(warp_obs.base_pos_z, warp_env, (NUM_ENVS, 1), asset_cfg=cfg) + assert_close(actual, expected) + assert_close(actual_cap, expected) + + def test_base_lin_vel(self, warp_env, stable_env, all_joints_cfg): + cfg = all_joints_cfg + expected = stable_obs.base_lin_vel(stable_env, asset_cfg=cfg) + actual = run_warp_obs(warp_obs.base_lin_vel, warp_env, (NUM_ENVS, 3), asset_cfg=cfg) + actual_cap = run_warp_obs_captured(warp_obs.base_lin_vel, warp_env, (NUM_ENVS, 3), asset_cfg=cfg) + assert_close(actual, expected) + assert_close(actual_cap, expected) + + def test_base_ang_vel(self, warp_env, stable_env, all_joints_cfg): + cfg = all_joints_cfg + expected = stable_obs.base_ang_vel(stable_env, asset_cfg=cfg) + actual = run_warp_obs(warp_obs.base_ang_vel, warp_env, (NUM_ENVS, 3), asset_cfg=cfg) + actual_cap = run_warp_obs_captured(warp_obs.base_ang_vel, warp_env, (NUM_ENVS, 3), asset_cfg=cfg) + assert_close(actual, expected) + assert_close(actual_cap, expected) + + def test_projected_gravity(self, warp_env, stable_env, all_joints_cfg): + cfg = all_joints_cfg + expected = stable_obs.projected_gravity(stable_env, asset_cfg=cfg) + actual = run_warp_obs(warp_obs.projected_gravity, warp_env, (NUM_ENVS, 3), asset_cfg=cfg) + actual_cap = run_warp_obs_captured(warp_obs.projected_gravity, warp_env, (NUM_ENVS, 3), asset_cfg=cfg) + assert_close(actual, expected) + assert_close(actual_cap, expected) + + # -- Joint observations (all joints) ---------------------------------------- + + def test_joint_pos_all(self, warp_env, stable_env, all_joints_cfg): + cfg = all_joints_cfg + expected = stable_obs.joint_pos(stable_env, asset_cfg=cfg) + actual = run_warp_obs(warp_obs.joint_pos, warp_env, (NUM_ENVS, NUM_JOINTS), asset_cfg=cfg) + actual_cap = run_warp_obs_captured(warp_obs.joint_pos, warp_env, (NUM_ENVS, NUM_JOINTS), asset_cfg=cfg) + assert_close(actual, expected) + assert_close(actual_cap, expected) + + def test_joint_vel_all(self, warp_env, stable_env, all_joints_cfg): + cfg = all_joints_cfg + expected = stable_obs.joint_vel(stable_env, asset_cfg=cfg) + actual = run_warp_obs(warp_obs.joint_vel, warp_env, (NUM_ENVS, NUM_JOINTS), asset_cfg=cfg) + actual_cap = run_warp_obs_captured(warp_obs.joint_vel, warp_env, (NUM_ENVS, NUM_JOINTS), asset_cfg=cfg) + assert_close(actual, expected) + assert_close(actual_cap, expected) + + # -- Joint observations (subset) ------------------------------------------- + + def test_joint_pos_subset(self, warp_env, stable_env, subset_cfg): + cfg = subset_cfg + n_selected = len(cfg.joint_ids) + expected = stable_obs.joint_pos(stable_env, asset_cfg=cfg) + actual = run_warp_obs(warp_obs.joint_pos, warp_env, (NUM_ENVS, n_selected), asset_cfg=cfg) + actual_cap = run_warp_obs_captured(warp_obs.joint_pos, warp_env, (NUM_ENVS, n_selected), asset_cfg=cfg) + assert_close(actual, expected) + assert_close(actual_cap, expected) + + def test_joint_vel_subset(self, warp_env, stable_env, subset_cfg): + cfg = subset_cfg + n_selected = len(cfg.joint_ids) + expected = stable_obs.joint_vel(stable_env, asset_cfg=cfg) + actual = run_warp_obs(warp_obs.joint_vel, warp_env, (NUM_ENVS, n_selected), asset_cfg=cfg) + actual_cap = run_warp_obs_captured(warp_obs.joint_vel, warp_env, (NUM_ENVS, n_selected), asset_cfg=cfg) + assert_close(actual, expected) + assert_close(actual_cap, expected) + + # -- Normalized joint position ---------------------------------------------- + + def test_joint_pos_limit_normalized(self, warp_env, stable_env, all_joints_cfg): + cfg = all_joints_cfg + expected = stable_obs.joint_pos_limit_normalized(stable_env, asset_cfg=cfg) + actual = run_warp_obs(warp_obs.joint_pos_limit_normalized, warp_env, (NUM_ENVS, NUM_JOINTS), asset_cfg=cfg) + actual_cap = run_warp_obs_captured( + warp_obs.joint_pos_limit_normalized, warp_env, (NUM_ENVS, NUM_JOINTS), asset_cfg=cfg + ) + assert_close(actual, expected) + assert_close(actual_cap, expected) + + # -- Action observation ----------------------------------------------------- + + def test_last_action(self, warp_env, stable_env, action_wp): + # Stable last_action returns env.action_manager.action (torch tensor) + expected = stable_obs.last_action(stable_env) + actual = run_warp_obs(warp_obs.last_action, warp_env, (NUM_ENVS, NUM_ACTIONS)) + actual_cap = run_warp_obs_captured(warp_obs.last_action, warp_env, (NUM_ENVS, NUM_ACTIONS)) + assert_close(actual, expected) + assert_close(actual_cap, expected) + + +# ============================================================================ +# Observation parity tests (from test_mdp_warp_parity_new_terms.py) +# ============================================================================ + + +class TestObservationParityNewTerms: + """Verify observation Warp kernels for newly migrated terms match stable torch implementations.""" + + def test_generated_commands(self, warp_env_bodies, stable_env_bodies): + expected = stable_obs.generated_commands(stable_env_bodies, command_name="vel") + actual = run_warp_obs(warp_obs.generated_commands, warp_env_bodies, (NUM_ENVS, CMD_DIM), command_name="vel") + actual_cap = run_warp_obs_captured( + warp_obs.generated_commands, warp_env_bodies, (NUM_ENVS, CMD_DIM), command_name="vel" + ) + assert_close(actual, expected) + assert_close(actual_cap, expected) + + +# ============================================================================ +# Capture-then-mutate-then-replay observation tests (from test_mdp_warp_parity.py) +# ============================================================================ + + +def _mutate_art_data(art_data: MockArticulationData, warp_env, rng_seed: int = 200): + """Mutate every data array in-place so captured graphs see fresh values.""" + mutate_art_data(art_data, warp_env, rng_seed=rng_seed) + + +class TestCapturedDataMutationObservations: + """Capture a graph, mutate buffer data in-place, replay -- results must match stable on the *new* data. + + This verifies observation MDP functions are truly capture-safe. + """ + + def _capture_mutate_check_obs(self, warp_fn, stable_fn, warp_env, stable_env, art_data, shape, **kwargs): + out = wp.zeros(shape, dtype=wp.float32, device=DEVICE) + warp_fn(warp_env, out, **kwargs) # warm-up + with wp.ScopedCapture() as cap: + warp_fn(warp_env, out, **kwargs) + _mutate_art_data(art_data, warp_env) + wp.capture_launch(cap.graph) + assert_close(wp.to_torch(out).clone(), stable_fn(stable_env, **kwargs)) + + def test_base_pos_z(self, warp_env, stable_env, art_data, all_joints_cfg): + self._capture_mutate_check_obs( + warp_obs.base_pos_z, + stable_obs.base_pos_z, + warp_env, + stable_env, + art_data, + (NUM_ENVS, 1), + asset_cfg=all_joints_cfg, + ) + + def test_base_lin_vel(self, warp_env, stable_env, art_data, all_joints_cfg): + self._capture_mutate_check_obs( + warp_obs.base_lin_vel, + stable_obs.base_lin_vel, + warp_env, + stable_env, + art_data, + (NUM_ENVS, 3), + asset_cfg=all_joints_cfg, + ) + + def test_base_ang_vel(self, warp_env, stable_env, art_data, all_joints_cfg): + self._capture_mutate_check_obs( + warp_obs.base_ang_vel, + stable_obs.base_ang_vel, + warp_env, + stable_env, + art_data, + (NUM_ENVS, 3), + asset_cfg=all_joints_cfg, + ) + + def test_projected_gravity(self, warp_env, stable_env, art_data, all_joints_cfg): + self._capture_mutate_check_obs( + warp_obs.projected_gravity, + stable_obs.projected_gravity, + warp_env, + stable_env, + art_data, + (NUM_ENVS, 3), + asset_cfg=all_joints_cfg, + ) + + def test_joint_pos(self, warp_env, stable_env, art_data, all_joints_cfg): + self._capture_mutate_check_obs( + warp_obs.joint_pos, + stable_obs.joint_pos, + warp_env, + stable_env, + art_data, + (NUM_ENVS, NUM_JOINTS), + asset_cfg=all_joints_cfg, + ) + + def test_joint_vel(self, warp_env, stable_env, art_data, all_joints_cfg): + self._capture_mutate_check_obs( + warp_obs.joint_vel, + stable_obs.joint_vel, + warp_env, + stable_env, + art_data, + (NUM_ENVS, NUM_JOINTS), + asset_cfg=all_joints_cfg, + ) + + def test_joint_pos_limit_normalized(self, warp_env, stable_env, art_data, all_joints_cfg): + self._capture_mutate_check_obs( + warp_obs.joint_pos_limit_normalized, + stable_obs.joint_pos_limit_normalized, + warp_env, + stable_env, + art_data, + (NUM_ENVS, NUM_JOINTS), + asset_cfg=all_joints_cfg, + ) + + def test_last_action(self, warp_env, stable_env, art_data): + self._capture_mutate_check_obs( + warp_obs.last_action, + stable_obs.last_action, + warp_env, + stable_env, + art_data, + (NUM_ENVS, NUM_ACTIONS), + ) + + +# ============================================================================ +# Capture-mutate-replay observation tests (from test_mdp_warp_parity_new_terms.py) +# ============================================================================ + + +class TestCapturedDataMutationObservationsNewTerms: + """Capture graph, mutate buffer data, replay -- verify new-terms observation results match stable.""" + + def test_generated_commands(self, warp_env_bodies, stable_env_bodies, art_data_bodies, cmd_tensor): + """Mutate command tensor, replay captured graph, verify new commands are read.""" + out = wp.zeros((NUM_ENVS, CMD_DIM), dtype=wp.float32, device=DEVICE) + warp_obs.generated_commands(warp_env_bodies, out, command_name="vel") + with wp.ScopedCapture() as cap: + warp_obs.generated_commands(warp_env_bodies, out, command_name="vel") + # Mutate the command tensor in-place (zero-copy view picks it up) + cmd_tensor[:] = torch.randn_like(cmd_tensor) + wp.capture_launch(cap.graph) + expected = stable_obs.generated_commands(stable_env_bodies, command_name="vel") + assert_close(wp.to_torch(out).clone(), expected) diff --git a/source/isaaclab_experimental/test/envs/mdp/test_rewards_warp_parity.py b/source/isaaclab_experimental/test/envs/mdp/test_rewards_warp_parity.py new file mode 100644 index 000000000000..69cabcd14a36 --- /dev/null +++ b/source/isaaclab_experimental/test/envs/mdp/test_rewards_warp_parity.py @@ -0,0 +1,567 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Parity tests for warp-first reward MDP terms.""" + +from __future__ import annotations + +import numpy as np +import pytest +import torch +import warp as wp + +# Skip entire module if no CUDA device available +wp.init() +pytestmark = pytest.mark.skipif(not wp.is_cuda_available(), reason="CUDA device required") + +import isaaclab_experimental.envs.mdp.rewards as warp_rew +from parity_helpers import ( + BODY_IDS, + CMD_DIM, + DEVICE, + NUM_ACTIONS, + NUM_BODIES, + NUM_ENVS, + NUM_JOINTS, + MockActionManagerTorch, + MockActionManagerWarp, + MockArticulation, + MockArticulationData, + MockBodyCfg, + MockCommandManager, + MockCommandTerm, + MockContactSensor, + MockContactSensorData, + MockScene, + MockSceneEntityCfg, + MockSensorCfg, + MockTerminationManager, + assert_close, + mutate_art_data, + mutate_body_data, + run_warp_rew, + run_warp_rew_captured, +) + +import isaaclab.envs.mdp.rewards as stable_rew + +# ============================================================================ +# Fixtures +# ============================================================================ + + +@pytest.fixture(autouse=True) +def _clear_caches(): + yield + for fn in [warp_rew.track_lin_vel_xy_exp, warp_rew.track_ang_vel_z_exp, warp_rew.undesired_contacts]: + for attr in list(vars(fn)): + if attr.startswith("_"): + delattr(fn, attr) + + +@pytest.fixture() +def art_data(): + return MockArticulationData(NUM_ENVS, NUM_JOINTS, DEVICE) + + +@pytest.fixture() +def art_data_bodies(): + return MockArticulationData(num_bodies=NUM_BODIES) + + +@pytest.fixture() +def env_origins(): + rng = np.random.RandomState(77) + origins_np = rng.randn(NUM_ENVS, 3).astype(np.float32) + return wp.array(origins_np, dtype=wp.vec3f, device=DEVICE) + + +@pytest.fixture() +def contact_data(): + return MockContactSensorData() + + +@pytest.fixture() +def cmd_tensor(): + rng = np.random.RandomState(99) + return torch.tensor(rng.randn(NUM_ENVS, CMD_DIM).astype(np.float32), device=DEVICE) + + +@pytest.fixture() +def cmd_term(): + return MockCommandTerm() + + +@pytest.fixture() +def scene(art_data, env_origins): + return MockScene({"robot": MockArticulation(art_data)}, env_origins) + + +@pytest.fixture() +def scene_bodies(art_data_bodies, env_origins, contact_data): + art = MockArticulation(art_data_bodies, num_bodies=NUM_BODIES) + sensor = MockContactSensor(contact_data) + return MockScene({"robot": art}, env_origins, sensors={"contact_sensor": sensor}) + + +@pytest.fixture() +def action_wp(): + rng = np.random.RandomState(99) + a = wp.array(rng.randn(NUM_ENVS, NUM_ACTIONS).astype(np.float32), device=DEVICE) + b = wp.array(rng.randn(NUM_ENVS, NUM_ACTIONS).astype(np.float32), device=DEVICE) + return a, b + + +@pytest.fixture() +def episode_length_buf(): + torch.manual_seed(55) + return torch.randint(0, 500, (NUM_ENVS,), dtype=torch.int64, device=DEVICE) + + +@pytest.fixture() +def term_mgr(): + return MockTerminationManager() + + +@pytest.fixture() +def warp_env(scene, action_wp, episode_length_buf, term_mgr): + """Env with warp action manager (for experimental functions).""" + + class _Env: + pass + + env = _Env() + env.scene = scene + env.action_manager = MockActionManagerWarp(action_wp[0], action_wp[1]) + env.termination_manager = term_mgr + env.num_envs = NUM_ENVS + env.device = DEVICE + env.episode_length_buf = episode_length_buf + env.step_dt = 0.02 + env.max_episode_length_s = 10.0 + env.rng_state_wp = wp.array(np.arange(NUM_ENVS, dtype=np.uint32) + 42, device=DEVICE) + return env + + +@pytest.fixture() +def stable_env(scene, action_wp, episode_length_buf, term_mgr): + """Env with torch action manager (for stable functions).""" + + class _Env: + pass + + env = _Env() + env.scene = scene + env.action_manager = MockActionManagerTorch(action_wp[0], action_wp[1]) + env.termination_manager = term_mgr + env.num_envs = NUM_ENVS + env.device = DEVICE + env.episode_length_buf = episode_length_buf + env.step_dt = 0.02 + env.max_episode_length_s = 10.0 + return env + + +@pytest.fixture() +def warp_env_bodies(scene_bodies, action_wp, episode_length_buf, cmd_tensor, cmd_term): + """Env with body-level data and command manager (for new-terms reward tests).""" + + class _Env: + pass + + env = _Env() + env.scene = scene_bodies + env.action_manager = MockActionManagerWarp(action_wp[0], action_wp[1]) + env.command_manager = MockCommandManager(cmd_tensor, cmd_term) + env.num_envs = NUM_ENVS + env.device = DEVICE + env.episode_length_buf = episode_length_buf + env.step_dt = 0.02 + env.max_episode_length = 500 + env.max_episode_length_s = 10.0 + env.rng_state_wp = wp.array(np.arange(NUM_ENVS, dtype=np.uint32) + 42, device=DEVICE) + return env + + +@pytest.fixture() +def stable_env_bodies(scene_bodies, action_wp, episode_length_buf, cmd_tensor, cmd_term): + """Env with body-level data and command manager (for stable new-terms reward tests).""" + + class _Env: + pass + + env = _Env() + env.scene = scene_bodies + env.action_manager = MockActionManagerWarp(action_wp[0], action_wp[1]) + env.command_manager = MockCommandManager(cmd_tensor, cmd_term) + env.num_envs = NUM_ENVS + env.device = DEVICE + env.episode_length_buf = episode_length_buf + env.step_dt = 0.02 + env.max_episode_length = 500 + env.max_episode_length_s = 10.0 + return env + + +@pytest.fixture() +def all_joints_cfg(): + return MockSceneEntityCfg("robot", list(range(NUM_JOINTS)), NUM_JOINTS, DEVICE) + + +@pytest.fixture() +def body_cfg(): + return MockBodyCfg("robot", BODY_IDS) + + +@pytest.fixture() +def sensor_cfg(): + return MockSensorCfg("contact_sensor", BODY_IDS) + + +# ============================================================================ +# Reward parity tests (from test_mdp_warp_parity.py) +# ============================================================================ + + +class TestRewardParity: + """Verify experimental reward Warp kernels match stable torch implementations.""" + + # -- General rewards -------------------------------------------------------- + + def test_is_alive(self, warp_env, stable_env, term_mgr): + # Set some envs as terminated so the reward is non-trivial + term_mgr.terminated[::2] = True + expected = stable_rew.is_alive(stable_env) + actual = run_warp_rew(warp_rew.is_alive, warp_env) + actual_cap = run_warp_rew_captured(warp_rew.is_alive, warp_env) + assert_close(actual, expected) + assert_close(actual_cap, expected) + + def test_is_terminated(self, warp_env, stable_env, term_mgr): + term_mgr.terminated[::3] = True + expected = stable_rew.is_terminated(stable_env) + actual = run_warp_rew(warp_rew.is_terminated, warp_env) + actual_cap = run_warp_rew_captured(warp_rew.is_terminated, warp_env) + assert_close(actual, expected) + assert_close(actual_cap, expected) + + # -- Root penalties --------------------------------------------------------- + + def test_lin_vel_z_l2(self, warp_env, stable_env, all_joints_cfg): + cfg = all_joints_cfg + expected = stable_rew.lin_vel_z_l2(stable_env, asset_cfg=cfg) + actual = run_warp_rew(warp_rew.lin_vel_z_l2, warp_env, asset_cfg=cfg) + actual_cap = run_warp_rew_captured(warp_rew.lin_vel_z_l2, warp_env, asset_cfg=cfg) + assert_close(actual, expected) + assert_close(actual_cap, expected) + + def test_ang_vel_xy_l2(self, warp_env, stable_env, all_joints_cfg): + cfg = all_joints_cfg + expected = stable_rew.ang_vel_xy_l2(stable_env, asset_cfg=cfg) + actual = run_warp_rew(warp_rew.ang_vel_xy_l2, warp_env, asset_cfg=cfg) + actual_cap = run_warp_rew_captured(warp_rew.ang_vel_xy_l2, warp_env, asset_cfg=cfg) + assert_close(actual, expected) + assert_close(actual_cap, expected) + + def test_flat_orientation_l2(self, warp_env, stable_env, all_joints_cfg): + cfg = all_joints_cfg + expected = stable_rew.flat_orientation_l2(stable_env, asset_cfg=cfg) + actual = run_warp_rew(warp_rew.flat_orientation_l2, warp_env, asset_cfg=cfg) + actual_cap = run_warp_rew_captured(warp_rew.flat_orientation_l2, warp_env, asset_cfg=cfg) + assert_close(actual, expected) + assert_close(actual_cap, expected) + + # -- Joint L2 penalties (masked) -------------------------------------------- + + def test_joint_vel_l2(self, warp_env, stable_env, all_joints_cfg): + cfg = all_joints_cfg + expected = stable_rew.joint_vel_l2(stable_env, asset_cfg=cfg) + actual = run_warp_rew(warp_rew.joint_vel_l2, warp_env, asset_cfg=cfg) + actual_cap = run_warp_rew_captured(warp_rew.joint_vel_l2, warp_env, asset_cfg=cfg) + assert_close(actual, expected) + assert_close(actual_cap, expected) + + def test_joint_acc_l2(self, warp_env, stable_env, all_joints_cfg): + cfg = all_joints_cfg + expected = stable_rew.joint_acc_l2(stable_env, asset_cfg=cfg) + actual = run_warp_rew(warp_rew.joint_acc_l2, warp_env, asset_cfg=cfg) + actual_cap = run_warp_rew_captured(warp_rew.joint_acc_l2, warp_env, asset_cfg=cfg) + assert_close(actual, expected) + assert_close(actual_cap, expected) + + def test_joint_torques_l2(self, warp_env, stable_env, all_joints_cfg): + cfg = all_joints_cfg + expected = stable_rew.joint_torques_l2(stable_env, asset_cfg=cfg) + actual = run_warp_rew(warp_rew.joint_torques_l2, warp_env, asset_cfg=cfg) + actual_cap = run_warp_rew_captured(warp_rew.joint_torques_l2, warp_env, asset_cfg=cfg) + assert_close(actual, expected) + assert_close(actual_cap, expected) + + # -- Joint L1 penalties (masked) -------------------------------------------- + + def test_joint_vel_l1(self, warp_env, stable_env, all_joints_cfg): + cfg = all_joints_cfg + expected = stable_rew.joint_vel_l1(stable_env, asset_cfg=cfg) + actual = run_warp_rew(warp_rew.joint_vel_l1, warp_env, asset_cfg=cfg) + actual_cap = run_warp_rew_captured(warp_rew.joint_vel_l1, warp_env, asset_cfg=cfg) + assert_close(actual, expected) + assert_close(actual_cap, expected) + + # -- Action penalties ------------------------------------------------------- + + def test_action_l2(self, warp_env, stable_env): + expected = stable_rew.action_l2(stable_env) + actual = run_warp_rew(warp_rew.action_l2, warp_env) + actual_cap = run_warp_rew_captured(warp_rew.action_l2, warp_env) + assert_close(actual, expected) + assert_close(actual_cap, expected) + + def test_action_rate_l2(self, warp_env, stable_env): + expected = stable_rew.action_rate_l2(stable_env) + actual = run_warp_rew(warp_rew.action_rate_l2, warp_env) + actual_cap = run_warp_rew_captured(warp_rew.action_rate_l2, warp_env) + assert_close(actual, expected) + assert_close(actual_cap, expected) + + # -- Limit penalties -------------------------------------------------------- + + def test_joint_pos_limits(self, warp_env, stable_env, all_joints_cfg): + cfg = all_joints_cfg + expected = stable_rew.joint_pos_limits(stable_env, asset_cfg=cfg) + actual = run_warp_rew(warp_rew.joint_pos_limits, warp_env, asset_cfg=cfg) + actual_cap = run_warp_rew_captured(warp_rew.joint_pos_limits, warp_env, asset_cfg=cfg) + assert_close(actual, expected) + assert_close(actual_cap, expected) + + # -- Additional penalties --------------------------------------------------- + + def test_joint_deviation_l1(self, warp_env, stable_env, all_joints_cfg): + cfg = all_joints_cfg + expected = stable_rew.joint_deviation_l1(stable_env, asset_cfg=cfg) + actual = run_warp_rew(warp_rew.joint_deviation_l1, warp_env, asset_cfg=cfg) + actual_cap = run_warp_rew_captured(warp_rew.joint_deviation_l1, warp_env, asset_cfg=cfg) + assert_close(actual, expected) + assert_close(actual_cap, expected) + + +# ============================================================================ +# New reward parity tests (from test_mdp_warp_parity_new_terms.py) +# ============================================================================ + + +class TestNewRewardParity: + """Verify newly migrated reward Warp kernels match stable torch implementations.""" + + def test_track_lin_vel_xy_exp(self, warp_env_bodies, stable_env_bodies, body_cfg): + cfg = MockBodyCfg("robot") + cfg.joint_ids = list(range(NUM_JOINTS)) # needed for stable + std = 0.25 + expected = stable_rew.track_lin_vel_xy_exp(stable_env_bodies, std=std, command_name="vel", asset_cfg=cfg) + actual = run_warp_rew( + warp_rew.track_lin_vel_xy_exp, warp_env_bodies, std=std, command_name="vel", asset_cfg=cfg + ) + actual_cap = run_warp_rew_captured( + warp_rew.track_lin_vel_xy_exp, warp_env_bodies, std=std, command_name="vel", asset_cfg=cfg + ) + assert_close(actual, expected) + assert_close(actual_cap, expected) + + def test_track_ang_vel_z_exp(self, warp_env_bodies, stable_env_bodies, body_cfg): + cfg = MockBodyCfg("robot") + cfg.joint_ids = list(range(NUM_JOINTS)) + std = 0.25 + expected = stable_rew.track_ang_vel_z_exp(stable_env_bodies, std=std, command_name="vel", asset_cfg=cfg) + actual = run_warp_rew(warp_rew.track_ang_vel_z_exp, warp_env_bodies, std=std, command_name="vel", asset_cfg=cfg) + actual_cap = run_warp_rew_captured( + warp_rew.track_ang_vel_z_exp, warp_env_bodies, std=std, command_name="vel", asset_cfg=cfg + ) + assert_close(actual, expected) + assert_close(actual_cap, expected) + + def test_undesired_contacts(self, warp_env_bodies, stable_env_bodies, sensor_cfg): + threshold = 1.0 + expected = stable_rew.undesired_contacts(stable_env_bodies, threshold=threshold, sensor_cfg=sensor_cfg) + actual = run_warp_rew(warp_rew.undesired_contacts, warp_env_bodies, threshold=threshold, sensor_cfg=sensor_cfg) + actual_cap = run_warp_rew_captured( + warp_rew.undesired_contacts, warp_env_bodies, threshold=threshold, sensor_cfg=sensor_cfg + ) + assert_close(actual, expected.float()) + assert_close(actual_cap, expected.float()) + + +# ============================================================================ +# Capture-then-mutate-then-replay reward tests (from test_mdp_warp_parity.py) +# ============================================================================ + + +def _mutate_art_data(art_data: MockArticulationData, warp_env, rng_seed: int = 200): + """Mutate every data array in-place so captured graphs see fresh values.""" + mutate_art_data(art_data, warp_env, rng_seed=rng_seed) + + +def _mutate_body_data(art_data: MockArticulationData, rng_seed=200): + """Mutate body-level and root-level data in-place so captured graphs see fresh values.""" + mutate_body_data(art_data, rng_seed=rng_seed) + + +class TestCapturedDataMutationRewards: + """Capture a graph, mutate buffer data in-place, replay -- results must match stable on the *new* data. + + This verifies reward MDP functions are truly capture-safe. + """ + + def _capture_mutate_check_rew(self, warp_fn, stable_fn, warp_env, stable_env, art_data, **kwargs): + out = wp.zeros((NUM_ENVS,), dtype=wp.float32, device=DEVICE) + warp_fn(warp_env, out, **kwargs) + with wp.ScopedCapture() as cap: + warp_fn(warp_env, out, **kwargs) + _mutate_art_data(art_data, warp_env) + wp.capture_launch(cap.graph) + assert_close(wp.to_torch(out).clone(), stable_fn(stable_env, **kwargs)) + + def test_lin_vel_z_l2(self, warp_env, stable_env, art_data, all_joints_cfg): + self._capture_mutate_check_rew( + warp_rew.lin_vel_z_l2, + stable_rew.lin_vel_z_l2, + warp_env, + stable_env, + art_data, + asset_cfg=all_joints_cfg, + ) + + def test_ang_vel_xy_l2(self, warp_env, stable_env, art_data, all_joints_cfg): + self._capture_mutate_check_rew( + warp_rew.ang_vel_xy_l2, + stable_rew.ang_vel_xy_l2, + warp_env, + stable_env, + art_data, + asset_cfg=all_joints_cfg, + ) + + def test_flat_orientation_l2(self, warp_env, stable_env, art_data, all_joints_cfg): + self._capture_mutate_check_rew( + warp_rew.flat_orientation_l2, + stable_rew.flat_orientation_l2, + warp_env, + stable_env, + art_data, + asset_cfg=all_joints_cfg, + ) + + def test_joint_vel_l2(self, warp_env, stable_env, art_data, all_joints_cfg): + self._capture_mutate_check_rew( + warp_rew.joint_vel_l2, + stable_rew.joint_vel_l2, + warp_env, + stable_env, + art_data, + asset_cfg=all_joints_cfg, + ) + + def test_joint_acc_l2(self, warp_env, stable_env, art_data, all_joints_cfg): + self._capture_mutate_check_rew( + warp_rew.joint_acc_l2, + stable_rew.joint_acc_l2, + warp_env, + stable_env, + art_data, + asset_cfg=all_joints_cfg, + ) + + def test_joint_torques_l2(self, warp_env, stable_env, art_data, all_joints_cfg): + self._capture_mutate_check_rew( + warp_rew.joint_torques_l2, + stable_rew.joint_torques_l2, + warp_env, + stable_env, + art_data, + asset_cfg=all_joints_cfg, + ) + + def test_action_l2(self, warp_env, stable_env, art_data): + self._capture_mutate_check_rew( + warp_rew.action_l2, + stable_rew.action_l2, + warp_env, + stable_env, + art_data, + ) + + def test_action_rate_l2(self, warp_env, stable_env, art_data): + self._capture_mutate_check_rew( + warp_rew.action_rate_l2, + stable_rew.action_rate_l2, + warp_env, + stable_env, + art_data, + ) + + def test_joint_pos_limits(self, warp_env, stable_env, art_data, all_joints_cfg): + self._capture_mutate_check_rew( + warp_rew.joint_pos_limits, + stable_rew.joint_pos_limits, + warp_env, + stable_env, + art_data, + asset_cfg=all_joints_cfg, + ) + + def test_joint_deviation_l1(self, warp_env, stable_env, art_data, all_joints_cfg): + self._capture_mutate_check_rew( + warp_rew.joint_deviation_l1, + stable_rew.joint_deviation_l1, + warp_env, + stable_env, + art_data, + asset_cfg=all_joints_cfg, + ) + + +# ============================================================================ +# Capture-mutate-replay reward tests for new terms (from test_mdp_warp_parity_new_terms.py) +# ============================================================================ + + +class TestCapturedDataMutationRewardsNewTerms: + """Capture graph, mutate buffer data, replay -- verify new-terms reward results match stable.""" + + def _capture_mutate_check_rew(self, warp_fn, stable_fn, warp_env, stable_env, art_data, **kwargs): + out = wp.zeros((NUM_ENVS,), dtype=wp.float32, device=DEVICE) + warp_fn(warp_env, out, **kwargs) + with wp.ScopedCapture() as cap: + warp_fn(warp_env, out, **kwargs) + _mutate_body_data(art_data) + wp.capture_launch(cap.graph) + expected = stable_fn(stable_env, **kwargs) + assert_close(wp.to_torch(out).clone(), expected) + + def test_track_lin_vel_xy_exp(self, warp_env_bodies, stable_env_bodies, art_data_bodies): + cfg = MockBodyCfg("robot") + cfg.joint_ids = list(range(NUM_JOINTS)) + self._capture_mutate_check_rew( + warp_rew.track_lin_vel_xy_exp, + stable_rew.track_lin_vel_xy_exp, + warp_env_bodies, + stable_env_bodies, + art_data_bodies, + std=0.25, + command_name="vel", + asset_cfg=cfg, + ) + + def test_track_ang_vel_z_exp(self, warp_env_bodies, stable_env_bodies, art_data_bodies): + cfg = MockBodyCfg("robot") + cfg.joint_ids = list(range(NUM_JOINTS)) + self._capture_mutate_check_rew( + warp_rew.track_ang_vel_z_exp, + stable_rew.track_ang_vel_z_exp, + warp_env_bodies, + stable_env_bodies, + art_data_bodies, + std=0.25, + command_name="vel", + asset_cfg=cfg, + ) diff --git a/source/isaaclab_experimental/test/envs/mdp/test_terminations_warp_parity.py b/source/isaaclab_experimental/test/envs/mdp/test_terminations_warp_parity.py new file mode 100644 index 000000000000..d82339e01228 --- /dev/null +++ b/source/isaaclab_experimental/test/envs/mdp/test_terminations_warp_parity.py @@ -0,0 +1,349 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Parity tests for warp-first termination MDP terms.""" + +from __future__ import annotations + +import numpy as np +import pytest +import torch +import warp as wp + +# Skip entire module if no CUDA device available +wp.init() +pytestmark = pytest.mark.skipif(not wp.is_cuda_available(), reason="CUDA device required") + +import isaaclab_experimental.envs.mdp.terminations as warp_term +from parity_helpers import ( + BODY_IDS, + CMD_DIM, + DEVICE, + NUM_ACTIONS, + NUM_BODIES, + NUM_ENVS, + NUM_JOINTS, + MockActionManagerTorch, + MockActionManagerWarp, + MockArticulation, + MockArticulationData, + MockCommandManager, + MockCommandTerm, + MockContactSensor, + MockContactSensorData, + MockScene, + MockSceneEntityCfg, + MockSensorCfg, + MockTerminationManager, + assert_equal, + mutate_art_data, + mutate_body_data, + run_warp_term, + run_warp_term_captured, +) + +import isaaclab.envs.mdp.terminations as stable_term + +# ============================================================================ +# Fixtures +# ============================================================================ + + +@pytest.fixture(autouse=True) +def _clear_caches(): + yield + for fn in [warp_term.illegal_contact]: + for attr in list(vars(fn)): + if attr.startswith("_"): + delattr(fn, attr) + + +@pytest.fixture() +def art_data(): + return MockArticulationData(NUM_ENVS, NUM_JOINTS, DEVICE) + + +@pytest.fixture() +def art_data_bodies(): + return MockArticulationData(num_bodies=NUM_BODIES) + + +@pytest.fixture() +def env_origins(): + rng = np.random.RandomState(77) + origins_np = rng.randn(NUM_ENVS, 3).astype(np.float32) + return wp.array(origins_np, dtype=wp.vec3f, device=DEVICE) + + +@pytest.fixture() +def contact_data(): + return MockContactSensorData() + + +@pytest.fixture() +def cmd_tensor(): + rng = np.random.RandomState(99) + return torch.tensor(rng.randn(NUM_ENVS, CMD_DIM).astype(np.float32), device=DEVICE) + + +@pytest.fixture() +def cmd_term(): + return MockCommandTerm() + + +@pytest.fixture() +def scene(art_data, env_origins): + return MockScene({"robot": MockArticulation(art_data)}, env_origins) + + +@pytest.fixture() +def scene_bodies(art_data_bodies, env_origins, contact_data): + art = MockArticulation(art_data_bodies, num_bodies=NUM_BODIES) + sensor = MockContactSensor(contact_data) + return MockScene({"robot": art}, env_origins, sensors={"contact_sensor": sensor}) + + +@pytest.fixture() +def action_wp(): + rng = np.random.RandomState(99) + a = wp.array(rng.randn(NUM_ENVS, NUM_ACTIONS).astype(np.float32), device=DEVICE) + b = wp.array(rng.randn(NUM_ENVS, NUM_ACTIONS).astype(np.float32), device=DEVICE) + return a, b + + +@pytest.fixture() +def episode_length_buf(): + torch.manual_seed(55) + return torch.randint(0, 500, (NUM_ENVS,), dtype=torch.int64, device=DEVICE) + + +@pytest.fixture() +def warp_env(scene, action_wp, episode_length_buf): + """Env with warp action manager (for experimental functions).""" + + class _Env: + pass + + env = _Env() + env.scene = scene + env.action_manager = MockActionManagerWarp(action_wp[0], action_wp[1]) + env.num_envs = NUM_ENVS + env.device = DEVICE + env.episode_length_buf = episode_length_buf + env.step_dt = 0.02 + env.max_episode_length_s = 10.0 + env.rng_state_wp = wp.array(np.arange(NUM_ENVS, dtype=np.uint32) + 42, device=DEVICE) + return env + + +@pytest.fixture() +def stable_env(scene, action_wp, episode_length_buf): + """Env with torch action manager (for stable functions).""" + + class _Env: + pass + + env = _Env() + env.scene = scene + env.action_manager = MockActionManagerTorch(action_wp[0], action_wp[1]) + env.num_envs = NUM_ENVS + env.device = DEVICE + env.episode_length_buf = episode_length_buf + env.step_dt = 0.02 + env.max_episode_length_s = 10.0 + return env + + +@pytest.fixture() +def warp_env_bodies(scene_bodies, action_wp, episode_length_buf, cmd_tensor, cmd_term): + """Env with body-level data and command manager (for new-terms termination tests).""" + + class _Env: + pass + + env = _Env() + env.scene = scene_bodies + env.action_manager = MockActionManagerWarp(action_wp[0], action_wp[1]) + env.command_manager = MockCommandManager(cmd_tensor, cmd_term) + env.num_envs = NUM_ENVS + env.device = DEVICE + env.episode_length_buf = episode_length_buf + env._episode_length_buf_wp = wp.from_torch(episode_length_buf) + env.step_dt = 0.02 + env.max_episode_length = 500 + env.max_episode_length_s = 10.0 + env.rng_state_wp = wp.array(np.arange(NUM_ENVS, dtype=np.uint32) + 42, device=DEVICE) + return env + + +@pytest.fixture() +def stable_env_bodies(scene_bodies, action_wp, episode_length_buf, cmd_tensor, cmd_term): + """Env with body-level data and command manager (for stable new-terms termination tests).""" + + class _Env: + pass + + env = _Env() + env.scene = scene_bodies + env.action_manager = MockActionManagerWarp(action_wp[0], action_wp[1]) + env.command_manager = MockCommandManager(cmd_tensor, cmd_term) + env.num_envs = NUM_ENVS + env.device = DEVICE + env.episode_length_buf = episode_length_buf + env._episode_length_buf_wp = wp.from_torch(episode_length_buf) + env.step_dt = 0.02 + env.max_episode_length = 500 + env.max_episode_length_s = 10.0 + # stable termination_manager needed for time_out + env.termination_manager = MockTerminationManager() + return env + + +@pytest.fixture() +def all_joints_cfg(): + return MockSceneEntityCfg("robot", list(range(NUM_JOINTS)), NUM_JOINTS, DEVICE) + + +@pytest.fixture() +def sensor_cfg(): + return MockSensorCfg("contact_sensor", BODY_IDS) + + +# ============================================================================ +# Termination parity tests (from test_mdp_warp_parity.py) +# ============================================================================ + + +class TestTerminationParity: + """Verify experimental termination Warp kernels match stable torch implementations.""" + + def test_root_height_below_minimum(self, warp_env, stable_env, all_joints_cfg): + cfg = all_joints_cfg + min_h = 0.5 + expected = stable_term.root_height_below_minimum(stable_env, minimum_height=min_h, asset_cfg=cfg) + actual = run_warp_term(warp_term.root_height_below_minimum, warp_env, minimum_height=min_h, asset_cfg=cfg) + actual_cap = run_warp_term_captured( + warp_term.root_height_below_minimum, warp_env, minimum_height=min_h, asset_cfg=cfg + ) + assert_equal(actual, expected) + assert_equal(actual_cap, expected) + + def test_joint_pos_out_of_manual_limit(self, warp_env, stable_env, all_joints_cfg): + cfg = all_joints_cfg + bounds = (-1.0, 1.0) + expected = stable_term.joint_pos_out_of_manual_limit(stable_env, bounds=bounds, asset_cfg=cfg) + actual = run_warp_term(warp_term.joint_pos_out_of_manual_limit, warp_env, bounds=bounds, asset_cfg=cfg) + actual_cap = run_warp_term_captured( + warp_term.joint_pos_out_of_manual_limit, warp_env, bounds=bounds, asset_cfg=cfg + ) + assert_equal(actual, expected) + assert_equal(actual_cap, expected) + + +# ============================================================================ +# Termination parity tests (from test_mdp_warp_parity_new_terms.py) +# ============================================================================ + + +class TestTerminationParityNewTerms: + """Verify termination Warp kernels for newly migrated terms match stable torch implementations.""" + + def test_time_out(self, warp_env_bodies, stable_env_bodies): + expected = stable_term.time_out(stable_env_bodies) + actual = run_warp_term(warp_term.time_out, warp_env_bodies) + actual_cap = run_warp_term_captured(warp_term.time_out, warp_env_bodies) + assert_equal(actual, expected) + assert_equal(actual_cap, expected) + + def test_illegal_contact(self, warp_env_bodies, stable_env_bodies, sensor_cfg): + threshold = 1.0 + expected = stable_term.illegal_contact(stable_env_bodies, threshold=threshold, sensor_cfg=sensor_cfg) + actual = run_warp_term(warp_term.illegal_contact, warp_env_bodies, threshold=threshold, sensor_cfg=sensor_cfg) + actual_cap = run_warp_term_captured( + warp_term.illegal_contact, warp_env_bodies, threshold=threshold, sensor_cfg=sensor_cfg + ) + assert_equal(actual, expected) + assert_equal(actual_cap, expected) + + +# ============================================================================ +# Capture-then-mutate-then-replay termination tests (from test_mdp_warp_parity.py) +# ============================================================================ + + +def _mutate_art_data(art_data: MockArticulationData, warp_env, rng_seed: int = 200): + """Mutate every data array in-place so captured graphs see fresh values.""" + mutate_art_data(art_data, warp_env, rng_seed=rng_seed) + + +def _mutate_body_data(art_data: MockArticulationData, rng_seed=200): + """Mutate body-level and root-level data in-place so captured graphs see fresh values.""" + mutate_body_data(art_data, rng_seed=rng_seed) + + +class TestCapturedDataMutationTerminations: + """Capture a graph, mutate buffer data in-place, replay -- results must match stable on the *new* data. + + This verifies termination MDP functions are truly capture-safe. + """ + + def _capture_mutate_check_term(self, warp_fn, stable_fn, warp_env, stable_env, art_data, **kwargs): + out = wp.zeros((NUM_ENVS,), dtype=wp.bool, device=DEVICE) + warp_fn(warp_env, out, **kwargs) + with wp.ScopedCapture() as cap: + warp_fn(warp_env, out, **kwargs) + _mutate_art_data(art_data, warp_env) + wp.capture_launch(cap.graph) + assert_equal(wp.to_torch(out).clone(), stable_fn(stable_env, **kwargs)) + + def test_root_height_below_minimum(self, warp_env, stable_env, art_data, all_joints_cfg): + self._capture_mutate_check_term( + warp_term.root_height_below_minimum, + stable_term.root_height_below_minimum, + warp_env, + stable_env, + art_data, + minimum_height=0.5, + asset_cfg=all_joints_cfg, + ) + + def test_joint_pos_out_of_manual_limit(self, warp_env, stable_env, art_data, all_joints_cfg): + # joint_pos_out_of_manual_limit uses a 2D kernel that only writes True + # (never clears to False), so the output must be zeroed before each call. + # We include the zeroing inside the captured graph. + bounds = (-1.0, 1.0) + cfg = all_joints_cfg + out = wp.zeros((NUM_ENVS,), dtype=wp.bool, device=DEVICE) + # warm-up + out.zero_() + warp_term.joint_pos_out_of_manual_limit(warp_env, out, bounds=bounds, asset_cfg=cfg) + # capture (including the zero) + with wp.ScopedCapture() as cap: + out.zero_() + warp_term.joint_pos_out_of_manual_limit(warp_env, out, bounds=bounds, asset_cfg=cfg) + _mutate_art_data(art_data, warp_env) + wp.capture_launch(cap.graph) + expected = stable_term.joint_pos_out_of_manual_limit(stable_env, bounds=bounds, asset_cfg=cfg) + assert_equal(wp.to_torch(out).clone(), expected) + + +# ============================================================================ +# Capture-mutate-replay termination tests for new terms (from test_mdp_warp_parity_new_terms.py) +# ============================================================================ + + +class TestCapturedDataMutationTerminationsNewTerms: + """Capture graph, mutate buffer data, replay -- verify new-terms termination results match stable.""" + + def test_time_out(self, warp_env_bodies, stable_env_bodies, art_data_bodies): + out = wp.zeros((NUM_ENVS,), dtype=wp.bool, device=DEVICE) + warp_term.time_out(warp_env_bodies, out) + with wp.ScopedCapture() as cap: + warp_term.time_out(warp_env_bodies, out) + # Mutate episode length in-place + warp_env_bodies.episode_length_buf[:] = torch.randint(0, 600, (NUM_ENVS,), dtype=torch.int64, device=DEVICE) + wp.capture_launch(cap.graph) + expected = stable_term.time_out(stable_env_bodies) + assert_equal(wp.to_torch(out).clone(), expected) diff --git a/source/isaaclab_experimental/test/utils/test_manager_call_switch.py b/source/isaaclab_experimental/test/utils/test_manager_call_switch.py new file mode 100644 index 000000000000..b4745939eaa0 --- /dev/null +++ b/source/isaaclab_experimental/test/utils/test_manager_call_switch.py @@ -0,0 +1,475 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Tests for ManagerCallSwitch config loading, mode resolution, and dispatch.""" + +from __future__ import annotations + +import json +import os +import unittest + +import warp as wp +from isaaclab_experimental.utils.manager_call_switch import ManagerCallMode, ManagerCallSwitch + + +@wp.kernel +def _add_one(a: wp.array(dtype=wp.float32), b: wp.array(dtype=wp.float32)): + i = wp.tid() + b[i] = a[i] + 1.0 + + +class TestManagerCallMode(unittest.TestCase): + """Tests for the ManagerCallMode enum.""" + + def test_enum_values(self): + self.assertEqual(ManagerCallMode.STABLE, 0) + self.assertEqual(ManagerCallMode.WARP_NOT_CAPTURED, 1) + self.assertEqual(ManagerCallMode.WARP_CAPTURED, 2) + + def test_ordering(self): + self.assertLess(ManagerCallMode.STABLE, ManagerCallMode.WARP_NOT_CAPTURED) + self.assertLess(ManagerCallMode.WARP_NOT_CAPTURED, ManagerCallMode.WARP_CAPTURED) + + +# ====================================================================== +# Config loading +# ====================================================================== + + +class TestConfigLoading(unittest.TestCase): + """Tests for ManagerCallSwitch config parsing from dict, JSON, env var, and None.""" + + def test_none_uses_default(self): + switch = ManagerCallSwitch(cfg_source=None) + self.assertEqual(switch.get_mode_for_manager("RewardManager"), ManagerCallMode.WARP_CAPTURED) + + def test_dict_config(self): + switch = ManagerCallSwitch(cfg_source={"default": 1}) + self.assertEqual(switch.get_mode_for_manager("RewardManager"), ManagerCallMode.WARP_NOT_CAPTURED) + + def test_dict_per_manager_override(self): + switch = ManagerCallSwitch(cfg_source={"default": 2, "RewardManager": 0}) + self.assertEqual(switch.get_mode_for_manager("RewardManager"), ManagerCallMode.STABLE) + self.assertEqual(switch.get_mode_for_manager("ActionManager"), ManagerCallMode.WARP_CAPTURED) + + def test_dict_without_default_key(self): + """A dict missing 'default' should inherit from DEFAULT_CONFIG.""" + switch = ManagerCallSwitch(cfg_source={"RewardManager": 0}) + # default should be 2 (from DEFAULT_CONFIG) + self.assertEqual(switch.get_mode_for_manager("ActionManager"), ManagerCallMode.WARP_CAPTURED) + self.assertEqual(switch.get_mode_for_manager("RewardManager"), ManagerCallMode.STABLE) + + def test_json_string_config(self): + cfg_str = json.dumps({"default": 1, "ObservationManager": 0}) + switch = ManagerCallSwitch(cfg_source=cfg_str) + self.assertEqual(switch.get_mode_for_manager("ObservationManager"), ManagerCallMode.STABLE) + self.assertEqual(switch.get_mode_for_manager("RewardManager"), ManagerCallMode.WARP_NOT_CAPTURED) + + def test_empty_string_uses_default(self): + switch = ManagerCallSwitch(cfg_source="") + self.assertEqual(switch.get_mode_for_manager("RewardManager"), ManagerCallMode.WARP_CAPTURED) + + def test_env_var_fallback(self): + """When cfg_source is None, should read from MANAGER_CALL_CONFIG env var.""" + old = os.environ.get(ManagerCallSwitch.ENV_VAR) + try: + os.environ[ManagerCallSwitch.ENV_VAR] = json.dumps({"default": 0}) + switch = ManagerCallSwitch(cfg_source=None) + self.assertEqual(switch.get_mode_for_manager("RewardManager"), ManagerCallMode.STABLE) + finally: + if old is None: + os.environ.pop(ManagerCallSwitch.ENV_VAR, None) + else: + os.environ[ManagerCallSwitch.ENV_VAR] = old + + def test_invalid_json_raises(self): + with self.assertRaises(json.JSONDecodeError): + ManagerCallSwitch(cfg_source="not valid json") + + def test_invalid_mode_value_raises(self): + with self.assertRaises(ValueError): + ManagerCallSwitch(cfg_source={"default": 99}) + + def test_non_int_mode_raises(self): + with self.assertRaises(TypeError): + ManagerCallSwitch(cfg_source={"default": "fast"}) + + def test_invalid_cfg_type_raises(self): + with self.assertRaises(TypeError): + ManagerCallSwitch(cfg_source=42) + + +# ====================================================================== +# Mode resolution and capping +# ====================================================================== + + +class TestModeResolution(unittest.TestCase): + """Tests for mode resolution, MAX_MODE_OVERRIDES, and dynamic capturability.""" + + def test_max_mode_override_caps_default(self): + """Scene is capped to WARP_NOT_CAPTURED by MAX_MODE_OVERRIDES.""" + switch = ManagerCallSwitch(cfg_source={"default": 2}) + # Scene has a static cap of WARP_NOT_CAPTURED + self.assertEqual( + switch.get_mode_for_manager("Scene"), + ManagerCallMode.WARP_NOT_CAPTURED, + ) + # Other managers should not be capped + self.assertEqual( + switch.get_mode_for_manager("RewardManager"), + ManagerCallMode.WARP_CAPTURED, + ) + + def test_max_modes_kwarg(self): + """max_modes kwarg should cap managers beyond MAX_MODE_OVERRIDES.""" + switch = ManagerCallSwitch( + cfg_source={"default": 2}, + max_modes={"RewardManager": ManagerCallMode.WARP_NOT_CAPTURED}, + ) + self.assertEqual( + switch.get_mode_for_manager("RewardManager"), + ManagerCallMode.WARP_NOT_CAPTURED, + ) + + def test_register_manager_capturability_downgrades(self): + """register_manager_capturability(False) should cap a manager to WARP_NOT_CAPTURED.""" + switch = ManagerCallSwitch(cfg_source={"default": 2}) + self.assertEqual(switch.get_mode_for_manager("RewardManager"), ManagerCallMode.WARP_CAPTURED) + + switch.register_manager_capturability("RewardManager", capturable=False) + self.assertEqual( + switch.get_mode_for_manager("RewardManager"), + ManagerCallMode.WARP_NOT_CAPTURED, + ) + + def test_register_capturability_true_is_noop(self): + """register_manager_capturability(True) should not change anything.""" + switch = ManagerCallSwitch(cfg_source={"default": 2}) + switch.register_manager_capturability("RewardManager", capturable=True) + self.assertEqual(switch.get_mode_for_manager("RewardManager"), ManagerCallMode.WARP_CAPTURED) + + def test_register_capturability_does_not_upgrade(self): + """If a manager is already capped to NOT_CAPTURED, registering capturable=False again shouldn't change it.""" + switch = ManagerCallSwitch(cfg_source={"default": 2}) + switch.register_manager_capturability("RewardManager", capturable=False) + switch.register_manager_capturability("RewardManager", capturable=False) + self.assertEqual( + switch.get_mode_for_manager("RewardManager"), + ManagerCallMode.WARP_NOT_CAPTURED, + ) + + def test_capturability_interacts_with_static_cap(self): + """Dynamic capturability should respect existing static caps.""" + switch = ManagerCallSwitch( + cfg_source={"default": 2}, + max_modes={"RewardManager": ManagerCallMode.WARP_NOT_CAPTURED}, + ) + # Already capped, register_capturability(False) should be harmless + switch.register_manager_capturability("RewardManager", capturable=False) + self.assertEqual( + switch.get_mode_for_manager("RewardManager"), + ManagerCallMode.WARP_NOT_CAPTURED, + ) + + def test_mode_0_not_affected_by_cap(self): + """A manager explicitly set to STABLE (0) should stay at 0 even with cap at 1.""" + switch = ManagerCallSwitch(cfg_source={"default": 2, "RewardManager": 0}) + switch.register_manager_capturability("RewardManager", capturable=False) + self.assertEqual(switch.get_mode_for_manager("RewardManager"), ManagerCallMode.STABLE) + + +# ====================================================================== +# Stage dispatch +# ====================================================================== + + +class TestStageDispatch(unittest.TestCase): + """Tests for call_stage routing through stable / warp-eager / warp-captured paths.""" + + def test_stable_mode_calls_stable_fn(self): + switch = ManagerCallSwitch(cfg_source={"default": 0}) + called = {"stable": False, "warp": False} + + def stable_fn(): + called["stable"] = True + return "stable_result" + + def warp_fn(): + called["warp"] = True + return "warp_result" + + result = switch.call_stage( + stage="RewardManager_compute", + warp_call={"fn": warp_fn}, + stable_call={"fn": stable_fn}, + ) + self.assertTrue(called["stable"]) + self.assertFalse(called["warp"]) + self.assertEqual(result, "stable_result") + + def test_stable_mode_without_stable_call_raises(self): + switch = ManagerCallSwitch(cfg_source={"default": 0}) + with self.assertRaises(ValueError): + switch.call_stage( + stage="RewardManager_compute", + warp_call={"fn": lambda: None}, + stable_call=None, + ) + + def test_warp_eager_mode_calls_warp_fn(self): + switch = ManagerCallSwitch(cfg_source={"default": 1}) + called = {"stable": False, "warp": False} + + def stable_fn(): + called["stable"] = True + return "stable_result" + + def warp_fn(): + called["warp"] = True + return "warp_result" + + result = switch.call_stage( + stage="RewardManager_compute", + warp_call={"fn": warp_fn}, + stable_call={"fn": stable_fn}, + ) + self.assertFalse(called["stable"]) + self.assertTrue(called["warp"]) + self.assertEqual(result, "warp_result") + + def test_output_transform(self): + """The 'output' key in call spec should transform the return value.""" + switch = ManagerCallSwitch(cfg_source={"default": 1}) + + def warp_fn(): + return [1, 2, 3] + + result = switch.call_stage( + stage="RewardManager_compute", + warp_call={"fn": warp_fn, "output": len}, + ) + self.assertEqual(result, 3) + + def test_args_and_kwargs_forwarded(self): + """call_stage should forward args and kwargs from the call spec.""" + switch = ManagerCallSwitch(cfg_source={"default": 1}) + received = {} + + def warp_fn(a, b, key=None): + received["a"] = a + received["b"] = b + received["key"] = key + + switch.call_stage( + stage="RewardManager_compute", + warp_call={"fn": warp_fn, "args": (1, 2), "kwargs": {"key": "val"}}, + ) + self.assertEqual(received, {"a": 1, "b": 2, "key": "val"}) + + +class TestStageDispatchCaptured(unittest.TestCase): + """Tests for WARP_CAPTURED mode (requires GPU).""" + + def setUp(self): + self.device = "cuda:0" + + def test_captured_mode_produces_correct_output(self): + """WARP_CAPTURED should capture and replay a warp kernel correctly.""" + switch = ManagerCallSwitch(cfg_source={"default": 2}) + src = wp.full(4, value=5.0, dtype=wp.float32, device=self.device) + dst = wp.zeros(4, dtype=wp.float32, device=self.device) + + def warp_fn(): + wp.launch(_add_one, dim=4, inputs=[src, dst], device=self.device) + return dst + + # First call: warm-up + capture + result = switch.call_stage( + stage="RewardManager_compute", + warp_call={"fn": warp_fn}, + ) + self.assertAlmostEqual(result.numpy()[0], 6.0, places=5) + + # Replay + wp.copy(src, wp.full(4, value=10.0, dtype=wp.float32, device=self.device)) + result2 = switch.call_stage( + stage="RewardManager_compute", + warp_call={"fn": warp_fn}, + ) + self.assertIs(result, result2, "Replay must return same reference") + self.assertAlmostEqual(result2.numpy()[0], 11.0, places=5) + + def test_captured_warmup_call_count(self): + """WARP_CAPTURED first call should invoke fn exactly 2 times (warm-up + capture).""" + switch = ManagerCallSwitch(cfg_source={"default": 2}) + src = wp.zeros(4, dtype=wp.float32, device=self.device) + dst = wp.zeros(4, dtype=wp.float32, device=self.device) + call_count = [0] + + def warp_fn(): + call_count[0] += 1 + wp.launch(_add_one, dim=4, inputs=[src, dst], device=self.device) + return dst + + # First call_stage: warm-up (1) + capture (2) + switch.call_stage(stage="RewardManager_compute", warp_call={"fn": warp_fn}) + self.assertEqual(call_count[0], 2, "First captured call should invoke fn twice (warm-up + capture)") + + # Second call_stage: replay only — no new fn invocation + switch.call_stage(stage="RewardManager_compute", warp_call={"fn": warp_fn}) + self.assertEqual(call_count[0], 2, "Replay should not invoke fn again") + + # Third call_stage: still replay + switch.call_stage(stage="RewardManager_compute", warp_call={"fn": warp_fn}) + self.assertEqual(call_count[0], 2) + + def test_captured_warmup_handles_hasattr_guard(self): + """Warm-up should flush first-call allocations so capture doesn't record them. + + This simulates the real-world pattern where MDP terms allocate scratch + buffers on first call using hasattr guards. + """ + switch = ManagerCallSwitch(cfg_source={"default": 2}) + src = wp.ones(8, dtype=wp.float32, device=self.device) + holder = {} + + def fn_with_guard(): + if "buf" not in holder: + # First-call allocation — must happen during warm-up, not capture + holder["buf"] = wp.zeros(8, dtype=wp.float32, device=self.device) + wp.launch(_add_one, dim=8, inputs=[src, holder["buf"]], device=self.device) + return holder["buf"] + + # Should not raise — warm-up handles the allocation outside capture context + result = switch.call_stage( + stage="RewardManager_compute", + warp_call={"fn": fn_with_guard}, + ) + result_np = result.numpy() + for val in result_np: + self.assertAlmostEqual(val, 2.0, places=5) + + # Replay should also work (allocation already done, only kernel replays) + wp.copy(src, wp.full(8, value=5.0, dtype=wp.float32, device=self.device)) + result2 = switch.call_stage( + stage="RewardManager_compute", + warp_call={"fn": fn_with_guard}, + ) + for val in result2.numpy(): + self.assertAlmostEqual(val, 6.0, places=5) + + def test_warp_eager_no_warmup(self): + """WARP_NOT_CAPTURED mode should call fn exactly once per call (no warm-up).""" + switch = ManagerCallSwitch(cfg_source={"default": 1}) + call_count = [0] + + def warp_fn(): + call_count[0] += 1 + + switch.call_stage(stage="RewardManager_compute", warp_call={"fn": warp_fn}) + self.assertEqual(call_count[0], 1, "Eager mode should call fn exactly once") + + switch.call_stage(stage="RewardManager_compute", warp_call={"fn": warp_fn}) + self.assertEqual(call_count[0], 2, "Eager mode should call fn again each time") + + +# ====================================================================== +# Graph invalidation +# ====================================================================== + + +class TestGraphInvalidation(unittest.TestCase): + """Tests for invalidate_graphs on ManagerCallSwitch.""" + + def setUp(self): + self.device = "cuda:0" + + def test_invalidate_forces_recapture(self): + switch = ManagerCallSwitch(cfg_source={"default": 2}) + src = wp.full(4, value=1.0, dtype=wp.float32, device=self.device) + dst = wp.zeros(4, dtype=wp.float32, device=self.device) + + call_count = [0] + + def warp_fn(): + call_count[0] += 1 + wp.launch(_add_one, dim=4, inputs=[src, dst], device=self.device) + return dst + + # First capture + switch.call_stage(stage="RewardManager_compute", warp_call={"fn": warp_fn}) + self.assertEqual(call_count[0], 2) # warm-up + capture + + # Replay — no new calls + switch.call_stage(stage="RewardManager_compute", warp_call={"fn": warp_fn}) + self.assertEqual(call_count[0], 2) + + # Invalidate + switch.invalidate_graphs() + + # Should re-warm-up + re-capture + switch.call_stage(stage="RewardManager_compute", warp_call={"fn": warp_fn}) + self.assertEqual(call_count[0], 4) + + +# ====================================================================== +# resolve_manager_class +# ====================================================================== + + +class TestResolveManagerClass(unittest.TestCase): + """Tests for resolve_manager_class.""" + + def test_stable_resolves_to_isaaclab_managers(self): + switch = ManagerCallSwitch(cfg_source={"default": 0}) + cls = switch.resolve_manager_class("RewardManager") + self.assertTrue(cls.__module__.startswith("isaaclab.managers")) + + def test_warp_resolves_to_experimental_managers(self): + switch = ManagerCallSwitch(cfg_source={"default": 1}) + cls = switch.resolve_manager_class("RewardManager") + self.assertTrue(cls.__module__.startswith("isaaclab_experimental")) + + def test_mode_override(self): + """mode_override should bypass the config for class resolution.""" + switch = ManagerCallSwitch(cfg_source={"default": 2}) + cls = switch.resolve_manager_class("RewardManager", mode_override=ManagerCallMode.STABLE) + self.assertTrue(cls.__module__.startswith("isaaclab.managers")) + + def test_invalid_manager_raises(self): + switch = ManagerCallSwitch(cfg_source={"default": 0}) + with self.assertRaises(AttributeError): + switch.resolve_manager_class("NonexistentManager") + + +# ====================================================================== +# Manager name parsing +# ====================================================================== + + +class TestManagerNameParsing(unittest.TestCase): + """Tests for stage name → manager name extraction.""" + + def test_valid_stage_name(self): + switch = ManagerCallSwitch(cfg_source={"default": 1}) + # Dispatch a stage with valid name format + called = [False] + + def fn(): + called[0] = True + + switch.call_stage(stage="RewardManager_compute", warp_call={"fn": fn}) + self.assertTrue(called[0]) + + def test_invalid_stage_name_raises(self): + switch = ManagerCallSwitch(cfg_source={"default": 1}) + with self.assertRaises(ValueError): + switch.call_stage(stage="nounderscore", warp_call={"fn": lambda: None}) + + +if __name__ == "__main__": + unittest.main() diff --git a/source/isaaclab_experimental/test/utils/test_warp_graph_cache.py b/source/isaaclab_experimental/test/utils/test_warp_graph_cache.py new file mode 100644 index 000000000000..1b9c10a76895 --- /dev/null +++ b/source/isaaclab_experimental/test/utils/test_warp_graph_cache.py @@ -0,0 +1,249 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Tests for WarpGraphCache capture/replay and warm-up behavior.""" + +from __future__ import annotations + +import unittest + +import warp as wp +from isaaclab_experimental.utils.warp_graph_cache import WarpGraphCache + + +@wp.kernel +def _add_one(a: wp.array(dtype=wp.float32), b: wp.array(dtype=wp.float32)): + """Simple warp kernel: b[i] = a[i] + 1.""" + i = wp.tid() + b[i] = a[i] + 1.0 + + +class TestWarpGraphCache(unittest.TestCase): + """Tests for :class:`WarpGraphCache`.""" + + def setUp(self): + self.device = "cuda:0" + self.cache = WarpGraphCache() + + # ------------------------------------------------------------------ + # Warm-up + # ------------------------------------------------------------------ + + def test_warmup_runs_before_capture(self): + """The function should be called eagerly (warm-up) before graph capture. + + We verify this by counting total invocations on the first call. + Warm-up = 1, capture = 1, so fn should be called exactly 2 times. + """ + call_count = [0] + src = wp.zeros(4, dtype=wp.float32, device=self.device) + dst = wp.zeros(4, dtype=wp.float32, device=self.device) + + def counted_launch(): + call_count[0] += 1 + wp.launch(_add_one, dim=4, inputs=[src, dst], device=self.device) + return dst + + # First call: warm-up + capture + self.cache.capture_or_replay("stage_a", counted_launch) + self.assertEqual(call_count[0], 2, "First call should invoke fn twice (warm-up + capture)") + + # Second call: replay only + self.cache.capture_or_replay("stage_a", counted_launch) + self.assertEqual(call_count[0], 2, "Replay should NOT invoke fn again") + + def test_warmup_flushes_first_call_allocations(self): + """Warm-up should handle first-call allocations so capture is clean. + + Simulates a hasattr guard pattern: allocate a buffer on first call only. + Without warm-up, the allocation would be recorded in the graph. + """ + holder = {} + src = wp.ones(8, dtype=wp.float32, device=self.device) + + def fn_with_hasattr_guard(): + if "buf" not in holder: + holder["buf"] = wp.zeros(8, dtype=wp.float32, device=self.device) + wp.launch(_add_one, dim=8, inputs=[src, holder["buf"]], device=self.device) + return holder["buf"] + + # Should not raise — warm-up handles the allocation outside capture + result = self.cache.capture_or_replay("guarded", fn_with_hasattr_guard) + self.assertIsNotNone(result) + + # Verify the kernel produced correct output + result_np = result.numpy() + for val in result_np: + self.assertAlmostEqual(val, 2.0, places=5) + + # ------------------------------------------------------------------ + # Capture / replay correctness + # ------------------------------------------------------------------ + + def test_capture_produces_correct_output(self): + """After capture, replaying the graph should produce correct results.""" + src = wp.full(4, value=3.0, dtype=wp.float32, device=self.device) + dst = wp.zeros(4, dtype=wp.float32, device=self.device) + + def my_fn(): + wp.launch(_add_one, dim=4, inputs=[src, dst], device=self.device) + return dst + + result = self.cache.capture_or_replay("compute", my_fn) + result_np = result.numpy() + for val in result_np: + self.assertAlmostEqual(val, 4.0, places=5) + + def test_replay_uses_updated_input(self): + """Replay should re-read from the same input buffer (pointer-stable). + + CUDA graph replay re-executes the same kernel on the same memory + addresses. If we update the input buffer in-place, the output + should reflect the new values. + """ + src = wp.full(4, value=1.0, dtype=wp.float32, device=self.device) + dst = wp.zeros(4, dtype=wp.float32, device=self.device) + + def my_fn(): + wp.launch(_add_one, dim=4, inputs=[src, dst], device=self.device) + return dst + + # Capture + self.cache.capture_or_replay("replay_test", my_fn) + + # Update input in-place + wp.copy(src, wp.full(4, value=10.0, dtype=wp.float32, device=self.device)) + + # Replay — should see updated input + result = self.cache.capture_or_replay("replay_test", my_fn) + result_np = result.numpy() + for val in result_np: + self.assertAlmostEqual(val, 11.0, places=5) + + def test_cached_result_is_same_reference(self): + """Replay should return the exact same object reference as capture.""" + src = wp.zeros(4, dtype=wp.float32, device=self.device) + dst = wp.zeros(4, dtype=wp.float32, device=self.device) + + def my_fn(): + wp.launch(_add_one, dim=4, inputs=[src, dst], device=self.device) + return dst + + result1 = self.cache.capture_or_replay("ref_test", my_fn) + result2 = self.cache.capture_or_replay("ref_test", my_fn) + self.assertIs(result1, result2, "Replay must return the same object reference") + + def test_multiple_stages_independent(self): + """Different stages should be captured and replayed independently.""" + src_a = wp.full(4, value=1.0, dtype=wp.float32, device=self.device) + dst_a = wp.zeros(4, dtype=wp.float32, device=self.device) + src_b = wp.full(4, value=5.0, dtype=wp.float32, device=self.device) + dst_b = wp.zeros(4, dtype=wp.float32, device=self.device) + + def fn_a(): + wp.launch(_add_one, dim=4, inputs=[src_a, dst_a], device=self.device) + return dst_a + + def fn_b(): + wp.launch(_add_one, dim=4, inputs=[src_b, dst_b], device=self.device) + return dst_b + + result_a = self.cache.capture_or_replay("stage_a", fn_a) + result_b = self.cache.capture_or_replay("stage_b", fn_b) + + self.assertAlmostEqual(result_a.numpy()[0], 2.0, places=5) + self.assertAlmostEqual(result_b.numpy()[0], 6.0, places=5) + + # Replay both + result_a2 = self.cache.capture_or_replay("stage_a", fn_a) + result_b2 = self.cache.capture_or_replay("stage_b", fn_b) + self.assertIs(result_a, result_a2) + self.assertIs(result_b, result_b2) + + # ------------------------------------------------------------------ + # Invalidation + # ------------------------------------------------------------------ + + def test_invalidate_all(self): + """invalidate() with no args should drop all cached graphs.""" + src = wp.zeros(4, dtype=wp.float32, device=self.device) + dst = wp.zeros(4, dtype=wp.float32, device=self.device) + + call_count = [0] + + def my_fn(): + call_count[0] += 1 + wp.launch(_add_one, dim=4, inputs=[src, dst], device=self.device) + return dst + + self.cache.capture_or_replay("s1", my_fn) + self.assertEqual(call_count[0], 2) # warm-up + capture + + self.cache.invalidate() + + # After invalidation, next call should re-warm-up and re-capture + self.cache.capture_or_replay("s1", my_fn) + self.assertEqual(call_count[0], 4) # 2 more (warm-up + capture) + + def test_invalidate_single_stage(self): + """invalidate(stage) should only drop the named stage.""" + src = wp.zeros(4, dtype=wp.float32, device=self.device) + dst_a = wp.zeros(4, dtype=wp.float32, device=self.device) + dst_b = wp.zeros(4, dtype=wp.float32, device=self.device) + + count_a = [0] + count_b = [0] + + def fn_a(): + count_a[0] += 1 + wp.launch(_add_one, dim=4, inputs=[src, dst_a], device=self.device) + return dst_a + + def fn_b(): + count_b[0] += 1 + wp.launch(_add_one, dim=4, inputs=[src, dst_b], device=self.device) + return dst_b + + self.cache.capture_or_replay("a", fn_a) + self.cache.capture_or_replay("b", fn_b) + self.assertEqual(count_a[0], 2) + self.assertEqual(count_b[0], 2) + + # Invalidate only "a" + self.cache.invalidate("a") + + self.cache.capture_or_replay("a", fn_a) + self.cache.capture_or_replay("b", fn_b) + self.assertEqual(count_a[0], 4, "Stage 'a' should re-capture after invalidation") + self.assertEqual(count_b[0], 2, "Stage 'b' should replay (not re-capture)") + + def test_invalidate_nonexistent_stage_is_noop(self): + """Invalidating a stage that was never captured should not raise.""" + self.cache.invalidate("nonexistent") # should not raise + + # ------------------------------------------------------------------ + # Args / kwargs forwarding + # ------------------------------------------------------------------ + + def test_args_and_kwargs_forwarded(self): + """capture_or_replay should forward args and kwargs to fn.""" + src = wp.full(4, value=2.0, dtype=wp.float32, device=self.device) + dst = wp.zeros(4, dtype=wp.float32, device=self.device) + + def my_fn(a, b, device="cuda:0"): + wp.launch(_add_one, dim=4, inputs=[a, b], device=device) + return b + + result = self.cache.capture_or_replay( + "args_test", + my_fn, + args=(src, dst), + kwargs={"device": self.device}, + ) + self.assertAlmostEqual(result.numpy()[0], 3.0, places=5) + + +if __name__ == "__main__": + unittest.main() diff --git a/source/isaaclab_mimic/changelog.d/.gitkeep b/source/isaaclab_mimic/changelog.d/.gitkeep new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/source/isaaclab_mimic/config/extension.toml b/source/isaaclab_mimic/config/extension.toml index 51161facc43c..f53461c3fc6f 100644 --- a/source/isaaclab_mimic/config/extension.toml +++ b/source/isaaclab_mimic/config/extension.toml @@ -1,7 +1,7 @@ [package] # Semantic Versioning is used: https://semver.org/ -version = "1.2.3" +version = "1.2.5" # Description category = "isaaclab" diff --git a/source/isaaclab_mimic/docs/CHANGELOG.rst b/source/isaaclab_mimic/docs/CHANGELOG.rst index cfbdbec2847c..782cf6f7d220 100644 --- a/source/isaaclab_mimic/docs/CHANGELOG.rst +++ b/source/isaaclab_mimic/docs/CHANGELOG.rst @@ -1,6 +1,30 @@ Changelog --------- +1.2.5 (2026-04-14) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Updated mobility path utilities to import from ``isaacsim.replicator.experimental.mobility_gen``. + + +1.2.4 (2026-04-06) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Made performance enhancing changes to data generation pipeline (elimate large tensor usage, reduce asyncio overhead and blocking) +* Locked h5py dependency to last stable version 3.15.1 to prevent package import errors on Windows with version 3.16.0. + +Added +^^^^^ + +* Added data generation test cases for all tasks (single and multi environment). + + 1.2.3 (2026-03-12) ~~~~~~~~~~~~~~~~~~~ diff --git a/source/isaaclab_mimic/isaaclab_mimic/datagen/data_generator.py b/source/isaaclab_mimic/isaaclab_mimic/datagen/data_generator.py index c72b40602831..6851a90256f2 100644 --- a/source/isaaclab_mimic/isaaclab_mimic/datagen/data_generator.py +++ b/source/isaaclab_mimic/isaaclab_mimic/datagen/data_generator.py @@ -6,13 +6,13 @@ """Base class for data generator.""" import asyncio +import contextlib import copy import logging from typing import Any import numpy as np import torch -import warp as wp import isaaclab.utils.math as PoseUtils @@ -33,6 +33,16 @@ from .datagen_info_pool import DataGenInfoPool +@contextlib.asynccontextmanager +async def _optional_lock(lock): + """Async context manager that acquires the lock only if it is not None.""" + if lock is not None: + async with lock: + yield + else: + yield + + def transform_source_data_segment_using_delta_object_pose( src_eef_poses: torch.Tensor, delta_obj_pose: torch.Tensor, @@ -664,10 +674,7 @@ async def generate( # noqa: C901 for subtask_constraint in self.env_cfg.task_constraint_configs: runtime_subtask_constraints_dict.update(subtask_constraint.generate_runtime_subtask_constraints()) - # save generated data in these variables - generated_states = [] - generated_obs = [] - generated_actions = [] + # Track if the generated trajectory was successful generated_success = False # some eef-specific state variables used during generation @@ -694,7 +701,8 @@ async def generate( # noqa: C901 # While loop that runs per time step while True: - async with self.src_demo_datagen_info_pool.asyncio_lock: + await asyncio.sleep(0) + async with _optional_lock(self.src_demo_datagen_info_pool.asyncio_lock): if len(self.src_demo_datagen_info_pool.datagen_infos) > prev_src_demo_datagen_info_pool_size: # src_demo_datagen_info_pool at this point may be updated with new demos, # So we need to update subtask boundaries again @@ -865,26 +873,24 @@ async def generate( # noqa: C901 # Update visualization if motion planner is available if motion_planner and motion_planner.visualize_spheres: - current_joints = wp.to_torch(self.env.scene["robot"].data.joint_pos)[env_id] + current_joints = self.env.scene["robot"].data.joint_pos.torch[env_id] motion_planner._update_visualization_at_joint_positions(current_joints) eef_waypoint_dict[eef_name] = waypoint multi_waypoint = MultiWaypoint(eef_waypoint_dict) + await asyncio.sleep(0) + # Execute the next waypoints for all eefs - exec_results = await multi_waypoint.execute( + exec_success = await multi_waypoint.execute( env=self.env, success_term=success_term, env_id=env_id, env_action_queue=env_action_queue, ) - # Update execution state buffers - if len(exec_results["states"]) > 0: - generated_states.extend(exec_results["states"]) - generated_obs.extend(exec_results["observations"]) - generated_actions.extend(exec_results["actions"]) - generated_success = generated_success or exec_results["success"] + # Update success state + generated_success = generated_success or exec_success # Get the navigation state if self.env_cfg.datagen_config.use_navigation_controller: @@ -983,10 +989,6 @@ async def generate( # noqa: C901 if all(eef_subtasks_done.values()): break - # Merge numpy arrays - if len(generated_actions) > 0: - generated_actions = torch.cat(generated_actions, dim=0) - # Set success to the recorded episode data and export to file self.env.recorder_manager.set_success_to_episodes( env_id_tensor, torch.tensor([[generated_success]], dtype=torch.bool, device=self.env.device) @@ -996,9 +998,6 @@ async def generate( # noqa: C901 results = dict( initial_state=new_initial_state, - states=generated_states, - observations=generated_obs, - actions=generated_actions, success=generated_success, ) return results diff --git a/source/isaaclab_mimic/isaaclab_mimic/datagen/generation.py b/source/isaaclab_mimic/isaaclab_mimic/datagen/generation.py index 71bb5e9925cd..1761cf9beaa7 100644 --- a/source/isaaclab_mimic/isaaclab_mimic/datagen/generation.py +++ b/source/isaaclab_mimic/isaaclab_mimic/datagen/generation.py @@ -78,6 +78,7 @@ def env_loop( env_action_queue: asyncio.Queue, shared_datagen_info_pool: DataGenInfoPool, asyncio_event_loop: asyncio.AbstractEventLoop, + data_gen_tasks: asyncio.Future | None = None, ): """Main asyncio loop for the environment. @@ -87,6 +88,8 @@ def env_loop( env_action_queue: The asyncio queue to handle actions to for executing actions. shared_datagen_info_pool: The shared datagen info pool that stores source demo info. asyncio_event_loop: The main asyncio event loop. + data_gen_tasks: The gathered async data generation future. When provided, the loop + will exit early if all tasks finish unexpectedly (e.g. due to an unhandled exception). """ global num_success, num_failures, num_attempts env_id_tensor = torch.tensor([0], dtype=torch.int64, device=env.device) @@ -97,17 +100,20 @@ def env_loop( # check if any environment needs to be reset while waiting for actions while env_action_queue.qsize() != env.num_envs: asyncio_event_loop.run_until_complete(asyncio.sleep(0)) + if data_gen_tasks is not None and data_gen_tasks.done(): + exc = data_gen_tasks.exception() + if exc is not None: + raise exc + return while not env_reset_queue.empty(): env_id_tensor[0] = env_reset_queue.get_nowait() env.reset(env_ids=env_id_tensor) env_reset_queue.task_done() actions = torch.zeros(env.action_space.shape) - - # get actions from all the data generators - for i in range(env.num_envs): - # an async-blocking call to get an action from a data generator - env_id, action = asyncio_event_loop.run_until_complete(env_action_queue.get()) + get_tasks = [env_action_queue.get() for _ in range(env.num_envs)] + results = asyncio_event_loop.run_until_complete(asyncio.gather(*get_tasks)) + for env_id, action in results: actions[env_id] = action # perform action on environment @@ -152,6 +158,7 @@ def setup_env_config( device: str, generation_num_trials: int | None = None, recorder_cfg: RecorderManagerBaseCfg | None = None, + dataset_compression: bool = True, ) -> tuple[Any, Any]: """Configure the environment for data generation. @@ -162,6 +169,8 @@ def setup_env_config( num_envs: Number of environments to run device: Device to run on generation_num_trials: Optional override for number of trials + recorder_cfg: Recorder manager configuration + dataset_compression: Whether to enable dataset compression Returns: tuple containing: @@ -198,6 +207,8 @@ def setup_env_config( env_cfg.recorders.dataset_export_dir_path = output_dir env_cfg.recorders.dataset_filename = output_file_name + env_cfg.recorders.dataset_compression = dataset_compression + if env_cfg.datagen_config.generation_keep_failed: env_cfg.recorders.dataset_export_mode = DatasetExportMode.EXPORT_SUCCEEDED_FAILED_IN_SEPARATE_FILES else: @@ -230,8 +241,7 @@ def setup_async_generation( asyncio_event_loop = asyncio.get_event_loop() env_reset_queue = asyncio.Queue() env_action_queue = asyncio.Queue() - shared_datagen_info_pool_lock = asyncio.Lock() - shared_datagen_info_pool = DataGenInfoPool(env, env.cfg, env.device, asyncio_lock=shared_datagen_info_pool_lock) + shared_datagen_info_pool = DataGenInfoPool(env, env.cfg, env.device) shared_datagen_info_pool.load_from_dataset_file(input_file) print(f"Loaded {shared_datagen_info_pool.num_datagen_infos} to datagen info pool") diff --git a/source/isaaclab_mimic/isaaclab_mimic/datagen/waypoint.py b/source/isaaclab_mimic/isaaclab_mimic/datagen/waypoint.py index 964cc2a49dda..a0f4083e868a 100644 --- a/source/isaaclab_mimic/isaaclab_mimic/datagen/waypoint.py +++ b/source/isaaclab_mimic/isaaclab_mimic/datagen/waypoint.py @@ -381,11 +381,8 @@ async def execute( env_action_queue: The asyncio queue to put the action into. Returns: - A dictionary containing the state, observation, action, and success of the multi-waypoint actions. + The success of the multi-waypoint actions. """ - # current state - state = env.scene.get_state(is_relative=True) - # construct action from target poses and gripper actions target_eef_pose_dict = {eef_name: waypoint.pose for eef_name, waypoint in self.waypoints.items()} gripper_action_dict = {eef_name: waypoint.gripper_action for eef_name, waypoint in self.waypoints.items()} @@ -412,18 +409,11 @@ async def execute( # step environment if env_action_queue is None: - obs, _, _, _, _ = env.step(play_action) + env.step(play_action) else: await env_action_queue.put((env_id, play_action[0])) await env_action_queue.join() - obs = env.obs_buf success = bool(success_term.func(env, **success_term.params)[env_id]) - result = dict( - states=[state], - observations=[obs], - actions=[play_action], - success=success, - ) - return result + return success diff --git a/source/isaaclab_mimic/isaaclab_mimic/locomanipulation_sdg/path_utils.py b/source/isaaclab_mimic/isaaclab_mimic/locomanipulation_sdg/path_utils.py index 3baacc3dfb31..46ade12e70a6 100644 --- a/source/isaaclab_mimic/isaaclab_mimic/locomanipulation_sdg/path_utils.py +++ b/source/isaaclab_mimic/isaaclab_mimic/locomanipulation_sdg/path_utils.py @@ -6,7 +6,7 @@ import torch -from isaacsim.replicator.mobility_gen.impl.path_planner import compress_path, generate_paths +from isaacsim.replicator.experimental.mobility_gen.impl.path_planner import compress_path, generate_paths from .occupancy_map_utils import OccupancyMap from .scene_utils import HasPose2d diff --git a/source/isaaclab_mimic/isaaclab_mimic/locomanipulation_sdg/scene_utils.py b/source/isaaclab_mimic/isaaclab_mimic/locomanipulation_sdg/scene_utils.py index 79cf307c9cb3..a0eb00fb4a58 100644 --- a/source/isaaclab_mimic/isaaclab_mimic/locomanipulation_sdg/scene_utils.py +++ b/source/isaaclab_mimic/isaaclab_mimic/locomanipulation_sdg/scene_utils.py @@ -10,7 +10,7 @@ import warp as wp import isaaclab.utils.math as math_utils -from isaaclab.sim.views import XformPrimView +from isaaclab.sim.views import FrameView from .occupancy_map_utils import OccupancyMap, intersect_occupancy_maps from .transform_utils import transform_mul @@ -85,7 +85,7 @@ def __init__(self, scene, entity_name: str, body_name: str): def get_pose(self): """Get the 3D pose of the entity.""" - body_link_state_w = wp.to_torch(self.scene[self.entity_name].data.body_link_state_w) + body_link_state_w = self.scene[self.entity_name].data.body_link_state_w.torch pose = body_link_state_w[ :, self.scene[self.entity_name].data.body_names.index(self.body_name), @@ -101,19 +101,21 @@ def __init__(self, scene, entity_name: str): self.scene = scene self.entity_name = entity_name - def _get_xform_view(self) -> XformPrimView: - """Return the XformPrimView for this asset, refreshing it if prims were not yet cloned.""" + def _get_xform_view(self) -> FrameView: + """Return the FrameView for this asset, refreshing it if prims were not yet cloned.""" xform_prim = self.scene[self.entity_name] if xform_prim.count == 0: # The view was created before environment cloning; rebuild it now that prims exist. - xform_prim = XformPrimView(xform_prim._prim_path, device=xform_prim.device) + xform_prim = FrameView(xform_prim._prim_path, device=xform_prim.device) self.scene.extras[self.entity_name] = xform_prim return xform_prim def get_pose(self): """Get the 3D pose of the entity.""" xform_prim = self._get_xform_view() - position, orientation = xform_prim.get_world_poses() + pos_w, quat_w = xform_prim.get_world_poses() + position = pos_w.torch + orientation = quat_w.torch pose = torch.cat([position, orientation], dim=-1) return pose @@ -122,7 +124,7 @@ def set_pose(self, pose: torch.Tensor): xform_prim = self._get_xform_view() position = pose[..., :3] orientation = pose[..., 3:] - xform_prim.set_world_poses(position, orientation, None) + xform_prim.set_world_poses(wp.from_torch(position.contiguous()), wp.from_torch(orientation.contiguous()), None) class RelativePose(HasPose): diff --git a/source/isaaclab_mimic/isaaclab_mimic/motion_planners/curobo/curobo_planner.py b/source/isaaclab_mimic/isaaclab_mimic/motion_planners/curobo/curobo_planner.py index 3761a5858f26..c03db9c32921 100644 --- a/source/isaaclab_mimic/isaaclab_mimic/motion_planners/curobo/curobo_planner.py +++ b/source/isaaclab_mimic/isaaclab_mimic/motion_planners/curobo/curobo_planner.py @@ -9,7 +9,6 @@ import numpy as np import torch -import warp as wp from curobo.cuda_robot_model.cuda_robot_model import CudaRobotModelState from curobo.geom.sdf.world import CollisionCheckerType @@ -194,7 +193,7 @@ def __init__( # Use env-local base translation for multi-env rendering consistency env_origin = self.env.scene.env_origins[env_id, :3] - base_translation = (wp.to_torch(self.robot.data.root_pos_w)[env_id, :3] - env_origin).detach().cpu().numpy() + base_translation = (self.robot.data.root_pos_w.torch[env_id, :3] - env_origin).detach().cpu().numpy() self.plan_visualizer = PlanVisualizer( robot_name=self.config.robot_name, recording_id=f"curobo_plan_{env_id}", @@ -628,8 +627,8 @@ def _sync_object_poses_with_isaaclab(self) -> None: # Get current pose from Lab (may be on CPU or CUDA depending on --device flag) obj = rigid_objects[object_name] env_origin = self.env.scene.env_origins[self.env_id] - current_pos_raw = wp.to_torch(obj.data.root_pos_w)[self.env_id] - env_origin - current_quat_raw = wp.to_torch(obj.data.root_quat_w)[self.env_id] # (x, y, z, w) + current_pos_raw = obj.data.root_pos_w.torch[self.env_id] - env_origin + current_quat_raw = obj.data.root_quat_w.torch[self.env_id] # (x, y, z, w) # Convert to cuRobo device and extract float values for pose list current_pos = self._to_curobo_device(current_pos_raw) @@ -669,8 +668,8 @@ def _sync_object_poses_with_isaaclab(self) -> None: # Get current pose and update in collision checker obj = rigid_objects[object_name] env_origin = self.env.scene.env_origins[self.env_id] - current_pos_raw = wp.to_torch(obj.data.root_pos_w)[self.env_id] - env_origin - current_quat_raw = wp.to_torch(obj.data.root_quat_w)[self.env_id] + current_pos_raw = obj.data.root_pos_w.torch[self.env_id] - env_origin + current_quat_raw = obj.data.root_quat_w.torch[self.env_id] current_pos = self._to_curobo_device(current_pos_raw) current_quat = self._to_curobo_device(current_quat_raw) @@ -933,7 +932,7 @@ def _get_current_joint_state_for_curobo(self) -> JointState: and zero velocity/acceleration. """ # Fetch joint position (shape: [1, num_joints]) - joint_pos_raw: torch.Tensor = wp.to_torch(self.robot.data.joint_pos)[self.env_id, :].unsqueeze(0) + joint_pos_raw: torch.Tensor = self.robot.data.joint_pos.torch[self.env_id, :].unsqueeze(0) joint_vel_raw: torch.Tensor = torch.zeros_like(joint_pos_raw) joint_acc_raw: torch.Tensor = torch.zeros_like(joint_pos_raw) @@ -1574,7 +1573,7 @@ def _update_visualization_at_joint_positions(self, joint_positions: torch.Tensor if self.frame_counter % self.sphere_update_freq != 0: return - original_joints: torch.Tensor = wp.to_torch(self.robot.data.joint_pos)[self.env_id].clone() + original_joints: torch.Tensor = self.robot.data.joint_pos.torch[self.env_id].clone() try: # Ensure joint positions are on environment device for robot commands @@ -1701,7 +1700,7 @@ def _create_sphere_config(self, sphere_idx: int, sphere, robot_link_count: int) opacity = 0.9 if is_attached else 0.5 # Calculate position in world frame (do not use env_origin) - root_translation = wp.to_torch(self.robot.data.root_pos_w)[self.env_id, :3].detach().cpu().numpy() + root_translation = self.robot.data.root_pos_w.torch[self.env_id, :3].detach().cpu().numpy() position = sphere.position.cpu().numpy() if hasattr(sphere.position, "cpu") else sphere.position if not is_attached: position = position + root_translation @@ -1788,7 +1787,7 @@ def update_world_and_plan_motion( gripper_closed = expected_attached_object is not None self._set_gripper_state(gripper_closed) current_attached = self.get_attached_objects() - gripper_pos = wp.to_torch(self.robot.data.joint_pos)[env_id, -2:] + gripper_pos = self.robot.data.joint_pos.torch[env_id, -2:] self.logger.debug(f"Current attached objects: {current_attached}") @@ -1810,13 +1809,13 @@ def update_world_and_plan_motion( if expected_attached_object in rigid_objects: obj = rigid_objects[expected_attached_object] origin = self.env.scene.env_origins[env_id] - obj_pos = wp.to_torch(obj.data.root_pos_w)[env_id] - origin + obj_pos = obj.data.root_pos_w.torch[env_id] - origin self.logger.debug(f"Isaac Lab object position: {obj_pos}") # Debug end-effector position ee_frame_cfg = SceneEntityCfg("ee_frame") ee_frame = self.env.scene[ee_frame_cfg.name] - ee_pos = wp.to_torch(ee_frame.data.target_pos_w)[env_id, 0, :] - origin + ee_pos = ee_frame.data.target_pos_w.torch[env_id, 0, :] - origin self.logger.debug(f"End-effector position: {ee_pos}") # Debug distance diff --git a/source/isaaclab_mimic/setup.py b/source/isaaclab_mimic/setup.py index 8a7890878196..e3d9e2dc6ac3 100644 --- a/source/isaaclab_mimic/setup.py +++ b/source/isaaclab_mimic/setup.py @@ -23,7 +23,7 @@ # jupyter notebook "ipywidgets==8.1.5", # data collection - "h5py", + "h5py==3.15.1", ] # nvidia-srl-usd-to-urdf depends on usd-core which has no aarch64 wheels @@ -56,13 +56,10 @@ extras_require=EXTRAS_REQUIRE, license="Apache-2.0", include_package_data=True, - python_requires=">=3.10", + python_requires=">=3.12", classifiers=[ "Natural Language :: English", - "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", - "Isaac Sim :: 5.0.0", - "Isaac Sim :: 5.1.0", "Isaac Sim :: 6.0.0", ], zip_safe=False, diff --git a/source/isaaclab_mimic/test/mimic_test_utils.py b/source/isaaclab_mimic/test/mimic_test_utils.py new file mode 100644 index 000000000000..1ffd7d466282 --- /dev/null +++ b/source/isaaclab_mimic/test/mimic_test_utils.py @@ -0,0 +1,83 @@ +# Copyright (c) 2024-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +"""Shared test utilities for isaaclab_mimic dataset generation tests.""" + +import contextlib +import os +import signal +import subprocess + +SUBPROCESS_GRACE_PERIOD = 15 +"""Grace period [s] after SIGTERM before sending SIGKILL.""" + +SUBPROCESS_DRAIN_TIMEOUT = 5 +"""Timeout [s] for draining remaining pipe output after killing a process group.""" + + +def _kill_process_group(pgid: int, sig: int): + """Send *sig* to every process in the group, ignoring errors if already dead.""" + with contextlib.suppress(ProcessLookupError): + os.killpg(pgid, sig) + + +def run_script(command: list[str], timeout: int = 5000) -> subprocess.CompletedProcess: + """Run a script in a subprocess and return a CompletedProcess. + + The Kit / Omniverse runtime's ``simulation_app.close()`` can hang + indefinitely when another ``SimulationApp`` instance is alive in the parent + test process (shared GPU / IPC resources). To avoid blocking the test + suite we use ``Popen`` with an explicit timeout: + + 1. Wait up to *timeout* seconds for the process to finish. + 2. On timeout send ``SIGTERM`` to the **entire process group** and wait + :data:`SUBPROCESS_GRACE_PERIOD` seconds. + 3. If still alive, ``SIGKILL`` the process group and collect remaining + output. + + The subprocess is started in its own session (``start_new_session=True``) + so that signals reach Kit child processes, and pipe draining after a kill + uses a bounded timeout to avoid blocking on orphaned FD holders. + + The captured *stdout* / *stderr* are returned regardless of how the process + terminated so that callers can validate the script's printed output. + + Args: + command: The command to execute as a list of strings. + timeout: Maximum time [s] to wait for the process to finish. + """ + process = subprocess.Popen( + command, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + start_new_session=True, + ) + pgid = os.getpgid(process.pid) + try: + stdout, stderr = process.communicate(timeout=timeout) + except subprocess.TimeoutExpired: + _kill_process_group(pgid, signal.SIGTERM) + try: + stdout, stderr = process.communicate(timeout=SUBPROCESS_GRACE_PERIOD) + except subprocess.TimeoutExpired: + _kill_process_group(pgid, signal.SIGKILL) + try: + stdout, stderr = process.communicate(timeout=SUBPROCESS_DRAIN_TIMEOUT) + except subprocess.TimeoutExpired: + # Orphaned grandchildren may still hold pipe FDs open. + # Close our ends so we don't block forever, then reap the + # zombie leader. + process.stdout.close() + process.stderr.close() + process.wait() + stdout, stderr = "", "" + + return subprocess.CompletedProcess( + args=command, + returncode=process.returncode, + stdout=stdout or "", + stderr=stderr or "", + ) diff --git a/source/isaaclab_mimic/test/test_curobo_planner_cube_stack.py b/source/isaaclab_mimic/test/test_curobo_planner_cube_stack.py index 04c5f4939f9c..8dea1cb14f74 100644 --- a/source/isaaclab_mimic/test/test_curobo_planner_cube_stack.py +++ b/source/isaaclab_mimic/test/test_curobo_planner_cube_stack.py @@ -27,7 +27,6 @@ import gymnasium as gym import torch -import warp as wp import isaaclab.utils.math as math_utils from isaaclab.assets import Articulation, RigidObject @@ -165,7 +164,7 @@ def _pose_from_xy_quat(self, xy: torch.Tensor, z: float, quat: torch.Tensor) -> def _get_cube_pos(self, cube_name: str) -> torch.Tensor: """Return the current world position of a cube's root (x, y, z).""" obj: RigidObject = self.env.scene[cube_name] - return wp.to_torch(obj.data.root_pos_w)[0, :3].clone().detach() + return obj.data.root_pos_w.torch[0, :3].clone().detach() def _place_pose_over_cube(self, cube_name: str, height_offset: float) -> torch.Tensor: """Compute a goal pose directly above the named cube using the latest pose.""" diff --git a/source/isaaclab_mimic/test/test_generate_dataset.py b/source/isaaclab_mimic/test/test_generate_dataset_franka_state.py similarity index 63% rename from source/isaaclab_mimic/test/test_generate_dataset.py rename to source/isaaclab_mimic/test/test_generate_dataset_franka_state.py index 63aceb95a678..cea7d31ea374 100644 --- a/source/isaaclab_mimic/test/test_generate_dataset.py +++ b/source/isaaclab_mimic/test/test_generate_dataset_franka_state.py @@ -11,65 +11,18 @@ simulation_app = AppLauncher(headless=True).app import os -import signal -import subprocess import sys import tempfile import pytest +from mimic_test_utils import run_script from isaaclab.utils.assets import ISAACLAB_NUCLEUS_DIR, retrieve_file_path DATASETS_DOWNLOAD_DIR = tempfile.mkdtemp(suffix="_Isaac-Stack-Cube-Franka-IK-Rel-Mimic-v0") NUCLEUS_DATASET_PATH = os.path.join(ISAACLAB_NUCLEUS_DIR, "Tests", "Mimic", "dataset.hdf5") -EXPECTED_SUCCESSFUL_ANNOTATIONS = 10 - -# Timeout for subprocess execution (seconds). The annotation / generation -# scripts run a full simulation loop which can take several minutes. A second, -# shorter grace period is given after the timeout to allow cleanup before the -# process is forcefully killed. -_SUBPROCESS_TIMEOUT = 600 -_SUBPROCESS_GRACE_PERIOD = 15 - - -def _run_script(command: list[str]) -> subprocess.CompletedProcess: - """Run a script in a subprocess and return a CompletedProcess. - - The Kit / Omniverse runtime's ``simulation_app.close()`` can hang - indefinitely when another ``SimulationApp`` instance is alive in the parent - test process (shared GPU / IPC resources). To avoid blocking the test - suite we use ``Popen`` with an explicit timeout: - - 1. Wait up to ``_SUBPROCESS_TIMEOUT`` seconds for the process to finish. - 2. On timeout send ``SIGTERM`` and wait ``_SUBPROCESS_GRACE_PERIOD`` seconds. - 3. If still alive, ``SIGKILL`` and collect remaining output. - - The captured *stdout* / *stderr* are returned regardless of how the process - terminated so that callers can validate the script's printed output. - """ - process = subprocess.Popen( - command, - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - text=True, - ) - try: - stdout, stderr = process.communicate(timeout=_SUBPROCESS_TIMEOUT) - except subprocess.TimeoutExpired: - # Script likely hung during simulation_app.close() – ask nicely first. - process.send_signal(signal.SIGTERM) - try: - stdout, stderr = process.communicate(timeout=_SUBPROCESS_GRACE_PERIOD) - except subprocess.TimeoutExpired: - process.kill() - stdout, stderr = process.communicate() - - return subprocess.CompletedProcess( - args=command, - returncode=process.returncode, - stdout=stdout or "", - stderr=stderr or "", - ) + +_SUBPROCESS_TIMEOUT = 5000 @pytest.fixture @@ -125,7 +78,7 @@ def setup_test_environment(): ] print(config_command) - result = _run_script(config_command) + result = run_script(config_command, timeout=_SUBPROCESS_TIMEOUT) print(f"Annotate demos result: {result.returncode}\n") @@ -155,9 +108,7 @@ def setup_test_environment(): except (ValueError, IndexError) as e: pytest.fail(f"Could not parse successful task count from line: '{success_line}'. Error: {e}") - assert successful_count == EXPECTED_SUCCESSFUL_ANNOTATIONS, ( - f"Expected {EXPECTED_SUCCESSFUL_ANNOTATIONS} successful annotations but got {successful_count}" - ) + assert successful_count > 0, "No successful annotations found." # Also verify the annotated output file was created assert os.path.exists(annotated_output_path), f"Annotated dataset file was not created at {annotated_output_path}" @@ -172,46 +123,51 @@ def setup_test_environment(): del os.environ["PYTHONUNBUFFERED"] -@pytest.mark.isaacsim_ci -def test_generate_dataset(setup_test_environment): - """Test the dataset generation script.""" - workflow_root = setup_test_environment - - annotated_input_path = os.path.join(DATASETS_DOWNLOAD_DIR, "annotated_dataset.hdf5") - generated_output_path = os.path.join(DATASETS_DOWNLOAD_DIR, "generated_dataset.hdf5") - - # Define the command to run the dataset generation script directly - # (bypassing isaaclab.sh — see fixture comments for rationale). +def _run_generation(workflow_root: str, input_file: str, output_file: str, num_envs: int): + """Build the generation command, run it, and assert success.""" command = [ sys.executable, os.path.join(workflow_root, "scripts/imitation_learning/isaaclab_mimic/generate_dataset.py"), "--input_file", - annotated_input_path, + input_file, "--output_file", - generated_output_path, + output_file, + "--num_envs", + str(num_envs), "--generation_num_trials", "1", "--headless", ] - result = _run_script(command) + result = run_script(command, timeout=_SUBPROCESS_TIMEOUT) - # Print the result for debugging purposes - print("Dataset generation result:") - print(result.stdout) # Print standard output from the command - print(result.stderr) # Print standard error from the command + print(f"State-based dataset generation result (num_envs={num_envs}):") + print(result.stdout) + print(result.stderr) - # Verify the generated dataset file was created. - # Note: we cannot rely solely on the exit code because the Kit runtime may - # reset it to 0 during cleanup, so we check the output file and stdout. - assert os.path.exists(generated_output_path), ( - f"Generated dataset file was not created at {generated_output_path}.\n" + assert os.path.exists(output_file), ( + f"Generated dataset file was not created at {output_file}.\n" f"returncode: {result.returncode}\nstderr: {result.stderr}" ) - # Check for the expected completion message in output combined_output = result.stdout + "\n" + result.stderr expected_output = "successes/attempts. Exiting" assert expected_output in combined_output, ( f"Could not find '{expected_output}' in output.\nstdout: {result.stdout}\nstderr: {result.stderr}" ) + + +def test_generate_dataset_franka_state(setup_test_environment): + """Test dataset generation for the state-based cube-stack environment (single env).""" + workflow_root = setup_test_environment + annotated_input_path = os.path.join(DATASETS_DOWNLOAD_DIR, "annotated_dataset.hdf5") + generated_output_path = os.path.join(DATASETS_DOWNLOAD_DIR, "generated_dataset.hdf5") + _run_generation(workflow_root, annotated_input_path, generated_output_path, num_envs=1) + + +def test_generate_dataset_franka_state_multi_env(setup_test_environment): + """Test dataset generation for the state-based cube-stack environment (5 envs).""" + workflow_root = setup_test_environment + annotated_input_path = os.path.join(DATASETS_DOWNLOAD_DIR, "annotated_dataset.hdf5") + generated_output_path = os.path.join(DATASETS_DOWNLOAD_DIR, "generated_dataset_multi_env.hdf5") + _run_generation(workflow_root, annotated_input_path, generated_output_path, num_envs=5) diff --git a/source/isaaclab_mimic/test/test_generate_dataset_franka_visuomotor.py b/source/isaaclab_mimic/test/test_generate_dataset_franka_visuomotor.py new file mode 100644 index 000000000000..4f4fe70d8a59 --- /dev/null +++ b/source/isaaclab_mimic/test/test_generate_dataset_franka_visuomotor.py @@ -0,0 +1,110 @@ +# Copyright (c) 2024-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +"""Test dataset generation for Isaac-Stack-Cube-Franka-IK-Rel-Visuomotor-Mimic-v0.""" + +from isaaclab.app import AppLauncher + +# launch omniverse app +simulation_app = AppLauncher(headless=True).app + +import os +import sys +import tempfile + +import pytest +from mimic_test_utils import run_script + +from isaaclab.utils.assets import ISAACLAB_NUCLEUS_DIR, retrieve_file_path + +_TASK_NAME = "Isaac-Stack-Cube-Franka-IK-Rel-Visuomotor-Mimic-v0" +DATASETS_DOWNLOAD_DIR = tempfile.mkdtemp(suffix=f"_{_TASK_NAME}") +NUCLEUS_ANNOTATED_DATASET_PATH = os.path.join( + ISAACLAB_NUCLEUS_DIR, "Mimic", "Tests", "annotated_dataset_franka_visuomotor_test.hdf5" +) + + +@pytest.fixture +def setup_visuomotor_test_environment(): + """Download the pre-annotated dataset and prepare the test environment.""" + if not os.path.exists(DATASETS_DOWNLOAD_DIR): + os.makedirs(DATASETS_DOWNLOAD_DIR) + + try: + downloaded_dataset_path = retrieve_file_path(NUCLEUS_ANNOTATED_DATASET_PATH, DATASETS_DOWNLOAD_DIR) + except Exception as e: + print(e) + pytest.fail( + "The pre-annotated dataset required for this test is currently unavailable. " + f"Dataset path: {NUCLEUS_ANNOTATED_DATASET_PATH}" + ) + + assert os.path.isfile(downloaded_dataset_path), ( + f"retrieve_file_path returned '{downloaded_dataset_path}' but the file does not exist on disk." + ) + + pythonunbuffered_env_var_ = os.environ.get("PYTHONUNBUFFERED") + os.environ["PYTHONUNBUFFERED"] = "1" + + current_dir = os.path.dirname(os.path.abspath(__file__)) + workflow_root = os.path.abspath(os.path.join(current_dir, "../../..")) + + yield workflow_root, downloaded_dataset_path + + if pythonunbuffered_env_var_: + os.environ["PYTHONUNBUFFERED"] = pythonunbuffered_env_var_ + else: + del os.environ["PYTHONUNBUFFERED"] + + +def _run_generation(workflow_root: str, input_file: str, output_file: str, num_envs: int): + """Build the generation command, run it, and assert success.""" + command = [ + sys.executable, + os.path.join(workflow_root, "scripts/imitation_learning/isaaclab_mimic/generate_dataset.py"), + "--task", + _TASK_NAME, + "--input_file", + input_file, + "--output_file", + output_file, + "--num_envs", + str(num_envs), + "--generation_num_trials", + "1", + "--enable_cameras", + "--headless", + ] + + result = run_script(command) + + print(f"Visuomotor dataset generation result (num_envs={num_envs}):") + print(result.stdout) + print(result.stderr) + + assert os.path.exists(output_file), ( + f"Generated dataset file was not created at {output_file}.\n" + f"returncode: {result.returncode}\nstderr: {result.stderr}" + ) + + combined_output = result.stdout + "\n" + result.stderr + expected_output = "successes/attempts. Exiting" + assert expected_output in combined_output, ( + f"Could not find '{expected_output}' in output.\nstdout: {result.stdout}\nstderr: {result.stderr}" + ) + + +def test_generate_dataset_franka_visuomotor(setup_visuomotor_test_environment): + """Test dataset generation for the visuomotor cube-stack environment (single env).""" + workflow_root, input_file = setup_visuomotor_test_environment + output_file = os.path.join(DATASETS_DOWNLOAD_DIR, "generated_dataset.hdf5") + _run_generation(workflow_root, input_file, output_file, num_envs=1) + + +def test_generate_dataset_franka_visuomotor_multi_env(setup_visuomotor_test_environment): + """Test dataset generation for the visuomotor cube-stack environment (5 envs).""" + workflow_root, input_file = setup_visuomotor_test_environment + output_file = os.path.join(DATASETS_DOWNLOAD_DIR, "generated_dataset_multi_env.hdf5") + _run_generation(workflow_root, input_file, output_file, num_envs=5) diff --git a/source/isaaclab_mimic/test/test_generate_dataset_gr1t2_nutpour.py b/source/isaaclab_mimic/test/test_generate_dataset_gr1t2_nutpour.py new file mode 100644 index 000000000000..ed41a827752e --- /dev/null +++ b/source/isaaclab_mimic/test/test_generate_dataset_gr1t2_nutpour.py @@ -0,0 +1,110 @@ +# Copyright (c) 2024-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +"""Test dataset generation for Isaac-NutPour-GR1T2-Pink-IK-Abs-Mimic-v0.""" + +from isaaclab.app import AppLauncher + +# launch omniverse app +simulation_app = AppLauncher(headless=True).app + +import os +import sys +import tempfile + +import pytest +from mimic_test_utils import run_script + +from isaaclab.utils.assets import ISAACLAB_NUCLEUS_DIR, retrieve_file_path + +_TASK_NAME = "Isaac-NutPour-GR1T2-Pink-IK-Abs-Mimic-v0" +DATASETS_DOWNLOAD_DIR = tempfile.mkdtemp(suffix=f"_{_TASK_NAME}") +NUCLEUS_ANNOTATED_DATASET_PATH = os.path.join( + ISAACLAB_NUCLEUS_DIR, "Mimic", "Tests", "annotated_dataset_gr1_nut_pouring_test.hdf5" +) + + +@pytest.fixture +def setup_nutpour_gr1t2_test_environment(): + """Download the pre-annotated dataset and prepare the test environment.""" + if not os.path.exists(DATASETS_DOWNLOAD_DIR): + os.makedirs(DATASETS_DOWNLOAD_DIR) + + try: + downloaded_dataset_path = retrieve_file_path(NUCLEUS_ANNOTATED_DATASET_PATH, DATASETS_DOWNLOAD_DIR) + except Exception as e: + print(e) + pytest.fail( + "The pre-annotated dataset required for this test is currently unavailable. " + f"Dataset path: {NUCLEUS_ANNOTATED_DATASET_PATH}" + ) + + assert os.path.isfile(downloaded_dataset_path), ( + f"retrieve_file_path returned '{downloaded_dataset_path}' but the file does not exist on disk." + ) + + pythonunbuffered_env_var_ = os.environ.get("PYTHONUNBUFFERED") + os.environ["PYTHONUNBUFFERED"] = "1" + + current_dir = os.path.dirname(os.path.abspath(__file__)) + workflow_root = os.path.abspath(os.path.join(current_dir, "../../..")) + + yield workflow_root, downloaded_dataset_path + + if pythonunbuffered_env_var_: + os.environ["PYTHONUNBUFFERED"] = pythonunbuffered_env_var_ + else: + del os.environ["PYTHONUNBUFFERED"] + + +def _run_generation(workflow_root: str, input_file: str, output_file: str, num_envs: int): + """Build the generation command, run it, and assert success.""" + command = [ + sys.executable, + os.path.join(workflow_root, "scripts/imitation_learning/isaaclab_mimic/generate_dataset.py"), + "--task", + _TASK_NAME, + "--input_file", + input_file, + "--output_file", + output_file, + "--num_envs", + str(num_envs), + "--generation_num_trials", + "1", + "--enable_cameras", + "--headless", + ] + + result = run_script(command) + + print(f"NutPour GR1T2 dataset generation result (num_envs={num_envs}):") + print(result.stdout) + print(result.stderr) + + assert os.path.exists(output_file), ( + f"Generated dataset file was not created at {output_file}.\n" + f"returncode: {result.returncode}\nstderr: {result.stderr}" + ) + + combined_output = result.stdout + "\n" + result.stderr + expected_output = "successes/attempts. Exiting" + assert expected_output in combined_output, ( + f"Could not find '{expected_output}' in output.\nstdout: {result.stdout}\nstderr: {result.stderr}" + ) + + +def test_generate_dataset_gr1t2_nutpour(setup_nutpour_gr1t2_test_environment): + """Test dataset generation for the GR1T2 nut-pour environment (single env).""" + workflow_root, input_file = setup_nutpour_gr1t2_test_environment + output_file = os.path.join(DATASETS_DOWNLOAD_DIR, "generated_dataset.hdf5") + _run_generation(workflow_root, input_file, output_file, num_envs=1) + + +def test_generate_dataset_gr1t2_nutpour_multi_env(setup_nutpour_gr1t2_test_environment): + """Test dataset generation for the GR1T2 nut-pour environment (5 envs).""" + workflow_root, input_file = setup_nutpour_gr1t2_test_environment + output_file = os.path.join(DATASETS_DOWNLOAD_DIR, "generated_dataset_multi_env.hdf5") + _run_generation(workflow_root, input_file, output_file, num_envs=5) diff --git a/source/isaaclab_mimic/test/test_generate_dataset_gr1t2_pickplace.py b/source/isaaclab_mimic/test/test_generate_dataset_gr1t2_pickplace.py new file mode 100644 index 000000000000..bd2017b5a7b0 --- /dev/null +++ b/source/isaaclab_mimic/test/test_generate_dataset_gr1t2_pickplace.py @@ -0,0 +1,109 @@ +# Copyright (c) 2024-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +"""Test dataset generation for Isaac-PickPlace-GR1T2-Abs-Mimic-v0.""" + +from isaaclab.app import AppLauncher + +# launch omniverse app +simulation_app = AppLauncher(headless=True).app + +import os +import sys +import tempfile + +import pytest +from mimic_test_utils import run_script + +from isaaclab.utils.assets import ISAACLAB_NUCLEUS_DIR, retrieve_file_path + +_TASK_NAME = "Isaac-PickPlace-GR1T2-Abs-Mimic-v0" +DATASETS_DOWNLOAD_DIR = tempfile.mkdtemp(suffix=f"_{_TASK_NAME}") +NUCLEUS_ANNOTATED_DATASET_PATH = os.path.join( + ISAACLAB_NUCLEUS_DIR, "Mimic", "Tests", "annotated_dataset_gr1_steering_wheel_test.hdf5" +) + + +@pytest.fixture +def setup_pickplace_gr1t2_test_environment(): + """Download the pre-annotated dataset and prepare the test environment.""" + if not os.path.exists(DATASETS_DOWNLOAD_DIR): + os.makedirs(DATASETS_DOWNLOAD_DIR) + + try: + downloaded_dataset_path = retrieve_file_path(NUCLEUS_ANNOTATED_DATASET_PATH, DATASETS_DOWNLOAD_DIR) + except Exception as e: + print(e) + pytest.fail( + "The pre-annotated dataset required for this test is currently unavailable. " + f"Dataset path: {NUCLEUS_ANNOTATED_DATASET_PATH}" + ) + + assert os.path.isfile(downloaded_dataset_path), ( + f"retrieve_file_path returned '{downloaded_dataset_path}' but the file does not exist on disk." + ) + + pythonunbuffered_env_var_ = os.environ.get("PYTHONUNBUFFERED") + os.environ["PYTHONUNBUFFERED"] = "1" + + current_dir = os.path.dirname(os.path.abspath(__file__)) + workflow_root = os.path.abspath(os.path.join(current_dir, "../../..")) + + yield workflow_root, downloaded_dataset_path + + if pythonunbuffered_env_var_: + os.environ["PYTHONUNBUFFERED"] = pythonunbuffered_env_var_ + else: + del os.environ["PYTHONUNBUFFERED"] + + +def _run_generation(workflow_root: str, input_file: str, output_file: str, num_envs: int): + """Build the generation command, run it, and assert success.""" + command = [ + sys.executable, + os.path.join(workflow_root, "scripts/imitation_learning/isaaclab_mimic/generate_dataset.py"), + "--task", + _TASK_NAME, + "--input_file", + input_file, + "--output_file", + output_file, + "--num_envs", + str(num_envs), + "--generation_num_trials", + "1", + "--headless", + ] + + result = run_script(command) + + print(f"PickPlace GR1T2 dataset generation result (num_envs={num_envs}):") + print(result.stdout) + print(result.stderr) + + assert os.path.exists(output_file), ( + f"Generated dataset file was not created at {output_file}.\n" + f"returncode: {result.returncode}\nstderr: {result.stderr}" + ) + + combined_output = result.stdout + "\n" + result.stderr + expected_output = "successes/attempts. Exiting" + assert expected_output in combined_output, ( + f"Could not find '{expected_output}' in output.\nstdout: {result.stdout}\nstderr: {result.stderr}" + ) + + +def test_generate_dataset_gr1t2_pickplace(setup_pickplace_gr1t2_test_environment): + """Test dataset generation for the GR1T2 pick-place environment (single env).""" + workflow_root, input_file = setup_pickplace_gr1t2_test_environment + output_file = os.path.join(DATASETS_DOWNLOAD_DIR, "generated_dataset.hdf5") + _run_generation(workflow_root, input_file, output_file, num_envs=1) + + +def test_generate_dataset_gr1t2_pickplace_multi_env(setup_pickplace_gr1t2_test_environment): + """Test dataset generation for the GR1T2 pick-place environment (5 envs).""" + workflow_root, input_file = setup_pickplace_gr1t2_test_environment + output_file = os.path.join(DATASETS_DOWNLOAD_DIR, "generated_dataset_multi_env.hdf5") + _run_generation(workflow_root, input_file, output_file, num_envs=5) diff --git a/source/isaaclab_mimic/test/test_generate_dataset_skillgen.py b/source/isaaclab_mimic/test/test_generate_dataset_skillgen.py index 6603b9ffcce1..b88c9b9a2eff 100644 --- a/source/isaaclab_mimic/test/test_generate_dataset_skillgen.py +++ b/source/isaaclab_mimic/test/test_generate_dataset_skillgen.py @@ -11,12 +11,11 @@ simulation_app = AppLauncher(headless=True).app import os -import signal -import subprocess import sys import tempfile import pytest +from mimic_test_utils import run_script from isaaclab.utils.assets import ISAACLAB_NUCLEUS_DIR, retrieve_file_path @@ -25,48 +24,7 @@ ISAACLAB_NUCLEUS_DIR, "Mimic", "franka_stack_datasets", "annotated_dataset_skillgen.hdf5" ) -# Timeout for subprocess execution (seconds). -_SUBPROCESS_TIMEOUT = 600 -_SUBPROCESS_GRACE_PERIOD = 15 - - -def _run_script(command: list[str]) -> subprocess.CompletedProcess: - """Run a script in a subprocess and return a CompletedProcess. - - The Kit / Omniverse runtime's ``simulation_app.close()`` can hang - indefinitely when another ``SimulationApp`` instance is alive in the parent - test process (shared GPU / IPC resources). To avoid blocking the test - suite we use ``Popen`` with an explicit timeout: - - 1. Wait up to ``_SUBPROCESS_TIMEOUT`` seconds for the process to finish. - 2. On timeout send ``SIGTERM`` and wait ``_SUBPROCESS_GRACE_PERIOD`` seconds. - 3. If still alive, ``SIGKILL`` and collect remaining output. - - The captured *stdout* / *stderr* are returned regardless of how the process - terminated so that callers can validate the script's printed output. - """ - process = subprocess.Popen( - command, - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - text=True, - ) - try: - stdout, stderr = process.communicate(timeout=_SUBPROCESS_TIMEOUT) - except subprocess.TimeoutExpired: - process.send_signal(signal.SIGTERM) - try: - stdout, stderr = process.communicate(timeout=_SUBPROCESS_GRACE_PERIOD) - except subprocess.TimeoutExpired: - process.kill() - stdout, stderr = process.communicate() - - return subprocess.CompletedProcess( - args=command, - returncode=process.returncode, - stdout=stdout or "", - stderr=stderr or "", - ) +_SUBPROCESS_TIMEOUT = 5000 @pytest.fixture @@ -132,7 +90,7 @@ def test_generate_dataset_skillgen(setup_skillgen_test_environment): "Isaac-Stack-Cube-Franka-IK-Rel-Skillgen-v0", ] - result = _run_script(command) + result = run_script(command, timeout=_SUBPROCESS_TIMEOUT) print("SkillGen dataset generation result:") print(result.stdout) diff --git a/source/isaaclab_newton/benchmark/assets/benchmark_articulation.py b/source/isaaclab_newton/benchmark/assets/benchmark_articulation.py new file mode 100644 index 000000000000..c9f11a5defb5 --- /dev/null +++ b/source/isaaclab_newton/benchmark/assets/benchmark_articulation.py @@ -0,0 +1,1296 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Micro-benchmarking framework for Articulation class (Newton backend). + +This module provides a benchmarking framework to measure the performance of setter and writer +methods in the Articulation class. Each method is benchmarked under three scenarios: + +1. **Torch List**: Inputs are PyTorch tensors with list indices (via deprecated wrappers). +2. **Torch Tensor**: Inputs are PyTorch tensors with tensor indices (via deprecated wrappers). +3. **Warp Mask**: Inputs are warp arrays with boolean masks (via ``_mask`` methods). + +Usage: + python benchmark_articulation.py [--num_iterations N] [--warmup_steps W] + [--num_instances I] [--num_bodies B] [--num_joints J] + +Example: + python benchmark_articulation.py --num_iterations 1000 --warmup_steps 10 + python benchmark_articulation.py --mode torch_list # Only run list-based benchmarks + python benchmark_articulation.py --mode warp_mask # Only run warp mask benchmarks +""" + +from __future__ import annotations + +"""Launch Isaac Sim Simulator first.""" + +import argparse + +from isaaclab.app import AppLauncher + +# add argparse arguments +parser = argparse.ArgumentParser(description="Benchmark Articulation methods (Newton backend).") +parser.add_argument("--num_iterations", type=int, default=1000, help="Number of iterations") +parser.add_argument("--warmup_steps", type=int, default=10, help="Number of warmup steps") +parser.add_argument("--num_instances", type=int, default=4096, help="Number of instances") +parser.add_argument("--num_bodies", type=int, default=12, help="Number of bodies") +parser.add_argument("--num_joints", type=int, default=11, help="Number of joints") +parser.add_argument("--mode", type=str, default="all", help="Benchmark mode (all, torch_list, torch_tensor, warp_mask)") +parser.add_argument("--output_dir", type=str, default=".", help="Output directory for results") +parser.add_argument("--backend", type=str, default="json", choices=["json", "osmo", "omniperf"], help="Metrics backend") +parser.add_argument("--no_shape_checks", action="store_true", help="Disable shape/dtype assertions") + +# append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +# parse the arguments +args = parser.parse_args() + +# launch omniverse app +app_launcher = AppLauncher(headless=True, args=args) +simulation_app = app_launcher.app + +"""Rest everything follows.""" + +import logging +import warnings + +import numpy as np +import torch +import warp as wp +from isaaclab_newton.test.mock_interfaces import ( + MockNewtonArticulationView, + MockWrenchComposer, + create_mock_newton_manager, +) + +from isaaclab.assets.articulation.articulation_cfg import ArticulationCfg +from isaaclab.test.benchmark import MethodBenchmarkDefinition, MethodBenchmarkRunner, MethodBenchmarkRunnerConfig + +# Suppress deprecation warnings during benchmarking +warnings.filterwarnings("ignore", category=DeprecationWarning) +warnings.filterwarnings("ignore", category=UserWarning) + +# Also suppress logging warnings +logging.getLogger("isaaclab_newton").setLevel(logging.ERROR) +logging.getLogger("isaaclab").setLevel(logging.ERROR) + + +# ============================================================================= +# Index Helpers +# ============================================================================= + + +def make_tensor_env_ids(num_instances: int, device: str) -> torch.Tensor: + """Create a tensor of environment IDs.""" + return torch.arange(num_instances, dtype=torch.int32, device=device) + + +def make_tensor_joint_ids(num_joints: int, device: str) -> torch.Tensor: + """Create a tensor of joint IDs.""" + return torch.arange(num_joints, dtype=torch.int32, device=device) + + +def make_tensor_body_ids(num_bodies: int, device: str) -> torch.Tensor: + """Create a tensor of body IDs.""" + return torch.arange(num_bodies, dtype=torch.int32, device=device) + + +# ============================================================================= +# Test Articulation Factory +# ============================================================================= + + +def create_test_articulation( + num_instances: int = 2, + num_joints: int = 6, + num_bodies: int = 7, + device: str = "cuda:0", +): + """Create a test Articulation instance with mocked dependencies.""" + from isaaclab_newton.assets.articulation.articulation import Articulation + + joint_names = [f"joint_{i}" for i in range(num_joints)] + body_names = [f"body_{i}" for i in range(num_bodies)] + + articulation = object.__new__(Articulation) + + articulation.cfg = ArticulationCfg( + prim_path="/World/Robot", + soft_joint_pos_limit_factor=1.0, + actuators={}, + ) + + # Create Newton mock view + mock_view = MockNewtonArticulationView( + num_instances=num_instances, + num_bodies=num_bodies, + num_joints=num_joints, + device=device, + joint_names=joint_names, + body_names=body_names, + ) + mock_view.set_random_mock_data() + mock_view._noop_setters = True + + object.__setattr__(articulation, "_root_view", mock_view) + object.__setattr__(articulation, "_device", device) + object.__setattr__(articulation, "_check_shapes", not args.no_shape_checks) + + # Create ArticulationData instance (NewtonManager already mocked at call site) + from isaaclab_newton.assets.articulation.articulation_data import ArticulationData + + data = ArticulationData(mock_view, device) + object.__setattr__(articulation, "_data", data) + + # Create mock wrench composers + mock_inst_wrench = MockWrenchComposer(articulation) + mock_perm_wrench = MockWrenchComposer(articulation) + object.__setattr__(articulation, "_instantaneous_wrench_composer", mock_inst_wrench) + object.__setattr__(articulation, "_permanent_wrench_composer", mock_perm_wrench) + + # Set up other required attributes + object.__setattr__(articulation, "actuators", {}) + object.__setattr__(articulation, "_has_implicit_actuators", False) + object.__setattr__(articulation, "_ALL_INDICES", wp.array(np.arange(num_instances, dtype=np.int32), device=device)) + object.__setattr__( + articulation, "_ALL_BODY_INDICES", wp.array(np.arange(num_bodies, dtype=np.int32), device=device) + ) + object.__setattr__( + articulation, "_ALL_JOINT_INDICES", wp.array(np.arange(num_joints, dtype=np.int32), device=device) + ) + object.__setattr__(articulation, "_ALL_ENV_MASK", wp.ones((num_instances,), dtype=wp.bool, device=device)) + object.__setattr__(articulation, "_ALL_JOINT_MASK", wp.ones((num_joints,), dtype=wp.bool, device=device)) + object.__setattr__(articulation, "_ALL_BODY_MASK", wp.ones((num_bodies,), dtype=wp.bool, device=device)) + object.__setattr__(articulation, "_ALL_FIXED_TENDON_INDICES", wp.array([], dtype=wp.int32, device=device)) + object.__setattr__(articulation, "_ALL_FIXED_TENDON_MASK", wp.zeros((0,), dtype=wp.bool, device=device)) + object.__setattr__(articulation, "_ALL_SPATIAL_TENDON_INDICES", wp.array([], dtype=wp.int32, device=device)) + object.__setattr__(articulation, "_ALL_SPATIAL_TENDON_MASK", wp.zeros((0,), dtype=wp.bool, device=device)) + + # Initialize joint targets + object.__setattr__( + articulation, "_joint_pos_target_sim", wp.zeros((num_instances, num_joints), dtype=wp.float32, device=device) + ) + object.__setattr__( + articulation, "_joint_vel_target_sim", wp.zeros((num_instances, num_joints), dtype=wp.float32, device=device) + ) + object.__setattr__( + articulation, + "_joint_effort_target_sim", + wp.zeros((num_instances, num_joints), dtype=wp.float32, device=device), + ) + + return articulation, mock_view + + +# ============================================================================= +# Input Generators (Torch-only for Newton backend) +# ============================================================================= + + +# --- Root Link Pose --- +def gen_root_link_pose_torch_list(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "root_pose": torch.rand(config.num_instances, 7, device=config.device, dtype=torch.float32), + "env_ids": list(range(config.num_instances)), + } + + +def gen_root_link_pose_torch_tensor(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "root_pose": torch.rand(config.num_instances, 7, device=config.device, dtype=torch.float32), + "env_ids": make_tensor_env_ids(config.num_instances, config.device), + } + + +# --- Root COM Pose --- +def gen_root_com_pose_torch_list(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "root_pose": torch.rand(config.num_instances, 7, device=config.device, dtype=torch.float32), + "env_ids": list(range(config.num_instances)), + } + + +def gen_root_com_pose_torch_tensor(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "root_pose": torch.rand(config.num_instances, 7, device=config.device, dtype=torch.float32), + "env_ids": make_tensor_env_ids(config.num_instances, config.device), + } + + +# --- Root Link Velocity --- +def gen_root_link_velocity_torch_list(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "root_velocity": torch.rand(config.num_instances, 6, device=config.device, dtype=torch.float32), + "env_ids": list(range(config.num_instances)), + } + + +def gen_root_link_velocity_torch_tensor(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "root_velocity": torch.rand(config.num_instances, 6, device=config.device, dtype=torch.float32), + "env_ids": make_tensor_env_ids(config.num_instances, config.device), + } + + +# --- Root COM Velocity --- +def gen_root_com_velocity_torch_list(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "root_velocity": torch.rand(config.num_instances, 6, device=config.device, dtype=torch.float32), + "env_ids": list(range(config.num_instances)), + } + + +def gen_root_com_velocity_torch_tensor(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "root_velocity": torch.rand(config.num_instances, 6, device=config.device, dtype=torch.float32), + "env_ids": make_tensor_env_ids(config.num_instances, config.device), + } + + +# --- Root State (Deprecated) --- +def gen_root_state_torch_list(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "root_state": torch.rand(config.num_instances, 13, device=config.device, dtype=torch.float32), + "env_ids": list(range(config.num_instances)), + } + + +def gen_root_state_torch_tensor(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "root_state": torch.rand(config.num_instances, 13, device=config.device, dtype=torch.float32), + "env_ids": make_tensor_env_ids(config.num_instances, config.device), + } + + +# --- Root COM State (Deprecated) --- +def gen_root_com_state_torch_list(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "root_state": torch.rand(config.num_instances, 13, device=config.device, dtype=torch.float32), + "env_ids": list(range(config.num_instances)), + } + + +def gen_root_com_state_torch_tensor(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "root_state": torch.rand(config.num_instances, 13, device=config.device, dtype=torch.float32), + "env_ids": make_tensor_env_ids(config.num_instances, config.device), + } + + +# --- Root Link State (Deprecated) --- +def gen_root_link_state_torch_list(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "root_state": torch.rand(config.num_instances, 13, device=config.device, dtype=torch.float32), + "env_ids": list(range(config.num_instances)), + } + + +def gen_root_link_state_torch_tensor(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "root_state": torch.rand(config.num_instances, 13, device=config.device, dtype=torch.float32), + "env_ids": make_tensor_env_ids(config.num_instances, config.device), + } + + +# --- Joint State --- +def gen_joint_state_torch_list(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "position": torch.rand(config.num_instances, config.num_joints, device=config.device, dtype=torch.float32), + "velocity": torch.rand(config.num_instances, config.num_joints, device=config.device, dtype=torch.float32), + "env_ids": list(range(config.num_instances)), + "joint_ids": list(range(config.num_joints)), + } + + +def gen_joint_state_torch_tensor(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "position": torch.rand(config.num_instances, config.num_joints, device=config.device, dtype=torch.float32), + "velocity": torch.rand(config.num_instances, config.num_joints, device=config.device, dtype=torch.float32), + "env_ids": make_tensor_env_ids(config.num_instances, config.device), + "joint_ids": make_tensor_joint_ids(config.num_joints, config.device), + } + + +# --- Joint Position --- +def gen_joint_position_torch_list(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "position": torch.rand(config.num_instances, config.num_joints, device=config.device, dtype=torch.float32), + "env_ids": list(range(config.num_instances)), + "joint_ids": list(range(config.num_joints)), + } + + +def gen_joint_position_torch_tensor(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "position": torch.rand(config.num_instances, config.num_joints, device=config.device, dtype=torch.float32), + "env_ids": make_tensor_env_ids(config.num_instances, config.device), + "joint_ids": make_tensor_joint_ids(config.num_joints, config.device), + } + + +# --- Joint Velocity --- +def gen_joint_velocity_torch_list(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "velocity": torch.rand(config.num_instances, config.num_joints, device=config.device, dtype=torch.float32), + "env_ids": list(range(config.num_instances)), + "joint_ids": list(range(config.num_joints)), + } + + +def gen_joint_velocity_torch_tensor(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "velocity": torch.rand(config.num_instances, config.num_joints, device=config.device, dtype=torch.float32), + "env_ids": make_tensor_env_ids(config.num_instances, config.device), + "joint_ids": make_tensor_joint_ids(config.num_joints, config.device), + } + + +# --- Joint Stiffness --- +def gen_joint_stiffness_torch_list(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "stiffness": torch.rand(config.num_instances, config.num_joints, device=config.device, dtype=torch.float32), + "env_ids": list(range(config.num_instances)), + "joint_ids": list(range(config.num_joints)), + } + + +def gen_joint_stiffness_torch_tensor(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "stiffness": torch.rand(config.num_instances, config.num_joints, device=config.device, dtype=torch.float32), + "env_ids": make_tensor_env_ids(config.num_instances, config.device), + "joint_ids": make_tensor_joint_ids(config.num_joints, config.device), + } + + +# --- Joint Damping --- +def gen_joint_damping_torch_list(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "damping": torch.rand(config.num_instances, config.num_joints, device=config.device, dtype=torch.float32), + "env_ids": list(range(config.num_instances)), + "joint_ids": list(range(config.num_joints)), + } + + +def gen_joint_damping_torch_tensor(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "damping": torch.rand(config.num_instances, config.num_joints, device=config.device, dtype=torch.float32), + "env_ids": make_tensor_env_ids(config.num_instances, config.device), + "joint_ids": make_tensor_joint_ids(config.num_joints, config.device), + } + + +# --- Joint Position Limit --- +def gen_joint_position_limit_torch_list(config: MethodBenchmarkRunnerConfig) -> dict: + lower = torch.rand(config.num_instances, config.num_joints, 1, device=config.device, dtype=torch.float32) * -3.14 + upper = torch.rand(config.num_instances, config.num_joints, 1, device=config.device, dtype=torch.float32) * 3.14 + return { + "limits": torch.cat([lower, upper], dim=-1), + "env_ids": list(range(config.num_instances)), + "joint_ids": list(range(config.num_joints)), + } + + +def gen_joint_position_limit_torch_tensor(config: MethodBenchmarkRunnerConfig) -> dict: + lower = torch.rand(config.num_instances, config.num_joints, 1, device=config.device, dtype=torch.float32) * -3.14 + upper = torch.rand(config.num_instances, config.num_joints, 1, device=config.device, dtype=torch.float32) * 3.14 + return { + "limits": torch.cat([lower, upper], dim=-1), + "env_ids": make_tensor_env_ids(config.num_instances, config.device), + "joint_ids": make_tensor_joint_ids(config.num_joints, config.device), + } + + +# --- Joint Velocity Limit --- +def gen_joint_velocity_limit_torch_list(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "limits": torch.rand(config.num_instances, config.num_joints, device=config.device, dtype=torch.float32) * 10.0, + "env_ids": list(range(config.num_instances)), + "joint_ids": list(range(config.num_joints)), + } + + +def gen_joint_velocity_limit_torch_tensor(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "limits": torch.rand(config.num_instances, config.num_joints, device=config.device, dtype=torch.float32) * 10.0, + "env_ids": make_tensor_env_ids(config.num_instances, config.device), + "joint_ids": make_tensor_joint_ids(config.num_joints, config.device), + } + + +# --- Joint Effort Limit --- +def gen_joint_effort_limit_torch_list(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "limits": ( + torch.rand(config.num_instances, config.num_joints, device=config.device, dtype=torch.float32) * 100.0 + ), + "env_ids": list(range(config.num_instances)), + "joint_ids": list(range(config.num_joints)), + } + + +def gen_joint_effort_limit_torch_tensor(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "limits": ( + torch.rand(config.num_instances, config.num_joints, device=config.device, dtype=torch.float32) * 100.0 + ), + "env_ids": make_tensor_env_ids(config.num_instances, config.device), + "joint_ids": make_tensor_joint_ids(config.num_joints, config.device), + } + + +# --- Joint Armature --- +def gen_joint_armature_torch_list(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "armature": ( + torch.rand(config.num_instances, config.num_joints, device=config.device, dtype=torch.float32) * 0.1 + ), + "env_ids": list(range(config.num_instances)), + "joint_ids": list(range(config.num_joints)), + } + + +def gen_joint_armature_torch_tensor(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "armature": ( + torch.rand(config.num_instances, config.num_joints, device=config.device, dtype=torch.float32) * 0.1 + ), + "env_ids": make_tensor_env_ids(config.num_instances, config.device), + "joint_ids": make_tensor_joint_ids(config.num_joints, config.device), + } + + +# --- Joint Friction Coefficient --- +def gen_joint_friction_coefficient_torch_list(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "joint_friction_coeff": ( + torch.rand(config.num_instances, config.num_joints, device=config.device, dtype=torch.float32) * 0.5 + ), + "env_ids": list(range(config.num_instances)), + "joint_ids": list(range(config.num_joints)), + } + + +def gen_joint_friction_coefficient_torch_tensor(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "joint_friction_coeff": ( + torch.rand(config.num_instances, config.num_joints, device=config.device, dtype=torch.float32) * 0.5 + ), + "env_ids": make_tensor_env_ids(config.num_instances, config.device), + "joint_ids": make_tensor_joint_ids(config.num_joints, config.device), + } + + +# --- Set Joint Position Target --- +def gen_set_joint_position_target_torch_list(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "target": torch.rand(config.num_instances, config.num_joints, device=config.device, dtype=torch.float32), + "env_ids": list(range(config.num_instances)), + "joint_ids": list(range(config.num_joints)), + } + + +def gen_set_joint_position_target_torch_tensor(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "target": torch.rand(config.num_instances, config.num_joints, device=config.device, dtype=torch.float32), + "env_ids": make_tensor_env_ids(config.num_instances, config.device), + "joint_ids": make_tensor_joint_ids(config.num_joints, config.device), + } + + +# --- Set Joint Velocity Target --- +def gen_set_joint_velocity_target_torch_list(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "target": torch.rand(config.num_instances, config.num_joints, device=config.device, dtype=torch.float32), + "env_ids": list(range(config.num_instances)), + "joint_ids": list(range(config.num_joints)), + } + + +def gen_set_joint_velocity_target_torch_tensor(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "target": torch.rand(config.num_instances, config.num_joints, device=config.device, dtype=torch.float32), + "env_ids": make_tensor_env_ids(config.num_instances, config.device), + "joint_ids": make_tensor_joint_ids(config.num_joints, config.device), + } + + +# --- Set Joint Effort Target --- +def gen_set_joint_effort_target_torch_list(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "target": torch.rand(config.num_instances, config.num_joints, device=config.device, dtype=torch.float32), + "env_ids": list(range(config.num_instances)), + "joint_ids": list(range(config.num_joints)), + } + + +def gen_set_joint_effort_target_torch_tensor(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "target": torch.rand(config.num_instances, config.num_joints, device=config.device, dtype=torch.float32), + "env_ids": make_tensor_env_ids(config.num_instances, config.device), + "joint_ids": make_tensor_joint_ids(config.num_joints, config.device), + } + + +# --- Set Masses --- +def gen_set_masses_torch_list(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "masses": torch.rand(config.num_instances, config.num_bodies, device=config.device, dtype=torch.float32), + "env_ids": list(range(config.num_instances)), + "body_ids": list(range(config.num_bodies)), + } + + +def gen_set_masses_torch_tensor(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "masses": torch.rand(config.num_instances, config.num_bodies, device=config.device, dtype=torch.float32), + "env_ids": make_tensor_env_ids(config.num_instances, config.device), + "body_ids": make_tensor_body_ids(config.num_bodies, config.device), + } + + +# --- Set CoMs --- +def gen_set_coms_torch_list(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "coms": torch.rand(config.num_instances, config.num_bodies, 3, device=config.device, dtype=torch.float32), + "env_ids": list(range(config.num_instances)), + "body_ids": list(range(config.num_bodies)), + } + + +def gen_set_coms_torch_tensor(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "coms": torch.rand(config.num_instances, config.num_bodies, 3, device=config.device, dtype=torch.float32), + "env_ids": make_tensor_env_ids(config.num_instances, config.device), + "body_ids": make_tensor_body_ids(config.num_bodies, config.device), + } + + +# --- Set Inertias --- +def gen_set_inertias_torch_list(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "inertias": torch.rand(config.num_instances, config.num_bodies, 9, device=config.device, dtype=torch.float32), + "env_ids": list(range(config.num_instances)), + "body_ids": list(range(config.num_bodies)), + } + + +def gen_set_inertias_torch_tensor(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "inertias": torch.rand(config.num_instances, config.num_bodies, 9, device=config.device, dtype=torch.float32), + "env_ids": make_tensor_env_ids(config.num_instances, config.device), + "body_ids": make_tensor_body_ids(config.num_bodies, config.device), + } + + +# --- Set External Force and Torque --- +def gen_set_external_force_and_torque_torch_list(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "forces": torch.rand(config.num_instances, config.num_bodies, 3, device=config.device, dtype=torch.float32), + "torques": torch.rand(config.num_instances, config.num_bodies, 3, device=config.device, dtype=torch.float32), + "env_ids": list(range(config.num_instances)), + } + + +def gen_set_external_force_and_torque_torch_tensor(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "forces": torch.rand(config.num_instances, config.num_bodies, 3, device=config.device, dtype=torch.float32), + "torques": torch.rand(config.num_instances, config.num_bodies, 3, device=config.device, dtype=torch.float32), + "env_ids": make_tensor_env_ids(config.num_instances, config.device), + } + + +# ============================================================================= +# Warp Mask Input Generators (for _mask methods) +# ============================================================================= + + +def _env_mask(config: MethodBenchmarkRunnerConfig) -> wp.array: + return wp.ones((config.num_instances,), dtype=wp.bool, device=config.device) + + +def _joint_mask(config: MethodBenchmarkRunnerConfig) -> wp.array: + return wp.ones((config.num_joints,), dtype=wp.bool, device=config.device) + + +def _body_mask(config: MethodBenchmarkRunnerConfig) -> wp.array: + return wp.ones((config.num_bodies,), dtype=wp.bool, device=config.device) + + +# --- Root Link Pose (mask) --- +def gen_root_link_pose_warp_mask(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "root_pose": torch.rand(config.num_instances, 7, device=config.device, dtype=torch.float32), + "env_mask": _env_mask(config), + } + + +# --- Root COM Pose (mask) --- +def gen_root_com_pose_warp_mask(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "root_pose": torch.rand(config.num_instances, 7, device=config.device, dtype=torch.float32), + "env_mask": _env_mask(config), + } + + +# --- Root Link Velocity (mask) --- +def gen_root_link_velocity_warp_mask(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "root_velocity": torch.rand(config.num_instances, 6, device=config.device, dtype=torch.float32), + "env_mask": _env_mask(config), + } + + +# --- Root COM Velocity (mask) --- +def gen_root_com_velocity_warp_mask(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "root_velocity": torch.rand(config.num_instances, 6, device=config.device, dtype=torch.float32), + "env_mask": _env_mask(config), + } + + +# --- Joint State (mask) --- +def gen_joint_state_warp_mask(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "position": torch.rand(config.num_instances, config.num_joints, device=config.device, dtype=torch.float32), + "velocity": torch.rand(config.num_instances, config.num_joints, device=config.device, dtype=torch.float32), + "joint_mask": _joint_mask(config), + "env_mask": _env_mask(config), + } + + +# --- Joint Position (mask) --- +def gen_joint_position_warp_mask(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "position": torch.rand(config.num_instances, config.num_joints, device=config.device, dtype=torch.float32), + "joint_mask": _joint_mask(config), + "env_mask": _env_mask(config), + } + + +# --- Joint Velocity (mask) --- +def gen_joint_velocity_warp_mask(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "velocity": torch.rand(config.num_instances, config.num_joints, device=config.device, dtype=torch.float32), + "joint_mask": _joint_mask(config), + "env_mask": _env_mask(config), + } + + +# --- Joint Stiffness (mask) --- +def gen_joint_stiffness_warp_mask(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "stiffness": torch.rand(config.num_instances, config.num_joints, device=config.device, dtype=torch.float32), + "joint_mask": _joint_mask(config), + "env_mask": _env_mask(config), + } + + +# --- Joint Damping (mask) --- +def gen_joint_damping_warp_mask(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "damping": torch.rand(config.num_instances, config.num_joints, device=config.device, dtype=torch.float32), + "joint_mask": _joint_mask(config), + "env_mask": _env_mask(config), + } + + +# --- Joint Position Limit (mask) --- +def gen_joint_position_limit_warp_mask(config: MethodBenchmarkRunnerConfig) -> dict: + lower = torch.rand(config.num_instances, config.num_joints, 1, device=config.device, dtype=torch.float32) * -3.14 + upper = torch.rand(config.num_instances, config.num_joints, 1, device=config.device, dtype=torch.float32) * 3.14 + return { + "limits": torch.cat([lower, upper], dim=-1), + "joint_mask": _joint_mask(config), + "env_mask": _env_mask(config), + } + + +# --- Joint Velocity Limit (mask) --- +def gen_joint_velocity_limit_warp_mask(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "limits": torch.rand(config.num_instances, config.num_joints, device=config.device, dtype=torch.float32) * 10.0, + "joint_mask": _joint_mask(config), + "env_mask": _env_mask(config), + } + + +# --- Joint Effort Limit (mask) --- +def gen_joint_effort_limit_warp_mask(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "limits": ( + torch.rand(config.num_instances, config.num_joints, device=config.device, dtype=torch.float32) * 100.0 + ), + "joint_mask": _joint_mask(config), + "env_mask": _env_mask(config), + } + + +# --- Joint Armature (mask) --- +def gen_joint_armature_warp_mask(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "armature": ( + torch.rand(config.num_instances, config.num_joints, device=config.device, dtype=torch.float32) * 0.1 + ), + "joint_mask": _joint_mask(config), + "env_mask": _env_mask(config), + } + + +# --- Joint Friction Coefficient (mask) --- +def gen_joint_friction_coefficient_warp_mask(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "joint_friction_coeff": ( + torch.rand(config.num_instances, config.num_joints, device=config.device, dtype=torch.float32) * 0.5 + ), + "joint_mask": _joint_mask(config), + "env_mask": _env_mask(config), + } + + +# --- Set Joint Position Target (mask) --- +def gen_set_joint_position_target_warp_mask(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "target": torch.rand(config.num_instances, config.num_joints, device=config.device, dtype=torch.float32), + "joint_mask": _joint_mask(config), + "env_mask": _env_mask(config), + } + + +# --- Set Joint Velocity Target (mask) --- +def gen_set_joint_velocity_target_warp_mask(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "target": torch.rand(config.num_instances, config.num_joints, device=config.device, dtype=torch.float32), + "joint_mask": _joint_mask(config), + "env_mask": _env_mask(config), + } + + +# --- Set Joint Effort Target (mask) --- +def gen_set_joint_effort_target_warp_mask(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "target": torch.rand(config.num_instances, config.num_joints, device=config.device, dtype=torch.float32), + "joint_mask": _joint_mask(config), + "env_mask": _env_mask(config), + } + + +# --- Set Masses (mask) --- +def gen_set_masses_warp_mask(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "masses": torch.rand(config.num_instances, config.num_bodies, device=config.device, dtype=torch.float32), + "body_mask": _body_mask(config), + "env_mask": _env_mask(config), + } + + +# --- Set CoMs (mask) --- +def gen_set_coms_warp_mask(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "coms": torch.rand(config.num_instances, config.num_bodies, 3, device=config.device, dtype=torch.float32), + "body_mask": _body_mask(config), + "env_mask": _env_mask(config), + } + + +# --- Set Inertias (mask) --- +def gen_set_inertias_warp_mask(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "inertias": torch.rand(config.num_instances, config.num_bodies, 9, device=config.device, dtype=torch.float32), + "body_mask": _body_mask(config), + "env_mask": _env_mask(config), + } + + +# ============================================================================= +# Benchmarks +# ============================================================================= + +BENCHMARKS = [ + # --- Root State (Deprecated, no _mask equivalent) --- + MethodBenchmarkDefinition( + name="write_root_state_to_sim", + method_name="write_root_state_to_sim", + input_generators={ + "torch_list": gen_root_state_torch_list, + "torch_tensor": gen_root_state_torch_tensor, + }, + category="root_state", + ), + MethodBenchmarkDefinition( + name="write_root_com_state_to_sim", + method_name="write_root_com_state_to_sim", + input_generators={ + "torch_list": gen_root_com_state_torch_list, + "torch_tensor": gen_root_com_state_torch_tensor, + }, + category="root_state", + ), + MethodBenchmarkDefinition( + name="write_root_link_state_to_sim", + method_name="write_root_link_state_to_sim", + input_generators={ + "torch_list": gen_root_link_state_torch_list, + "torch_tensor": gen_root_link_state_torch_tensor, + }, + category="root_state", + ), + # --- Root Pose / Velocity --- + MethodBenchmarkDefinition( + name="write_root_link_pose_to_sim", + method_name="write_root_link_pose_to_sim", + input_generators={ + "torch_list": gen_root_link_pose_torch_list, + "torch_tensor": gen_root_link_pose_torch_tensor, + }, + category="root_pose", + ), + MethodBenchmarkDefinition( + name="write_root_link_pose_to_sim_mask", + method_name="write_root_link_pose_to_sim_mask", + input_generators={"warp_mask": gen_root_link_pose_warp_mask}, + category="root_pose", + ), + MethodBenchmarkDefinition( + name="write_root_com_pose_to_sim", + method_name="write_root_com_pose_to_sim", + input_generators={ + "torch_list": gen_root_com_pose_torch_list, + "torch_tensor": gen_root_com_pose_torch_tensor, + }, + category="root_pose", + ), + MethodBenchmarkDefinition( + name="write_root_com_pose_to_sim_mask", + method_name="write_root_com_pose_to_sim_mask", + input_generators={"warp_mask": gen_root_com_pose_warp_mask}, + category="root_pose", + ), + MethodBenchmarkDefinition( + name="write_root_link_velocity_to_sim", + method_name="write_root_link_velocity_to_sim", + input_generators={ + "torch_list": gen_root_link_velocity_torch_list, + "torch_tensor": gen_root_link_velocity_torch_tensor, + }, + category="root_velocity", + ), + MethodBenchmarkDefinition( + name="write_root_link_velocity_to_sim_mask", + method_name="write_root_link_velocity_to_sim_mask", + input_generators={"warp_mask": gen_root_link_velocity_warp_mask}, + category="root_velocity", + ), + MethodBenchmarkDefinition( + name="write_root_com_velocity_to_sim", + method_name="write_root_com_velocity_to_sim", + input_generators={ + "torch_list": gen_root_com_velocity_torch_list, + "torch_tensor": gen_root_com_velocity_torch_tensor, + }, + category="root_velocity", + ), + MethodBenchmarkDefinition( + name="write_root_com_velocity_to_sim_mask", + method_name="write_root_com_velocity_to_sim_mask", + input_generators={"warp_mask": gen_root_com_velocity_warp_mask}, + category="root_velocity", + ), + # --- Joint State --- + MethodBenchmarkDefinition( + name="write_joint_state_to_sim", + method_name="write_joint_state_to_sim", + input_generators={ + "torch_list": gen_joint_state_torch_list, + "torch_tensor": gen_joint_state_torch_tensor, + }, + category="joint_state", + ), + MethodBenchmarkDefinition( + name="write_joint_state_to_sim_mask", + method_name="write_joint_state_to_sim_mask", + input_generators={"warp_mask": gen_joint_state_warp_mask}, + category="joint_state", + ), + MethodBenchmarkDefinition( + name="write_joint_position_to_sim", + method_name="write_joint_position_to_sim", + input_generators={ + "torch_list": gen_joint_position_torch_list, + "torch_tensor": gen_joint_position_torch_tensor, + }, + category="joint_state", + ), + MethodBenchmarkDefinition( + name="write_joint_position_to_sim_mask", + method_name="write_joint_position_to_sim_mask", + input_generators={"warp_mask": gen_joint_position_warp_mask}, + category="joint_state", + ), + MethodBenchmarkDefinition( + name="write_joint_velocity_to_sim", + method_name="write_joint_velocity_to_sim", + input_generators={ + "torch_list": gen_joint_velocity_torch_list, + "torch_tensor": gen_joint_velocity_torch_tensor, + }, + category="joint_state", + ), + MethodBenchmarkDefinition( + name="write_joint_velocity_to_sim_mask", + method_name="write_joint_velocity_to_sim_mask", + input_generators={"warp_mask": gen_joint_velocity_warp_mask}, + category="joint_state", + ), + # --- Joint Params --- + MethodBenchmarkDefinition( + name="write_joint_stiffness_to_sim", + method_name="write_joint_stiffness_to_sim", + input_generators={ + "torch_list": gen_joint_stiffness_torch_list, + "torch_tensor": gen_joint_stiffness_torch_tensor, + }, + category="joint_params", + ), + MethodBenchmarkDefinition( + name="write_joint_stiffness_to_sim_mask", + method_name="write_joint_stiffness_to_sim_mask", + input_generators={"warp_mask": gen_joint_stiffness_warp_mask}, + category="joint_params", + ), + MethodBenchmarkDefinition( + name="write_joint_damping_to_sim", + method_name="write_joint_damping_to_sim", + input_generators={ + "torch_list": gen_joint_damping_torch_list, + "torch_tensor": gen_joint_damping_torch_tensor, + }, + category="joint_params", + ), + MethodBenchmarkDefinition( + name="write_joint_damping_to_sim_mask", + method_name="write_joint_damping_to_sim_mask", + input_generators={"warp_mask": gen_joint_damping_warp_mask}, + category="joint_params", + ), + MethodBenchmarkDefinition( + name="write_joint_position_limit_to_sim", + method_name="write_joint_position_limit_to_sim", + input_generators={ + "torch_list": gen_joint_position_limit_torch_list, + "torch_tensor": gen_joint_position_limit_torch_tensor, + }, + category="joint_params", + ), + MethodBenchmarkDefinition( + name="write_joint_position_limit_to_sim_mask", + method_name="write_joint_position_limit_to_sim_mask", + input_generators={"warp_mask": gen_joint_position_limit_warp_mask}, + category="joint_params", + ), + MethodBenchmarkDefinition( + name="write_joint_velocity_limit_to_sim", + method_name="write_joint_velocity_limit_to_sim", + input_generators={ + "torch_list": gen_joint_velocity_limit_torch_list, + "torch_tensor": gen_joint_velocity_limit_torch_tensor, + }, + category="joint_params", + ), + MethodBenchmarkDefinition( + name="write_joint_velocity_limit_to_sim_mask", + method_name="write_joint_velocity_limit_to_sim_mask", + input_generators={"warp_mask": gen_joint_velocity_limit_warp_mask}, + category="joint_params", + ), + MethodBenchmarkDefinition( + name="write_joint_effort_limit_to_sim", + method_name="write_joint_effort_limit_to_sim", + input_generators={ + "torch_list": gen_joint_effort_limit_torch_list, + "torch_tensor": gen_joint_effort_limit_torch_tensor, + }, + category="joint_params", + ), + MethodBenchmarkDefinition( + name="write_joint_effort_limit_to_sim_mask", + method_name="write_joint_effort_limit_to_sim_mask", + input_generators={"warp_mask": gen_joint_effort_limit_warp_mask}, + category="joint_params", + ), + MethodBenchmarkDefinition( + name="write_joint_armature_to_sim", + method_name="write_joint_armature_to_sim", + input_generators={ + "torch_list": gen_joint_armature_torch_list, + "torch_tensor": gen_joint_armature_torch_tensor, + }, + category="joint_params", + ), + MethodBenchmarkDefinition( + name="write_joint_armature_to_sim_mask", + method_name="write_joint_armature_to_sim_mask", + input_generators={"warp_mask": gen_joint_armature_warp_mask}, + category="joint_params", + ), + MethodBenchmarkDefinition( + name="write_joint_friction_coefficient_to_sim", + method_name="write_joint_friction_coefficient_to_sim", + input_generators={ + "torch_list": gen_joint_friction_coefficient_torch_list, + "torch_tensor": gen_joint_friction_coefficient_torch_tensor, + }, + category="joint_params", + ), + MethodBenchmarkDefinition( + name="write_joint_friction_coefficient_to_sim_mask", + method_name="write_joint_friction_coefficient_to_sim_mask", + input_generators={"warp_mask": gen_joint_friction_coefficient_warp_mask}, + category="joint_params", + ), + # --- Joint Targets --- + MethodBenchmarkDefinition( + name="set_joint_position_target", + method_name="set_joint_position_target", + input_generators={ + "torch_list": gen_set_joint_position_target_torch_list, + "torch_tensor": gen_set_joint_position_target_torch_tensor, + }, + category="joint_targets", + ), + MethodBenchmarkDefinition( + name="set_joint_position_target_mask", + method_name="set_joint_position_target_mask", + input_generators={"warp_mask": gen_set_joint_position_target_warp_mask}, + category="joint_targets", + ), + MethodBenchmarkDefinition( + name="set_joint_velocity_target", + method_name="set_joint_velocity_target", + input_generators={ + "torch_list": gen_set_joint_velocity_target_torch_list, + "torch_tensor": gen_set_joint_velocity_target_torch_tensor, + }, + category="joint_targets", + ), + MethodBenchmarkDefinition( + name="set_joint_velocity_target_mask", + method_name="set_joint_velocity_target_mask", + input_generators={"warp_mask": gen_set_joint_velocity_target_warp_mask}, + category="joint_targets", + ), + MethodBenchmarkDefinition( + name="set_joint_effort_target", + method_name="set_joint_effort_target", + input_generators={ + "torch_list": gen_set_joint_effort_target_torch_list, + "torch_tensor": gen_set_joint_effort_target_torch_tensor, + }, + category="joint_targets", + ), + MethodBenchmarkDefinition( + name="set_joint_effort_target_mask", + method_name="set_joint_effort_target_mask", + input_generators={"warp_mask": gen_set_joint_effort_target_warp_mask}, + category="joint_targets", + ), + # --- Body Properties --- + MethodBenchmarkDefinition( + name="set_masses", + method_name="set_masses", + input_generators={ + "torch_list": gen_set_masses_torch_list, + "torch_tensor": gen_set_masses_torch_tensor, + }, + category="body_props", + ), + MethodBenchmarkDefinition( + name="set_masses_mask", + method_name="set_masses_mask", + input_generators={"warp_mask": gen_set_masses_warp_mask}, + category="body_props", + ), + MethodBenchmarkDefinition( + name="set_coms", + method_name="set_coms", + input_generators={ + "torch_list": gen_set_coms_torch_list, + "torch_tensor": gen_set_coms_torch_tensor, + }, + category="body_props", + ), + MethodBenchmarkDefinition( + name="set_coms_mask", + method_name="set_coms_mask", + input_generators={"warp_mask": gen_set_coms_warp_mask}, + category="body_props", + ), + MethodBenchmarkDefinition( + name="set_inertias", + method_name="set_inertias", + input_generators={ + "torch_list": gen_set_inertias_torch_list, + "torch_tensor": gen_set_inertias_torch_tensor, + }, + category="body_props", + ), + MethodBenchmarkDefinition( + name="set_inertias_mask", + method_name="set_inertias_mask", + input_generators={"warp_mask": gen_set_inertias_warp_mask}, + category="body_props", + ), + MethodBenchmarkDefinition( + name="set_external_force_and_torque", + method_name="set_external_force_and_torque", + input_generators={ + "torch_list": gen_set_external_force_and_torque_torch_list, + "torch_tensor": gen_set_external_force_and_torque_torch_tensor, + }, + category="external_wrench", + ), +] + + +# ============================================================================= +# Fill-Ratio Benchmarks (5%, 95%, 100% of env_ids filled) +# ============================================================================= + +FILL_RATIOS = {"5pct": 0.05, "95pct": 0.95, "100pct": 1.0} + + +def _make_fill_ratio_generator(base_gen_fn, fill_ratio): + """Create a generator that subsets env_ids to a given fill ratio. + + Only env_ids are subsetted — joint_ids and body_ids remain full-range. + Data tensors keyed on env count are sliced to match. + """ + + def generator(config): + n = max(1, int(config.num_instances * fill_ratio)) + base_inputs = base_gen_fn(config) + inputs = {} + for key, val in base_inputs.items(): + if key == "env_ids": + inputs[key] = ( + torch.randperm(config.num_instances, device=config.device)[:n].sort().values.to(torch.int32) + ) + elif isinstance(val, torch.Tensor) and val.dim() >= 1 and val.shape[0] == config.num_instances: + inputs[key] = val[:n] + else: + inputs[key] = val + return inputs + + return generator + + +def _make_fill_ratio_mask_generator(base_mask_gen_fn, fill_ratio): + """Create a mask generator with a given fill ratio. + + Sets a random subset of the env_mask entries to True. Data stays full-sized (mask methods expect full data). + """ + + def generator(config): + base_inputs = base_mask_gen_fn(config) + n = max(1, int(config.num_instances * fill_ratio)) + # Create a mask with n random entries set to True + perm = torch.randperm(config.num_instances, device=config.device) + mask_tensor = torch.zeros(config.num_instances, dtype=torch.bool, device=config.device) + mask_tensor[perm[:n]] = True + base_inputs["env_mask"] = wp.from_torch(mask_tensor, dtype=wp.bool) + return base_inputs + + return generator + + +def _build_fill_benchmarks(): + """Auto-generate fill-ratio benchmark definitions from existing generators.""" + fill_benchmarks = [] + for bm in BENCHMARKS: + generators = {} + # Add tensor fill variants from torch_tensor generators + if "torch_tensor" in bm.input_generators: + base_gen = bm.input_generators["torch_tensor"] + for suffix, ratio in FILL_RATIOS.items(): + generators[f"tensor_{suffix}"] = _make_fill_ratio_generator(base_gen, ratio) + # Add mask fill variants from warp_mask generators + if "warp_mask" in bm.input_generators: + base_gen = bm.input_generators["warp_mask"] + for suffix, ratio in FILL_RATIOS.items(): + generators[f"mask_{suffix}"] = _make_fill_ratio_mask_generator(base_gen, ratio) + if generators: + fill_benchmarks.append( + MethodBenchmarkDefinition( + name=bm.name, + method_name=bm.method_name, + input_generators=generators, + category=f"{bm.category}_fill", + ) + ) + return fill_benchmarks + + +FILL_BENCHMARKS = _build_fill_benchmarks() + + +def main(): + """Main entry point for the benchmarking script.""" + config = MethodBenchmarkRunnerConfig( + num_iterations=args.num_iterations, + warmup_steps=args.warmup_steps, + num_instances=args.num_instances, + num_bodies=args.num_bodies, + num_joints=args.num_joints, + device=args.device, + mode=args.mode, + ) + + # Patch the NewtonManager for both articulation and articulation_data modules + with ( + create_mock_newton_manager( + "isaaclab_newton.assets.articulation.articulation_data.SimulationManager", + gravity=(0.0, 0.0, -9.81), + ), + create_mock_newton_manager( + "isaaclab_newton.assets.articulation.articulation.SimulationManager", + gravity=(0.0, 0.0, -9.81), + ), + ): + # Create the test articulation + articulation, _ = create_test_articulation( + num_instances=config.num_instances, + num_bodies=config.num_bodies, + num_joints=config.num_joints, + device=config.device, + ) + + print( + f"Benchmarking Articulation (Newton) with {config.num_instances} instances, {config.num_bodies} bodies," + f" {config.num_joints} joints..." + ) + + # Create runner and run benchmarks + runner = MethodBenchmarkRunner( + benchmark_name="newton_articulation_benchmark", + config=config, + backend_type=args.backend, + output_path=args.output_dir, + use_recorders=True, + ) + + runner.run_benchmarks(BENCHMARKS, articulation) + + print("\n" + "=" * 80) + print("Fill-Ratio Benchmarks (env_ids at 5%, 95%, 100% fill)") + print("=" * 80) + + runner.run_benchmarks(FILL_BENCHMARKS, articulation) + runner.finalize() + + # Close the simulation app + simulation_app.close() + + +if __name__ == "__main__": + main() diff --git a/source/isaaclab_newton/benchmark/assets/benchmark_articulation_data.py b/source/isaaclab_newton/benchmark/assets/benchmark_articulation_data.py new file mode 100644 index 000000000000..59fb541767bc --- /dev/null +++ b/source/isaaclab_newton/benchmark/assets/benchmark_articulation_data.py @@ -0,0 +1,342 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Micro-benchmarking framework for ArticulationData class (Newton backend). + +This module provides a benchmarking framework to measure the performance of all properties +in the Newton ArticulationData class. Each property is run multiple times with randomized mock data, +and timing statistics (mean and standard deviation) are reported. + +Usage: + python benchmark_articulation_data.py [--num_iterations N] [--warmup_steps W] + [--num_instances I] [--num_bodies B] [--num_joints J] + +Example: + python benchmark_articulation_data.py --num_iterations 10000 --warmup_steps 10 +""" + +from __future__ import annotations + +"""Launch Isaac Sim Simulator first.""" + +import argparse + +from isaaclab.app import AppLauncher + +# add argparse arguments +parser = argparse.ArgumentParser( + description="Micro-benchmarking framework for ArticulationData class (Newton backend).", + formatter_class=argparse.ArgumentDefaultsHelpFormatter, +) +parser.add_argument("--num_iterations", type=int, default=1000, help="Number of iterations") +parser.add_argument("--warmup_steps", type=int, default=10, help="Number of warmup steps") +parser.add_argument("--num_instances", type=int, default=4096, help="Number of instances") +parser.add_argument("--num_bodies", type=int, default=12, help="Number of bodies") +parser.add_argument("--num_joints", type=int, default=11, help="Number of joints") +parser.add_argument("--output_dir", type=str, default=".", help="Output directory for results") +parser.add_argument("--backend", type=str, default="json", choices=["json", "osmo", "omniperf"], help="Metrics backend") + +# append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +# parse the arguments +args = parser.parse_args() + +# launch omniverse app +app_launcher = AppLauncher(headless=True, args=args) +simulation_app = app_launcher.app + +"""Rest everything follows.""" + +import warnings + +import numpy as np +import warp as wp +from isaaclab_newton.test.mock_interfaces import MockNewtonArticulationView, create_mock_newton_manager + +from isaaclab.test.benchmark import MethodBenchmarkRunner, MethodBenchmarkRunnerConfig + +# Suppress deprecation warnings during benchmarking +warnings.filterwarnings("ignore", category=DeprecationWarning) +warnings.filterwarnings("ignore", category=UserWarning) + + +# ============================================================================= +# Skip Lists +# ============================================================================= + +# List of deprecated properties - skip these +DEPRECATED_PROPERTIES = { + "root_pose_w", + "root_pos_w", + "root_quat_w", + "root_vel_w", + "root_lin_vel_w", + "root_ang_vel_w", + "root_lin_vel_b", + "root_ang_vel_b", + "body_pose_w", + "body_pos_w", + "body_quat_w", + "body_vel_w", + "body_lin_vel_w", + "body_ang_vel_w", + "body_acc_w", + "body_lin_acc_w", + "body_ang_acc_w", + "com_pos_b", + "com_quat_b", + "joint_limits", + "joint_friction", + "fixed_tendon_limit", + "applied_torque", + "computed_torque", + "joint_dynamic_friction", + "joint_effort_target", + "joint_viscous_friction", + "joint_velocity_limits", + # Combined state properties marked as deprecated + "root_state_w", + "root_link_state_w", + "root_com_state_w", + "body_state_w", + "body_link_state_w", + "body_com_state_w", +} + +# List of properties that raise NotImplementedError - skip these +NOT_IMPLEMENTED_PROPERTIES = { + "fixed_tendon_stiffness", + "fixed_tendon_damping", + "fixed_tendon_limit_stiffness", + "fixed_tendon_rest_length", + "fixed_tendon_offset", + "fixed_tendon_pos_limits", + "spatial_tendon_stiffness", + "spatial_tendon_damping", + "spatial_tendon_limit_stiffness", + "spatial_tendon_offset", + "body_incoming_joint_wrench_b", +} + +# Removed default_* properties that raise RuntimeError +REMOVED_PROPERTIES = { + "default_fixed_tendon_damping", + "default_fixed_tendon_limit", + "default_fixed_tendon_limit_stiffness", + "default_fixed_tendon_offset", + "default_fixed_tendon_pos_limits", + "default_fixed_tendon_rest_length", + "default_fixed_tendon_stiffness", + "default_inertia", + "default_joint_armature", + "default_joint_damping", + "default_joint_dynamic_friction_coeff", + "default_joint_friction", + "default_joint_friction_coeff", + "default_joint_limits", + "default_joint_pos_limits", + "default_joint_stiffness", + "default_joint_viscous_friction_coeff", + "default_mass", + "default_spatial_tendon_damping", + "default_spatial_tendon_limit_stiffness", + "default_spatial_tendon_offset", + "default_spatial_tendon_stiffness", +} + +# Private/internal properties and methods to skip +INTERNAL_PROPERTIES = { + "_create_simulation_bindings", + "_create_buffers", + "update", + "is_primed", + "device", + "body_names", + "joint_names", + "fixed_tendon_names", + "spatial_tendon_names", + "GRAVITY_VEC_W", + "GRAVITY_VEC_W_TORCH", + "FORWARD_VEC_B", + "FORWARD_VEC_B_TORCH", + "ALL_ENV_MASK", + "ALL_BODY_MASK", + "ALL_JOINT_MASK", + "ENV_MASK", + "BODY_MASK", + "JOINT_MASK", +} + +# Dependency mapping for properties +PROPERTY_DEPENDENCIES = { + "root_link_lin_vel_w": ["root_link_vel_w"], + "root_link_ang_vel_w": ["root_link_vel_w"], + "root_link_lin_vel_b": ["root_link_vel_b"], + "root_link_ang_vel_b": ["root_link_vel_b"], + "root_com_pos_w": ["root_com_pose_w"], + "root_com_quat_w": ["root_com_pose_w"], + "root_com_lin_vel_b": ["root_com_vel_b"], + "root_com_ang_vel_b": ["root_com_vel_b"], + "root_com_lin_vel_w": ["root_com_vel_w"], + "root_com_ang_vel_w": ["root_com_vel_w"], + "root_link_pos_w": ["root_link_pose_w"], + "root_link_quat_w": ["root_link_pose_w"], + "body_link_lin_vel_w": ["body_link_vel_w"], + "body_link_ang_vel_w": ["body_link_vel_w"], + "body_link_pos_w": ["body_link_pose_w"], + "body_link_quat_w": ["body_link_pose_w"], + "body_com_pos_w": ["body_com_pose_w"], + "body_com_quat_w": ["body_com_pose_w"], + "body_com_lin_vel_w": ["body_com_vel_w"], + "body_com_ang_vel_w": ["body_com_vel_w"], + "body_com_lin_acc_w": ["body_com_acc_w"], + "body_com_ang_acc_w": ["body_com_acc_w"], + "body_com_quat_b": ["body_com_pose_b"], +} + + +# ============================================================================= +# Benchmark Functions +# ============================================================================= + + +def get_benchmarkable_properties(articulation_data) -> list[str]: + """Get list of properties that can be benchmarked.""" + all_properties = [] + + for name in dir(articulation_data): + if name.startswith("_"): + continue + if name in DEPRECATED_PROPERTIES: + continue + if name in NOT_IMPLEMENTED_PROPERTIES: + continue + if name in REMOVED_PROPERTIES: + continue + if name in INTERNAL_PROPERTIES: + continue + + try: + attr = getattr(type(articulation_data), name, None) + if isinstance(attr, property): + all_properties.append(name) + except Exception: + pass + + return sorted(all_properties) + + +def setup_mock_environment(config: MethodBenchmarkRunnerConfig) -> MockNewtonArticulationView: + """Set up the mock environment for benchmarking.""" + mock_view = MockNewtonArticulationView( + num_instances=config.num_instances, + num_bodies=config.num_bodies, + num_joints=config.num_joints, + device=config.device, + ) + return mock_view + + +def main(): + """Main entry point for the benchmarking script.""" + config = MethodBenchmarkRunnerConfig( + num_iterations=args.num_iterations, + warmup_steps=args.warmup_steps, + num_instances=args.num_instances, + num_bodies=args.num_bodies, + num_joints=args.num_joints, + device=args.device, + ) + + # Patch the NewtonManager for the articulation_data module + with create_mock_newton_manager( + "isaaclab_newton.assets.articulation.articulation_data.SimulationManager", + gravity=(0.0, 0.0, -9.81), + ): + # Setup mock environment + mock_view = setup_mock_environment(config) + mock_view.set_random_mock_data() + + # Import ArticulationData inside the patch context + from isaaclab_newton.assets.articulation.articulation_data import ArticulationData + + # Create ArticulationData instance + articulation_data = ArticulationData(mock_view, config.device) + + # Get list of properties to benchmark + properties = get_benchmarkable_properties(articulation_data) + + # Generator that updates mock data and invalidates timestamp + def gen_mock_data(cfg: MethodBenchmarkRunnerConfig) -> dict: + N, L, J = cfg.num_instances, cfg.num_bodies, cfg.num_joints + dev = cfg.device + + # Update root transforms + root_tf_np = np.random.randn(N, 1, 7).astype(np.float32) + root_tf_np[..., 3:7] /= np.linalg.norm(root_tf_np[..., 3:7], axis=-1, keepdims=True) + mock_view.set_mock_root_transforms(wp.array(root_tf_np, dtype=wp.transformf, device=dev)) + + # Update root velocities + root_vel_np = np.random.randn(N, 1, 6).astype(np.float32) + mock_view.set_mock_root_velocities(wp.array(root_vel_np, dtype=wp.spatial_vectorf, device=dev)) + + # Update link transforms + link_tf_np = np.random.randn(N, 1, L, 7).astype(np.float32) + link_tf_np[..., 3:7] /= np.linalg.norm(link_tf_np[..., 3:7], axis=-1, keepdims=True) + mock_view.set_mock_link_transforms(wp.array(link_tf_np, dtype=wp.transformf, device=dev)) + + # Update link velocities + link_vel_np = np.random.randn(N, 1, L, 6).astype(np.float32) + mock_view.set_mock_link_velocities(wp.array(link_vel_np, dtype=wp.spatial_vectorf, device=dev)) + + # Update DOF state + mock_view.set_mock_dof_positions( + wp.array(np.random.randn(N, 1, J).astype(np.float32), dtype=wp.float32, device=dev) + ) + mock_view.set_mock_dof_velocities( + wp.array(np.random.randn(N, 1, J).astype(np.float32), dtype=wp.float32, device=dev) + ) + + # Update body properties + mock_view.set_mock_coms( + wp.array(np.random.randn(N, 1, L, 3).astype(np.float32), dtype=wp.vec3f, device=dev) + ) + mock_view.set_mock_inertias( + wp.array(np.random.randn(N, 1, L, 9).astype(np.float32), dtype=wp.mat33f, device=dev) + ) + mock_view.set_mock_masses( + wp.array((np.random.rand(N, 1, L) * 10 + 0.1).astype(np.float32), dtype=wp.float32, device=dev) + ) + + # Invalidate timestamp to trigger recomputation + articulation_data._sim_timestamp += 1.0 + return {} + + # Create runner + runner = MethodBenchmarkRunner( + benchmark_name="newton_articulation_data_benchmark", + config=config, + backend_type=args.backend, + output_path=args.output_dir, + use_recorders=True, + ) + + # Run property benchmarks + runner.run_property_benchmarks( + target_data=articulation_data, + properties=properties, + gen_mock_data=gen_mock_data, + dependencies=PROPERTY_DEPENDENCIES, + category="property", + ) + + runner.finalize() + + # Close the simulation app + simulation_app.close() + + +if __name__ == "__main__": + main() diff --git a/source/isaaclab_newton/benchmark/assets/benchmark_rigid_object.py b/source/isaaclab_newton/benchmark/assets/benchmark_rigid_object.py new file mode 100644 index 000000000000..e0df122d4f00 --- /dev/null +++ b/source/isaaclab_newton/benchmark/assets/benchmark_rigid_object.py @@ -0,0 +1,623 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Micro-benchmarking framework for RigidObject class (Newton backend). + +This module provides a benchmarking framework to measure the performance of setter and writer +methods in the RigidObject class. Each method is benchmarked under three scenarios: + +1. **Torch List**: Inputs are PyTorch tensors with list indices (via deprecated wrappers). +2. **Torch Tensor**: Inputs are PyTorch tensors with tensor indices (via deprecated wrappers). +3. **Warp Mask**: Inputs are warp arrays with boolean masks (via ``_mask`` methods). + +Usage: + python benchmark_rigid_object.py [--num_iterations N] [--warmup_steps W] + [--num_instances I] [--num_bodies B] + +Example: + python benchmark_rigid_object.py --num_iterations 1000 --warmup_steps 10 + python benchmark_rigid_object.py --mode torch_list # Only run list-based benchmarks + python benchmark_rigid_object.py --mode warp_mask # Only run warp mask benchmarks +""" + +from __future__ import annotations + +"""Launch Isaac Sim Simulator first.""" + +import argparse + +from isaaclab.app import AppLauncher + +# add argparse arguments +parser = argparse.ArgumentParser(description="Benchmark RigidObject methods (Newton backend).") +parser.add_argument("--num_iterations", type=int, default=1000, help="Number of iterations") +parser.add_argument("--warmup_steps", type=int, default=10, help="Number of warmup steps") +parser.add_argument("--num_instances", type=int, default=4096, help="Number of instances") +parser.add_argument("--num_bodies", type=int, default=1, help="Number of bodies") +parser.add_argument("--mode", type=str, default="all", help="Benchmark mode (all, torch_list, torch_tensor, warp_mask)") +parser.add_argument("--output_dir", type=str, default=".", help="Output directory for results") +parser.add_argument("--backend", type=str, default="json", choices=["json", "osmo", "omniperf"], help="Metrics backend") +parser.add_argument("--no_shape_checks", action="store_true", help="Disable shape/dtype assertions") + +# append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +# parse the arguments +args = parser.parse_args() + +# launch omniverse app +app_launcher = AppLauncher(headless=True, args=args) +simulation_app = app_launcher.app + +"""Rest everything follows.""" + +import logging +import warnings + +import numpy as np +import torch +import warp as wp +from isaaclab_newton.test.mock_interfaces import ( + MockNewtonArticulationView, + MockWrenchComposer, + create_mock_newton_manager, +) + +from isaaclab.assets.rigid_object.rigid_object_cfg import RigidObjectCfg +from isaaclab.test.benchmark import MethodBenchmarkDefinition, MethodBenchmarkRunner, MethodBenchmarkRunnerConfig + +# Suppress deprecation warnings during benchmarking +warnings.filterwarnings("ignore", category=DeprecationWarning) +warnings.filterwarnings("ignore", category=UserWarning) + +# Also suppress logging warnings +logging.getLogger("isaaclab_newton").setLevel(logging.ERROR) +logging.getLogger("isaaclab").setLevel(logging.ERROR) + + +# ============================================================================= +# Index Helpers +# ============================================================================= + + +def make_tensor_env_ids(num_instances: int, device: str) -> torch.Tensor: + """Create a tensor of environment IDs.""" + return torch.arange(num_instances, dtype=torch.int32, device=device) + + +def make_tensor_body_ids(num_bodies: int, device: str) -> torch.Tensor: + """Create a tensor of body IDs.""" + return torch.arange(num_bodies, dtype=torch.int32, device=device) + + +# ============================================================================= +# Test RigidObject Factory +# ============================================================================= + + +def create_test_rigid_object( + num_instances: int = 2, + num_bodies: int = 1, + device: str = "cuda:0", +): + """Create a test RigidObject instance with mocked dependencies.""" + from isaaclab_newton.assets.rigid_object.rigid_object import RigidObject + + body_names = [f"body_{i}" for i in range(num_bodies)] + + rigid_object = object.__new__(RigidObject) + + rigid_object.cfg = RigidObjectCfg( + prim_path="/World/Object", + ) + + # Create Newton mock view + mock_view = MockNewtonArticulationView( + num_instances=num_instances, + num_bodies=num_bodies, + num_joints=0, + device=device, + joint_names=[], + body_names=body_names, + ) + mock_view.set_random_mock_data() + mock_view._noop_setters = True + + object.__setattr__(rigid_object, "_root_view", mock_view) + object.__setattr__(rigid_object, "_device", device) + object.__setattr__(rigid_object, "_check_shapes", not args.no_shape_checks) + + # Create RigidObjectData instance (NewtonManager already mocked at call site) + from isaaclab_newton.assets.rigid_object.rigid_object_data import RigidObjectData + + data = RigidObjectData(mock_view, device) + object.__setattr__(rigid_object, "_data", data) + + # Create mock wrench composers + mock_inst_wrench = MockWrenchComposer(rigid_object) + mock_perm_wrench = MockWrenchComposer(rigid_object) + object.__setattr__(rigid_object, "_instantaneous_wrench_composer", mock_inst_wrench) + object.__setattr__(rigid_object, "_permanent_wrench_composer", mock_perm_wrench) + + # Set up other required attributes + object.__setattr__(rigid_object, "actuators", {}) + object.__setattr__(rigid_object, "_ALL_INDICES", wp.array(np.arange(num_instances, dtype=np.int32), device=device)) + object.__setattr__( + rigid_object, "_ALL_BODY_INDICES", wp.array(np.arange(num_bodies, dtype=np.int32), device=device) + ) + object.__setattr__(rigid_object, "_ALL_ENV_MASK", wp.ones((num_instances,), dtype=wp.bool, device=device)) + object.__setattr__(rigid_object, "_ALL_BODY_MASK", wp.ones((num_bodies,), dtype=wp.bool, device=device)) + + # set information about rigid body into data + data.body_names = body_names + + return rigid_object, mock_view + + +# ============================================================================= +# Input Generators (Torch-only for Newton backend) +# ============================================================================= + + +# --- Root Link Pose --- +def gen_root_link_pose_torch_list(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "root_pose": torch.rand(config.num_instances, 7, device=config.device, dtype=torch.float32), + "env_ids": list(range(config.num_instances)), + } + + +def gen_root_link_pose_torch_tensor(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "root_pose": torch.rand(config.num_instances, 7, device=config.device, dtype=torch.float32), + "env_ids": make_tensor_env_ids(config.num_instances, config.device), + } + + +# --- Root COM Pose --- +def gen_root_com_pose_torch_list(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "root_pose": torch.rand(config.num_instances, 7, device=config.device, dtype=torch.float32), + "env_ids": list(range(config.num_instances)), + } + + +def gen_root_com_pose_torch_tensor(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "root_pose": torch.rand(config.num_instances, 7, device=config.device, dtype=torch.float32), + "env_ids": make_tensor_env_ids(config.num_instances, config.device), + } + + +# --- Root Link Velocity --- +def gen_root_link_velocity_torch_list(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "root_velocity": torch.rand(config.num_instances, 6, device=config.device, dtype=torch.float32), + "env_ids": list(range(config.num_instances)), + } + + +def gen_root_link_velocity_torch_tensor(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "root_velocity": torch.rand(config.num_instances, 6, device=config.device, dtype=torch.float32), + "env_ids": make_tensor_env_ids(config.num_instances, config.device), + } + + +# --- Root COM Velocity --- +def gen_root_com_velocity_torch_list(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "root_velocity": torch.rand(config.num_instances, 6, device=config.device, dtype=torch.float32), + "env_ids": list(range(config.num_instances)), + } + + +def gen_root_com_velocity_torch_tensor(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "root_velocity": torch.rand(config.num_instances, 6, device=config.device, dtype=torch.float32), + "env_ids": make_tensor_env_ids(config.num_instances, config.device), + } + + +# --- Set Masses --- +def gen_set_masses_torch_list(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "masses": torch.rand(config.num_instances, config.num_bodies, device=config.device, dtype=torch.float32), + "env_ids": list(range(config.num_instances)), + "body_ids": list(range(config.num_bodies)), + } + + +def gen_set_masses_torch_tensor(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "masses": torch.rand(config.num_instances, config.num_bodies, device=config.device, dtype=torch.float32), + "env_ids": make_tensor_env_ids(config.num_instances, config.device), + "body_ids": make_tensor_body_ids(config.num_bodies, config.device), + } + + +# --- Set CoMs --- +def gen_set_coms_torch_list(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "coms": torch.rand(config.num_instances, config.num_bodies, 3, device=config.device, dtype=torch.float32), + "env_ids": list(range(config.num_instances)), + "body_ids": list(range(config.num_bodies)), + } + + +def gen_set_coms_torch_tensor(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "coms": torch.rand(config.num_instances, config.num_bodies, 3, device=config.device, dtype=torch.float32), + "env_ids": make_tensor_env_ids(config.num_instances, config.device), + "body_ids": make_tensor_body_ids(config.num_bodies, config.device), + } + + +# --- Set Inertias --- +def gen_set_inertias_torch_list(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "inertias": torch.rand(config.num_instances, config.num_bodies, 9, device=config.device, dtype=torch.float32), + "env_ids": list(range(config.num_instances)), + "body_ids": list(range(config.num_bodies)), + } + + +def gen_set_inertias_torch_tensor(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "inertias": torch.rand(config.num_instances, config.num_bodies, 9, device=config.device, dtype=torch.float32), + "env_ids": make_tensor_env_ids(config.num_instances, config.device), + "body_ids": make_tensor_body_ids(config.num_bodies, config.device), + } + + +# --- Set External Force and Torque --- +def gen_set_external_force_and_torque_torch_list(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "forces": torch.rand(config.num_instances, config.num_bodies, 3, device=config.device, dtype=torch.float32), + "torques": torch.rand(config.num_instances, config.num_bodies, 3, device=config.device, dtype=torch.float32), + "env_ids": list(range(config.num_instances)), + } + + +def gen_set_external_force_and_torque_torch_tensor(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "forces": torch.rand(config.num_instances, config.num_bodies, 3, device=config.device, dtype=torch.float32), + "torques": torch.rand(config.num_instances, config.num_bodies, 3, device=config.device, dtype=torch.float32), + "env_ids": make_tensor_env_ids(config.num_instances, config.device), + } + + +# ============================================================================= +# Warp Mask Input Generators (for _mask methods) +# ============================================================================= + + +def _env_mask(config: MethodBenchmarkRunnerConfig) -> wp.array: + return wp.ones((config.num_instances,), dtype=wp.bool, device=config.device) + + +def _body_mask(config: MethodBenchmarkRunnerConfig) -> wp.array: + return wp.ones((config.num_bodies,), dtype=wp.bool, device=config.device) + + +# --- Root Link Pose (mask) --- +def gen_root_link_pose_warp_mask(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "root_pose": torch.rand(config.num_instances, 7, device=config.device, dtype=torch.float32), + "env_mask": _env_mask(config), + } + + +# --- Root COM Pose (mask) --- +def gen_root_com_pose_warp_mask(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "root_pose": torch.rand(config.num_instances, 7, device=config.device, dtype=torch.float32), + "env_mask": _env_mask(config), + } + + +# --- Root Link Velocity (mask) --- +def gen_root_link_velocity_warp_mask(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "root_velocity": torch.rand(config.num_instances, 6, device=config.device, dtype=torch.float32), + "env_mask": _env_mask(config), + } + + +# --- Root COM Velocity (mask) --- +def gen_root_com_velocity_warp_mask(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "root_velocity": torch.rand(config.num_instances, 6, device=config.device, dtype=torch.float32), + "env_mask": _env_mask(config), + } + + +# --- Set Masses (mask) --- +def gen_set_masses_warp_mask(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "masses": torch.rand(config.num_instances, config.num_bodies, device=config.device, dtype=torch.float32), + "body_mask": _body_mask(config), + "env_mask": _env_mask(config), + } + + +# --- Set CoMs (mask) --- +def gen_set_coms_warp_mask(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "coms": torch.rand(config.num_instances, config.num_bodies, 3, device=config.device, dtype=torch.float32), + "body_mask": _body_mask(config), + "env_mask": _env_mask(config), + } + + +# --- Set Inertias (mask) --- +def gen_set_inertias_warp_mask(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "inertias": torch.rand(config.num_instances, config.num_bodies, 9, device=config.device, dtype=torch.float32), + "body_mask": _body_mask(config), + "env_mask": _env_mask(config), + } + + +# ============================================================================= +# Benchmarks +# ============================================================================= + +BENCHMARKS = [ + # --- Root Pose / Velocity --- + MethodBenchmarkDefinition( + name="write_root_link_pose_to_sim", + method_name="write_root_link_pose_to_sim", + input_generators={ + "torch_list": gen_root_link_pose_torch_list, + "torch_tensor": gen_root_link_pose_torch_tensor, + }, + category="root_pose", + ), + MethodBenchmarkDefinition( + name="write_root_link_pose_to_sim_mask", + method_name="write_root_link_pose_to_sim_mask", + input_generators={"warp_mask": gen_root_link_pose_warp_mask}, + category="root_pose", + ), + MethodBenchmarkDefinition( + name="write_root_com_pose_to_sim", + method_name="write_root_com_pose_to_sim", + input_generators={ + "torch_list": gen_root_com_pose_torch_list, + "torch_tensor": gen_root_com_pose_torch_tensor, + }, + category="root_pose", + ), + MethodBenchmarkDefinition( + name="write_root_com_pose_to_sim_mask", + method_name="write_root_com_pose_to_sim_mask", + input_generators={"warp_mask": gen_root_com_pose_warp_mask}, + category="root_pose", + ), + MethodBenchmarkDefinition( + name="write_root_link_velocity_to_sim", + method_name="write_root_link_velocity_to_sim", + input_generators={ + "torch_list": gen_root_link_velocity_torch_list, + "torch_tensor": gen_root_link_velocity_torch_tensor, + }, + category="root_velocity", + ), + MethodBenchmarkDefinition( + name="write_root_link_velocity_to_sim_mask", + method_name="write_root_link_velocity_to_sim_mask", + input_generators={"warp_mask": gen_root_link_velocity_warp_mask}, + category="root_velocity", + ), + MethodBenchmarkDefinition( + name="write_root_com_velocity_to_sim", + method_name="write_root_com_velocity_to_sim", + input_generators={ + "torch_list": gen_root_com_velocity_torch_list, + "torch_tensor": gen_root_com_velocity_torch_tensor, + }, + category="root_velocity", + ), + MethodBenchmarkDefinition( + name="write_root_com_velocity_to_sim_mask", + method_name="write_root_com_velocity_to_sim_mask", + input_generators={"warp_mask": gen_root_com_velocity_warp_mask}, + category="root_velocity", + ), + # --- Body Properties --- + MethodBenchmarkDefinition( + name="set_masses", + method_name="set_masses", + input_generators={ + "torch_list": gen_set_masses_torch_list, + "torch_tensor": gen_set_masses_torch_tensor, + }, + category="body_props", + ), + MethodBenchmarkDefinition( + name="set_masses_mask", + method_name="set_masses_mask", + input_generators={"warp_mask": gen_set_masses_warp_mask}, + category="body_props", + ), + MethodBenchmarkDefinition( + name="set_coms", + method_name="set_coms", + input_generators={ + "torch_list": gen_set_coms_torch_list, + "torch_tensor": gen_set_coms_torch_tensor, + }, + category="body_props", + ), + MethodBenchmarkDefinition( + name="set_coms_mask", + method_name="set_coms_mask", + input_generators={"warp_mask": gen_set_coms_warp_mask}, + category="body_props", + ), + MethodBenchmarkDefinition( + name="set_inertias", + method_name="set_inertias", + input_generators={ + "torch_list": gen_set_inertias_torch_list, + "torch_tensor": gen_set_inertias_torch_tensor, + }, + category="body_props", + ), + MethodBenchmarkDefinition( + name="set_inertias_mask", + method_name="set_inertias_mask", + input_generators={"warp_mask": gen_set_inertias_warp_mask}, + category="body_props", + ), + MethodBenchmarkDefinition( + name="set_external_force_and_torque", + method_name="set_external_force_and_torque", + input_generators={ + "torch_list": gen_set_external_force_and_torque_torch_list, + "torch_tensor": gen_set_external_force_and_torque_torch_tensor, + }, + category="external_wrench", + ), +] + + +# ============================================================================= +# Fill-Ratio Benchmarks (5%, 95%, 100% of env_ids filled) +# ============================================================================= + +FILL_RATIOS = {"5pct": 0.05, "95pct": 0.95, "100pct": 1.0} + + +def _make_fill_ratio_generator(base_gen_fn, fill_ratio): + """Create a generator that subsets env_ids to a given fill ratio. + + Only env_ids are subsetted — body_ids remain full-range. + Data tensors keyed on env count are sliced to match. + """ + + def generator(config): + n = max(1, int(config.num_instances * fill_ratio)) + base_inputs = base_gen_fn(config) + inputs = {} + for key, val in base_inputs.items(): + if key == "env_ids": + inputs[key] = ( + torch.randperm(config.num_instances, device=config.device)[:n].sort().values.to(torch.int32) + ) + elif isinstance(val, torch.Tensor) and val.dim() >= 1 and val.shape[0] == config.num_instances: + inputs[key] = val[:n] + else: + inputs[key] = val + return inputs + + return generator + + +def _make_fill_ratio_mask_generator(base_mask_gen_fn, fill_ratio): + """Create a mask generator with a given fill ratio. + + Sets a random subset of the env_mask entries to True. Data stays full-sized (mask methods expect full data). + """ + + def generator(config): + base_inputs = base_mask_gen_fn(config) + n = max(1, int(config.num_instances * fill_ratio)) + # Create a mask with n random entries set to True + perm = torch.randperm(config.num_instances, device=config.device) + mask_tensor = torch.zeros(config.num_instances, dtype=torch.bool, device=config.device) + mask_tensor[perm[:n]] = True + base_inputs["env_mask"] = wp.from_torch(mask_tensor, dtype=wp.bool) + return base_inputs + + return generator + + +def _build_fill_benchmarks(): + """Auto-generate fill-ratio benchmark definitions from existing generators.""" + fill_benchmarks = [] + for bm in BENCHMARKS: + generators = {} + # Add tensor fill variants from torch_tensor generators + if "torch_tensor" in bm.input_generators: + base_gen = bm.input_generators["torch_tensor"] + for suffix, ratio in FILL_RATIOS.items(): + generators[f"tensor_{suffix}"] = _make_fill_ratio_generator(base_gen, ratio) + # Add mask fill variants from warp_mask generators + if "warp_mask" in bm.input_generators: + base_gen = bm.input_generators["warp_mask"] + for suffix, ratio in FILL_RATIOS.items(): + generators[f"mask_{suffix}"] = _make_fill_ratio_mask_generator(base_gen, ratio) + if generators: + fill_benchmarks.append( + MethodBenchmarkDefinition( + name=bm.name, + method_name=bm.method_name, + input_generators=generators, + category=f"{bm.category}_fill", + ) + ) + return fill_benchmarks + + +FILL_BENCHMARKS = _build_fill_benchmarks() + + +def main(): + """Main entry point for the benchmarking script.""" + config = MethodBenchmarkRunnerConfig( + num_iterations=args.num_iterations, + warmup_steps=args.warmup_steps, + num_instances=args.num_instances, + num_bodies=args.num_bodies, + num_joints=0, + device=args.device, + mode=args.mode, + ) + + # Patch the NewtonManager for both rigid_object and rigid_object_data modules + with ( + create_mock_newton_manager( + "isaaclab_newton.assets.rigid_object.rigid_object_data.SimulationManager", + gravity=(0.0, 0.0, -9.81), + ), + create_mock_newton_manager( + "isaaclab_newton.assets.rigid_object.rigid_object.SimulationManager", + gravity=(0.0, 0.0, -9.81), + ), + ): + # Create the test rigid object + rigid_object, _ = create_test_rigid_object( + num_instances=config.num_instances, + num_bodies=config.num_bodies, + device=config.device, + ) + + print(f"Benchmarking RigidObject (Newton) with {config.num_instances} instances, {config.num_bodies} bodies...") + + # Create runner and run benchmarks + runner = MethodBenchmarkRunner( + benchmark_name="newton_rigid_object_benchmark", + config=config, + backend_type=args.backend, + output_path=args.output_dir, + use_recorders=True, + ) + + runner.run_benchmarks(BENCHMARKS, rigid_object) + + print("\n" + "=" * 80) + print("Fill-Ratio Benchmarks (env_ids at 5%, 95%, 100% fill)") + print("=" * 80) + + runner.run_benchmarks(FILL_BENCHMARKS, rigid_object) + runner.finalize() + + # Close the simulation app + simulation_app.close() + + +if __name__ == "__main__": + main() diff --git a/source/isaaclab_newton/benchmark/assets/benchmark_rigid_object_collection.py b/source/isaaclab_newton/benchmark/assets/benchmark_rigid_object_collection.py new file mode 100644 index 000000000000..f75c7d0d03b8 --- /dev/null +++ b/source/isaaclab_newton/benchmark/assets/benchmark_rigid_object_collection.py @@ -0,0 +1,654 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Micro-benchmarking framework for RigidObjectCollection class (Newton backend). + +This module provides a benchmarking framework to measure the performance of setter and writer +methods in the RigidObjectCollection class. Each method is benchmarked under three scenarios: + +1. **Torch List**: Inputs are PyTorch tensors with list indices (via deprecated wrappers). +2. **Torch Tensor**: Inputs are PyTorch tensors with tensor indices (via deprecated wrappers). +3. **Warp Mask**: Inputs are warp arrays with boolean masks (via ``_mask`` methods). + +Usage: + python benchmark_rigid_object_collection.py [--num_iterations N] [--warmup_steps W] + [--num_instances I] [--num_bodies B] + +Example: + python benchmark_rigid_object_collection.py --num_iterations 1000 --warmup_steps 10 + python benchmark_rigid_object_collection.py --mode torch_list # Only run list-based benchmarks + python benchmark_rigid_object_collection.py --mode warp_mask # Only run warp mask benchmarks +""" + +from __future__ import annotations + +"""Launch Isaac Sim Simulator first.""" + +import argparse + +from isaaclab.app import AppLauncher + +# add argparse arguments +parser = argparse.ArgumentParser(description="Benchmark RigidObjectCollection methods (Newton backend).") +parser.add_argument("--num_iterations", type=int, default=1000, help="Number of iterations") +parser.add_argument("--warmup_steps", type=int, default=10, help="Number of warmup steps") +parser.add_argument("--num_instances", type=int, default=4096, help="Number of instances") +parser.add_argument("--num_bodies", type=int, default=3, help="Number of bodies (object types)") +parser.add_argument("--mode", type=str, default="all", help="Benchmark mode (all, torch_list, torch_tensor, warp_mask)") +parser.add_argument("--output_dir", type=str, default=".", help="Output directory for results") +parser.add_argument("--backend", type=str, default="json", choices=["json", "osmo", "omniperf"], help="Metrics backend") +parser.add_argument("--no_shape_checks", action="store_true", help="Disable shape/dtype assertions") + +# append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +# parse the arguments +args = parser.parse_args() + +# launch omniverse app +app_launcher = AppLauncher(headless=True, args=args) +simulation_app = app_launcher.app + +"""Rest everything follows.""" + +import logging +import warnings + +import numpy as np +import torch +import warp as wp +from isaaclab_newton.test.mock_interfaces import ( + MockWrenchComposer, + create_mock_newton_manager, +) +from isaaclab_newton.test.mock_interfaces.views import MockNewtonCollectionView + +from isaaclab.assets.rigid_object_collection.rigid_object_collection_cfg import RigidObjectCollectionCfg +from isaaclab.test.benchmark import MethodBenchmarkDefinition, MethodBenchmarkRunner, MethodBenchmarkRunnerConfig + +# Suppress deprecation warnings during benchmarking +warnings.filterwarnings("ignore", category=DeprecationWarning) +warnings.filterwarnings("ignore", category=UserWarning) + +# Also suppress logging warnings +logging.getLogger("isaaclab_newton").setLevel(logging.ERROR) +logging.getLogger("isaaclab").setLevel(logging.ERROR) + + +# ============================================================================= +# Index Helpers +# ============================================================================= + + +def make_tensor_env_ids(num_instances: int, device: str) -> torch.Tensor: + """Create a tensor of environment IDs.""" + return torch.arange(num_instances, dtype=torch.int32, device=device) + + +def make_tensor_body_ids(num_bodies: int, device: str) -> torch.Tensor: + """Create a tensor of body IDs.""" + return torch.arange(num_bodies, dtype=torch.int32, device=device) + + +# ============================================================================= +# Test RigidObjectCollection Factory +# ============================================================================= + + +def create_test_collection( + num_instances: int = 2, + num_bodies: int = 3, + device: str = "cuda:0", +): + """Create a test RigidObjectCollection instance with mocked dependencies.""" + from isaaclab_newton.assets.rigid_object_collection.rigid_object_collection import RigidObjectCollection + + object_names = [f"object_{i}" for i in range(num_bodies)] + + collection = object.__new__(RigidObjectCollection) + + # Create a minimal config with dummy rigid objects + from isaaclab.assets.rigid_object.rigid_object_cfg import RigidObjectCfg + + rigid_objects = {name: RigidObjectCfg(prim_path=f"/World/{name}") for name in object_names} + collection.cfg = RigidObjectCollectionCfg(rigid_objects=rigid_objects) + + # Create Newton mock view + mock_view = MockNewtonCollectionView( + num_envs=num_instances, + num_bodies=num_bodies, + device=device, + body_names=object_names, + ) + mock_view.set_random_mock_data() + mock_view._noop_setters = True + + object.__setattr__(collection, "_root_view", mock_view) + object.__setattr__(collection, "_device", device) + object.__setattr__(collection, "_body_names_list", object_names) + object.__setattr__(collection, "_check_shapes", not args.no_shape_checks) + + # Create RigidObjectCollectionData instance (NewtonManager already mocked at call site) + from isaaclab_newton.assets.rigid_object_collection.rigid_object_collection_data import RigidObjectCollectionData + + data = RigidObjectCollectionData(mock_view, num_bodies, device) + object.__setattr__(collection, "_data", data) + + # Create mock wrench composers + mock_inst_wrench = MockWrenchComposer(collection) + mock_perm_wrench = MockWrenchComposer(collection) + object.__setattr__(collection, "_instantaneous_wrench_composer", mock_inst_wrench) + object.__setattr__(collection, "_permanent_wrench_composer", mock_perm_wrench) + + # Set up other required attributes + object.__setattr__( + collection, "_ALL_ENV_INDICES", wp.array(np.arange(num_instances, dtype=np.int32), device=device) + ) + object.__setattr__(collection, "_ALL_BODY_INDICES", wp.array(np.arange(num_bodies, dtype=np.int32), device=device)) + object.__setattr__(collection, "_ALL_ENV_MASK", wp.ones((num_instances,), dtype=wp.bool, device=device)) + object.__setattr__(collection, "_ALL_BODY_MASK", wp.ones((num_bodies,), dtype=wp.bool, device=device)) + + # Temporary 2D wrench buffer for write_data_to_sim + object.__setattr__( + collection, + "_wrench_buffer", + wp.zeros((num_instances, num_bodies), dtype=wp.spatial_vectorf, device=device), + ) + + return collection, mock_view + + +# ============================================================================= +# Input Generators (Torch-only for Newton backend) +# ============================================================================= + + +# --- Body Link Pose --- +def gen_body_link_pose_torch_list(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "body_poses": torch.rand(config.num_instances, config.num_bodies, 7, device=config.device, dtype=torch.float32), + "env_ids": list(range(config.num_instances)), + "body_ids": list(range(config.num_bodies)), + } + + +def gen_body_link_pose_torch_tensor(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "body_poses": torch.rand(config.num_instances, config.num_bodies, 7, device=config.device, dtype=torch.float32), + "env_ids": make_tensor_env_ids(config.num_instances, config.device), + "body_ids": make_tensor_body_ids(config.num_bodies, config.device), + } + + +# --- Body COM Pose --- +def gen_body_com_pose_torch_list(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "body_poses": torch.rand(config.num_instances, config.num_bodies, 7, device=config.device, dtype=torch.float32), + "env_ids": list(range(config.num_instances)), + "body_ids": list(range(config.num_bodies)), + } + + +def gen_body_com_pose_torch_tensor(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "body_poses": torch.rand(config.num_instances, config.num_bodies, 7, device=config.device, dtype=torch.float32), + "env_ids": make_tensor_env_ids(config.num_instances, config.device), + "body_ids": make_tensor_body_ids(config.num_bodies, config.device), + } + + +# --- Body Link Velocity --- +def gen_body_link_velocity_torch_list(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "body_velocities": torch.rand( + config.num_instances, config.num_bodies, 6, device=config.device, dtype=torch.float32 + ), + "env_ids": list(range(config.num_instances)), + "body_ids": list(range(config.num_bodies)), + } + + +def gen_body_link_velocity_torch_tensor(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "body_velocities": torch.rand( + config.num_instances, config.num_bodies, 6, device=config.device, dtype=torch.float32 + ), + "env_ids": make_tensor_env_ids(config.num_instances, config.device), + "body_ids": make_tensor_body_ids(config.num_bodies, config.device), + } + + +# --- Body COM Velocity --- +def gen_body_com_velocity_torch_list(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "body_velocities": torch.rand( + config.num_instances, config.num_bodies, 6, device=config.device, dtype=torch.float32 + ), + "env_ids": list(range(config.num_instances)), + "body_ids": list(range(config.num_bodies)), + } + + +def gen_body_com_velocity_torch_tensor(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "body_velocities": torch.rand( + config.num_instances, config.num_bodies, 6, device=config.device, dtype=torch.float32 + ), + "env_ids": make_tensor_env_ids(config.num_instances, config.device), + "body_ids": make_tensor_body_ids(config.num_bodies, config.device), + } + + +# --- Set Masses --- +def gen_set_masses_torch_list(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "masses": torch.rand(config.num_instances, config.num_bodies, device=config.device, dtype=torch.float32), + "env_ids": list(range(config.num_instances)), + "body_ids": list(range(config.num_bodies)), + } + + +def gen_set_masses_torch_tensor(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "masses": torch.rand(config.num_instances, config.num_bodies, device=config.device, dtype=torch.float32), + "env_ids": make_tensor_env_ids(config.num_instances, config.device), + "body_ids": make_tensor_body_ids(config.num_bodies, config.device), + } + + +# --- Set CoMs --- +def gen_set_coms_torch_list(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "coms": torch.rand(config.num_instances, config.num_bodies, 3, device=config.device, dtype=torch.float32), + "env_ids": list(range(config.num_instances)), + "body_ids": list(range(config.num_bodies)), + } + + +def gen_set_coms_torch_tensor(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "coms": torch.rand(config.num_instances, config.num_bodies, 3, device=config.device, dtype=torch.float32), + "env_ids": make_tensor_env_ids(config.num_instances, config.device), + "body_ids": make_tensor_body_ids(config.num_bodies, config.device), + } + + +# --- Set Inertias --- +def gen_set_inertias_torch_list(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "inertias": torch.rand(config.num_instances, config.num_bodies, 9, device=config.device, dtype=torch.float32), + "env_ids": list(range(config.num_instances)), + "body_ids": list(range(config.num_bodies)), + } + + +def gen_set_inertias_torch_tensor(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "inertias": torch.rand(config.num_instances, config.num_bodies, 9, device=config.device, dtype=torch.float32), + "env_ids": make_tensor_env_ids(config.num_instances, config.device), + "body_ids": make_tensor_body_ids(config.num_bodies, config.device), + } + + +# --- Set External Force and Torque --- +def gen_set_external_force_and_torque_torch_list(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "forces": torch.rand(config.num_instances, config.num_bodies, 3, device=config.device, dtype=torch.float32), + "torques": torch.rand(config.num_instances, config.num_bodies, 3, device=config.device, dtype=torch.float32), + "env_ids": list(range(config.num_instances)), + } + + +def gen_set_external_force_and_torque_torch_tensor(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "forces": torch.rand(config.num_instances, config.num_bodies, 3, device=config.device, dtype=torch.float32), + "torques": torch.rand(config.num_instances, config.num_bodies, 3, device=config.device, dtype=torch.float32), + "env_ids": make_tensor_env_ids(config.num_instances, config.device), + } + + +# ============================================================================= +# Warp Mask Input Generators (for _mask methods) +# ============================================================================= + + +def _env_mask(config: MethodBenchmarkRunnerConfig) -> wp.array: + return wp.ones((config.num_instances,), dtype=wp.bool, device=config.device) + + +def _body_mask(config: MethodBenchmarkRunnerConfig) -> wp.array: + return wp.ones((config.num_bodies,), dtype=wp.bool, device=config.device) + + +# --- Body Link Pose (mask) --- +def gen_body_link_pose_warp_mask(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "body_poses": torch.rand(config.num_instances, config.num_bodies, 7, device=config.device, dtype=torch.float32), + "env_mask": _env_mask(config), + } + + +# --- Body COM Pose (mask) --- +def gen_body_com_pose_warp_mask(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "body_poses": torch.rand(config.num_instances, config.num_bodies, 7, device=config.device, dtype=torch.float32), + "env_mask": _env_mask(config), + } + + +# --- Body Link Velocity (mask) --- +def gen_body_link_velocity_warp_mask(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "body_velocities": torch.rand( + config.num_instances, config.num_bodies, 6, device=config.device, dtype=torch.float32 + ), + "env_mask": _env_mask(config), + } + + +# --- Body COM Velocity (mask) --- +def gen_body_com_velocity_warp_mask(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "body_velocities": torch.rand( + config.num_instances, config.num_bodies, 6, device=config.device, dtype=torch.float32 + ), + "env_mask": _env_mask(config), + } + + +# --- Set Masses (mask) --- +def gen_set_masses_warp_mask(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "masses": torch.rand(config.num_instances, config.num_bodies, device=config.device, dtype=torch.float32), + "body_mask": _body_mask(config), + "env_mask": _env_mask(config), + } + + +# --- Set CoMs (mask) --- +def gen_set_coms_warp_mask(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "coms": torch.rand(config.num_instances, config.num_bodies, 3, device=config.device, dtype=torch.float32), + "body_mask": _body_mask(config), + "env_mask": _env_mask(config), + } + + +# --- Set Inertias (mask) --- +def gen_set_inertias_warp_mask(config: MethodBenchmarkRunnerConfig) -> dict: + return { + "inertias": torch.rand(config.num_instances, config.num_bodies, 9, device=config.device, dtype=torch.float32), + "body_mask": _body_mask(config), + "env_mask": _env_mask(config), + } + + +# ============================================================================= +# Benchmarks +# ============================================================================= + +BENCHMARKS = [ + # --- Body Link Pose --- + MethodBenchmarkDefinition( + name="write_body_link_pose_to_sim", + method_name="write_body_link_pose_to_sim", + input_generators={ + "torch_list": gen_body_link_pose_torch_list, + "torch_tensor": gen_body_link_pose_torch_tensor, + }, + category="body_pose", + ), + MethodBenchmarkDefinition( + name="write_body_link_pose_to_sim_mask", + method_name="write_body_link_pose_to_sim_mask", + input_generators={"warp_mask": gen_body_link_pose_warp_mask}, + category="body_pose", + ), + # --- Body COM Pose --- + MethodBenchmarkDefinition( + name="write_body_com_pose_to_sim", + method_name="write_body_com_pose_to_sim", + input_generators={ + "torch_list": gen_body_com_pose_torch_list, + "torch_tensor": gen_body_com_pose_torch_tensor, + }, + category="body_pose", + ), + MethodBenchmarkDefinition( + name="write_body_com_pose_to_sim_mask", + method_name="write_body_com_pose_to_sim_mask", + input_generators={"warp_mask": gen_body_com_pose_warp_mask}, + category="body_pose", + ), + # --- Body Link Velocity --- + MethodBenchmarkDefinition( + name="write_body_link_velocity_to_sim", + method_name="write_body_link_velocity_to_sim", + input_generators={ + "torch_list": gen_body_link_velocity_torch_list, + "torch_tensor": gen_body_link_velocity_torch_tensor, + }, + category="body_velocity", + ), + MethodBenchmarkDefinition( + name="write_body_link_velocity_to_sim_mask", + method_name="write_body_link_velocity_to_sim_mask", + input_generators={"warp_mask": gen_body_link_velocity_warp_mask}, + category="body_velocity", + ), + # --- Body COM Velocity --- + MethodBenchmarkDefinition( + name="write_body_com_velocity_to_sim", + method_name="write_body_com_velocity_to_sim", + input_generators={ + "torch_list": gen_body_com_velocity_torch_list, + "torch_tensor": gen_body_com_velocity_torch_tensor, + }, + category="body_velocity", + ), + MethodBenchmarkDefinition( + name="write_body_com_velocity_to_sim_mask", + method_name="write_body_com_velocity_to_sim_mask", + input_generators={"warp_mask": gen_body_com_velocity_warp_mask}, + category="body_velocity", + ), + # --- Body Properties --- + MethodBenchmarkDefinition( + name="set_masses", + method_name="set_masses", + input_generators={ + "torch_list": gen_set_masses_torch_list, + "torch_tensor": gen_set_masses_torch_tensor, + }, + category="body_props", + ), + MethodBenchmarkDefinition( + name="set_masses_mask", + method_name="set_masses_mask", + input_generators={"warp_mask": gen_set_masses_warp_mask}, + category="body_props", + ), + MethodBenchmarkDefinition( + name="set_coms", + method_name="set_coms", + input_generators={ + "torch_list": gen_set_coms_torch_list, + "torch_tensor": gen_set_coms_torch_tensor, + }, + category="body_props", + ), + MethodBenchmarkDefinition( + name="set_coms_mask", + method_name="set_coms_mask", + input_generators={"warp_mask": gen_set_coms_warp_mask}, + category="body_props", + ), + MethodBenchmarkDefinition( + name="set_inertias", + method_name="set_inertias", + input_generators={ + "torch_list": gen_set_inertias_torch_list, + "torch_tensor": gen_set_inertias_torch_tensor, + }, + category="body_props", + ), + MethodBenchmarkDefinition( + name="set_inertias_mask", + method_name="set_inertias_mask", + input_generators={"warp_mask": gen_set_inertias_warp_mask}, + category="body_props", + ), + # --- External Force and Torque --- + MethodBenchmarkDefinition( + name="set_external_force_and_torque", + method_name="set_external_force_and_torque", + input_generators={ + "torch_list": gen_set_external_force_and_torque_torch_list, + "torch_tensor": gen_set_external_force_and_torque_torch_tensor, + }, + category="external_wrench", + ), +] + + +# ============================================================================= +# Fill-Ratio Benchmarks (5%, 95%, 100% of env_ids filled) +# ============================================================================= + +FILL_RATIOS = {"5pct": 0.05, "95pct": 0.95, "100pct": 1.0} + + +def _make_fill_ratio_generator(base_gen_fn, fill_ratio): + """Create a generator that subsets env_ids to a given fill ratio. + + Only env_ids are subsetted -- body_ids remain full-range. + Data tensors keyed on env count are sliced to match. + """ + + def generator(config): + n = max(1, int(config.num_instances * fill_ratio)) + base_inputs = base_gen_fn(config) + inputs = {} + for key, val in base_inputs.items(): + if key == "env_ids": + inputs[key] = ( + torch.randperm(config.num_instances, device=config.device)[:n].sort().values.to(torch.int32) + ) + elif isinstance(val, torch.Tensor) and val.dim() >= 1 and val.shape[0] == config.num_instances: + inputs[key] = val[:n] + else: + inputs[key] = val + return inputs + + return generator + + +def _make_fill_ratio_mask_generator(base_mask_gen_fn, fill_ratio): + """Create a mask generator with a given fill ratio. + + Sets a random subset of the env_mask entries to True. Data stays full-sized (mask methods expect full data). + """ + + def generator(config): + base_inputs = base_mask_gen_fn(config) + n = max(1, int(config.num_instances * fill_ratio)) + # Create a mask with n random entries set to True + perm = torch.randperm(config.num_instances, device=config.device) + mask_tensor = torch.zeros(config.num_instances, dtype=torch.bool, device=config.device) + mask_tensor[perm[:n]] = True + base_inputs["env_mask"] = wp.from_torch(mask_tensor, dtype=wp.bool) + return base_inputs + + return generator + + +def _build_fill_benchmarks(): + """Auto-generate fill-ratio benchmark definitions from existing generators.""" + fill_benchmarks = [] + for bm in BENCHMARKS: + generators = {} + # Add tensor fill variants from torch_tensor generators + if "torch_tensor" in bm.input_generators: + base_gen = bm.input_generators["torch_tensor"] + for suffix, ratio in FILL_RATIOS.items(): + generators[f"tensor_{suffix}"] = _make_fill_ratio_generator(base_gen, ratio) + # Add mask fill variants from warp_mask generators + if "warp_mask" in bm.input_generators: + base_gen = bm.input_generators["warp_mask"] + for suffix, ratio in FILL_RATIOS.items(): + generators[f"mask_{suffix}"] = _make_fill_ratio_mask_generator(base_gen, ratio) + if generators: + fill_benchmarks.append( + MethodBenchmarkDefinition( + name=bm.name, + method_name=bm.method_name, + input_generators=generators, + category=f"{bm.category}_fill", + ) + ) + return fill_benchmarks + + +FILL_BENCHMARKS = _build_fill_benchmarks() + + +def main(): + """Main entry point for the benchmarking script.""" + config = MethodBenchmarkRunnerConfig( + num_iterations=args.num_iterations, + warmup_steps=args.warmup_steps, + num_instances=args.num_instances, + num_bodies=args.num_bodies, + num_joints=0, + device=args.device, + mode=args.mode, + ) + + # Patch the NewtonManager for both collection and collection_data modules + with ( + create_mock_newton_manager( + "isaaclab_newton.assets.rigid_object_collection.rigid_object_collection_data.SimulationManager", + gravity=(0.0, 0.0, -9.81), + ), + create_mock_newton_manager( + "isaaclab_newton.assets.rigid_object_collection.rigid_object_collection.SimulationManager", + gravity=(0.0, 0.0, -9.81), + ), + ): + # Create the test collection + collection, _ = create_test_collection( + num_instances=config.num_instances, + num_bodies=config.num_bodies, + device=config.device, + ) + + print( + f"Benchmarking RigidObjectCollection (Newton) with {config.num_instances} instances, " + f"{config.num_bodies} bodies..." + ) + + # Create runner and run benchmarks + runner = MethodBenchmarkRunner( + benchmark_name="newton_rigid_object_collection_benchmark", + config=config, + backend_type=args.backend, + output_path=args.output_dir, + use_recorders=True, + ) + + runner.run_benchmarks(BENCHMARKS, collection) + + print("\n" + "=" * 80) + print("Fill-Ratio Benchmarks (env_ids at 5%, 95%, 100% fill)") + print("=" * 80) + + runner.run_benchmarks(FILL_BENCHMARKS, collection) + runner.finalize() + + # Close the simulation app + simulation_app.close() + + +if __name__ == "__main__": + main() diff --git a/source/isaaclab_newton/benchmark/assets/benchmark_rigid_object_collection_data.py b/source/isaaclab_newton/benchmark/assets/benchmark_rigid_object_collection_data.py new file mode 100644 index 000000000000..e397b42d2ec4 --- /dev/null +++ b/source/isaaclab_newton/benchmark/assets/benchmark_rigid_object_collection_data.py @@ -0,0 +1,252 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Micro-benchmarking framework for RigidObjectCollectionData class (Newton backend). + +This module provides a benchmarking framework to measure the performance of all properties +in the Newton RigidObjectCollectionData class. Each property is run multiple times with +randomized mock data, and timing statistics (mean and standard deviation) are reported. + +Usage: + python benchmark_rigid_object_collection_data.py [--num_iterations N] [--warmup_steps W] + [--num_instances I] [--num_bodies B] + +Example: + python benchmark_rigid_object_collection_data.py --num_iterations 10000 --warmup_steps 10 +""" + +from __future__ import annotations + +"""Launch Isaac Sim Simulator first.""" + +import argparse + +from isaaclab.app import AppLauncher + +# add argparse arguments +parser = argparse.ArgumentParser( + description="Micro-benchmarking framework for RigidObjectCollectionData class (Newton backend).", + formatter_class=argparse.ArgumentDefaultsHelpFormatter, +) +parser.add_argument("--num_iterations", type=int, default=1000, help="Number of iterations") +parser.add_argument("--warmup_steps", type=int, default=10, help="Number of warmup steps") +parser.add_argument("--num_instances", type=int, default=4096, help="Number of instances") +parser.add_argument("--num_bodies", type=int, default=3, help="Number of bodies (object types)") +parser.add_argument("--output_dir", type=str, default=".", help="Output directory for results") +parser.add_argument("--backend", type=str, default="json", choices=["json", "osmo", "omniperf"], help="Metrics backend") + +# append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +# parse the arguments +args = parser.parse_args() + +# launch omniverse app +app_launcher = AppLauncher(headless=True, args=args) +simulation_app = app_launcher.app + +"""Rest everything follows.""" + +import warnings + +import numpy as np +import warp as wp +from isaaclab_newton.test.mock_interfaces import create_mock_newton_manager +from isaaclab_newton.test.mock_interfaces.views import MockNewtonCollectionView + +from isaaclab.test.benchmark import MethodBenchmarkRunner, MethodBenchmarkRunnerConfig + +# Suppress deprecation warnings during benchmarking +warnings.filterwarnings("ignore", category=DeprecationWarning) +warnings.filterwarnings("ignore", category=UserWarning) + + +# ============================================================================= +# Skip Lists +# ============================================================================= + +# List of deprecated properties - skip these +DEPRECATED_PROPERTIES = { + "default_body_state", + "body_state_w", + "body_link_state_w", + "body_com_state_w", +} + +# List of properties that raise NotImplementedError - skip these +NOT_IMPLEMENTED_PROPERTIES = set() + +# Removed default_* properties that raise RuntimeError +REMOVED_PROPERTIES = { + "default_inertia", + "default_mass", +} + +# Private/internal properties and methods to skip +INTERNAL_PROPERTIES = { + "_create_simulation_bindings", + "_create_buffers", + "update", + "is_primed", + "device", + "body_names", + "object_names", + "GRAVITY_VEC_W", + "GRAVITY_VEC_W_TORCH", + "FORWARD_VEC_B", + "FORWARD_VEC_B_TORCH", + "ALL_ENV_MASK", + "ENV_MASK", + "ALL_OBJECT_MASK", + "OBJECT_MASK", + "num_bodies", + "num_instances", +} + +# Dependency mapping for properties +PROPERTY_DEPENDENCIES = { + "body_link_pos_w": ["body_link_pose_w"], + "body_link_quat_w": ["body_link_pose_w"], + "body_link_lin_vel_w": ["body_link_vel_w"], + "body_link_ang_vel_w": ["body_link_vel_w"], + "body_com_pos_w": ["body_com_pose_w"], + "body_com_quat_w": ["body_com_pose_w"], + "body_com_lin_vel_w": ["body_com_vel_w"], + "body_com_ang_vel_w": ["body_com_vel_w"], + "body_com_lin_acc_w": ["body_com_acc_w"], + "body_com_ang_acc_w": ["body_com_acc_w"], + "body_com_quat_b": ["body_com_pose_b"], +} + + +# ============================================================================= +# Benchmark Functions +# ============================================================================= + + +def get_benchmarkable_properties(data) -> list[str]: + """Get list of properties that can be benchmarked.""" + all_properties = [] + + for name in dir(data): + if name.startswith("_"): + continue + if name in DEPRECATED_PROPERTIES: + continue + if name in NOT_IMPLEMENTED_PROPERTIES: + continue + if name in REMOVED_PROPERTIES: + continue + if name in INTERNAL_PROPERTIES: + continue + + try: + attr = getattr(type(data), name, None) + if isinstance(attr, property): + all_properties.append(name) + except Exception: + pass + + return sorted(all_properties) + + +def setup_mock_environment(config: MethodBenchmarkRunnerConfig) -> MockNewtonCollectionView: + """Set up the mock environment for benchmarking.""" + mock_view = MockNewtonCollectionView( + num_envs=config.num_instances, + num_bodies=config.num_bodies, + device=config.device, + ) + return mock_view + + +def main(): + """Main entry point for the benchmarking script.""" + config = MethodBenchmarkRunnerConfig( + num_iterations=args.num_iterations, + warmup_steps=args.warmup_steps, + num_instances=args.num_instances, + num_bodies=args.num_bodies, + num_joints=0, + device=args.device, + ) + + # Patch the NewtonManager for the collection_data module + with create_mock_newton_manager( + "isaaclab_newton.assets.rigid_object_collection.rigid_object_collection_data.SimulationManager", + gravity=(0.0, 0.0, -9.81), + ): + # Setup mock environment + mock_view = setup_mock_environment(config) + mock_view.set_random_mock_data() + + # Import RigidObjectCollectionData inside the patch context + from isaaclab_newton.assets.rigid_object_collection.rigid_object_collection_data import ( + RigidObjectCollectionData, + ) + + # Create RigidObjectCollectionData instance + data = RigidObjectCollectionData(mock_view, config.num_bodies, config.device) + + # Get list of properties to benchmark + properties = get_benchmarkable_properties(data) + + N, B = config.num_instances, config.num_bodies + dev = config.device + + # Generator that updates mock data and invalidates timestamp + def gen_mock_data(cfg: MethodBenchmarkRunnerConfig) -> dict: + # Update root transforms (shape: N, B, 7) + root_tf_np = np.random.randn(N, B, 7).astype(np.float32) + root_tf_np[..., 3:7] /= np.linalg.norm(root_tf_np[..., 3:7], axis=-1, keepdims=True) + mock_view._root_transforms = wp.array(root_tf_np, dtype=wp.transformf, device=dev) + + # Update root velocities (shape: N, B, 6) + root_vel_np = np.random.randn(N, B, 6).astype(np.float32) + mock_view._root_velocities = wp.array(root_vel_np, dtype=wp.spatial_vectorf, device=dev) + + # Update body properties (attributes have trailing link dim of 1: N, B, 1) + mock_view._attributes["body_com"] = wp.array( + np.random.randn(N, B, 1, 3).astype(np.float32), dtype=wp.vec3f, device=dev + ) + mock_view._attributes["body_mass"] = wp.array( + (np.random.rand(N, B, 1) * 10 + 0.1).astype(np.float32), dtype=wp.float32, device=dev + ) + mock_view._attributes["body_inertia"] = wp.array( + np.random.randn(N, B, 1, 9).astype(np.float32), dtype=wp.mat33f, device=dev + ) + + # Re-create simulation bindings to pick up the new mock data + data._create_simulation_bindings() + + # Invalidate timestamp to trigger recomputation + data._sim_timestamp += 1.0 + return {} + + # Create runner + runner = MethodBenchmarkRunner( + benchmark_name="newton_rigid_object_collection_data_benchmark", + config=config, + backend_type=args.backend, + output_path=args.output_dir, + use_recorders=True, + ) + + # Run property benchmarks + runner.run_property_benchmarks( + target_data=data, + properties=properties, + gen_mock_data=gen_mock_data, + dependencies=PROPERTY_DEPENDENCIES, + category="property", + ) + + runner.finalize() + + # Close the simulation app + simulation_app.close() + + +if __name__ == "__main__": + main() diff --git a/source/isaaclab_newton/benchmark/assets/benchmark_rigid_object_data.py b/source/isaaclab_newton/benchmark/assets/benchmark_rigid_object_data.py new file mode 100644 index 000000000000..b8889e1fcd2c --- /dev/null +++ b/source/isaaclab_newton/benchmark/assets/benchmark_rigid_object_data.py @@ -0,0 +1,285 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Micro-benchmarking framework for RigidObjectData class (Newton backend). + +This module provides a benchmarking framework to measure the performance of all properties +in the Newton RigidObjectData class. Each property is run multiple times with randomized mock data, +and timing statistics (mean and standard deviation) are reported. + +Usage: + python benchmark_rigid_object_data.py [--num_iterations N] [--warmup_steps W] + [--num_instances I] + +Example: + python benchmark_rigid_object_data.py --num_iterations 10000 --warmup_steps 10 +""" + +from __future__ import annotations + +"""Launch Isaac Sim Simulator first.""" + +import argparse + +from isaaclab.app import AppLauncher + +# add argparse arguments +parser = argparse.ArgumentParser( + description="Micro-benchmarking framework for RigidObjectData class (Newton backend).", + formatter_class=argparse.ArgumentDefaultsHelpFormatter, +) +parser.add_argument("--num_iterations", type=int, default=1000, help="Number of iterations") +parser.add_argument("--warmup_steps", type=int, default=10, help="Number of warmup steps") +parser.add_argument("--num_instances", type=int, default=4096, help="Number of instances") +parser.add_argument("--output_dir", type=str, default=".", help="Output directory for results") +parser.add_argument("--backend", type=str, default="json", choices=["json", "osmo", "omniperf"], help="Metrics backend") + +# append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +# parse the arguments +args = parser.parse_args() + +# launch omniverse app +app_launcher = AppLauncher(headless=True, args=args) +simulation_app = app_launcher.app + +"""Rest everything follows.""" + +import warnings + +import numpy as np +import warp as wp +from isaaclab_newton.test.mock_interfaces import MockNewtonArticulationView, create_mock_newton_manager + +from isaaclab.test.benchmark import MethodBenchmarkRunner, MethodBenchmarkRunnerConfig + +# Suppress deprecation warnings during benchmarking +warnings.filterwarnings("ignore", category=DeprecationWarning) +warnings.filterwarnings("ignore", category=UserWarning) + + +# ============================================================================= +# Skip Lists +# ============================================================================= + +# List of deprecated properties - skip these +DEPRECATED_PROPERTIES = { + "default_root_state", + "root_pose_w", + "root_pos_w", + "root_quat_w", + "root_vel_w", + "root_lin_vel_w", + "root_ang_vel_w", + "root_lin_vel_b", + "root_ang_vel_b", + "body_pose_w", + "body_pos_w", + "body_quat_w", + "body_vel_w", + "body_lin_vel_w", + "body_ang_vel_w", + "body_acc_w", + "body_lin_acc_w", + "body_ang_acc_w", + "com_pos_b", + "com_quat_b", + # Combined state properties marked as deprecated + "root_state_w", + "root_link_state_w", + "root_com_state_w", + "body_state_w", + "body_link_state_w", + "body_com_state_w", +} + +# List of properties that raise NotImplementedError - skip these +NOT_IMPLEMENTED_PROPERTIES = set() + +# Removed default_* properties that raise RuntimeError +REMOVED_PROPERTIES = { + "default_inertia", + "default_mass", +} + +# Private/internal properties and methods to skip +INTERNAL_PROPERTIES = { + "_create_simulation_bindings", + "_create_buffers", + "update", + "is_primed", + "device", + "body_names", + "GRAVITY_VEC_W", + "GRAVITY_VEC_W_TORCH", + "FORWARD_VEC_B", + "FORWARD_VEC_B_TORCH", + "ALL_ENV_MASK", + "ENV_MASK", +} + +# Dependency mapping for properties +PROPERTY_DEPENDENCIES = { + "root_link_lin_vel_w": ["root_link_vel_w"], + "root_link_ang_vel_w": ["root_link_vel_w"], + "root_link_lin_vel_b": ["root_link_vel_b"], + "root_link_ang_vel_b": ["root_link_vel_b"], + "root_com_pos_w": ["root_com_pose_w"], + "root_com_quat_w": ["root_com_pose_w"], + "root_com_lin_vel_b": ["root_com_vel_b"], + "root_com_ang_vel_b": ["root_com_vel_b"], + "root_com_lin_vel_w": ["root_com_vel_w"], + "root_com_ang_vel_w": ["root_com_vel_w"], + "root_link_pos_w": ["root_link_pose_w"], + "root_link_quat_w": ["root_link_pose_w"], + "body_link_lin_vel_w": ["body_link_vel_w"], + "body_link_ang_vel_w": ["body_link_vel_w"], + "body_link_pos_w": ["body_link_pose_w"], + "body_link_quat_w": ["body_link_pose_w"], + "body_com_pos_w": ["body_com_pose_w"], + "body_com_quat_w": ["body_com_pose_w"], + "body_com_lin_vel_w": ["body_com_vel_w"], + "body_com_ang_vel_w": ["body_com_vel_w"], + "body_com_lin_acc_w": ["body_com_acc_w"], + "body_com_ang_acc_w": ["body_com_acc_w"], + "body_com_quat_b": ["body_com_pose_b"], +} + + +# ============================================================================= +# Benchmark Functions +# ============================================================================= + + +def get_benchmarkable_properties(rigid_object_data) -> list[str]: + """Get list of properties that can be benchmarked.""" + all_properties = [] + + for name in dir(rigid_object_data): + if name.startswith("_"): + continue + if name in DEPRECATED_PROPERTIES: + continue + if name in NOT_IMPLEMENTED_PROPERTIES: + continue + if name in REMOVED_PROPERTIES: + continue + if name in INTERNAL_PROPERTIES: + continue + + try: + attr = getattr(type(rigid_object_data), name, None) + if isinstance(attr, property): + all_properties.append(name) + except Exception: + pass + + return sorted(all_properties) + + +def setup_mock_environment(config: MethodBenchmarkRunnerConfig) -> MockNewtonArticulationView: + """Set up the mock environment for benchmarking.""" + mock_view = MockNewtonArticulationView( + num_instances=config.num_instances, + num_bodies=config.num_bodies, + num_joints=0, + device=config.device, + ) + return mock_view + + +def main(): + """Main entry point for the benchmarking script.""" + config = MethodBenchmarkRunnerConfig( + num_iterations=args.num_iterations, + warmup_steps=args.warmup_steps, + num_instances=args.num_instances, + num_bodies=1, + num_joints=0, + device=args.device, + ) + + # Patch the NewtonManager for the rigid_object_data module + with create_mock_newton_manager( + "isaaclab_newton.assets.rigid_object.rigid_object_data.SimulationManager", + gravity=(0.0, 0.0, -9.81), + ): + # Setup mock environment + mock_view = setup_mock_environment(config) + mock_view.set_random_mock_data() + + # Import RigidObjectData inside the patch context + from isaaclab_newton.assets.rigid_object.rigid_object_data import RigidObjectData + + # Create RigidObjectData instance + rigid_object_data = RigidObjectData(mock_view, config.device) + + # Get list of properties to benchmark + properties = get_benchmarkable_properties(rigid_object_data) + + # Generator that updates mock data and invalidates timestamp + def gen_mock_data(cfg: MethodBenchmarkRunnerConfig) -> dict: + N, L = cfg.num_instances, cfg.num_bodies + dev = cfg.device + + # Update root transforms + root_tf_np = np.random.randn(N, 1, 7).astype(np.float32) + root_tf_np[..., 3:7] /= np.linalg.norm(root_tf_np[..., 3:7], axis=-1, keepdims=True) + mock_view.set_mock_root_transforms(wp.array(root_tf_np, dtype=wp.transformf, device=dev)) + + # Update root velocities + root_vel_np = np.random.randn(N, 1, 6).astype(np.float32) + mock_view.set_mock_root_velocities(wp.array(root_vel_np, dtype=wp.spatial_vectorf, device=dev)) + + # Update link transforms + link_tf_np = np.random.randn(N, 1, L, 7).astype(np.float32) + link_tf_np[..., 3:7] /= np.linalg.norm(link_tf_np[..., 3:7], axis=-1, keepdims=True) + mock_view.set_mock_link_transforms(wp.array(link_tf_np, dtype=wp.transformf, device=dev)) + + # Update link velocities + link_vel_np = np.random.randn(N, 1, L, 6).astype(np.float32) + mock_view.set_mock_link_velocities(wp.array(link_vel_np, dtype=wp.spatial_vectorf, device=dev)) + + # Update body properties + mock_view.set_mock_coms( + wp.array(np.random.randn(N, 1, L, 3).astype(np.float32), dtype=wp.vec3f, device=dev) + ) + mock_view.set_mock_inertias( + wp.array(np.random.randn(N, 1, L, 9).astype(np.float32), dtype=wp.mat33f, device=dev) + ) + mock_view.set_mock_masses( + wp.array((np.random.rand(N, 1, L) * 10 + 0.1).astype(np.float32), dtype=wp.float32, device=dev) + ) + + # Invalidate timestamp to trigger recomputation + rigid_object_data._sim_timestamp += 1.0 + return {} + + # Create runner + runner = MethodBenchmarkRunner( + benchmark_name="newton_rigid_object_data_benchmark", + config=config, + backend_type=args.backend, + output_path=args.output_dir, + use_recorders=True, + ) + + # Run property benchmarks + runner.run_property_benchmarks( + target_data=rigid_object_data, + properties=properties, + gen_mock_data=gen_mock_data, + dependencies=PROPERTY_DEPENDENCIES, + category="property", + ) + + runner.finalize() + + # Close the simulation app + simulation_app.close() + + +if __name__ == "__main__": + main() diff --git a/source/isaaclab_newton/changelog.d/.gitkeep b/source/isaaclab_newton/changelog.d/.gitkeep new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/source/isaaclab_newton/changelog.d/clone-plan-visualizer-cleanup.minor.rst b/source/isaaclab_newton/changelog.d/clone-plan-visualizer-cleanup.minor.rst new file mode 100644 index 000000000000..6fed4677a471 --- /dev/null +++ b/source/isaaclab_newton/changelog.d/clone-plan-visualizer-cleanup.minor.rst @@ -0,0 +1,9 @@ +Removed +^^^^^^^ + +* **Breaking:** Removed + ``isaaclab_newton.cloner.newton_replicate.create_newton_visualizer_prebuild_clone_fn``. + Callers that need a Newton model for visualization should call + :func:`~isaaclab_newton.cloner.newton_replicate.newton_visualizer_prebuild` + directly with the ``(sources, destinations, env_ids, mask, positions)`` bundle + derived from :meth:`~isaaclab.sim.SimulationContext.get_clone_plans`. diff --git a/source/isaaclab_newton/changelog.d/mtrepte-expand_viz_markers.skip b/source/isaaclab_newton/changelog.d/mtrepte-expand_viz_markers.skip new file mode 100644 index 000000000000..a23b7c7322b3 --- /dev/null +++ b/source/isaaclab_newton/changelog.d/mtrepte-expand_viz_markers.skip @@ -0,0 +1 @@ +Marker visualization changes are covered by the isaaclab fragment. diff --git a/source/isaaclab_newton/changelog.d/mym-newton-manager-abstraction.rst b/source/isaaclab_newton/changelog.d/mym-newton-manager-abstraction.rst new file mode 100644 index 000000000000..1ad8a9265830 --- /dev/null +++ b/source/isaaclab_newton/changelog.d/mym-newton-manager-abstraction.rst @@ -0,0 +1,14 @@ +Changed +^^^^^^^ + +* Changed :class:`~isaaclab_newton.physics.NewtonManager` to dispatch through + solver-specific manager subclasses while preserving the existing + ``NewtonCfg(solver_cfg=...)`` configuration pattern. + +Deprecated +^^^^^^^^^^ + +* Deprecated :attr:`~isaaclab_newton.physics.NewtonSolverCfg.solver_type` for + manager dispatch in favor of + :attr:`~isaaclab_newton.physics.NewtonSolverCfg.class_type`. Existing configs + remain valid, but new code should rely on ``class_type``. diff --git a/source/isaaclab_newton/changelog.d/pr-5458-merge-develop.rst b/source/isaaclab_newton/changelog.d/pr-5458-merge-develop.rst new file mode 100644 index 000000000000..30eb959531c2 --- /dev/null +++ b/source/isaaclab_newton/changelog.d/pr-5458-merge-develop.rst @@ -0,0 +1,13 @@ +Removed +^^^^^^^ + +* Removed the unimplemented ``ArticulationData.body_incoming_joint_wrench_b`` + accessor. Add :class:`~isaaclab.sensors.JointWrenchSensorCfg` to the scene + and read :attr:`~isaaclab.sensors.JointWrenchSensorData.force` and + :attr:`~isaaclab.sensors.JointWrenchSensorData.torque` instead. + +Fixed +^^^^^ + +* Fixed :class:`~isaaclab_newton.sensors.JointWrenchSensor` initialization for + USD assets whose articulation root is nested below the configured asset prim. diff --git a/source/isaaclab_newton/changelog.d/rschmitt_decouple_rednerer_camera.rst b/source/isaaclab_newton/changelog.d/rschmitt_decouple_rednerer_camera.rst new file mode 100644 index 000000000000..1c3efcb5c33e --- /dev/null +++ b/source/isaaclab_newton/changelog.d/rschmitt_decouple_rednerer_camera.rst @@ -0,0 +1,4 @@ +Changed +^^^^^^^^ + +* Modified the newton renderer to use the new patterns from renderer/camera decoupling. diff --git a/source/isaaclab_newton/config/extension.toml b/source/isaaclab_newton/config/extension.toml index 154968319a0c..0a8eed8000c2 100644 --- a/source/isaaclab_newton/config/extension.toml +++ b/source/isaaclab_newton/config/extension.toml @@ -1,7 +1,7 @@ [package] # Note: Semantic Versioning is used: https://semver.org/ -version = "0.5.9" +version = "0.5.26" # Description title = "Newton simulation interfaces for IsaacLab core package" diff --git a/source/isaaclab_newton/docs/CHANGELOG.rst b/source/isaaclab_newton/docs/CHANGELOG.rst index 59a80364d19f..d9626a890476 100644 --- a/source/isaaclab_newton/docs/CHANGELOG.rst +++ b/source/isaaclab_newton/docs/CHANGELOG.rst @@ -1,8 +1,256 @@ Changelog --------- -0.5.9 (2026-03-16) -~~~~~~~~~~~~~~~~~~ +0.5.26 (2026-04-30) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :class:`~isaaclab_newton.sensors.JointWrenchSensor`. + + +0.5.25 (2026-04-28) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :class:`~isaaclab_newton.physics.KaminoSolverCfg` to support Newton's Kamino + solver backend, a Proximal-ADMM based solver for constrained rigid multi-body dynamics. +* Added fused :meth:`~isaaclab_newton.assets.Articulation.write_joint_state_to_sim_index` + and :meth:`~isaaclab_newton.assets.Articulation.write_joint_state_to_sim_mask` that + write joint position and velocity in a single kernel launch instead of two. + +Changed +^^^^^^^ + +* Removed dead state-buffer output parameters from 8 root pose/velocity warp kernels + in :mod:`~isaaclab_newton.assets.kernels`, reducing kernel argument marshalling + overhead. + +Fixed +^^^^^ + +* Replaced boolean ``_fk_dirty`` and ``_kamino_needs_fk`` flags with per-world + reset masks (``_world_reset_mask`` and ``_fk_reset_mask``). Asset write methods + now call :meth:`~isaaclab_newton.physics.NewtonManager.invalidate_fk` with + ``env_mask``/``env_ids`` and ``articulation_ids``, so ``eval_fk`` and + ``SolverKamino.reset()`` only operate on dirtied environments. Rigid object + and rigid object collection write methods now also trigger FK invalidation. +* Fixed CUDA error 700 (illegal memory access) when calling ``SolverKamino.reset()`` + after CUDA graph capture. ``StateKamino.from_newton()`` lazily allocates + ``body_f_total``, ``joint_q_prev``, and ``joint_lambdas`` via ``wp.clone``/``wp.zeros`` + during the first ``step()`` inside graph capture. These memory-pool addresses become + stale without a warm-up ``wp.capture_launch`` replay to pin them before any eager + ``solver.reset()`` call. + + +0.5.24 (2026-04-27) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :class:`~isaaclab_newton.physics.NewtonShapeCfg` exposing + per-shape collision defaults (``margin``, ``gap``) via + :attr:`~isaaclab_newton.physics.NewtonCfg.default_shape_cfg`. + :meth:`~isaaclab_newton.physics.NewtonManager.create_builder` now + forwards the wrapper onto Newton's upstream + ``ModelBuilder.default_shape_cfg`` via + :func:`~isaaclab.utils.checked_apply`. The previous code only set + ``gap`` and left ``margin`` at Newton's upstream default of ``0.0``, + causing all non-Anymal-D robots to fail to learn rough-terrain + locomotion on triangle-mesh terrain. ``RoughPhysicsCfg`` opts in to + ``margin=0.01``. + + +0.5.23 (2026-04-24) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Updated :class:`~isaaclab_newton.sim.views.NewtonSiteFrameView` to match the + new :class:`~isaaclab.sim.views.BaseFrameView` ProxyArray return contract. + See the ``isaaclab`` 4.6.15 changelog for migration guidance. + + +0.5.22 (2026-04-23) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Properties on the following data classes now return + :class:`~isaaclab.utils.warp.ProxyArray` instead of raw ``wp.array``: + :class:`~isaaclab_newton.assets.articulation.ArticulationData`, + :class:`~isaaclab_newton.assets.rigid_object.RigidObjectData`, + :class:`~isaaclab_newton.assets.rigid_object_collection.RigidObjectCollectionData`, + :class:`~isaaclab_newton.sensors.contact_sensor.ContactSensorData`, + :class:`~isaaclab_newton.sensors.frame_transformer.FrameTransformerData`, + :class:`~isaaclab_newton.sensors.imu.ImuData`, and + :class:`~isaaclab_newton.sensors.pva.PvaData`. + Use ``.torch`` for a cached zero-copy ``torch.Tensor`` view, or ``.warp`` for + the underlying ``wp.array``. Implicit torch operations (arithmetic, + ``torch.*`` functions) work during the deprecation period but emit a warning. + + +0.5.21 (2026-04-23) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed flakiness in ``test_body_root_state_properties`` by bounding the random spin velocity so + numerical drift stays within the position tolerance over the simulated trajectory. + + +0.5.20 (2026-04-22) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :class:`~isaaclab_newton.sim.views.XformPrimView` providing the Newton + backend implementation for xform prim views. + +Changed +^^^^^^^ + +* Renamed :class:`~isaaclab_newton.sim.views.NewtonSiteXformPrimView` to + :class:`~isaaclab_newton.sim.views.NewtonSiteFrameView`. Old name is kept as a deprecated alias. + + +0.5.19 (2026-04-22) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Updated ``write_data_to_sim`` in :class:`~isaaclab_newton.assets.Articulation`, + :class:`~isaaclab_newton.assets.RigidObject`, and :class:`~isaaclab_newton.assets.RigidObjectCollection` + to use the dual-buffer :class:`~isaaclab.utils.wrench_composer.WrenchComposer`. Composed wrenches are + applied after body-frame composition. +* Updated the PhysX Tensor API docstring link in :class:`~isaaclab_newton.assets.ArticulationData` + from ``omni.physics.tensors.impl.api`` to ``omni.physics.tensors.api`` to track the upstream + Isaac Sim module relocation (the ``impl`` submodule was removed). + + +0.5.18 (2026-04-21) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Upgraded Newton from ``2684d75`` to ``a27277e``. Includes collision improvements, contact quality fixes, + hydroelastic contact optimization, and memory usage fixes in CollisionPipeline. For details see + ``Newton changelog ``. +* Pinned ``mujoco`` and ``mujoco-warp`` to ``3.6.0`` to align with the Newton library. + + +0.5.17 (2026-04-20) +~~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed Newton visualization colors drifting from the USD stage by calling + :func:`~isaaclab.sim.utils.newton_model_utils.replace_newton_shape_colors` + after the model is finalized in :class:`~isaaclab_newton.physics.NewtonManager`. + +Changed +^^^^^^^ + +* Changed Newton Warp tiled camera outputs to clear with a light linear gray + (0xFFEEEEEE, 93% gray, fully opaque) background via ``SensorTiledCamera.ClearData`` + in :class:`~isaaclab_newton.renderers.NewtonWarpRenderer`. + +0.5.16 (2026-04-17) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed incorrect attribute name ``contact_margin`` on Newton + ``ShapeConfig`` in + :meth:`~isaaclab_newton.physics.NewtonManager.create_builder`. The + field was renamed to ``gap`` in Newton PR #1732. The typo created a + dead attribute so the intended 1 cm default shape gap was never applied. + + +0.5.15 (2026-04-16) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :class:`~isaaclab_newton.sensors.pva.Pva` sensor wrapping Newton's + body state (``body_q``, ``body_qd``, ``body_qdd``) to provide world-frame + pose and body-frame velocities/accelerations. + + +0.5.14 (2026-04-14) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :class:`~isaaclab_newton.sensors.Imu` sensor wrapping Newton's + ``SensorIMU``, providing angular velocity and linear acceleration in the + sensor's body frame. + + +0.5.13 (2026-04-13) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :class:`~isaaclab_newton.physics.NewtonCollisionPipelineCfg` to expose Newton + collision pipeline parameters via :attr:`~isaaclab_newton.physics.NewtonCfg.collision_cfg`. +* Added :attr:`~isaaclab_newton.physics.MJWarpSolverCfg.tolerance` for solver convergence control. + +Fixed +^^^^^ + +* Fixed truthiness check on hydroelastic config dict in collision pipeline + initialization. An explicit ``is not None`` check is now used so that + :class:`~isaaclab_newton.physics.newton_collision_cfg.HydroelasticSDFCfg` + with all-default values is no longer silently skipped. + + +0.5.12 (2026-04-13) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added ``set_friction_index/mask`` and ``set_restitution_index/mask`` methods to + Newton assets for native material property randomization. + + +0.5.11 (2026-04-13) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :class:`~isaaclab_newton.sensors.frame_transformer.FrameTransformer` sensor + wrapping Newton's ``SensorFrameTransform``. Supports per-env source/target site + registration, wildcard body matching, and zero-copy transform views. + + +0.5.10 (2026-04-05) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed NaN after env reset caused by stale ``body_q`` in the collision + pipeline. Added :meth:`~isaaclab_newton.physics.NewtonManager.invalidate_fk` + so articulation write methods trigger ``eval_fk`` before the next + ``collide()``. Fixed ^^^^^ diff --git a/source/isaaclab_newton/isaaclab_newton/assets/articulation/articulation.py b/source/isaaclab_newton/isaaclab_newton/assets/articulation/articulation.py index 689f81b0c573..c3c6eca044f7 100644 --- a/source/isaaclab_newton/isaaclab_newton/assets/articulation/articulation.py +++ b/source/isaaclab_newton/isaaclab_newton/assets/articulation/articulation.py @@ -256,40 +256,23 @@ def write_data_to_sim(self): # write external wrench if self._instantaneous_wrench_composer.active or self._permanent_wrench_composer.active: if self._instantaneous_wrench_composer.active: - # Compose instantaneous wrench with permanent wrench - self._instantaneous_wrench_composer.add_forces_and_torques_index( - forces=self._permanent_wrench_composer.composed_force, - torques=self._permanent_wrench_composer.composed_torque, - body_ids=self._ALL_BODY_INDICES, - env_ids=self._ALL_INDICES, - ) - # Apply both instantaneous and permanent wrench to the simulation - wp.launch( - shared_kernels.update_wrench_array_with_force_and_torque, - dim=(self.num_instances, self.num_bodies), - device=self.device, - inputs=[ - self._instantaneous_wrench_composer.composed_force, - self._instantaneous_wrench_composer.composed_torque, - self._data._sim_bind_body_external_wrench, - self._ALL_ENV_MASK, - self._ALL_BODY_MASK, - ], - ) + composer = self._instantaneous_wrench_composer + composer.add_raw_buffers_from(self._permanent_wrench_composer) else: - # Apply permanent wrench to the simulation - wp.launch( - shared_kernels.update_wrench_array_with_force_and_torque, - dim=(self.num_instances, self.num_bodies), - device=self.device, - inputs=[ - self._permanent_wrench_composer.composed_force, - self._permanent_wrench_composer.composed_torque, - self._data._sim_bind_body_external_wrench, - self._ALL_ENV_MASK, - self._ALL_BODY_MASK, - ], - ) + composer = self._permanent_wrench_composer + composer.compose_to_body_frame() + wp.launch( + shared_kernels.update_wrench_array_with_force_and_torque, + dim=(self.num_instances, self.num_bodies), + device=self.device, + inputs=[ + composer.out_force_b, + composer.out_torque_b, + self._data._sim_bind_body_external_wrench, + self._ALL_ENV_MASK, + self._ALL_BODY_MASK, + ], + ) self._instantaneous_wrench_composer.reset() # apply actuator models @@ -469,6 +452,9 @@ def write_root_link_pose_to_sim_index( root_pose: Root poses in simulation frame. Shape is (len(env_ids), 7) or (len(env_ids),) with dtype wp.transformf. env_ids: Environment indices. If None, then all indices are used. + + Note: + Triggers per-environment FK recomputation and solver reset (Kamino) for the affected environments. """ # resolve all indices env_ids = self._resolve_env_ids(env_ids) @@ -483,8 +469,6 @@ def write_root_link_pose_to_sim_index( ], outputs=[ self.data.root_link_pose_w, - None, # self.data._root_link_state_w.data, - None, # self.data._root_state_w.data, ], device=self.device, ) @@ -495,6 +479,7 @@ def write_root_link_pose_to_sim_index( if self.data._root_state_w is not None: self.data._root_state_w.timestamp = -1.0 self.data._fk_timestamp = -1.0 # Forces a kinematic update to get the latest body link poses. + SimulationManager.invalidate_fk(env_ids=env_ids, articulation_ids=self._root_view.articulation_ids) if self.data._body_com_pose_w is not None: self.data._body_com_pose_w.timestamp = -1.0 if self.data._body_state_w is not None: @@ -525,6 +510,9 @@ def write_root_link_pose_to_sim_mask( root_pose: Root poses in simulation frame. Shape is (num_instances, 7) or (num_instances,) with dtype wp.transformf. env_mask: Environment mask. If None, then all the instances are updated. Shape is (num_instances,). + + Note: + Triggers per-environment FK recomputation and solver reset (Kamino) for the affected environments. """ env_mask = self._resolve_mask(env_mask, self._ALL_ENV_MASK) self.assert_shape_and_dtype_mask(root_pose, (env_mask,), wp.transformf, "root_pose") @@ -538,8 +526,6 @@ def write_root_link_pose_to_sim_mask( ], outputs=[ self.data.root_link_pose_w, - None, # self.data._root_link_state_w.data, - None, # self.data._root_state_w.data, ], device=self.device, ) @@ -550,6 +536,7 @@ def write_root_link_pose_to_sim_mask( if self.data._root_state_w is not None: self.data._root_state_w.timestamp = -1.0 self.data._fk_timestamp = -1.0 # Forces a kinematic update to get the latest body link poses. + SimulationManager.invalidate_fk(env_mask=env_mask, articulation_ids=self._root_view.articulation_ids) if self.data._body_com_pose_w is not None: self.data._body_com_pose_w.timestamp = -1.0 if self.data._body_state_w is not None: @@ -581,6 +568,9 @@ def write_root_com_pose_to_sim_index( root_pose: Root center of mass poses in simulation frame. Shape is (len(env_ids), 7) or (len(env_ids),) with dtype wp.transformf. env_ids: Environment indices. If None, then all indices are used. + + Note: + Triggers per-environment FK recomputation and solver reset (Kamino) for the affected environments. """ # resolve all indices env_ids = self._resolve_env_ids(env_ids) @@ -599,9 +589,6 @@ def write_root_com_pose_to_sim_index( outputs=[ self.data.root_com_pose_w, self.data.root_link_pose_w, - None, # self.data._root_com_state_w.data, - None, # self.data._root_link_state_w.data, - None, # self.data._root_state_w.data, ], device=self.device, ) @@ -614,6 +601,7 @@ def write_root_com_pose_to_sim_index( if self.data._root_state_w is not None: self.data._root_state_w.timestamp = -1.0 self.data._fk_timestamp = -1.0 # Forces a kinematic update to get the latest body link poses. + SimulationManager.invalidate_fk(env_ids=env_ids, articulation_ids=self._root_view.articulation_ids) if self.data._body_com_pose_w is not None: self.data._body_com_pose_w.timestamp = -1.0 if self.data._body_state_w is not None: @@ -645,6 +633,9 @@ def write_root_com_pose_to_sim_mask( root_pose: Root center of mass poses in simulation frame. Shape is (num_instances, 7) or (num_instances,) with dtype wp.transformf. env_mask: Environment mask. If None, then all the instances are updated. Shape is (num_instances,). + + Note: + Triggers per-environment FK recomputation and solver reset (Kamino) for the affected environments. """ env_mask = self._resolve_mask(env_mask, self._ALL_ENV_MASK) self.assert_shape_and_dtype_mask(root_pose, (env_mask,), wp.transformf, "root_pose") @@ -659,9 +650,6 @@ def write_root_com_pose_to_sim_mask( outputs=[ self.data.root_com_pose_w, self.data.root_link_pose_w, - None, # self.data._root_com_state_w.data, - None, # self.data._root_link_state_w.data, - None, # self.data._root_state_w.data, ], device=self.device, ) @@ -674,6 +662,7 @@ def write_root_com_pose_to_sim_mask( if self.data._root_state_w is not None: self.data._root_state_w.timestamp = -1.0 self.data._fk_timestamp = -1.0 # Forces a kinematic update to get the latest body link poses. + SimulationManager.invalidate_fk(env_mask=env_mask, articulation_ids=self._root_view.articulation_ids) if self.data._body_com_pose_w is not None: self.data._body_com_pose_w.timestamp = -1.0 if self.data._body_state_w is not None: @@ -774,8 +763,6 @@ def write_root_com_velocity_to_sim_index( outputs=[ self.data.root_com_vel_w, self.data.body_com_acc_w, - None, # self.data._root_state_w.data, - None, # self.data._root_com_state_w.data, ], device=self.device, ) @@ -822,8 +809,6 @@ def write_root_com_velocity_to_sim_mask( outputs=[ self.data.root_com_vel_w, self.data.body_com_acc_w, - None, # self.data._root_state_w.data, - None, # self.data._root_com_state_w.data, ], device=self.device, ) @@ -876,9 +861,6 @@ def write_root_link_velocity_to_sim_index( self.data.root_link_vel_w, self.data.root_com_vel_w, self.data.body_com_acc_w, - None, # self.data._root_link_state_w.data, - None, # self.data._root_state_w.data, - None, # self.data._root_com_state_w.data, ], device=self.device, ) @@ -930,9 +912,6 @@ def write_root_link_velocity_to_sim_mask( self.data.root_link_vel_w, self.data.root_com_vel_w, self.data.body_com_acc_w, - None, # self.data._root_link_state_w.data, - None, # self.data._root_state_w.data, - None, # self.data._root_com_state_w.data, ], device=self.device, ) @@ -944,6 +923,66 @@ def write_root_link_velocity_to_sim_mask( if self.data._root_com_state_w is not None: self.data._root_com_state_w.timestamp = -1.0 + def write_joint_state_to_sim_index( + self, + *, + position: torch.Tensor | wp.array, + velocity: torch.Tensor | wp.array, + joint_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ): + """Write joint positions and velocities in a single fused kernel launch. + + .. note:: + This method expects partial data. + + .. tip:: + Both the index and mask methods have dedicated optimized implementations. Performance is similar for both. + However, to allow graphed pipelines, the mask method must be used. + + Args: + position: Joint positions. Shape is (len(env_ids), len(joint_ids)). + velocity: Joint velocities. Shape is (len(env_ids), len(joint_ids)). + joint_ids: Joint indices. If None, then all joints are used. + env_ids: Environment indices. If None, then all indices are used. + """ + env_ids = self._resolve_env_ids(env_ids) + joint_ids = self._resolve_joint_ids(joint_ids) + self.assert_shape_and_dtype(position, (env_ids.shape[0], joint_ids.shape[0]), wp.float32, "position") + self.assert_shape_and_dtype(velocity, (env_ids.shape[0], joint_ids.shape[0]), wp.float32, "velocity") + wp.launch( + articulation_kernels.write_joint_state_data_index, + dim=(env_ids.shape[0], joint_ids.shape[0]), + inputs=[ + position, + velocity, + env_ids, + joint_ids, + ], + outputs=[ + self.data.joint_pos, + self.data.joint_vel, + self.data._previous_joint_vel, + self.data.joint_acc, + ], + device=self.device, + ) + # Invalidate FK timestamp so body poses are recomputed on next access. + self.data._fk_timestamp = -1.0 + SimulationManager.invalidate_fk() + if self.data._body_link_vel_w is not None: + self.data._body_link_vel_w.timestamp = -1.0 + if self.data._body_com_pose_b is not None: + self.data._body_com_pose_b.timestamp = -1.0 + if self.data._body_com_pose_w is not None: + self.data._body_com_pose_w.timestamp = -1.0 + if self.data._body_state_w is not None: + self.data._body_state_w.timestamp = -1.0 + if self.data._body_link_state_w is not None: + self.data._body_link_state_w.timestamp = -1.0 + if self.data._body_com_state_w is not None: + self.data._body_com_state_w.timestamp = -1.0 + def write_joint_state_to_sim_mask( self, *, @@ -967,9 +1006,42 @@ def write_joint_state_to_sim_mask( joint_mask: Joint mask. If None, then all joints are used. Shape is (num_joints,). env_mask: Environment mask. If None, then all the instances are updated. Shape is (num_instances,). """ - # set into simulation - self.write_joint_position_to_sim_mask(position, env_mask=env_mask, joint_mask=joint_mask) - self.write_joint_velocity_to_sim_mask(velocity, env_mask=env_mask, joint_mask=joint_mask) + env_mask = self._resolve_mask(env_mask, self._ALL_ENV_MASK) + joint_mask = self._resolve_mask(joint_mask, self._ALL_JOINT_MASK) + self.assert_shape_and_dtype_mask(position, (env_mask, joint_mask), wp.float32, "position") + self.assert_shape_and_dtype_mask(velocity, (env_mask, joint_mask), wp.float32, "velocity") + wp.launch( + articulation_kernels.write_joint_state_data_mask, + dim=(env_mask.shape[0], joint_mask.shape[0]), + inputs=[ + position, + velocity, + env_mask, + joint_mask, + ], + outputs=[ + self.data.joint_pos, + self.data.joint_vel, + self.data._previous_joint_vel, + self.data.joint_acc, + ], + device=self.device, + ) + # Invalidate FK timestamp so body poses are recomputed on next access. + self.data._fk_timestamp = -1.0 + SimulationManager.invalidate_fk() + if self.data._body_link_vel_w is not None: + self.data._body_link_vel_w.timestamp = -1.0 + if self.data._body_com_pose_b is not None: + self.data._body_com_pose_b.timestamp = -1.0 + if self.data._body_com_pose_w is not None: + self.data._body_com_pose_w.timestamp = -1.0 + if self.data._body_state_w is not None: + self.data._body_state_w.timestamp = -1.0 + if self.data._body_link_state_w is not None: + self.data._body_link_state_w.timestamp = -1.0 + if self.data._body_com_state_w is not None: + self.data._body_com_state_w.timestamp = -1.0 def write_joint_position_to_sim_index( self, @@ -991,6 +1063,9 @@ def write_joint_position_to_sim_index( position: Joint positions. Shape is (len(env_ids), len(joint_ids)). joint_ids: Joint indices. If None, then all joints are used. env_ids: Environment indices. If None, then all indices are used. + + Note: + Triggers per-environment FK recomputation and solver reset (Kamino) for the affected environments. """ # resolve all indices env_ids = self._resolve_env_ids(env_ids) @@ -1012,6 +1087,7 @@ def write_joint_position_to_sim_index( ) # Invalidate FK timestamp so body poses are recomputed on next access. self.data._fk_timestamp = -1.0 + SimulationManager.invalidate_fk(env_ids=env_ids, articulation_ids=self._root_view.articulation_ids) # Need to invalidate the buffer to trigger the update with the new root pose. # Only invalidate if the buffer has been accessed (not None). if self.data._body_link_vel_w is not None: @@ -1047,6 +1123,9 @@ def write_joint_position_to_sim_mask( position: Joint positions. Shape is (num_instances, num_joints). joint_mask: Joint mask. If None, then all joints are used. Shape is (num_joints,). env_mask: Environment mask. If None, then all the instances are updated. Shape is (num_instances,). + + Note: + Triggers per-environment FK recomputation and solver reset (Kamino) for the affected environments. """ env_mask = self._resolve_mask(env_mask, self._ALL_ENV_MASK) joint_mask = self._resolve_mask(joint_mask, self._ALL_JOINT_MASK) @@ -1066,6 +1145,7 @@ def write_joint_position_to_sim_mask( ) # Invalidate FK timestamp so body poses are recomputed on next access. self.data._fk_timestamp = -1.0 + SimulationManager.invalidate_fk(env_mask=env_mask, articulation_ids=self._root_view.articulation_ids) # Need to invalidate the buffer to trigger the update with the new root pose. # Only invalidate if the buffer has been accessed (not None). if self.data._body_link_vel_w is not None: @@ -3245,9 +3325,9 @@ def _create_buffers(self): # tendon names are set in _process_tendons function # -- joint commands (sent to the simulation after actuator processing) - self._joint_pos_target_sim = wp.zeros_like(self.data.joint_pos_target, device=self.device) - self._joint_vel_target_sim = wp.zeros_like(self.data.joint_pos_target, device=self.device) - self._joint_effort_target_sim = wp.zeros_like(self.data.joint_pos_target, device=self.device) + self._joint_pos_target_sim = wp.zeros_like(self.data.joint_pos_target.warp, device=self.device) + self._joint_vel_target_sim = wp.zeros_like(self.data.joint_pos_target.warp, device=self.device) + self._joint_effort_target_sim = wp.zeros_like(self.data.joint_pos_target.warp, device=self.device) # soft joint position limits (recommended not to be too close to limits). wp.launch( @@ -3351,12 +3431,12 @@ def _process_actuators_cfg(self): joint_ids=joint_ids, num_envs=self.num_instances, device=self.device, - stiffness=wp.to_torch(self._data.joint_stiffness)[:, joint_ids], - damping=wp.to_torch(self._data.joint_damping)[:, joint_ids], - armature=wp.to_torch(self._data.joint_armature)[:, joint_ids], - friction=wp.to_torch(self._data.joint_friction_coeff)[:, joint_ids], - effort_limit=wp.to_torch(self._data.joint_effort_limits)[:, joint_ids].clone(), - velocity_limit=wp.to_torch(self._data.joint_vel_limits)[:, joint_ids], + stiffness=self._data.joint_stiffness.torch[:, joint_ids], + damping=self._data.joint_damping.torch[:, joint_ids], + armature=self._data.joint_armature.torch[:, joint_ids], + friction=self._data.joint_friction_coeff.torch[:, joint_ids], + effort_limit=self._data.joint_effort_limits.torch[:, joint_ids].clone(), + velocity_limit=self._data.joint_vel_limits.torch[:, joint_ids], ) # store actuator group self.actuators[actuator_name] = actuator @@ -3483,16 +3563,16 @@ def _apply_actuator_model(self): # prepare input for actuator model based on cached data # TODO : A tensor dict would be nice to do the indexing of all tensors together control_action = ArticulationActions( - joint_positions=wp.to_torch(self._data.joint_pos_target)[:, actuator.joint_indices], - joint_velocities=wp.to_torch(self._data.joint_vel_target)[:, actuator.joint_indices], - joint_efforts=wp.to_torch(self._data.joint_effort_target)[:, actuator.joint_indices], + joint_positions=self._data.joint_pos_target.torch[:, actuator.joint_indices], + joint_velocities=self._data.joint_vel_target.torch[:, actuator.joint_indices], + joint_efforts=self._data.joint_effort_target.torch[:, actuator.joint_indices], joint_indices=actuator.joint_indices, ) # compute joint command from the actuator model control_action = actuator.compute( control_action, - joint_pos=wp.to_torch(self._data.joint_pos)[:, actuator.joint_indices], - joint_vel=wp.to_torch(self._data.joint_vel)[:, actuator.joint_indices], + joint_pos=self._data.joint_pos.torch[:, actuator.joint_indices], + joint_vel=self._data.joint_vel.torch[:, actuator.joint_indices], ) # update targets (these are set into the simulation) joint_indices = actuator.joint_indices @@ -3555,9 +3635,9 @@ def _validate_cfg(self): return # check that the default values are within the limits - joint_pos_limits_lower = wp.to_torch(self._data.joint_pos_limits_lower)[0] - joint_pos_limits_upper = wp.to_torch(self._data.joint_pos_limits_upper)[0] - default_joint_pos = wp.to_torch(self._data.default_joint_pos)[0] + joint_pos_limits_lower = self._data.joint_pos_limits_lower.torch[0] + joint_pos_limits_upper = self._data.joint_pos_limits_upper.torch[0] + default_joint_pos = self._data.default_joint_pos.torch[0] out_of_range = default_joint_pos < joint_pos_limits_lower out_of_range |= default_joint_pos > joint_pos_limits_upper violated_indices = torch.nonzero(out_of_range, as_tuple=False).squeeze(-1) @@ -3574,8 +3654,8 @@ def _validate_cfg(self): raise ValueError(msg) # check that the default joint velocities are within the limits - joint_max_vel = wp.to_torch(self._data.joint_vel_limits)[0] - default_joint_vel = wp.to_torch(self._data.default_joint_vel)[0] + joint_max_vel = self._data.joint_vel_limits.torch[0] + default_joint_vel = self._data.default_joint_vel.torch[0] out_of_range = torch.abs(default_joint_vel) > joint_max_vel violated_indices = torch.nonzero(out_of_range, as_tuple=False).squeeze(-1) if len(violated_indices) > 0: @@ -3615,19 +3695,19 @@ def format_limits(_, v: tuple[float, float]) -> str: # -- gains # Use data properties which have already been cloned and stored during initialization # This avoids issues with indexedarray or empty arrays from root_view - stiffnesses = wp.to_torch(self.data.joint_stiffness)[0].cpu().tolist() - dampings = wp.to_torch(self.data.joint_damping)[0].cpu().tolist() + stiffnesses = self.data.joint_stiffness.torch[0].cpu().tolist() + dampings = self.data.joint_damping.torch[0].cpu().tolist() # -- properties - armatures = wp.to_torch(self.data.joint_armature)[0].cpu().tolist() + armatures = self.data.joint_armature.torch[0].cpu().tolist() # For friction, use the individual components from data - friction_coeff = wp.to_torch(self.data.joint_friction_coeff)[0].cpu() + friction_coeff = self.data.joint_friction_coeff.torch[0].cpu() static_frictions = friction_coeff.tolist() # -- limits # joint_pos_limits is vec2f array, convert to torch and extract [lower, upper] pairs - position_limits_torch = wp.to_torch(self.data.joint_pos_limits)[0].cpu() # shape: (num_joints, 2) + position_limits_torch = self.data.joint_pos_limits.torch[0].cpu() # shape: (num_joints, 2) position_limits = [tuple(pos_limit.tolist()) for pos_limit in position_limits_torch] - velocity_limits = wp.to_torch(self.data.joint_vel_limits)[0].cpu().tolist() - effort_limits = wp.to_torch(self.data.joint_effort_limits)[0].cpu().tolist() + velocity_limits = self.data.joint_vel_limits.torch[0].cpu().tolist() + effort_limits = self.data.joint_effort_limits.torch[0].cpu().tolist() # create table for term information joint_table = PrettyTable() joint_table.title = f"Simulation Joint Information (Prim path: {self.cfg.prim_path})" @@ -3672,9 +3752,6 @@ def format_limits(_, v: tuple[float, float]) -> str: def _resolve_env_ids(self, env_ids: Sequence[int] | torch.Tensor | wp.array | None) -> wp.array: """Resolve environment indices to a warp array. - .. note:: - We need to convert torch tensors to warp arrays since the TensorAPI views only support warp arrays. - Args: env_ids: Environment indices. If None, then all indices are used. @@ -3684,7 +3761,6 @@ def _resolve_env_ids(self, env_ids: Sequence[int] | torch.Tensor | wp.array | No if (env_ids is None) or (env_ids == slice(None)): return self._ALL_INDICES if isinstance(env_ids, torch.Tensor): - # Convert int64 to int32 if needed, as warp expects int32 if env_ids.dtype == torch.int64: env_ids = env_ids.to(torch.int32) return wp.from_torch(env_ids, dtype=wp.int32) @@ -3695,9 +3771,6 @@ def _resolve_env_ids(self, env_ids: Sequence[int] | torch.Tensor | wp.array | No def _resolve_joint_ids(self, joint_ids: Sequence[int] | torch.Tensor | wp.array | None) -> wp.array | torch.Tensor: """Resolve joint indices to a warp array or tensor. - .. note:: - We do not need to convert torch tensors to warp arrays since they never get passed to the TensorAPI views. - Args: joint_ids: Joint indices. If None, then all indices are used. @@ -3708,6 +3781,10 @@ def _resolve_joint_ids(self, joint_ids: Sequence[int] | torch.Tensor | wp.array return wp.array(joint_ids, dtype=wp.int32, device=self.device) if (joint_ids is None) or (joint_ids == slice(None)): return self._ALL_JOINT_INDICES + if isinstance(joint_ids, torch.Tensor): + if joint_ids.dtype == torch.int64: + joint_ids = joint_ids.to(torch.int32) + return wp.from_torch(joint_ids, dtype=wp.int32) return joint_ids def _resolve_body_ids(self, body_ids: Sequence[int] | torch.Tensor | wp.array | None) -> wp.array | torch.Tensor: @@ -3723,6 +3800,10 @@ def _resolve_body_ids(self, body_ids: Sequence[int] | torch.Tensor | wp.array | return wp.array(body_ids, dtype=wp.int32, device=self.device) if (body_ids is None) or (body_ids == slice(None)): return self._ALL_BODY_INDICES + if isinstance(body_ids, torch.Tensor): + if body_ids.dtype == torch.int64: + body_ids = body_ids.to(torch.int32) + return wp.from_torch(body_ids, dtype=wp.int32) return body_ids def _resolve_fixed_tendon_ids( @@ -3861,14 +3942,11 @@ def write_joint_state_to_sim( joint_ids: Sequence[int] | torch.Tensor | wp.array | None = None, env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, ): - """Deprecated, same as :meth:`write_joint_position_to_sim_index` and - :meth:`write_joint_velocity_to_sim_index`.""" + """Deprecated, same as :meth:`write_joint_state_to_sim_index`.""" warnings.warn( "The function 'write_joint_state_to_sim' will be deprecated in a future release. Please" - " use 'write_joint_position_to_sim_index' and 'write_joint_velocity_to_sim_index' instead.", + " use 'write_joint_state_to_sim_index' instead.", DeprecationWarning, stacklevel=2, ) - # set into simulation - self.write_joint_position_to_sim_index(position=position, joint_ids=joint_ids, env_ids=env_ids) - self.write_joint_velocity_to_sim_index(velocity=velocity, joint_ids=joint_ids, env_ids=env_ids) + self.write_joint_state_to_sim_index(position=position, velocity=velocity, joint_ids=joint_ids, env_ids=env_ids) diff --git a/source/isaaclab_newton/isaaclab_newton/assets/articulation/articulation_data.py b/source/isaaclab_newton/isaaclab_newton/assets/articulation/articulation_data.py index 4dc9507dbe59..a22ba73e1725 100644 --- a/source/isaaclab_newton/isaaclab_newton/assets/articulation/articulation_data.py +++ b/source/isaaclab_newton/isaaclab_newton/assets/articulation/articulation_data.py @@ -15,6 +15,8 @@ from isaaclab.assets.articulation.base_articulation_data import BaseArticulationData from isaaclab.utils.buffers import TimestampedBufferWarp as TimestampedBuffer from isaaclab.utils.math import normalize +from isaaclab.utils.warp import ProxyArray +from isaaclab.utils.warp.utils import capture_unsafe from isaaclab_newton.assets import kernels as shared_kernels from isaaclab_newton.assets.articulation import kernels as articulation_kernels @@ -26,6 +28,13 @@ # import logger logger = logging.getLogger(__name__) +_LAZY_CAPTURE_REASON = ( + "This is a lazily-computed derived property guarded by a Python timestamp check " + "that is invisible during graph replay. Use Tier 1 base data (root_link_pose_w, " + "root_com_vel_w, body_link_pose_w, body_com_vel_w, joint_pos, joint_vel) and " + "inline the computation in your warp kernel. See GRAPH_CAPTURE_MIGRATION.md." +) + class ArticulationData(BaseArticulationData): """Data container for an articulation. @@ -74,8 +83,8 @@ def __init__(self, root_view: ArticulationView, device: str): forward_vec = torch.tensor((1.0, 0.0, 0.0), device=self.device).repeat(self._root_view.count, 1) # Initialize constants - self.GRAVITY_VEC_W = wp.from_torch(gravity_dir, dtype=wp.vec3f) - self.FORWARD_VEC_B = wp.from_torch(forward_vec, dtype=wp.vec3f) + self.GRAVITY_VEC_W = ProxyArray(wp.from_torch(gravity_dir, dtype=wp.vec3f)) + self.FORWARD_VEC_B = ProxyArray(wp.from_torch(forward_vec, dtype=wp.vec3f)) self._create_simulation_bindings() self._create_buffers() @@ -139,13 +148,13 @@ def update(self, dt: float) -> None: """ @property - def default_root_pose(self) -> wp.array: + def default_root_pose(self) -> ProxyArray: """Default root pose ``[pos, quat]`` in the local environment frame. The position and quaternion are of the articulation root's actor frame. Shape is (num_instances), dtype = wp.transformf. In torch this resolves to (num_instances, 7). """ - return self._default_root_pose + return self._default_root_pose_ta @default_root_pose.setter def default_root_pose(self, value: wp.array) -> None: @@ -162,13 +171,13 @@ def default_root_pose(self, value: wp.array) -> None: self._default_root_pose.assign(value) @property - def default_root_vel(self) -> wp.array: + def default_root_vel(self) -> ProxyArray: """Default root velocity ``[lin_vel, ang_vel]`` in the local environment frame. The linear and angular velocities are of the articulation root's center of mass frame. Shape is (num_instances), dtype = wp.spatial_vectorf. In torch this resolves to (num_instances, 6). """ - return self._default_root_vel + return self._default_root_vel_ta @default_root_vel.setter def default_root_vel(self, value: wp.array) -> None: @@ -185,14 +194,14 @@ def default_root_vel(self, value: wp.array) -> None: self._default_root_vel.assign(value) @property - def default_joint_pos(self) -> wp.array: + def default_joint_pos(self) -> ProxyArray: """Default joint positions of all joints. Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to (num_instances, num_joints). This quantity is configured through the :attr:`isaaclab.assets.ArticulationCfg.init_state` parameter. """ - return self._default_joint_pos + return self._default_joint_pos_ta @default_joint_pos.setter def default_joint_pos(self, value: wp.array) -> None: @@ -209,14 +218,14 @@ def default_joint_pos(self, value: wp.array) -> None: self._default_joint_pos.assign(value) @property - def default_joint_vel(self) -> wp.array: + def default_joint_vel(self) -> ProxyArray: """Default joint velocities of all joints. Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to (num_instances, num_joints). This quantity is configured through the :attr:`isaaclab.assets.ArticulationCfg.init_state` parameter. """ - return self._default_joint_vel + return self._default_joint_vel_ta @default_joint_vel.setter def default_joint_vel(self, value: wp.array) -> None: @@ -237,7 +246,7 @@ def default_joint_vel(self, value: wp.array) -> None: """ @property - def joint_pos_target(self) -> wp.array: + def joint_pos_target(self) -> ProxyArray: """Joint position targets commanded by the user. Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to (num_instances, num_joints). @@ -246,10 +255,10 @@ def joint_pos_target(self) -> wp.array: For an explicit actuator model, the targets are used to compute the joint torques (see :attr:`applied_torque`), which are then set into the simulation. """ - return self._joint_pos_target + return self._joint_pos_target_ta @property - def joint_vel_target(self) -> wp.array: + def joint_vel_target(self) -> ProxyArray: """Joint velocity targets commanded by the user. Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to (num_instances, num_joints). @@ -258,10 +267,10 @@ def joint_vel_target(self) -> wp.array: For an explicit actuator model, the targets are used to compute the joint torques (see :attr:`applied_torque`), which are then set into the simulation. """ - return self._joint_vel_target + return self._joint_vel_target_ta @property - def joint_effort_target(self) -> wp.array: + def joint_effort_target(self) -> ProxyArray: """Joint effort targets commanded by the user. Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to (num_instances, num_joints). @@ -270,14 +279,14 @@ def joint_effort_target(self) -> wp.array: For an explicit actuator model, the targets are used to compute the joint torques (see :attr:`applied_torque`), which are then set into the simulation. """ - return self._joint_effort_target + return self._joint_effort_target_ta """ Joint commands -- Explicit actuators. """ @property - def computed_torque(self) -> wp.array: + def computed_torque(self) -> ProxyArray: """Joint torques computed from the actuator model (before clipping). Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to (num_instances, num_joints). @@ -286,10 +295,10 @@ def computed_torque(self) -> wp.array: It is exposed for users who want to inspect the computations inside the actuator model. For instance, to penalize the learning agent for a difference between the computed and applied torques. """ - return self._computed_torque + return self._computed_torque_ta @property - def applied_torque(self) -> wp.array: + def applied_torque(self) -> ProxyArray: """Joint torques applied from the actuator model (after clipping). Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to (num_instances, num_joints). @@ -297,60 +306,60 @@ def applied_torque(self) -> wp.array: These torques are set into the simulation, after clipping the :attr:`computed_torque` based on the actuator model. """ - return self._applied_torque + return self._applied_torque_ta """ Joint properties """ @property - def joint_stiffness(self) -> wp.array: + def joint_stiffness(self) -> ProxyArray: """Joint stiffness provided to the simulation. Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to (num_instances, num_joints). In the case of explicit actuators, the value for the corresponding joints is zero. """ - return self._sim_bind_joint_stiffness_sim + return self._joint_stiffness_ta @property - def joint_damping(self) -> wp.array: + def joint_damping(self) -> ProxyArray: """Joint damping provided to the simulation. Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to (num_instances, num_joints). In the case of explicit actuators, the value for the corresponding joints is zero. """ - return self._sim_bind_joint_damping_sim + return self._joint_damping_ta @property - def joint_armature(self) -> wp.array: + def joint_armature(self) -> ProxyArray: """Joint armature provided to the simulation. Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to (num_instances, num_joints). """ - return self._sim_bind_joint_armature + return self._joint_armature_ta @property - def joint_friction_coeff(self) -> wp.array: + def joint_friction_coeff(self) -> ProxyArray: """Joint static friction coefficient provided to the simulation. Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to (num_instances, num_joints). """ - return self._sim_bind_joint_friction_coeff + return self._joint_friction_coeff_ta @property - def joint_pos_limits_lower(self) -> wp.array: + def joint_pos_limits_lower(self) -> ProxyArray: """Joint position limits lower provided to the simulation. Shape is (num_instances, num_joints).""" - return self._sim_bind_joint_pos_limits_lower + return self._joint_pos_limits_lower_ta @property - def joint_pos_limits_upper(self) -> wp.array: + def joint_pos_limits_upper(self) -> ProxyArray: """Joint position limits upper provided to the simulation. Shape is (num_instances, num_joints).""" - return self._sim_bind_joint_pos_limits_upper + return self._joint_pos_limits_upper_ta @property - def joint_pos_limits(self) -> wp.array: + def joint_pos_limits(self) -> ProxyArray: """Joint position limits provided to the simulation. Shape is (num_instances, num_joints, 2), dtype = wp.vec2f. In torch this resolves to @@ -362,6 +371,7 @@ def joint_pos_limits(self) -> wp.array: self._joint_pos_limits = wp.zeros( (self._num_instances, self._num_joints), dtype=wp.vec2f, device=self.device ) + self._joint_pos_limits_ta = ProxyArray(self._joint_pos_limits) wp.launch( articulation_kernels.concat_joint_pos_limits_lower_and_upper, dim=(self._num_instances, self._num_joints), @@ -374,30 +384,30 @@ def joint_pos_limits(self) -> wp.array: ], device=self.device, ) - return self._joint_pos_limits + return self._joint_pos_limits_ta @property - def joint_vel_limits(self) -> wp.array: + def joint_vel_limits(self) -> ProxyArray: """Joint maximum velocity provided to the simulation. Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to (num_instances, num_joints). """ - return self._sim_bind_joint_vel_limits_sim + return self._joint_vel_limits_ta @property - def joint_effort_limits(self) -> wp.array: + def joint_effort_limits(self) -> ProxyArray: """Joint maximum effort provided to the simulation. Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to (num_instances, num_joints). """ - return self._sim_bind_joint_effort_limits_sim + return self._joint_effort_limits_ta """ Joint properties - Custom. """ @property - def soft_joint_pos_limits(self) -> wp.array: + def soft_joint_pos_limits(self) -> ProxyArray: r"""Soft joint positions limits for all joints. Shape is (num_instances, num_joints), dtype = wp.vec2f. In torch this resolves to @@ -418,10 +428,10 @@ def soft_joint_pos_limits(self) -> wp.array: The soft joint position limits help specify a safety region around the joint limits. It isn't used by the simulation, but is useful for learning agents to prevent the joint positions from violating the limits. """ - return self._soft_joint_pos_limits + return self._soft_joint_pos_limits_ta @property - def soft_joint_vel_limits(self) -> wp.array: + def soft_joint_vel_limits(self) -> ProxyArray: """Soft joint velocity limits for all joints. Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to (num_instances, num_joints). @@ -429,22 +439,22 @@ def soft_joint_vel_limits(self) -> wp.array: These are obtained from the actuator model. It may differ from :attr:`joint_vel_limits` if the actuator model has a variable velocity limit model. For instance, in a variable gear ratio actuator model. """ - return self._soft_joint_vel_limits + return self._soft_joint_vel_limits_ta @property - def gear_ratio(self) -> wp.array: + def gear_ratio(self) -> ProxyArray: """Gear ratio for relating motor torques to applied Joint torques. Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to (num_instances, num_joints). """ - return self._gear_ratio + return self._gear_ratio_ta """ Fixed tendon properties. """ @property - def fixed_tendon_stiffness(self) -> wp.array: + def fixed_tendon_stiffness(self) -> ProxyArray: """Fixed tendon stiffness provided to the simulation. Shape is (num_instances, num_fixed_tendons), dtype = wp.float32. In torch this resolves to @@ -453,7 +463,7 @@ def fixed_tendon_stiffness(self) -> wp.array: raise NotImplementedError @property - def fixed_tendon_damping(self) -> wp.array: + def fixed_tendon_damping(self) -> ProxyArray: """Fixed tendon damping provided to the simulation. Shape is (num_instances, num_fixed_tendons), dtype = wp.float32. In torch this resolves to @@ -462,7 +472,7 @@ def fixed_tendon_damping(self) -> wp.array: raise NotImplementedError @property - def fixed_tendon_limit_stiffness(self) -> wp.array: + def fixed_tendon_limit_stiffness(self) -> ProxyArray: """Fixed tendon limit stiffness provided to the simulation. Shape is (num_instances, num_fixed_tendons), dtype = wp.float32. In torch this resolves to @@ -471,7 +481,7 @@ def fixed_tendon_limit_stiffness(self) -> wp.array: raise NotImplementedError @property - def fixed_tendon_rest_length(self) -> wp.array: + def fixed_tendon_rest_length(self) -> ProxyArray: """Fixed tendon rest length provided to the simulation. Shape is (num_instances, num_fixed_tendons), dtype = wp.float32. In torch this resolves to @@ -480,7 +490,7 @@ def fixed_tendon_rest_length(self) -> wp.array: raise NotImplementedError @property - def fixed_tendon_offset(self) -> wp.array: + def fixed_tendon_offset(self) -> ProxyArray: """Fixed tendon offset provided to the simulation. Shape is (num_instances, num_fixed_tendons), dtype = wp.float32. In torch this resolves to @@ -489,7 +499,7 @@ def fixed_tendon_offset(self) -> wp.array: raise NotImplementedError @property - def fixed_tendon_pos_limits(self) -> wp.array: + def fixed_tendon_pos_limits(self) -> ProxyArray: """Fixed tendon position limits provided to the simulation. Shape is (num_instances, num_fixed_tendons, 2), dtype = wp.vec2f. In torch this resolves to @@ -502,7 +512,7 @@ def fixed_tendon_pos_limits(self) -> wp.array: """ @property - def spatial_tendon_stiffness(self) -> wp.array: + def spatial_tendon_stiffness(self) -> ProxyArray: """Spatial tendon stiffness provided to the simulation. Shape is (num_instances, num_spatial_tendons), dtype = wp.float32. In torch this resolves to @@ -511,7 +521,7 @@ def spatial_tendon_stiffness(self) -> wp.array: raise NotImplementedError @property - def spatial_tendon_damping(self) -> wp.array: + def spatial_tendon_damping(self) -> ProxyArray: """Spatial tendon damping provided to the simulation. Shape is (num_instances, num_spatial_tendons), dtype = wp.float32. In torch this resolves to @@ -520,7 +530,7 @@ def spatial_tendon_damping(self) -> wp.array: raise NotImplementedError @property - def spatial_tendon_limit_stiffness(self) -> wp.array: + def spatial_tendon_limit_stiffness(self) -> ProxyArray: """Spatial tendon limit stiffness provided to the simulation. Shape is (num_instances, num_spatial_tendons), dtype = wp.float32. In torch this resolves to @@ -529,7 +539,7 @@ def spatial_tendon_limit_stiffness(self) -> wp.array: raise NotImplementedError @property - def spatial_tendon_offset(self) -> wp.array: + def spatial_tendon_offset(self) -> ProxyArray: """Spatial tendon offset provided to the simulation. Shape is (num_instances, num_spatial_tendons), dtype = wp.float32. In torch this resolves to @@ -542,7 +552,7 @@ def spatial_tendon_offset(self) -> wp.array: """ @property - def root_link_pose_w(self) -> wp.array: + def root_link_pose_w(self) -> ProxyArray: """Root link pose ``[pos, quat]`` in simulation world frame. Shape is (num_instances,), dtype = wp.transformf. In torch this resolves to (num_instances, 7). @@ -550,10 +560,11 @@ def root_link_pose_w(self) -> wp.array: This quantity is the pose of the articulation root's actor frame relative to the world. The orientation is provided in (x, y, z, w) format. """ - return self._sim_bind_root_link_pose_w + return self._root_link_pose_w_ta @property - def root_link_vel_w(self) -> wp.array: + @capture_unsafe(_LAZY_CAPTURE_REASON) + def root_link_vel_w(self) -> ProxyArray: """Root link velocity ``[lin_vel, ang_vel]`` in simulation world frame. Shape is (num_instances,), dtype = wp.spatial_vectorf. In torch this resolves to (num_instances, 6). @@ -566,9 +577,9 @@ def root_link_vel_w(self) -> wp.array: shared_kernels.get_root_link_vel_from_root_com_vel, dim=self._num_instances, inputs=[ - self.root_com_vel_w, - self.root_link_pose_w, - self.body_com_pos_b, + self.root_com_vel_w.warp, + self.root_link_pose_w.warp, + self.body_com_pos_b.warp, ], outputs=[ self._root_link_vel_w.data, @@ -577,10 +588,11 @@ def root_link_vel_w(self) -> wp.array: ) self._root_link_vel_w.timestamp = self._sim_timestamp - return self._root_link_vel_w.data + return self._root_link_vel_w_ta @property - def root_com_pose_w(self) -> wp.array: + @capture_unsafe(_LAZY_CAPTURE_REASON) + def root_com_pose_w(self) -> ProxyArray: """Root center of mass pose ``[pos, quat]`` in simulation world frame. Shape is (num_instances,), dtype = wp.transformf. In torch this resolves to (num_instances, 7). @@ -594,8 +606,8 @@ def root_com_pose_w(self) -> wp.array: shared_kernels.get_root_com_pose_from_root_link_pose, dim=self._num_instances, inputs=[ - self.root_link_pose_w, - self.body_com_pos_b, + self.root_link_pose_w.warp, + self.body_com_pos_b.warp, ], outputs=[ self._root_com_pose_w.data, @@ -604,10 +616,10 @@ def root_com_pose_w(self) -> wp.array: ) self._root_com_pose_w.timestamp = self._sim_timestamp - return self._root_com_pose_w.data + return self._root_com_pose_w_ta @property - def root_com_vel_w(self) -> wp.array: + def root_com_vel_w(self) -> ProxyArray: """Root center of mass velocity ``[lin_vel, ang_vel]`` in simulation world frame. Shape is (num_instances,), dtype = wp.spatial_vectorf. In torch this resolves to (num_instances, 6). @@ -615,31 +627,31 @@ def root_com_vel_w(self) -> wp.array: This quantity contains the linear and angular velocities of the articulation root's center of mass frame relative to the world. """ - return self._sim_bind_root_com_vel_w + return self._root_com_vel_w_ta """ Body state properties. """ @property - def body_mass(self) -> wp.array: + def body_mass(self) -> ProxyArray: """Body mass ``wp.float32`` in the world frame. Shape is (num_instances, num_bodies), dtype = wp.float32. In torch this resolves to (num_instances, num_bodies). """ - return self._sim_bind_body_mass + return self._body_mass_ta @property - def body_inertia(self) -> wp.array: + def body_inertia(self) -> ProxyArray: """Flattened body inertia in the world frame. Shape is (num_instances, num_bodies, 9), dtype = wp.float32. In torch this resolves to (num_instances, num_bodies, 9). """ - return self._sim_bind_body_inertia + return self._body_inertia_ta @property - def body_link_pose_w(self) -> wp.array: + def body_link_pose_w(self) -> ProxyArray: """Body link pose ``[pos, quat]`` in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.transformf. In torch this resolves to @@ -651,10 +663,11 @@ def body_link_pose_w(self) -> wp.array: if self._fk_timestamp < self._sim_timestamp: SimulationManager.forward() self._fk_timestamp = self._sim_timestamp - return self._sim_bind_body_link_pose_w + return self._body_link_pose_w_ta @property - def body_link_vel_w(self) -> wp.array: + @capture_unsafe(_LAZY_CAPTURE_REASON) + def body_link_vel_w(self) -> ProxyArray: """Body link velocity ``[lin_vel, ang_vel]`` in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.spatial_vectorf. In torch this resolves to @@ -668,9 +681,9 @@ def body_link_vel_w(self) -> wp.array: shared_kernels.get_body_link_vel_from_body_com_vel, dim=(self._num_instances, self._num_bodies), inputs=[ - self.body_com_vel_w, - self.body_link_pose_w, - self.body_com_pos_b, + self.body_com_vel_w.warp, + self.body_link_pose_w.warp, + self.body_com_pos_b.warp, ], outputs=[ self._body_link_vel_w.data, @@ -679,10 +692,11 @@ def body_link_vel_w(self) -> wp.array: ) self._body_link_vel_w.timestamp = self._sim_timestamp - return self._body_link_vel_w.data + return self._body_link_vel_w_ta @property - def body_com_pose_w(self) -> wp.array: + @capture_unsafe(_LAZY_CAPTURE_REASON) + def body_com_pose_w(self) -> ProxyArray: """Body center of mass pose ``[pos, quat]`` in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.transformf. In torch this resolves to @@ -696,8 +710,8 @@ def body_com_pose_w(self) -> wp.array: shared_kernels.get_body_com_pose_from_body_link_pose, dim=(self._num_instances, self._num_bodies), inputs=[ - self.body_link_pose_w, - self.body_com_pos_b, + self.body_link_pose_w.warp, + self.body_com_pos_b.warp, ], outputs=[ self._body_com_pose_w.data, @@ -706,10 +720,10 @@ def body_com_pose_w(self) -> wp.array: ) self._body_com_pose_w.timestamp = self._sim_timestamp - return self._body_com_pose_w.data + return self._body_com_pose_w_ta @property - def body_com_vel_w(self) -> wp.array: + def body_com_vel_w(self) -> ProxyArray: """Body center of mass velocity ``[lin_vel, ang_vel]`` in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.spatial_vectorf. In torch this resolves to @@ -718,10 +732,10 @@ def body_com_vel_w(self) -> wp.array: This quantity contains the linear and angular velocities of the articulation links' center of mass frame relative to the world. """ - return self._sim_bind_body_com_vel_w + return self._body_com_vel_w_ta @property - def body_com_acc_w(self): + def body_com_acc_w(self) -> ProxyArray: """Acceleration of all bodies center of mass ``[lin_acc, ang_acc]``. Shape is (num_instances, num_bodies), dtype = wp.spatial_vectorf. In torch this resolves to @@ -746,10 +760,10 @@ def body_com_acc_w(self): # set the buffer data and timestamp self._body_com_acc_w.timestamp = self._sim_timestamp # update the previous velocity - return self._body_com_acc_w.data + return self._body_com_acc_w_ta @property - def body_com_pos_b(self) -> wp.array: + def body_com_pos_b(self) -> ProxyArray: """Center of mass position of all of the bodies in their respective link frames. Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to @@ -757,10 +771,10 @@ def body_com_pos_b(self) -> wp.array: This quantity is the center of mass location relative to its body's link frame. """ - return self._sim_bind_body_com_pos_b + return self._body_com_pos_b_ta @property - def body_com_pose_b(self) -> wp.array: + def body_com_pose_b(self) -> ProxyArray: """Center of mass pose ``[pos, quat]`` of all bodies in their respective body's link frames. Shape is (num_instances, num_bodies), dtype = wp.transformf. In torch this resolves to @@ -781,7 +795,7 @@ def body_com_pose_b(self) -> wp.array: shared_kernels.make_dummy_body_com_pose_b, dim=(self._num_instances, self._num_bodies), inputs=[ - self.body_com_pos_b, + self.body_com_pos_b.warp, ], outputs=[ self._body_com_pose_b.data, @@ -789,48 +803,32 @@ def body_com_pose_b(self) -> wp.array: device=self.device, ) self._body_com_pose_b.timestamp = self._sim_timestamp - return self._body_com_pose_b.data - - @property - def body_incoming_joint_wrench_b(self) -> wp.array: - """Joint reaction wrench applied from body parent to child body in parent body frame. - - Shape is (num_instances, num_bodies), dtype = wp.spatial_vectorf. In torch this resolves to - (num_instances, num_bodies, 6). All body reaction wrenches are provided including the root body to the - world of an articulation. - - For more information on joint wrenches, please check the `PhysX documentation`_ and the - underlying `PhysX Tensor API`_. - - .. _PhysX documentation: https://nvidia-omniverse.github.io/PhysX/physx/5.5.1/docs/Articulations.html#link-incoming-joint-force - .. _PhysX Tensor API: https://docs.omniverse.nvidia.com/kit/docs/omni_physics/latest/extensions/runtime/source/omni.physics.tensors/docs/api/python.html#omni.physics.tensors.impl.api.ArticulationView.get_link_incoming_joint_force - """ - raise NotImplementedError("Not implemented for Newton") + return self._body_com_pose_b_ta """ Joint state properties. """ @property - def joint_pos(self) -> wp.array: + def joint_pos(self) -> ProxyArray: """Joint positions of all joints. Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to (num_instances, num_joints). """ - return self._sim_bind_joint_pos + return self._joint_pos_ta @property - def joint_vel(self) -> wp.array: + def joint_vel(self) -> ProxyArray: """Joint velocities of all joints. Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to (num_instances, num_joints). """ - return self._sim_bind_joint_vel + return self._joint_vel_ta @property - def joint_acc(self) -> wp.array: + def joint_acc(self) -> ProxyArray: """Joint acceleration of all joints. Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to @@ -843,7 +841,7 @@ def joint_acc(self) -> wp.array: articulation_kernels.get_joint_acc_from_joint_vel, dim=(self._num_instances, self._num_joints), inputs=[ - self.joint_vel, + self.joint_vel.warp, self._previous_joint_vel, time_elapsed, ], @@ -853,14 +851,15 @@ def joint_acc(self) -> wp.array: device=self.device, ) self._joint_acc.timestamp = self._sim_timestamp - return self._joint_acc.data + return self._joint_acc_ta """ Derived Properties. """ @property - def projected_gravity_b(self): + @capture_unsafe(_LAZY_CAPTURE_REASON) + def projected_gravity_b(self) -> ProxyArray: """Projection of the gravity direction on base frame. Shape is (num_instances), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). @@ -869,15 +868,16 @@ def projected_gravity_b(self): wp.launch( shared_kernels.quat_apply_inverse_1D_kernel, dim=self._num_instances, - inputs=[self.GRAVITY_VEC_W, self.root_link_quat_w], + inputs=[self.GRAVITY_VEC_W.warp, self.root_link_quat_w.warp], outputs=[self._projected_gravity_b.data], device=self.device, ) self._projected_gravity_b.timestamp = self._sim_timestamp - return self._projected_gravity_b.data + return self._projected_gravity_b_ta @property - def heading_w(self): + @capture_unsafe(_LAZY_CAPTURE_REASON) + def heading_w(self) -> ProxyArray: """Yaw heading of the base frame (in radians). Shape is (num_instances), dtype = wp.float32. In torch this resolves to (num_instances,). @@ -890,15 +890,16 @@ def heading_w(self): wp.launch( shared_kernels.root_heading_w, dim=self._num_instances, - inputs=[self.FORWARD_VEC_B, self.root_link_quat_w], + inputs=[self.FORWARD_VEC_B.warp, self.root_link_quat_w.warp], outputs=[self._heading_w.data], device=self.device, ) self._heading_w.timestamp = self._sim_timestamp - return self._heading_w.data + return self._heading_w_ta @property - def root_link_lin_vel_b(self) -> wp.array: + @capture_unsafe(_LAZY_CAPTURE_REASON) + def root_link_lin_vel_b(self) -> ProxyArray: """Root link linear velocity in base frame. Shape is (num_instances), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). @@ -910,19 +911,20 @@ def root_link_lin_vel_b(self) -> wp.array: self._root_link_lin_vel_b = TimestampedBuffer( shape=(self._num_instances,), dtype=wp.vec3f, device=self.device ) + self._root_link_lin_vel_b_ta = ProxyArray(self._root_link_lin_vel_b.data) if self._root_link_lin_vel_b.timestamp < self._sim_timestamp: wp.launch( shared_kernels.quat_apply_inverse_1D_kernel, dim=self._num_instances, - inputs=[self.root_link_lin_vel_w, self.root_link_quat_w], + inputs=[self.root_link_lin_vel_w.warp, self.root_link_quat_w.warp], outputs=[self._root_link_lin_vel_b.data], device=self.device, ) self._root_link_lin_vel_b.timestamp = self._sim_timestamp - return self._root_link_lin_vel_b.data + return self._root_link_lin_vel_b_ta @property - def root_link_ang_vel_b(self) -> wp.array: + def root_link_ang_vel_b(self) -> ProxyArray: """Root link angular velocity in base frame. Shape is (num_instances), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). @@ -934,19 +936,20 @@ def root_link_ang_vel_b(self) -> wp.array: self._root_link_ang_vel_b = TimestampedBuffer( shape=(self._num_instances,), dtype=wp.vec3f, device=self.device ) + self._root_link_ang_vel_b_ta = ProxyArray(self._root_link_ang_vel_b.data) if self._root_link_ang_vel_b.timestamp < self._sim_timestamp: wp.launch( shared_kernels.quat_apply_inverse_1D_kernel, dim=self._num_instances, - inputs=[self.root_link_ang_vel_w, self.root_link_quat_w], + inputs=[self.root_link_ang_vel_w.warp, self.root_link_quat_w.warp], outputs=[self._root_link_ang_vel_b.data], device=self.device, ) self._root_link_ang_vel_b.timestamp = self._sim_timestamp - return self._root_link_ang_vel_b.data + return self._root_link_ang_vel_b_ta @property - def root_com_lin_vel_b(self) -> wp.array: + def root_com_lin_vel_b(self) -> ProxyArray: """Root center of mass linear velocity in base frame. Shape is (num_instances), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). @@ -958,19 +961,20 @@ def root_com_lin_vel_b(self) -> wp.array: self._root_com_lin_vel_b = TimestampedBuffer( shape=(self._num_instances,), dtype=wp.vec3f, device=self.device ) + self._root_com_lin_vel_b_ta = ProxyArray(self._root_com_lin_vel_b.data) if self._root_com_lin_vel_b.timestamp < self._sim_timestamp: wp.launch( shared_kernels.quat_apply_inverse_1D_kernel, dim=self._num_instances, - inputs=[self.root_com_lin_vel_w, self.root_link_quat_w], + inputs=[self.root_com_lin_vel_w.warp, self.root_link_quat_w.warp], outputs=[self._root_com_lin_vel_b.data], device=self.device, ) self._root_com_lin_vel_b.timestamp = self._sim_timestamp - return self._root_com_lin_vel_b.data + return self._root_com_lin_vel_b_ta @property - def root_com_ang_vel_b(self) -> wp.array: + def root_com_ang_vel_b(self) -> ProxyArray: """Root center of mass angular velocity in base frame. Shape is (num_instances), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). @@ -982,103 +986,134 @@ def root_com_ang_vel_b(self) -> wp.array: self._root_com_ang_vel_b = TimestampedBuffer( shape=(self._num_instances,), dtype=wp.vec3f, device=self.device ) + self._root_com_ang_vel_b_ta = ProxyArray(self._root_com_ang_vel_b.data) if self._root_com_ang_vel_b.timestamp < self._sim_timestamp: wp.launch( shared_kernels.quat_apply_inverse_1D_kernel, dim=self._num_instances, - inputs=[self.root_com_ang_vel_w, self.root_link_quat_w], + inputs=[self.root_com_ang_vel_w.warp, self.root_link_quat_w.warp], outputs=[self._root_com_ang_vel_b.data], device=self.device, ) self._root_com_ang_vel_b.timestamp = self._sim_timestamp - return self._root_com_ang_vel_b.data + return self._root_com_ang_vel_b_ta """ Sliced properties. """ @property - def root_link_pos_w(self) -> wp.array: + def root_link_pos_w(self) -> ProxyArray: """Root link position in simulation world frame. Shape is (num_instances), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). This quantity is the position of the actor frame of the root rigid body relative to the world. """ - return self._get_pos_from_transform(self._root_link_pos_w, self.root_link_pose_w) + self._root_link_pos_w = self._get_pos_from_transform(self._root_link_pos_w, self.root_link_pose_w.warp) + if self._root_link_pos_w_ta is None: + self._root_link_pos_w_ta = ProxyArray(self._root_link_pos_w) + return self._root_link_pos_w_ta @property - def root_link_quat_w(self) -> wp.array: + def root_link_quat_w(self) -> ProxyArray: """Root link orientation (x, y, z, w) in simulation world frame. Shape is (num_instances), dtype = wp.quatf. In torch this resolves to (num_instances, 4). This quantity is the orientation of the actor frame of the root rigid body. """ - return self._get_quat_from_transform(self._root_link_quat_w, self.root_link_pose_w) + self._root_link_quat_w = self._get_quat_from_transform(self._root_link_quat_w, self.root_link_pose_w.warp) + if self._root_link_quat_w_ta is None: + self._root_link_quat_w_ta = ProxyArray(self._root_link_quat_w) + return self._root_link_quat_w_ta @property - def root_link_lin_vel_w(self) -> wp.array: + def root_link_lin_vel_w(self) -> ProxyArray: """Root linear velocity in simulation world frame. Shape is (num_instances), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). This quantity is the linear velocity of the root rigid body's actor frame relative to the world. """ - return self._get_top_from_spatial_vector(self._root_link_lin_vel_w, self.root_link_vel_w) + self._root_link_lin_vel_w = self._get_top_from_spatial_vector( + self._root_link_lin_vel_w, self.root_link_vel_w.warp + ) + if self._root_link_lin_vel_w_ta is None: + self._root_link_lin_vel_w_ta = ProxyArray(self._root_link_lin_vel_w) + return self._root_link_lin_vel_w_ta @property - def root_link_ang_vel_w(self) -> wp.array: + def root_link_ang_vel_w(self) -> ProxyArray: """Root link angular velocity in simulation world frame. Shape is (num_instances), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). This quantity is the angular velocity of the actor frame of the root rigid body relative to the world. """ - return self._get_bottom_from_spatial_vector(self._root_link_ang_vel_w, self.root_link_vel_w) + self._root_link_ang_vel_w = self._get_bottom_from_spatial_vector( + self._root_link_ang_vel_w, self.root_link_vel_w.warp + ) + if self._root_link_ang_vel_w_ta is None: + self._root_link_ang_vel_w_ta = ProxyArray(self._root_link_ang_vel_w) + return self._root_link_ang_vel_w_ta @property - def root_com_pos_w(self) -> wp.array: + def root_com_pos_w(self) -> ProxyArray: """Root center of mass position in simulation world frame. Shape is (num_instances), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). This quantity is the position of the center of mass frame of the root rigid body relative to the world. """ - return self._get_pos_from_transform(self._root_com_pos_w, self.root_com_pose_w) + self._root_com_pos_w = self._get_pos_from_transform(self._root_com_pos_w, self.root_com_pose_w.warp) + if self._root_com_pos_w_ta is None: + self._root_com_pos_w_ta = ProxyArray(self._root_com_pos_w) + return self._root_com_pos_w_ta @property - def root_com_quat_w(self) -> wp.array: + def root_com_quat_w(self) -> ProxyArray: """Root center of mass orientation (x, y, z, w) in simulation world frame. Shape is (num_instances), dtype = wp.quatf. In torch this resolves to (num_instances, 4). This quantity is the orientation of the principal axes of inertia of the root rigid body relative to the world. """ - return self._get_quat_from_transform(self._root_com_quat_w, self.root_com_pose_w) + self._root_com_quat_w = self._get_quat_from_transform(self._root_com_quat_w, self.root_com_pose_w.warp) + if self._root_com_quat_w_ta is None: + self._root_com_quat_w_ta = ProxyArray(self._root_com_quat_w) + return self._root_com_quat_w_ta @property - def root_com_lin_vel_w(self) -> wp.array: + def root_com_lin_vel_w(self) -> ProxyArray: """Root center of mass linear velocity in simulation world frame. Shape is (num_instances), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). This quantity is the linear velocity of the root rigid body's center of mass frame relative to the world. """ - return self._get_top_from_spatial_vector(self._root_com_lin_vel_w, self.root_com_vel_w) + self._root_com_lin_vel_w = self._get_top_from_spatial_vector(self._root_com_lin_vel_w, self.root_com_vel_w.warp) + if self._root_com_lin_vel_w_ta is None: + self._root_com_lin_vel_w_ta = ProxyArray(self._root_com_lin_vel_w) + return self._root_com_lin_vel_w_ta @property - def root_com_ang_vel_w(self) -> wp.array: + def root_com_ang_vel_w(self) -> ProxyArray: """Root center of mass angular velocity in simulation world frame. Shape is (num_instances), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). This quantity is the angular velocity of the root rigid body's center of mass frame relative to the world. """ - return self._get_bottom_from_spatial_vector(self._root_com_ang_vel_w, self.root_com_vel_w) + self._root_com_ang_vel_w = self._get_bottom_from_spatial_vector( + self._root_com_ang_vel_w, self.root_com_vel_w.warp + ) + if self._root_com_ang_vel_w_ta is None: + self._root_com_ang_vel_w_ta = ProxyArray(self._root_com_ang_vel_w) + return self._root_com_ang_vel_w_ta @property - def body_link_pos_w(self) -> wp.array: + def body_link_pos_w(self) -> ProxyArray: """Positions of all bodies in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to @@ -1086,10 +1121,13 @@ def body_link_pos_w(self) -> wp.array: This quantity is the position of the articulation bodies' actor frame relative to the world. """ - return self._get_pos_from_transform(self._body_link_pos_w, self.body_link_pose_w) + self._body_link_pos_w = self._get_pos_from_transform(self._body_link_pos_w, self.body_link_pose_w.warp) + if self._body_link_pos_w_ta is None: + self._body_link_pos_w_ta = ProxyArray(self._body_link_pos_w) + return self._body_link_pos_w_ta @property - def body_link_quat_w(self) -> wp.array: + def body_link_quat_w(self) -> ProxyArray: """Orientation (x, y, z, w) of all bodies in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.quatf. In torch this resolves to @@ -1097,10 +1135,13 @@ def body_link_quat_w(self) -> wp.array: This quantity is the orientation of the articulation bodies' actor frame relative to the world. """ - return self._get_quat_from_transform(self._body_link_quat_w, self.body_link_pose_w) + self._body_link_quat_w = self._get_quat_from_transform(self._body_link_quat_w, self.body_link_pose_w.warp) + if self._body_link_quat_w_ta is None: + self._body_link_quat_w_ta = ProxyArray(self._body_link_quat_w) + return self._body_link_quat_w_ta @property - def body_link_lin_vel_w(self) -> wp.array: + def body_link_lin_vel_w(self) -> ProxyArray: """Linear velocity of all bodies in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to @@ -1108,10 +1149,15 @@ def body_link_lin_vel_w(self) -> wp.array: This quantity is the linear velocity of the articulation bodies' actor frame relative to the world. """ - return self._get_top_from_spatial_vector(self._body_link_lin_vel_w, self.body_link_vel_w) + self._body_link_lin_vel_w = self._get_top_from_spatial_vector( + self._body_link_lin_vel_w, self.body_link_vel_w.warp + ) + if self._body_link_lin_vel_w_ta is None: + self._body_link_lin_vel_w_ta = ProxyArray(self._body_link_lin_vel_w) + return self._body_link_lin_vel_w_ta @property - def body_link_ang_vel_w(self) -> wp.array: + def body_link_ang_vel_w(self) -> ProxyArray: """Angular velocity of all bodies in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to @@ -1119,10 +1165,15 @@ def body_link_ang_vel_w(self) -> wp.array: This quantity is the angular velocity of the articulation bodies' actor frame relative to the world. """ - return self._get_bottom_from_spatial_vector(self._body_link_ang_vel_w, self.body_link_vel_w) + self._body_link_ang_vel_w = self._get_bottom_from_spatial_vector( + self._body_link_ang_vel_w, self.body_link_vel_w.warp + ) + if self._body_link_ang_vel_w_ta is None: + self._body_link_ang_vel_w_ta = ProxyArray(self._body_link_ang_vel_w) + return self._body_link_ang_vel_w_ta @property - def body_com_pos_w(self) -> wp.array: + def body_com_pos_w(self) -> ProxyArray: """Positions of all bodies in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to @@ -1130,10 +1181,13 @@ def body_com_pos_w(self) -> wp.array: This quantity is the position of the articulation bodies' center of mass frame. """ - return self._get_pos_from_transform(self._body_com_pos_w, self.body_com_pose_w) + self._body_com_pos_w = self._get_pos_from_transform(self._body_com_pos_w, self.body_com_pose_w.warp) + if self._body_com_pos_w_ta is None: + self._body_com_pos_w_ta = ProxyArray(self._body_com_pos_w) + return self._body_com_pos_w_ta @property - def body_com_quat_w(self) -> wp.array: + def body_com_quat_w(self) -> ProxyArray: """Orientation (x, y, z, w) of the principal axes of inertia of all bodies in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.quatf. In torch this resolves to @@ -1141,10 +1195,13 @@ def body_com_quat_w(self) -> wp.array: This quantity is the orientation of the principal axes of inertia of the articulation bodies. """ - return self._get_quat_from_transform(self._body_com_quat_w, self.body_com_pose_w) + self._body_com_quat_w = self._get_quat_from_transform(self._body_com_quat_w, self.body_com_pose_w.warp) + if self._body_com_quat_w_ta is None: + self._body_com_quat_w_ta = ProxyArray(self._body_com_quat_w) + return self._body_com_quat_w_ta @property - def body_com_lin_vel_w(self) -> wp.array: + def body_com_lin_vel_w(self) -> ProxyArray: """Linear velocity of all bodies in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to @@ -1152,10 +1209,13 @@ def body_com_lin_vel_w(self) -> wp.array: This quantity is the linear velocity of the articulation bodies' center of mass frame. """ - return self._get_top_from_spatial_vector(self._body_com_lin_vel_w, self.body_com_vel_w) + self._body_com_lin_vel_w = self._get_top_from_spatial_vector(self._body_com_lin_vel_w, self.body_com_vel_w.warp) + if self._body_com_lin_vel_w_ta is None: + self._body_com_lin_vel_w_ta = ProxyArray(self._body_com_lin_vel_w) + return self._body_com_lin_vel_w_ta @property - def body_com_ang_vel_w(self) -> wp.array: + def body_com_ang_vel_w(self) -> ProxyArray: """Angular velocity of all bodies in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to @@ -1163,10 +1223,15 @@ def body_com_ang_vel_w(self) -> wp.array: This quantity is the angular velocity of the articulation bodies' center of mass frame. """ - return self._get_bottom_from_spatial_vector(self._body_com_ang_vel_w, self.body_com_vel_w) + self._body_com_ang_vel_w = self._get_bottom_from_spatial_vector( + self._body_com_ang_vel_w, self.body_com_vel_w.warp + ) + if self._body_com_ang_vel_w_ta is None: + self._body_com_ang_vel_w_ta = ProxyArray(self._body_com_ang_vel_w) + return self._body_com_ang_vel_w_ta @property - def body_com_lin_acc_w(self) -> wp.array: + def body_com_lin_acc_w(self) -> ProxyArray: """Linear acceleration of all bodies in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to @@ -1174,10 +1239,13 @@ def body_com_lin_acc_w(self) -> wp.array: This quantity is the linear acceleration of the articulation bodies' center of mass frame. """ - return self._get_top_from_spatial_vector(self._body_com_lin_acc_w, self.body_com_acc_w) + self._body_com_lin_acc_w = self._get_top_from_spatial_vector(self._body_com_lin_acc_w, self.body_com_acc_w.warp) + if self._body_com_lin_acc_w_ta is None: + self._body_com_lin_acc_w_ta = ProxyArray(self._body_com_lin_acc_w) + return self._body_com_lin_acc_w_ta @property - def body_com_ang_acc_w(self) -> wp.array: + def body_com_ang_acc_w(self) -> ProxyArray: """Angular acceleration of all bodies in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to @@ -1185,10 +1253,15 @@ def body_com_ang_acc_w(self) -> wp.array: This quantity is the angular acceleration of the articulation bodies' center of mass frame. """ - return self._get_bottom_from_spatial_vector(self._body_com_ang_acc_w, self.body_com_acc_w) + self._body_com_ang_acc_w = self._get_bottom_from_spatial_vector( + self._body_com_ang_acc_w, self.body_com_acc_w.warp + ) + if self._body_com_ang_acc_w_ta is None: + self._body_com_ang_acc_w_ta = ProxyArray(self._body_com_ang_acc_w) + return self._body_com_ang_acc_w_ta @property - def body_com_quat_b(self) -> wp.array: + def body_com_quat_b(self) -> ProxyArray: """Orientation (x, y, z, w) of the principal axes of inertia of all of the bodies in their respective link frames. @@ -1197,7 +1270,10 @@ def body_com_quat_b(self) -> wp.array: This quantity is the orientation of the principal axes of inertia relative to its body's link frame. """ - return self._get_quat_from_transform(self._body_com_quat_b, self.body_com_pose_b) + self._body_com_quat_b = self._get_quat_from_transform(self._body_com_quat_b, self.body_com_pose_b.warp) + if self._body_com_quat_b_ta is None: + self._body_com_quat_b_ta = ProxyArray(self._body_com_quat_b) + return self._body_com_quat_b_ta def _create_simulation_bindings(self) -> None: """Create simulation bindings for the root data. @@ -1324,6 +1400,11 @@ def _create_simulation_bindings(self) -> None: (self._num_instances, 0), dtype=wp.float32, device=self.device ) + # Re-pin ProxyArray wrappers to the newly created sim bindings. + # On first init, _create_buffers() handles this after all buffers exist. + if hasattr(self, "_root_link_pose_w_ta"): + self._pin_proxy_arrays() + def _create_buffers(self) -> None: """Create buffers for the root data.""" super()._create_buffers() @@ -1429,7 +1510,6 @@ def _create_buffers(self) -> None: shape=(self._num_instances, self._num_joints), dtype=wp.float32, device=self.device ) # Empty memory pre-allocations - self._body_incoming_joint_wrench_b = None self._root_link_lin_vel_b = None self._root_link_ang_vel_b = None self._root_com_lin_vel_b = None @@ -1462,6 +1542,146 @@ def _create_buffers(self) -> None: self._body_com_ang_acc_w = None self._default_root_state = None + # Pin all ProxyArray wrappers to current buffers. + self._pin_proxy_arrays() + + def _pin_proxy_arrays(self) -> None: + """Create or rebind all pinned ProxyArray wrappers. + + Called from :meth:`_create_buffers` on first initialization and from + :meth:`_create_simulation_bindings` after a full simulation reset when + the solver recreates its internal arrays. + """ + is_rebind = hasattr(self, "_root_link_pose_w_ta") + + if is_rebind: + # Rebind sim-bound ProxyArrays to new solver arrays + self._root_link_pose_w_ta = ProxyArray(self._sim_bind_root_link_pose_w) + self._root_com_vel_w_ta = ProxyArray(self._sim_bind_root_com_vel_w) + self._body_link_pose_w_ta = ProxyArray(self._sim_bind_body_link_pose_w) + self._body_com_vel_w_ta = ProxyArray(self._sim_bind_body_com_vel_w) + self._joint_pos_ta = ProxyArray(self._sim_bind_joint_pos) + self._joint_vel_ta = ProxyArray(self._sim_bind_joint_vel) + self._joint_stiffness_ta = ProxyArray(self._sim_bind_joint_stiffness_sim) + self._joint_damping_ta = ProxyArray(self._sim_bind_joint_damping_sim) + self._joint_armature_ta = ProxyArray(self._sim_bind_joint_armature) + self._joint_friction_coeff_ta = ProxyArray(self._sim_bind_joint_friction_coeff) + self._joint_pos_limits_lower_ta = ProxyArray(self._sim_bind_joint_pos_limits_lower) + self._joint_pos_limits_upper_ta = ProxyArray(self._sim_bind_joint_pos_limits_upper) + self._joint_vel_limits_ta = ProxyArray(self._sim_bind_joint_vel_limits_sim) + self._joint_effort_limits_ta = ProxyArray(self._sim_bind_joint_effort_limits_sim) + self._body_mass_ta = ProxyArray(self._sim_bind_body_mass) + self._body_inertia_ta = ProxyArray(self._sim_bind_body_inertia) + self._body_com_pos_b_ta = ProxyArray(self._sim_bind_body_com_pos_b) + else: + # First-time creation: pin ProxyArrays to current buffers + # Category 1: sim-bound and pre-allocated buffers + # Sim-bound pointers are re-created on full reset; _create_simulation_bindings() + # calls rebind() on each ProxyArray to keep them in sync. + self._root_link_pose_w_ta = ProxyArray(self._sim_bind_root_link_pose_w) + self._root_com_vel_w_ta = ProxyArray(self._sim_bind_root_com_vel_w) + self._body_link_pose_w_ta = ProxyArray(self._sim_bind_body_link_pose_w) + self._body_com_vel_w_ta = ProxyArray(self._sim_bind_body_com_vel_w) + self._joint_pos_ta = ProxyArray(self._sim_bind_joint_pos) + self._joint_vel_ta = ProxyArray(self._sim_bind_joint_vel) + self._default_root_pose_ta = ProxyArray(self._default_root_pose) + self._default_root_vel_ta = ProxyArray(self._default_root_vel) + self._default_joint_pos_ta = ProxyArray(self._default_joint_pos) + self._default_joint_vel_ta = ProxyArray(self._default_joint_vel) + self._joint_pos_target_ta = ProxyArray(self._joint_pos_target) + self._joint_vel_target_ta = ProxyArray(self._joint_vel_target) + self._joint_effort_target_ta = ProxyArray(self._joint_effort_target) + self._computed_torque_ta = ProxyArray(self._computed_torque) + self._applied_torque_ta = ProxyArray(self._applied_torque) + self._joint_stiffness_ta = ProxyArray(self._sim_bind_joint_stiffness_sim) + self._joint_damping_ta = ProxyArray(self._sim_bind_joint_damping_sim) + self._joint_armature_ta = ProxyArray(self._sim_bind_joint_armature) + self._joint_friction_coeff_ta = ProxyArray(self._sim_bind_joint_friction_coeff) + self._joint_pos_limits_lower_ta = ProxyArray(self._sim_bind_joint_pos_limits_lower) + self._joint_pos_limits_upper_ta = ProxyArray(self._sim_bind_joint_pos_limits_upper) + self._joint_vel_limits_ta = ProxyArray(self._sim_bind_joint_vel_limits_sim) + self._joint_effort_limits_ta = ProxyArray(self._sim_bind_joint_effort_limits_sim) + self._soft_joint_pos_limits_ta = ProxyArray(self._soft_joint_pos_limits) + self._soft_joint_vel_limits_ta = ProxyArray(self._soft_joint_vel_limits) + self._gear_ratio_ta = ProxyArray(self._gear_ratio) + self._body_mass_ta = ProxyArray(self._sim_bind_body_mass) + self._body_inertia_ta = ProxyArray(self._sim_bind_body_inertia) + self._body_com_pos_b_ta = ProxyArray(self._sim_bind_body_com_pos_b) + + # Category 2: TimestampedBuffer properties + self._root_link_vel_w_ta = ProxyArray(self._root_link_vel_w.data) + self._body_link_vel_w_ta = ProxyArray(self._body_link_vel_w.data) + self._root_com_pose_w_ta = ProxyArray(self._root_com_pose_w.data) + self._body_com_pose_w_ta = ProxyArray(self._body_com_pose_w.data) + self._body_com_acc_w_ta = ProxyArray(self._body_com_acc_w.data) + self._body_com_pose_b_ta = ProxyArray(self._body_com_pose_b.data) + self._projected_gravity_b_ta = ProxyArray(self._projected_gravity_b.data) + self._heading_w_ta = ProxyArray(self._heading_w.data) + self._joint_acc_ta = ProxyArray(self._joint_acc.data) + + # -- deprecated state properties (lazy); type annotations declared once here + self._root_state_w_ta: ProxyArray | None = None + self._root_link_state_w_ta: ProxyArray | None = None + self._root_com_state_w_ta: ProxyArray | None = None + self._default_root_state_ta: ProxyArray | None = None + self._body_state_w_ta: ProxyArray | None = None + self._body_link_state_w_ta: ProxyArray | None = None + self._body_com_state_w_ta: ProxyArray | None = None + + # Invalidate lazy sliced ProxyArrays AND their backing wp.arrays so they are + # re-created from fresh data on next access. On first init the backing fields + # are already None (set by _create_buffers), so the assignments below are + # harmless no-ops. On rebind they reset stale pointers into freed transform + # memory after a sim reset. + self._root_link_pos_w_ta: ProxyArray | None = None + self._root_link_pos_w = None + self._root_link_quat_w_ta: ProxyArray | None = None + self._root_link_quat_w = None + self._root_link_lin_vel_w_ta: ProxyArray | None = None + self._root_link_lin_vel_w = None + self._root_link_ang_vel_w_ta: ProxyArray | None = None + self._root_link_ang_vel_w = None + self._root_com_pos_w_ta: ProxyArray | None = None + self._root_com_pos_w = None + self._root_com_quat_w_ta: ProxyArray | None = None + self._root_com_quat_w = None + self._root_com_lin_vel_w_ta: ProxyArray | None = None + self._root_com_lin_vel_w = None + self._root_com_ang_vel_w_ta: ProxyArray | None = None + self._root_com_ang_vel_w = None + self._body_link_pos_w_ta: ProxyArray | None = None + self._body_link_pos_w = None + self._body_link_quat_w_ta: ProxyArray | None = None + self._body_link_quat_w = None + self._body_link_lin_vel_w_ta: ProxyArray | None = None + self._body_link_lin_vel_w = None + self._body_link_ang_vel_w_ta: ProxyArray | None = None + self._body_link_ang_vel_w = None + self._body_com_pos_w_ta: ProxyArray | None = None + self._body_com_pos_w = None + self._body_com_quat_w_ta: ProxyArray | None = None + self._body_com_quat_w = None + self._body_com_lin_vel_w_ta: ProxyArray | None = None + self._body_com_lin_vel_w = None + self._body_com_ang_vel_w_ta: ProxyArray | None = None + self._body_com_ang_vel_w = None + self._body_com_lin_acc_w_ta: ProxyArray | None = None + self._body_com_lin_acc_w = None + self._body_com_ang_acc_w_ta: ProxyArray | None = None + self._body_com_ang_acc_w = None + self._body_com_quat_b_ta: ProxyArray | None = None + self._body_com_quat_b = None + self._joint_pos_limits_ta: ProxyArray | None = None + self._joint_pos_limits = None + self._root_link_lin_vel_b_ta: ProxyArray | None = None + self._root_link_lin_vel_b = None + self._root_link_ang_vel_b_ta: ProxyArray | None = None + self._root_link_ang_vel_b = None + self._root_com_lin_vel_b_ta: ProxyArray | None = None + self._root_com_lin_vel_b = None + self._root_com_ang_vel_b_ta: ProxyArray | None = None + self._root_com_ang_vel_b = None + """ Internal helpers. """ @@ -1666,7 +1886,7 @@ def _get_bottom_from_spatial_vector(self, source: wp.array | None, spatial_vecto """ @property - def root_state_w(self) -> wp.array: + def root_state_w(self) -> ProxyArray: """Deprecated, same as :attr:`root_link_pose_w` and :attr:`root_com_vel_w`.""" warnings.warn( "The `root_state_w` property will be deprecated in a IsaacLab 4.0. Please use `root_link_pose_w` and " @@ -1678,13 +1898,14 @@ def root_state_w(self) -> wp.array: self._root_state_w = TimestampedBuffer( shape=(self._num_instances,), dtype=shared_kernels.vec13f, device=self.device ) + self._root_state_w_ta = ProxyArray(self._root_state_w.data) if self._root_state_w.timestamp < self._sim_timestamp: wp.launch( shared_kernels.concat_root_pose_and_vel_to_state, dim=(self._num_instances), inputs=[ - self.root_link_pose_w, - self.root_com_vel_w, + self.root_link_pose_w.warp, + self.root_com_vel_w.warp, ], outputs=[ self._root_state_w.data, @@ -1693,10 +1914,10 @@ def root_state_w(self) -> wp.array: ) self._root_state_w.timestamp = self._sim_timestamp - return self._root_state_w.data + return self._root_state_w_ta @property - def root_link_state_w(self) -> wp.array: + def root_link_state_w(self) -> ProxyArray: """Deprecated, same as :attr:`root_link_pose_w` and :attr:`root_link_vel_w`.""" warnings.warn( "The `root_link_state_w` property will be deprecated in a IsaacLab 4.0. Please use `root_link_pose_w` and " @@ -1708,13 +1929,14 @@ def root_link_state_w(self) -> wp.array: self._root_link_state_w = TimestampedBuffer( shape=(self._num_instances,), dtype=shared_kernels.vec13f, device=self.device ) + self._root_link_state_w_ta = ProxyArray(self._root_link_state_w.data) if self._root_link_state_w.timestamp < self._sim_timestamp: wp.launch( shared_kernels.concat_root_pose_and_vel_to_state, dim=self._num_instances, inputs=[ - self.root_link_pose_w, - self.root_link_vel_w, + self.root_link_pose_w.warp, + self.root_link_vel_w.warp, ], outputs=[ self._root_link_state_w.data, @@ -1723,10 +1945,10 @@ def root_link_state_w(self) -> wp.array: ) self._root_link_state_w.timestamp = self._sim_timestamp - return self._root_link_state_w.data + return self._root_link_state_w_ta @property - def root_com_state_w(self) -> wp.array: + def root_com_state_w(self) -> ProxyArray: """Deprecated, same as :attr:`root_com_pose_w` and :attr:`root_com_vel_w`.""" warnings.warn( "The `root_com_state_w` property will be deprecated in a IsaacLab 4.0. Please use `root_com_pose_w` and " @@ -1738,13 +1960,14 @@ def root_com_state_w(self) -> wp.array: self._root_com_state_w = TimestampedBuffer( shape=(self._num_instances,), dtype=shared_kernels.vec13f, device=self.device ) + self._root_com_state_w_ta = ProxyArray(self._root_com_state_w.data) if self._root_com_state_w.timestamp < self._sim_timestamp: wp.launch( shared_kernels.concat_root_pose_and_vel_to_state, dim=self._num_instances, inputs=[ - self.root_com_pose_w, - self.root_com_vel_w, + self.root_com_pose_w.warp, + self.root_com_vel_w.warp, ], outputs=[ self._root_com_state_w.data, @@ -1753,10 +1976,10 @@ def root_com_state_w(self) -> wp.array: ) self._root_com_state_w.timestamp = self._sim_timestamp - return self._root_com_state_w.data + return self._root_com_state_w_ta @property - def default_root_state(self) -> wp.array: + def default_root_state(self) -> ProxyArray: """Default root state ``[pos, quat, lin_vel, ang_vel]`` in the local environment frame. @@ -1773,6 +1996,7 @@ def default_root_state(self) -> wp.array: ) if self._default_root_state is None: self._default_root_state = wp.zeros((self._num_instances), dtype=shared_kernels.vec13f, device=self.device) + self._default_root_state_ta = ProxyArray(self._default_root_state) wp.launch( shared_kernels.concat_root_pose_and_vel_to_state, dim=self._num_instances, @@ -1785,10 +2009,10 @@ def default_root_state(self) -> wp.array: ], device=self.device, ) - return self._default_root_state + return self._default_root_state_ta @property - def body_state_w(self): + def body_state_w(self) -> ProxyArray: """State of all bodies `[pos, quat, lin_vel, ang_vel]` in simulation world frame. Shape is (num_instances, num_bodies, 13). @@ -1805,13 +2029,14 @@ def body_state_w(self): self._body_state_w = TimestampedBuffer( (self._num_instances, self._num_bodies), self.device, shared_kernels.vec13f ) + self._body_state_w_ta = ProxyArray(self._body_state_w.data) if self._body_state_w.timestamp < self._sim_timestamp: wp.launch( shared_kernels.concat_body_pose_and_vel_to_state, dim=(self._num_instances, self._num_bodies), inputs=[ - self.body_link_pose_w, - self.body_com_vel_w, + self.body_link_pose_w.warp, + self.body_com_vel_w.warp, ], outputs=[ self._body_state_w.data, @@ -1820,10 +2045,10 @@ def body_state_w(self): ) self._body_state_w.timestamp = self._sim_timestamp - return self._body_state_w.data + return self._body_state_w_ta @property - def body_link_state_w(self): + def body_link_state_w(self) -> ProxyArray: """State of all bodies' link frame`[pos, quat, lin_vel, ang_vel]` in simulation world frame. Shape is (num_instances, num_bodies, 13). @@ -1839,13 +2064,14 @@ def body_link_state_w(self): self._body_link_state_w = TimestampedBuffer( (self._num_instances, self._num_bodies), self.device, shared_kernels.vec13f ) + self._body_link_state_w_ta = ProxyArray(self._body_link_state_w.data) if self._body_link_state_w.timestamp < self._sim_timestamp: wp.launch( shared_kernels.concat_body_pose_and_vel_to_state, dim=(self._num_instances, self._num_bodies), inputs=[ - self.body_link_pose_w, - self.body_link_vel_w, + self.body_link_pose_w.warp, + self.body_link_vel_w.warp, ], outputs=[ self._body_link_state_w.data, @@ -1854,10 +2080,10 @@ def body_link_state_w(self): ) self._body_link_state_w.timestamp = self._sim_timestamp - return self._body_link_state_w.data + return self._body_link_state_w_ta @property - def body_com_state_w(self): + def body_com_state_w(self) -> ProxyArray: """State of all bodies center of mass `[pos, quat, lin_vel, ang_vel]` in simulation world frame. Shape is (num_instances, num_bodies, 13). @@ -1875,13 +2101,14 @@ def body_com_state_w(self): self._body_com_state_w = TimestampedBuffer( (self._num_instances, self._num_bodies), self.device, shared_kernels.vec13f ) + self._body_com_state_w_ta = ProxyArray(self._body_com_state_w.data) if self._body_com_state_w.timestamp < self._sim_timestamp: wp.launch( shared_kernels.concat_body_pose_and_vel_to_state, dim=(self._num_instances, self._num_bodies), inputs=[ - self.body_com_pose_w, - self.body_com_vel_w, + self.body_com_pose_w.warp, + self.body_com_vel_w.warp, ], outputs=[ self._body_com_state_w.data, @@ -1890,4 +2117,4 @@ def body_com_state_w(self): ) self._body_com_state_w.timestamp = self._sim_timestamp - return self._body_com_state_w.data + return self._body_com_state_w_ta diff --git a/source/isaaclab_newton/isaaclab_newton/assets/articulation/kernels.py b/source/isaaclab_newton/isaaclab_newton/assets/articulation/kernels.py index 6dc714d4e9ce..5e66b867c09a 100644 --- a/source/isaaclab_newton/isaaclab_newton/assets/articulation/kernels.py +++ b/source/isaaclab_newton/isaaclab_newton/assets/articulation/kernels.py @@ -123,6 +123,67 @@ def write_joint_vel_data_mask( joint_acc[i, j] = 0.0 +@wp.kernel +def write_joint_state_data_index( + pos_data: wp.array2d(dtype=wp.float32), + vel_data: wp.array2d(dtype=wp.float32), + env_ids: wp.array(dtype=wp.int32), + joint_ids: wp.array(dtype=wp.int32), + joint_pos: wp.array2d(dtype=wp.float32), + joint_vel: wp.array2d(dtype=wp.float32), + prev_joint_vel: wp.array2d(dtype=wp.float32), + joint_acc: wp.array2d(dtype=wp.float32), +): + """Write joint position and velocity data in a single kernel launch. + + Args: + pos_data: Input joint positions. Shape is (num_selected_envs, num_selected_joints). + vel_data: Input joint velocities. Shape is (num_selected_envs, num_selected_joints). + env_ids: Environment indices. Shape is (num_selected_envs,). + joint_ids: Joint indices. Shape is (num_selected_joints,). + joint_pos: Output joint positions. Shape is (num_envs, num_joints). + joint_vel: Output joint velocities. Shape is (num_envs, num_joints). + prev_joint_vel: Output previous joint velocities. Shape is (num_envs, num_joints). + joint_acc: Output joint accelerations (reset to 0). Shape is (num_envs, num_joints). + """ + i, j = wp.tid() + joint_pos[env_ids[i], joint_ids[j]] = pos_data[i, j] + joint_vel[env_ids[i], joint_ids[j]] = vel_data[i, j] + prev_joint_vel[env_ids[i], joint_ids[j]] = vel_data[i, j] + joint_acc[env_ids[i], joint_ids[j]] = 0.0 + + +@wp.kernel +def write_joint_state_data_mask( + pos_data: wp.array2d(dtype=wp.float32), + vel_data: wp.array2d(dtype=wp.float32), + env_mask: wp.array(dtype=wp.bool), + joint_mask: wp.array(dtype=wp.bool), + joint_pos: wp.array2d(dtype=wp.float32), + joint_vel: wp.array2d(dtype=wp.float32), + prev_joint_vel: wp.array2d(dtype=wp.float32), + joint_acc: wp.array2d(dtype=wp.float32), +): + """Write joint position and velocity data in a single kernel launch using masks. + + Args: + pos_data: Input joint positions. Shape is (num_envs, num_joints). + vel_data: Input joint velocities. Shape is (num_envs, num_joints). + env_mask: Environment mask. Shape is (num_envs,). + joint_mask: Joint mask. Shape is (num_joints,). + joint_pos: Output joint positions. Shape is (num_envs, num_joints). + joint_vel: Output joint velocities. Shape is (num_envs, num_joints). + prev_joint_vel: Output previous joint velocities. Shape is (num_envs, num_joints). + joint_acc: Output joint accelerations (reset to 0). Shape is (num_envs, num_joints). + """ + i, j = wp.tid() + if env_mask[i] and joint_mask[j]: + joint_pos[i, j] = pos_data[i, j] + joint_vel[i, j] = vel_data[i, j] + prev_joint_vel[i, j] = vel_data[i, j] + joint_acc[i, j] = 0.0 + + @wp.kernel def write_joint_limit_data_to_buffer_index( in_data: wp.array2d(dtype=wp.vec2f), diff --git a/source/isaaclab_newton/isaaclab_newton/assets/kernels.py b/source/isaaclab_newton/isaaclab_newton/assets/kernels.py index 9a9aaf402d87..a6435af0dbb8 100644 --- a/source/isaaclab_newton/isaaclab_newton/assets/kernels.py +++ b/source/isaaclab_newton/isaaclab_newton/assets/kernels.py @@ -472,29 +472,18 @@ def set_root_link_pose_to_sim_index( data: wp.array(dtype=wp.transformf), env_ids: wp.array(dtype=wp.int32), root_link_pose_w: wp.array(dtype=wp.transformf), - root_link_state_w: wp.array(dtype=vec13f), - root_state_w: wp.array(dtype=vec13f), ): """Write root link pose data to simulation buffers. - This kernel writes root link poses from the input array to the output buffers - and optionally updates the corresponding state vectors. + This kernel writes root link poses from the input array to the output buffer. Args: data: Input array of root link poses. Shape is (num_selected_envs,). env_ids: Input array of environment indices to write to. Shape is (num_selected_envs,). root_link_pose_w: Output array where root link poses are written. Shape is (num_envs,). - root_link_state_w: Output array where root link states are updated (pose portion). - Shape is (num_envs,). Can be None if not needed. - root_state_w: Output array where root states are updated (pose portion). - Shape is (num_envs,). Can be None if not needed. """ i = wp.tid() root_link_pose_w[env_ids[i]] = data[i] - if root_link_state_w: - root_link_state_w[env_ids[i]] = set_state_transforms_func(root_link_state_w[env_ids[i]], data[i]) - if root_state_w: - root_state_w[env_ids[i]] = set_state_transforms_func(root_state_w[env_ids[i]], data[i]) @wp.kernel @@ -502,30 +491,19 @@ def set_root_link_pose_to_sim_mask( data: wp.array(dtype=wp.transformf), env_mask: wp.array(dtype=wp.bool), root_link_pose_w: wp.array(dtype=wp.transformf), - root_link_state_w: wp.array(dtype=vec13f), - root_state_w: wp.array(dtype=vec13f), ): """Write root link pose data to simulation buffers. - This kernel writes root link poses from the input array to the output buffers - and optionally updates the corresponding state vectors. + This kernel writes root link poses from the input array to the output buffer. Args: data: Input array of root link poses. Shape is (num_instances,). env_mask: Input array of environment mask. Shape is (num_instances,). root_link_pose_w: Output array where root link poses are written. Shape is (num_envs,). - root_link_state_w: Output array where root link states are updated (pose portion). - Shape is (num_envs,). Can be None if not needed. - root_state_w: Output array where root states are updated (pose portion). - Shape is (num_envs,). Can be None if not needed. """ i = wp.tid() if env_mask[i]: root_link_pose_w[i] = data[i] - if root_link_state_w: - root_link_state_w[i] = set_state_transforms_func(root_link_state_w[i], data[i]) - if root_state_w: - root_state_w[i] = set_state_transforms_func(root_state_w[i], data[i]) @wp.kernel @@ -535,15 +513,11 @@ def set_root_com_pose_to_sim_index( env_ids: wp.array(dtype=wp.int32), root_com_pose_w: wp.array(dtype=wp.transformf), root_link_pose_w: wp.array(dtype=wp.transformf), - root_com_state_w: wp.array(dtype=vec13f), - root_link_state_w: wp.array(dtype=vec13f), - root_state_w: wp.array(dtype=vec13f), ): """Write root COM pose data to simulation buffers. - This kernel writes root COM poses from the input array to the output buffers, - computes the corresponding link pose from the COM pose, and optionally updates - the corresponding state vectors. + This kernel writes root COM poses from the input array to the output buffers + and computes the corresponding link pose from the COM pose. Args: data: Input array of root COM poses. Shape is (num_selected_envs,). @@ -553,27 +527,13 @@ def set_root_com_pose_to_sim_index( root_com_pose_w: Output array where root COM poses are written. Shape is (num_envs,). root_link_pose_w: Output array where root link poses (derived from COM) are written. Shape is (num_envs,). - root_com_state_w: Output array where root COM states are updated (pose portion). - Shape is (num_envs,). Can be None if not needed. - root_link_state_w: Output array where root link states are updated (pose portion). - Shape is (num_envs,). Can be None if not needed. - root_state_w: Output array where root states are updated (pose portion). - Shape is (num_envs,). Can be None if not needed. """ i = wp.tid() root_com_pose_w[env_ids[i]] = data[i] - if root_com_state_w: - root_com_state_w[env_ids[i]] = set_state_transforms_func(root_com_state_w[env_ids[i]], data[i]) # Get the com pose in the link frame root_link_pose_w[env_ids[i]] = get_com_pose_in_link_frame_func( root_com_pose_w[env_ids[i]], body_com_pos_b[env_ids[i], 0] ) - if root_link_state_w: - root_link_state_w[env_ids[i]] = set_state_transforms_func( - root_link_state_w[env_ids[i]], root_link_pose_w[env_ids[i]] - ) - if root_state_w: - root_state_w[env_ids[i]] = set_state_transforms_func(root_state_w[env_ids[i]], root_link_pose_w[env_ids[i]]) @wp.kernel @@ -583,15 +543,11 @@ def set_root_com_pose_to_sim_mask( env_mask: wp.array(dtype=wp.bool), root_com_pose_w: wp.array(dtype=wp.transformf), root_link_pose_w: wp.array(dtype=wp.transformf), - root_com_state_w: wp.array(dtype=vec13f), - root_link_state_w: wp.array(dtype=vec13f), - root_state_w: wp.array(dtype=vec13f), ): """Write root COM pose data to simulation buffers. - This kernel writes root COM poses from the input array to the output buffers, - computes the corresponding link pose from the COM pose, and optionally updates - the corresponding state vectors. + This kernel writes root COM poses from the input array to the output buffers + and computes the corresponding link pose from the COM pose. Args: data: Input array of root COM poses. Shape is (num_instances,). @@ -601,24 +557,12 @@ def set_root_com_pose_to_sim_mask( root_com_pose_w: Output array where root COM poses are written. Shape is (num_envs,). root_link_pose_w: Output array where root link poses (derived from COM) are written. Shape is (num_envs,). - root_com_state_w: Output array where root COM states are updated (pose portion). - Shape is (num_envs,). Can be None if not needed. - root_link_state_w: Output array where root link states are updated (pose portion). - Shape is (num_envs,). Can be None if not needed. - root_state_w: Output array where root states are updated (pose portion). - Shape is (num_envs,). Can be None if not needed. """ i = wp.tid() if env_mask[i]: root_com_pose_w[i] = data[i] - if root_com_state_w: - root_com_state_w[i] = set_state_transforms_func(root_com_state_w[i], data[i]) # Get the com pose in the link frame root_link_pose_w[i] = get_com_pose_in_link_frame_func(root_com_pose_w[i], body_com_pos_b[i, 0]) - if root_link_state_w: - root_link_state_w[i] = set_state_transforms_func(root_link_state_w[i], root_link_pose_w[i]) - if root_state_w: - root_state_w[i] = set_state_transforms_func(root_state_w[i], root_link_pose_w[i]) @wp.kernel @@ -628,14 +572,11 @@ def set_root_com_velocity_to_sim_index( num_bodies: wp.int32, root_com_velocity_w: wp.array(dtype=wp.spatial_vectorf), body_acc_w: wp.array2d(dtype=wp.spatial_vectorf), - root_state_w: wp.array(dtype=vec13f), - root_com_state_w: wp.array(dtype=vec13f), ): """Write root COM velocity data to simulation buffers. - This kernel writes root COM velocities from the input array to the output buffers, - optionally updates the corresponding state vectors, and zeros out the body - acceleration buffer to prevent reporting stale values. + This kernel writes root COM velocities from the input array to the output buffers + and zeros out the body acceleration buffer to prevent reporting stale values. Args: data: Input array of root COM spatial velocities. Shape is (num_selected_envs,). @@ -644,17 +585,9 @@ def set_root_com_velocity_to_sim_index( root_com_velocity_w: Output array where root COM velocities are written. Shape is (num_envs,). body_acc_w: Output array where body accelerations are zeroed. Shape is (num_envs, num_bodies). - root_state_w: Output array where root states are updated (velocity portion). - Shape is (num_envs,). Can be None if not needed. - root_com_state_w: Output array where root COM states are updated (velocity portion). - Shape is (num_envs,). Can be None if not needed. """ i = wp.tid() root_com_velocity_w[env_ids[i]] = data[i] - if root_state_w: - root_state_w[env_ids[i]] = set_state_velocities_func(root_state_w[env_ids[i]], data[i]) - if root_com_state_w: - root_com_state_w[env_ids[i]] = set_state_velocities_func(root_com_state_w[env_ids[i]], data[i]) # Make the acceleration zero to prevent reporting old values for j in range(num_bodies): body_acc_w[env_ids[i], j] = wp.spatial_vectorf(0.0, 0.0, 0.0, 0.0, 0.0, 0.0) @@ -667,14 +600,11 @@ def set_root_com_velocity_to_sim_mask( num_bodies: wp.int32, root_com_velocity_w: wp.array(dtype=wp.spatial_vectorf), body_acc_w: wp.array2d(dtype=wp.spatial_vectorf), - root_state_w: wp.array(dtype=vec13f), - root_com_state_w: wp.array(dtype=vec13f), ): """Write root COM velocity data to simulation buffers. - This kernel writes root COM velocities from the input array to the output buffers, - optionally updates the corresponding state vectors, and zeros out the body - acceleration buffer to prevent reporting stale values. + This kernel writes root COM velocities from the input array to the output buffers + and zeros out the body acceleration buffer to prevent reporting stale values. Args: data: Input array of root COM spatial velocities. Shape is (num_instances,). @@ -683,18 +613,10 @@ def set_root_com_velocity_to_sim_mask( root_com_velocity_w: Output array where root COM velocities are written. Shape is (num_envs,). body_acc_w: Output array where body accelerations are zeroed. Shape is (num_envs, num_bodies). - root_state_w: Output array where root states are updated (velocity portion). - Shape is (num_envs,). Can be None if not needed. - root_com_state_w: Output array where root COM states are updated (velocity portion). - Shape is (num_envs,). Can be None if not needed. """ i = wp.tid() if env_mask[i]: root_com_velocity_w[i] = data[i] - if root_state_w: - root_state_w[i] = set_state_velocities_func(root_state_w[i], data[i]) - if root_com_state_w: - root_com_state_w[i] = set_state_velocities_func(root_com_state_w[i], data[i]) # Make the acceleration zero to prevent reporting old values for j in range(num_bodies): body_acc_w[i, j] = wp.spatial_vectorf(0.0, 0.0, 0.0, 0.0, 0.0, 0.0) @@ -710,15 +632,12 @@ def set_root_link_velocity_to_sim_index( root_link_velocity_w: wp.array(dtype=wp.spatial_vectorf), root_com_velocity_w: wp.array(dtype=wp.spatial_vectorf), body_acc_w: wp.array2d(dtype=wp.spatial_vectorf), - root_link_state_w: wp.array(dtype=vec13f), - root_state_w: wp.array(dtype=vec13f), - root_com_state_w: wp.array(dtype=vec13f), ): """Write root link velocity data to simulation buffers. This kernel writes root link velocities from the input array to the output buffers, - computes the corresponding COM velocity from the link velocity, optionally updates - the corresponding state vectors, and zeros out the body acceleration buffer. + computes the corresponding COM velocity from the link velocity, and zeros out + the body acceleration buffer. Args: data: Input array of root link spatial velocities. Shape is (num_selected_envs,). @@ -733,27 +652,13 @@ def set_root_link_velocity_to_sim_index( are written. Shape is (num_envs,). body_acc_w: Output array where body accelerations are zeroed. Shape is (num_envs, num_bodies). - root_link_state_w: Output array where root link states are updated (velocity portion). - Shape is (num_envs,). Can be None if not needed. - root_state_w: Output array where root states are updated (velocity portion). - Shape is (num_envs,). Can be None if not needed. - root_com_state_w: Output array where root COM states are updated (velocity portion). - Shape is (num_envs,). Can be None if not needed. """ i = wp.tid() root_link_velocity_w[env_ids[i]] = data[i] - if root_link_state_w: - root_link_state_w[env_ids[i]] = set_state_velocities_func(root_link_state_w[env_ids[i]], data[i]) # Get the link velocity in the com frame root_com_velocity_w[env_ids[i]] = get_link_velocity_in_com_frame_func( root_link_velocity_w[env_ids[i]], link_pose_w[env_ids[i]], body_com_pos_b[env_ids[i], 0] ) - if root_com_state_w: - root_com_state_w[env_ids[i]] = set_state_velocities_func( - root_com_state_w[env_ids[i]], root_com_velocity_w[env_ids[i]] - ) - if root_state_w: - root_state_w[env_ids[i]] = set_state_velocities_func(root_state_w[env_ids[i]], root_com_velocity_w[env_ids[i]]) # Make the acceleration zero to prevent reporting old values for j in range(num_bodies): body_acc_w[env_ids[i], j] = wp.spatial_vectorf(0.0, 0.0, 0.0, 0.0, 0.0, 0.0) @@ -769,15 +674,12 @@ def set_root_link_velocity_to_sim_mask( root_link_velocity_w: wp.array(dtype=wp.spatial_vectorf), root_com_velocity_w: wp.array(dtype=wp.spatial_vectorf), body_acc_w: wp.array2d(dtype=wp.spatial_vectorf), - root_link_state_w: wp.array(dtype=vec13f), - root_state_w: wp.array(dtype=vec13f), - root_com_state_w: wp.array(dtype=vec13f), ): """Write root link velocity data to simulation buffers. This kernel writes root link velocities from the input array to the output buffers, - computes the corresponding COM velocity from the link velocity, optionally updates - the corresponding state vectors, and zeros out the body acceleration buffer. + computes the corresponding COM velocity from the link velocity, and zeros out + the body acceleration buffer. Args: data: Input array of root link spatial velocities. Shape is (num_instances,). @@ -792,26 +694,14 @@ def set_root_link_velocity_to_sim_mask( are written. Shape is (num_envs,). body_acc_w: Output array where body accelerations are zeroed. Shape is (num_envs, num_bodies). - root_link_state_w: Output array where root link states are updated (velocity portion). - Shape is (num_envs,). Can be None if not needed. - root_state_w: Output array where root states are updated (velocity portion). - Shape is (num_envs,). Can be None if not needed. - root_com_state_w: Output array where root COM states are updated (velocity portion). - Shape is (num_envs,). Can be None if not needed. """ i = wp.tid() if env_mask[i]: root_link_velocity_w[i] = data[i] - if root_link_state_w: - root_link_state_w[i] = set_state_velocities_func(root_link_state_w[i], data[i]) # Get the link velocity in the com frame root_com_velocity_w[i] = get_link_velocity_in_com_frame_func( root_link_velocity_w[i], link_pose_w[i], body_com_pos_b[i, 0] ) - if root_com_state_w: - root_com_state_w[i] = set_state_velocities_func(root_com_state_w[i], root_com_velocity_w[i]) - if root_state_w: - root_state_w[i] = set_state_velocities_func(root_state_w[i], root_com_velocity_w[i]) # Make the acceleration zero to prevent reporting old values for j in range(num_bodies): body_acc_w[i, j] = wp.spatial_vectorf(0.0, 0.0, 0.0, 0.0, 0.0, 0.0) diff --git a/source/isaaclab_newton/isaaclab_newton/assets/rigid_object/rigid_object.py b/source/isaaclab_newton/isaaclab_newton/assets/rigid_object/rigid_object.py index 5e02e3622985..7e31fa22b60f 100644 --- a/source/isaaclab_newton/isaaclab_newton/assets/rigid_object/rigid_object.py +++ b/source/isaaclab_newton/isaaclab_newton/assets/rigid_object/rigid_object.py @@ -143,40 +143,23 @@ def write_data_to_sim(self) -> None: # write external wrench if self._instantaneous_wrench_composer.active or self._permanent_wrench_composer.active: if self._instantaneous_wrench_composer.active: - # Compose instantaneous wrench with permanent wrench - self._instantaneous_wrench_composer.add_forces_and_torques_index( - forces=self._permanent_wrench_composer.composed_force, - torques=self._permanent_wrench_composer.composed_torque, - body_ids=self._ALL_BODY_INDICES, - env_ids=self._ALL_INDICES, - ) - # Apply both instantaneous and permanent wrench to the simulation - wp.launch( - shared_kernels.update_wrench_array_with_force_and_torque, - dim=(self.num_instances, self.num_bodies), - device=self.device, - inputs=[ - self._instantaneous_wrench_composer.composed_force, - self._instantaneous_wrench_composer.composed_torque, - self._data._sim_bind_body_external_wrench, - self._ALL_ENV_MASK, - self._ALL_BODY_MASK, - ], - ) + composer = self._instantaneous_wrench_composer + composer.add_raw_buffers_from(self._permanent_wrench_composer) else: - # Apply permanent wrench to the simulation - wp.launch( - shared_kernels.update_wrench_array_with_force_and_torque, - dim=(self.num_instances, self.num_bodies), - device=self.device, - inputs=[ - self._permanent_wrench_composer.composed_force, - self._permanent_wrench_composer.composed_torque, - self._data._sim_bind_body_external_wrench, - self._ALL_ENV_MASK, - self._ALL_BODY_MASK, - ], - ) + composer = self._permanent_wrench_composer + composer.compose_to_body_frame() + wp.launch( + shared_kernels.update_wrench_array_with_force_and_torque, + dim=(self.num_instances, self.num_bodies), + device=self.device, + inputs=[ + composer.out_force_b, + composer.out_torque_b, + self._data._sim_bind_body_external_wrench, + self._ALL_ENV_MASK, + self._ALL_BODY_MASK, + ], + ) self._instantaneous_wrench_composer.reset() def update(self, dt: float) -> None: @@ -326,6 +309,9 @@ def write_root_link_pose_to_sim_index( root_pose: Root link poses in simulation frame. Shape is (len(env_ids), 7) or (num_instances, 7), or (len(env_ids),) / (num_instances,) with dtype wp.transformf. env_ids: Environment indices. If None, then all indices are used. + + Note: + Triggers per-environment FK recomputation and solver reset (Kamino) for the affected environments. """ # resolve all indices env_ids = self._resolve_env_ids(env_ids) @@ -340,8 +326,6 @@ def write_root_link_pose_to_sim_index( ], outputs=[ self.data.root_link_pose_w, - None, # self.data._root_link_state_w.data, - None, # self.data._root_state_w.data, ], device=self.device, ) @@ -350,6 +334,7 @@ def write_root_link_pose_to_sim_index( self.data._root_link_state_w.timestamp = -1.0 if self.data._root_state_w is not None: self.data._root_state_w.timestamp = -1.0 + SimulationManager.invalidate_fk(env_ids=env_ids, articulation_ids=self._root_view.articulation_ids) def write_root_link_pose_to_sim_mask( self, @@ -372,6 +357,9 @@ def write_root_link_pose_to_sim_mask( root_pose: Root poses in simulation frame. Shape is (num_instances, 7) or (num_instances,) with dtype wp.transformf. env_mask: Environment mask. If None, then all the instances are updated. Shape is (num_instances,). + + Note: + Triggers per-environment FK recomputation and solver reset (Kamino) for the affected environments. """ if env_mask is None: env_mask = self._ALL_ENV_MASK @@ -386,8 +374,6 @@ def write_root_link_pose_to_sim_mask( ], outputs=[ self.data.root_link_pose_w, - None, # self.data._root_link_state_w.data, - None, # self.data._root_state_w.data, ], device=self.device, ) @@ -396,6 +382,7 @@ def write_root_link_pose_to_sim_mask( self.data._root_link_state_w.timestamp = -1.0 if self.data._root_state_w is not None: self.data._root_state_w.timestamp = -1.0 + SimulationManager.invalidate_fk(env_mask=env_mask, articulation_ids=self._root_view.articulation_ids) def write_root_com_pose_to_sim_index( self, @@ -419,6 +406,9 @@ def write_root_com_pose_to_sim_index( root_pose: Root center of mass poses in simulation frame. Shape is (len(env_ids), 7) or (num_instances, 7), or (len(env_ids),) / (num_instances,) with dtype wp.transformf. env_ids: Environment indices. If None, then all indices are used. + + Note: + Triggers per-environment FK recomputation and solver reset (Kamino) for the affected environments. """ # resolve all indices env_ids = self._resolve_env_ids(env_ids) @@ -437,9 +427,6 @@ def write_root_com_pose_to_sim_index( outputs=[ self.data.root_com_pose_w, self.data.root_link_pose_w, - None, # self.data._root_com_state_w.data, - None, # self.data._root_link_state_w.data, - None, # self.data._root_state_w.data, ], device=self.device, ) @@ -450,6 +437,7 @@ def write_root_com_pose_to_sim_index( self.data._root_link_state_w.timestamp = -1.0 if self.data._root_state_w is not None: self.data._root_state_w.timestamp = -1.0 + SimulationManager.invalidate_fk(env_ids=env_ids, articulation_ids=self._root_view.articulation_ids) def write_root_com_pose_to_sim_mask( self, @@ -473,6 +461,9 @@ def write_root_com_pose_to_sim_mask( root_pose: Root center of mass poses in simulation frame. Shape is (num_instances, 7) or (num_instances,) with dtype wp.transformf. env_mask: Environment mask. If None, then all the instances are updated. Shape is (num_instances,). + + Note: + Triggers per-environment FK recomputation and solver reset (Kamino) for the affected environments. """ if env_mask is None: env_mask = self._ALL_ENV_MASK @@ -488,9 +479,6 @@ def write_root_com_pose_to_sim_mask( outputs=[ self.data.root_com_pose_w, self.data.root_link_pose_w, - None, # self.data._root_com_state_w.data, - None, # self.data._root_link_state_w.data, - None, # self.data._root_state_w.data, ], device=self.device, ) @@ -501,6 +489,7 @@ def write_root_com_pose_to_sim_mask( self.data._root_link_state_w.timestamp = -1.0 if self.data._root_state_w is not None: self.data._root_state_w.timestamp = -1.0 + SimulationManager.invalidate_fk(env_mask=env_mask, articulation_ids=self._root_view.articulation_ids) def write_root_com_velocity_to_sim_index( self, @@ -527,6 +516,9 @@ def write_root_com_velocity_to_sim_index( Shape is (len(env_ids), 6) or (num_instances, 6), or (len(env_ids),) / (num_instances,) with dtype wp.spatial_vectorf. env_ids: Environment indices. If None, then all indices are used. + + Note: + Triggers per-environment FK recomputation and solver reset (Kamino) for the affected environments. """ # resolve all indices env_ids = self._resolve_env_ids(env_ids) @@ -543,8 +535,6 @@ def write_root_com_velocity_to_sim_index( outputs=[ self.data.root_com_vel_w, self.data.body_com_acc_w, - None, # self.data._root_state_w.data, - None, # self.data._root_com_state_w.data, ], device=self.device, ) @@ -552,6 +542,7 @@ def write_root_com_velocity_to_sim_index( self.data._root_state_w.timestamp = -1.0 if self.data._root_com_state_w is not None: self.data._root_com_state_w.timestamp = -1.0 + SimulationManager.invalidate_fk(env_ids=env_ids, articulation_ids=self._root_view.articulation_ids) def write_root_com_velocity_to_sim_mask( self, @@ -577,6 +568,9 @@ def write_root_com_velocity_to_sim_mask( root_velocity: Root center of mass velocities in simulation world frame. Shape is (num_instances, 6) or (num_instances,) with dtype wp.spatial_vectorf. env_mask: Environment mask. If None, then all the instances are updated. Shape is (num_instances,). + + Note: + Triggers per-environment FK recomputation and solver reset (Kamino) for the affected environments. """ if env_mask is None: env_mask = self._ALL_ENV_MASK @@ -592,8 +586,6 @@ def write_root_com_velocity_to_sim_mask( outputs=[ self.data.root_com_vel_w, self.data.body_com_acc_w, - None, # self.data._root_state_w.data, - None, # self.data._root_com_state_w.data, ], device=self.device, ) @@ -601,6 +593,7 @@ def write_root_com_velocity_to_sim_mask( self.data._root_state_w.timestamp = -1.0 if self.data._root_com_state_w is not None: self.data._root_com_state_w.timestamp = -1.0 + SimulationManager.invalidate_fk(env_mask=env_mask, articulation_ids=self._root_view.articulation_ids) def write_root_link_velocity_to_sim_index( self, @@ -627,6 +620,9 @@ def write_root_link_velocity_to_sim_index( Shape is (len(env_ids), 6) or (num_instances, 6), or (len(env_ids),) / (num_instances,) with dtype wp.spatial_vectorf. env_ids: Environment indices. If None, then all indices are used. + + Note: + Triggers per-environment FK recomputation and solver reset (Kamino) for the affected environments. """ # resolve all indices env_ids = self._resolve_env_ids(env_ids) @@ -647,9 +643,6 @@ def write_root_link_velocity_to_sim_index( self.data.root_link_vel_w, self.data.root_com_vel_w, self.data.body_com_acc_w, - None, # self.data._root_link_state_w.data, - None, # self.data._root_state_w.data, - None, # self.data._root_com_state_w.data, ], device=self.device, ) @@ -659,6 +652,7 @@ def write_root_link_velocity_to_sim_index( self.data._root_state_w.timestamp = -1.0 if self.data._root_com_state_w is not None: self.data._root_com_state_w.timestamp = -1.0 + SimulationManager.invalidate_fk(env_ids=env_ids, articulation_ids=self._root_view.articulation_ids) def write_root_link_velocity_to_sim_mask( self, @@ -684,6 +678,9 @@ def write_root_link_velocity_to_sim_mask( root_velocity: Root frame velocities in simulation world frame. Shape is (num_instances, 6) or (num_instances,) with dtype wp.spatial_vectorf. env_mask: Environment mask. If None, then all the instances are updated. Shape is (num_instances,). + + Note: + Triggers per-environment FK recomputation and solver reset (Kamino) for the affected environments. """ if env_mask is None: env_mask = self._ALL_ENV_MASK @@ -702,9 +699,6 @@ def write_root_link_velocity_to_sim_mask( self.data.root_link_vel_w, self.data.root_com_vel_w, self.data.body_com_acc_w, - None, # self.data._root_link_state_w.data, - None, # self.data._root_state_w.data, - None, # self.data._root_com_state_w.data, ], device=self.device, ) @@ -714,6 +708,7 @@ def write_root_link_velocity_to_sim_mask( self.data._root_state_w.timestamp = -1.0 if self.data._root_com_state_w is not None: self.data._root_com_state_w.timestamp = -1.0 + SimulationManager.invalidate_fk(env_mask=env_mask, articulation_ids=self._root_view.articulation_ids) """ Operations - Setters. @@ -1093,9 +1088,6 @@ def _process_cfg(self) -> None: def _resolve_env_ids(self, env_ids: Sequence[int] | torch.Tensor | wp.array | None) -> wp.array | torch.Tensor: """Resolve environment indices to a warp array or tensor. - .. note:: - We need to convert torch tensors to warp arrays since the TensorAPI views only support warp arrays. - Args: env_ids: Environment indices. If None, then all indices are used. @@ -1104,28 +1096,31 @@ def _resolve_env_ids(self, env_ids: Sequence[int] | torch.Tensor | wp.array | No """ if (env_ids is None) or (env_ids == slice(None)): return self._ALL_INDICES - elif isinstance(env_ids, list): - return wp.array(env_ids, dtype=wp.int32, device=self.device) if isinstance(env_ids, torch.Tensor): - return wp.from_torch(env_ids.to(torch.int32), dtype=wp.int32) + if env_ids.dtype == torch.int64: + env_ids = env_ids.to(torch.int32) + return wp.from_torch(env_ids, dtype=wp.int32) + if isinstance(env_ids, list): + return wp.array(env_ids, dtype=wp.int32, device=self.device) return env_ids def _resolve_body_ids(self, body_ids: Sequence[int] | torch.Tensor | wp.array | None) -> wp.array | torch.Tensor: """Resolve body indices to a warp array or tensor. - .. note:: - We do not need to convert torch tensors to warp arrays since they never get passed to the TensorAPI views. - Args: body_ids: Body indices. If None, then all indices are used. Returns: A warp array of body indices or a tensor of body indices. """ + if isinstance(body_ids, list): + return wp.array(body_ids, dtype=wp.int32, device=self.device) if (body_ids is None) or (body_ids == slice(None)): return self._ALL_BODY_INDICES - elif isinstance(body_ids, list): - return wp.array(body_ids, dtype=wp.int32, device=self.device) + if isinstance(body_ids, torch.Tensor): + if body_ids.dtype == torch.int64: + body_ids = body_ids.to(torch.int32) + return wp.from_torch(body_ids, dtype=wp.int32) return body_ids """ diff --git a/source/isaaclab_newton/isaaclab_newton/assets/rigid_object/rigid_object_data.py b/source/isaaclab_newton/isaaclab_newton/assets/rigid_object/rigid_object_data.py index 7a8c85a57753..0e9ecc8a41d0 100644 --- a/source/isaaclab_newton/isaaclab_newton/assets/rigid_object/rigid_object_data.py +++ b/source/isaaclab_newton/isaaclab_newton/assets/rigid_object/rigid_object_data.py @@ -15,6 +15,8 @@ from isaaclab.assets.rigid_object.base_rigid_object_data import BaseRigidObjectData from isaaclab.utils.buffers import TimestampedBufferWarp as TimestampedBuffer from isaaclab.utils.math import normalize +from isaaclab.utils.warp import ProxyArray +from isaaclab.utils.warp.utils import capture_unsafe from isaaclab_newton.assets import kernels as shared_kernels from isaaclab_newton.physics import NewtonManager as SimulationManager @@ -26,6 +28,13 @@ # import logger logger = logging.getLogger(__name__) +_LAZY_CAPTURE_REASON = ( + "This is a lazily-computed derived property guarded by a Python timestamp check " + "that is invisible during graph replay. Use Tier 1 base data (root_link_pose_w, " + "root_com_vel_w, body_link_pose_w, body_com_vel_w) and inline the computation " + "in your warp kernel. See GRAPH_CAPTURE_MIGRATION.md." +) + class RigidObjectData(BaseRigidObjectData): """Data container for a rigid object. @@ -76,8 +85,8 @@ def __init__(self, root_view: ArticulationView, device: str): forward_vec = torch.tensor((1.0, 0.0, 0.0), device=self.device).repeat(self._root_view.count, 1) # Initialize constants - self.GRAVITY_VEC_W = wp.from_torch(gravity_dir, dtype=wp.vec3f) - self.FORWARD_VEC_B = wp.from_torch(forward_vec, dtype=wp.vec3f) + self.GRAVITY_VEC_W = ProxyArray(wp.from_torch(gravity_dir, dtype=wp.vec3f)) + self.FORWARD_VEC_B = ProxyArray(wp.from_torch(forward_vec, dtype=wp.vec3f)) self._create_simulation_bindings() self._create_buffers() @@ -128,13 +137,13 @@ def update(self, dt: float) -> None: """ @property - def default_root_pose(self) -> wp.array: + def default_root_pose(self) -> ProxyArray: """Default root pose ``[pos, quat]`` in local environment frame. Shape is (num_instances,), dtype = wp.transformf. In torch this resolves to (num_instances, 7). The position and quaternion are of the rigid body's actor frame. """ - return self._default_root_pose + return self._default_root_pose_ta @default_root_pose.setter def default_root_pose(self, value: wp.array) -> None: @@ -151,13 +160,13 @@ def default_root_pose(self, value: wp.array) -> None: self._default_root_pose.assign(value) @property - def default_root_vel(self) -> wp.array: + def default_root_vel(self) -> ProxyArray: """Default root velocity ``[lin_vel, ang_vel]`` in local environment frame. Shape is (num_instances,), dtype = wp.spatial_vectorf. In torch this resolves to (num_instances, 6). The linear and angular velocities are of the rigid body's center of mass frame. """ - return self._default_root_vel + return self._default_root_vel_ta @default_root_vel.setter def default_root_vel(self, value: wp.array) -> None: @@ -178,17 +187,18 @@ def default_root_vel(self, value: wp.array) -> None: """ @property - def root_link_pose_w(self) -> wp.array: + def root_link_pose_w(self) -> ProxyArray: """Root link pose ``[pos, quat]`` in simulation world frame. Shape is (num_instances,), dtype = wp.transformf. In torch this resolves to (num_instances, 7). This quantity is the pose of the actor frame of the root rigid body relative to the world. The orientation is provided in (x, y, z, w) format. """ - return self._sim_bind_root_link_pose_w + return self._root_link_pose_w_ta @property - def root_link_vel_w(self) -> wp.array: + @capture_unsafe(_LAZY_CAPTURE_REASON) + def root_link_vel_w(self) -> ProxyArray: """Root link velocity ``[lin_vel, ang_vel]`` in simulation world frame. Shape is (num_instances,), dtype = wp.spatial_vectorf. In torch this resolves to (num_instances, 6). @@ -201,9 +211,9 @@ def root_link_vel_w(self) -> wp.array: shared_kernels.get_root_link_vel_from_root_com_vel, dim=self._num_instances, inputs=[ - self.root_com_vel_w, - self.root_link_pose_w, - self.body_com_pos_b, + self.root_com_vel_w.warp, + self.root_link_pose_w.warp, + self.body_com_pos_b.warp, ], outputs=[ self._root_link_vel_w.data, @@ -212,10 +222,11 @@ def root_link_vel_w(self) -> wp.array: ) self._root_link_vel_w.timestamp = self._sim_timestamp - return self._root_link_vel_w.data + return self._root_link_vel_w_ta @property - def root_com_pose_w(self) -> wp.array: + @capture_unsafe(_LAZY_CAPTURE_REASON) + def root_com_pose_w(self) -> ProxyArray: """Root center of mass pose ``[pos, quat]`` in simulation world frame. Shape is (num_instances,), dtype = wp.transformf. In torch this resolves to (num_instances, 7). @@ -228,8 +239,8 @@ def root_com_pose_w(self) -> wp.array: shared_kernels.get_root_com_pose_from_root_link_pose, dim=self._num_instances, inputs=[ - self.root_link_pose_w, - self.body_com_pos_b, + self.root_link_pose_w.warp, + self.body_com_pos_b.warp, ], outputs=[ self._root_com_pose_w.data, @@ -238,82 +249,88 @@ def root_com_pose_w(self) -> wp.array: ) self._root_com_pose_w.timestamp = self._sim_timestamp - return self._root_com_pose_w.data + return self._root_com_pose_w_ta @property - def root_com_vel_w(self) -> wp.array: + def root_com_vel_w(self) -> ProxyArray: """Root center of mass velocity ``[lin_vel, ang_vel]`` in simulation world frame. Shape is (num_instances,), dtype = wp.spatial_vectorf. In torch this resolves to (num_instances, 6). This quantity contains the linear and angular velocities of the root rigid body's center of mass frame relative to the world. """ - return self._sim_bind_root_com_vel_w + return self._root_com_vel_w_ta """ Body state properties. """ @property - def body_mass(self) -> wp.array: + def body_mass(self) -> ProxyArray: """Mass of all bodies in the simulation world frame. Shape is (num_instances, 1, 1), dtype = wp.float32. In torch this resolves to (num_instances, 1, 1). """ - return self._sim_bind_body_mass + return self._body_mass_ta @property - def body_inertia(self) -> wp.array: + def body_inertia(self) -> ProxyArray: """Inertia of all bodies in the simulation world frame. Shape is (num_instances, 1, 9), dtype = wp.float32. In torch this resolves to (num_instances, 1, 9). """ - return self._sim_bind_body_inertia + return self._body_inertia_ta @property - def body_link_pose_w(self) -> wp.array: + def body_link_pose_w(self) -> ProxyArray: """Body link pose ``[pos, quat]`` in simulation world frame. Shape is (num_instances, 1), dtype = wp.transformf. In torch this resolves to (num_instances, 1, 7). This quantity is the pose of the actor frame of the rigid body relative to the world. The orientation is provided in (x, y, z, w) format. """ - return self._sim_bind_body_link_pose_w + return self._body_link_pose_w_ta @property - def body_link_vel_w(self) -> wp.array: + @capture_unsafe(_LAZY_CAPTURE_REASON) + def body_link_vel_w(self) -> ProxyArray: """Body link velocity ``[lin_vel, ang_vel]`` in simulation world frame. Shape is (num_instances, 1), dtype = wp.spatial_vectorf. In torch this resolves to (num_instances, 1, 6). This quantity contains the linear and angular velocities of the actor frame of the root rigid body relative to the world. """ - return self.root_link_vel_w.reshape((self._num_instances, 1)) + if self._body_link_vel_w_ta is None: + self._body_link_vel_w_ta = ProxyArray(self.root_link_vel_w.warp.reshape((self._num_instances, 1))) + return self._body_link_vel_w_ta @property - def body_com_pose_w(self) -> wp.array: + @capture_unsafe(_LAZY_CAPTURE_REASON) + def body_com_pose_w(self) -> ProxyArray: """Body center of mass pose ``[pos, quat]`` in simulation world frame. Shape is (num_instances, 1), dtype = wp.transformf. In torch this resolves to (num_instances, 1, 7). This quantity is the pose of the center of mass frame of the rigid body relative to the world. The orientation is provided in (x, y, z, w) format. """ - return self.root_com_pose_w.reshape((self._num_instances, 1)) + if self._body_com_pose_w_ta is None: + self._body_com_pose_w_ta = ProxyArray(self.root_com_pose_w.warp.reshape((self._num_instances, 1))) + return self._body_com_pose_w_ta @property - def body_com_vel_w(self) -> wp.array: + def body_com_vel_w(self) -> ProxyArray: """Body center of mass velocity ``[lin_vel, ang_vel]`` in simulation world frame. Shape is (num_instances, 1), dtype = wp.spatial_vectorf. In torch this resolves to (num_instances, 1, 6). This quantity contains the linear and angular velocities of the root rigid body's center of mass frame relative to the world. """ - return self._sim_bind_body_com_vel_w + return self._body_com_vel_w_ta @property - def body_com_acc_w(self) -> wp.array: + def body_com_acc_w(self) -> ProxyArray: """Acceleration of all bodies ``[lin_acc, ang_acc]`` in the simulation world frame. Shape is (num_instances, 1), dtype = wp.spatial_vectorf. In torch this resolves to (num_instances, 1, 6). @@ -336,19 +353,19 @@ def body_com_acc_w(self) -> wp.array: # set the buffer data and timestamp self._body_com_acc_w.timestamp = self._sim_timestamp # update the previous velocity - return self._body_com_acc_w.data + return self._body_com_acc_w_ta @property - def body_com_pos_b(self) -> wp.array: + def body_com_pos_b(self) -> ProxyArray: """Center of mass position of all of the bodies in their respective link frames. Shape is (num_instances, 1), dtype = wp.vec3f. In torch this resolves to (num_instances, 1, 3). This quantity is the center of mass location relative to its body's link frame. """ - return self._sim_bind_body_com_pos_b + return self._body_com_pos_b_ta @property - def body_com_pose_b(self) -> wp.array: + def body_com_pose_b(self) -> ProxyArray: """Center of mass pose ``[pos, quat]`` of all bodies in their respective body's link frames. Shape is (num_instances, 1), dtype = wp.transformf. In torch this resolves to (num_instances, 1, 7). @@ -367,7 +384,7 @@ def body_com_pose_b(self) -> wp.array: shared_kernels.make_dummy_body_com_pose_b, dim=(self._num_instances, 1), inputs=[ - self.body_com_pos_b, + self.body_com_pos_b.warp, ], outputs=[ self._body_com_pose_b.data, @@ -375,14 +392,15 @@ def body_com_pose_b(self) -> wp.array: device=self.device, ) self._body_com_pose_b.timestamp = self._sim_timestamp - return self._body_com_pose_b.data + return self._body_com_pose_b_ta """ Derived Properties. """ @property - def projected_gravity_b(self) -> wp.array: + @capture_unsafe(_LAZY_CAPTURE_REASON) + def projected_gravity_b(self) -> ProxyArray: """Projection of the gravity direction on base frame. Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). @@ -391,15 +409,16 @@ def projected_gravity_b(self) -> wp.array: wp.launch( shared_kernels.quat_apply_inverse_1D_kernel, dim=self._num_instances, - inputs=[self.GRAVITY_VEC_W, self.root_link_quat_w], + inputs=[self.GRAVITY_VEC_W.warp, self.root_link_quat_w.warp], outputs=[self._projected_gravity_b.data], device=self.device, ) self._projected_gravity_b.timestamp = self._sim_timestamp - return self._projected_gravity_b.data + return self._projected_gravity_b_ta @property - def heading_w(self) -> wp.array: + @capture_unsafe(_LAZY_CAPTURE_REASON) + def heading_w(self) -> ProxyArray: """Yaw heading of the base frame (in radians). Shape is (num_instances,), dtype = wp.float32. In torch this resolves to (num_instances,). @@ -412,15 +431,16 @@ def heading_w(self) -> wp.array: wp.launch( shared_kernels.root_heading_w, dim=self._num_instances, - inputs=[self.FORWARD_VEC_B, self.root_link_quat_w], + inputs=[self.FORWARD_VEC_B.warp, self.root_link_quat_w.warp], outputs=[self._heading_w.data], device=self.device, ) self._heading_w.timestamp = self._sim_timestamp - return self._heading_w.data + return self._heading_w_ta @property - def root_link_lin_vel_b(self) -> wp.array: + @capture_unsafe(_LAZY_CAPTURE_REASON) + def root_link_lin_vel_b(self) -> ProxyArray: """Root link linear velocity in base frame. Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). @@ -431,19 +451,20 @@ def root_link_lin_vel_b(self) -> wp.array: self._root_link_lin_vel_b = TimestampedBuffer( shape=(self._num_instances,), dtype=wp.vec3f, device=self.device ) + self._root_link_lin_vel_b_ta = ProxyArray(self._root_link_lin_vel_b.data) if self._root_link_lin_vel_b.timestamp < self._sim_timestamp: wp.launch( shared_kernels.quat_apply_inverse_1D_kernel, dim=self._num_instances, - inputs=[self.root_link_lin_vel_w, self.root_link_quat_w], + inputs=[self.root_link_lin_vel_w.warp, self.root_link_quat_w.warp], outputs=[self._root_link_lin_vel_b.data], device=self.device, ) self._root_link_lin_vel_b.timestamp = self._sim_timestamp - return self._root_link_lin_vel_b.data + return self._root_link_lin_vel_b_ta @property - def root_link_ang_vel_b(self) -> wp.array: + def root_link_ang_vel_b(self) -> ProxyArray: """Root link angular velocity in base frame. Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). @@ -454,19 +475,20 @@ def root_link_ang_vel_b(self) -> wp.array: self._root_link_ang_vel_b = TimestampedBuffer( shape=(self._num_instances,), dtype=wp.vec3f, device=self.device ) + self._root_link_ang_vel_b_ta = ProxyArray(self._root_link_ang_vel_b.data) if self._root_link_ang_vel_b.timestamp < self._sim_timestamp: wp.launch( shared_kernels.quat_apply_inverse_1D_kernel, dim=self._num_instances, - inputs=[self.root_link_ang_vel_w, self.root_link_quat_w], + inputs=[self.root_link_ang_vel_w.warp, self.root_link_quat_w.warp], outputs=[self._root_link_ang_vel_b.data], device=self.device, ) self._root_link_ang_vel_b.timestamp = self._sim_timestamp - return self._root_link_ang_vel_b.data + return self._root_link_ang_vel_b_ta @property - def root_com_lin_vel_b(self) -> wp.array: + def root_com_lin_vel_b(self) -> ProxyArray: """Root center of mass linear velocity in base frame. Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). @@ -477,19 +499,20 @@ def root_com_lin_vel_b(self) -> wp.array: self._root_com_lin_vel_b = TimestampedBuffer( shape=(self._num_instances,), dtype=wp.vec3f, device=self.device ) + self._root_com_lin_vel_b_ta = ProxyArray(self._root_com_lin_vel_b.data) if self._root_com_lin_vel_b.timestamp < self._sim_timestamp: wp.launch( shared_kernels.quat_apply_inverse_1D_kernel, dim=self._num_instances, - inputs=[self.root_com_lin_vel_w, self.root_link_quat_w], + inputs=[self.root_com_lin_vel_w.warp, self.root_link_quat_w.warp], outputs=[self._root_com_lin_vel_b.data], device=self.device, ) self._root_com_lin_vel_b.timestamp = self._sim_timestamp - return self._root_com_lin_vel_b.data + return self._root_com_lin_vel_b_ta @property - def root_com_ang_vel_b(self) -> wp.array: + def root_com_ang_vel_b(self) -> ProxyArray: """Root center of mass angular velocity in base frame. Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). @@ -500,192 +523,264 @@ def root_com_ang_vel_b(self) -> wp.array: self._root_com_ang_vel_b = TimestampedBuffer( shape=(self._num_instances,), dtype=wp.vec3f, device=self.device ) + self._root_com_ang_vel_b_ta = ProxyArray(self._root_com_ang_vel_b.data) if self._root_com_ang_vel_b.timestamp < self._sim_timestamp: wp.launch( shared_kernels.quat_apply_inverse_1D_kernel, dim=self._num_instances, - inputs=[self.root_com_ang_vel_w, self.root_link_quat_w], + inputs=[self.root_com_ang_vel_w.warp, self.root_link_quat_w.warp], outputs=[self._root_com_ang_vel_b.data], device=self.device, ) self._root_com_ang_vel_b.timestamp = self._sim_timestamp - return self._root_com_ang_vel_b.data + return self._root_com_ang_vel_b_ta """ Sliced properties. """ @property - def root_link_pos_w(self) -> wp.array: + def root_link_pos_w(self) -> ProxyArray: """Root link position in simulation world frame. Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). This quantity is the position of the actor frame of the root rigid body relative to the world. """ - return self._get_pos_from_transform(self._root_link_pos_w, self.root_link_pose_w) + self._root_link_pos_w = self._get_pos_from_transform(self._root_link_pos_w, self.root_link_pose_w.warp) + if self._root_link_pos_w_ta is None: + self._root_link_pos_w_ta = ProxyArray(self._root_link_pos_w) + return self._root_link_pos_w_ta @property - def root_link_quat_w(self) -> wp.array: + def root_link_quat_w(self) -> ProxyArray: """Root link orientation (x, y, z, w) in simulation world frame. Shape is (num_instances,), dtype = wp.quatf. In torch this resolves to (num_instances, 4). This quantity is the orientation of the actor frame of the root rigid body. """ - return self._get_quat_from_transform(self._root_link_quat_w, self.root_link_pose_w) + self._root_link_quat_w = self._get_quat_from_transform(self._root_link_quat_w, self.root_link_pose_w.warp) + if self._root_link_quat_w_ta is None: + self._root_link_quat_w_ta = ProxyArray(self._root_link_quat_w) + return self._root_link_quat_w_ta @property - def root_link_lin_vel_w(self) -> wp.array: + def root_link_lin_vel_w(self) -> ProxyArray: """Root linear velocity in simulation world frame. Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). This quantity is the linear velocity of the root rigid body's actor frame relative to the world. """ - return self._get_top_from_spatial_vector(self._root_link_lin_vel_w, self.root_link_vel_w) + self._root_link_lin_vel_w = self._get_top_from_spatial_vector( + self._root_link_lin_vel_w, self.root_link_vel_w.warp + ) + if self._root_link_lin_vel_w_ta is None: + self._root_link_lin_vel_w_ta = ProxyArray(self._root_link_lin_vel_w) + return self._root_link_lin_vel_w_ta @property - def root_link_ang_vel_w(self) -> wp.array: + def root_link_ang_vel_w(self) -> ProxyArray: """Root link angular velocity in simulation world frame. Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). This quantity is the angular velocity of the actor frame of the root rigid body relative to the world. """ - return self._get_bottom_from_spatial_vector(self._root_link_ang_vel_w, self.root_link_vel_w) + self._root_link_ang_vel_w = self._get_bottom_from_spatial_vector( + self._root_link_ang_vel_w, self.root_link_vel_w.warp + ) + if self._root_link_ang_vel_w_ta is None: + self._root_link_ang_vel_w_ta = ProxyArray(self._root_link_ang_vel_w) + return self._root_link_ang_vel_w_ta @property - def root_com_pos_w(self) -> wp.array: + def root_com_pos_w(self) -> ProxyArray: """Root center of mass position in simulation world frame. Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). This quantity is the position of the center of mass frame of the root rigid body relative to the world. """ - return self._get_pos_from_transform(self._root_com_pos_w, self.root_com_pose_w) + self._root_com_pos_w = self._get_pos_from_transform(self._root_com_pos_w, self.root_com_pose_w.warp) + if self._root_com_pos_w_ta is None: + self._root_com_pos_w_ta = ProxyArray(self._root_com_pos_w) + return self._root_com_pos_w_ta @property - def root_com_quat_w(self) -> wp.array: + def root_com_quat_w(self) -> ProxyArray: """Root center of mass orientation (x, y, z, w) in simulation world frame. Shape is (num_instances,), dtype = wp.quatf. In torch this resolves to (num_instances, 4). This quantity is the orientation of the principal axes of inertia of the root rigid body relative to the world. """ - return self._get_quat_from_transform(self._root_com_quat_w, self.root_com_pose_w) + self._root_com_quat_w = self._get_quat_from_transform(self._root_com_quat_w, self.root_com_pose_w.warp) + if self._root_com_quat_w_ta is None: + self._root_com_quat_w_ta = ProxyArray(self._root_com_quat_w) + return self._root_com_quat_w_ta @property - def root_com_lin_vel_w(self) -> wp.array: + def root_com_lin_vel_w(self) -> ProxyArray: """Root center of mass linear velocity in simulation world frame. Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). This quantity is the linear velocity of the root rigid body's center of mass frame relative to the world. """ - return self._get_top_from_spatial_vector(self._root_com_lin_vel_w, self.root_com_vel_w) + self._root_com_lin_vel_w = self._get_top_from_spatial_vector(self._root_com_lin_vel_w, self.root_com_vel_w.warp) + if self._root_com_lin_vel_w_ta is None: + self._root_com_lin_vel_w_ta = ProxyArray(self._root_com_lin_vel_w) + return self._root_com_lin_vel_w_ta @property - def root_com_ang_vel_w(self) -> wp.array: + def root_com_ang_vel_w(self) -> ProxyArray: """Root center of mass angular velocity in simulation world frame. Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). This quantity is the angular velocity of the root rigid body's center of mass frame relative to the world. """ - return self._get_bottom_from_spatial_vector(self._root_com_ang_vel_w, self.root_com_vel_w) + self._root_com_ang_vel_w = self._get_bottom_from_spatial_vector( + self._root_com_ang_vel_w, self.root_com_vel_w.warp + ) + if self._root_com_ang_vel_w_ta is None: + self._root_com_ang_vel_w_ta = ProxyArray(self._root_com_ang_vel_w) + return self._root_com_ang_vel_w_ta @property - def body_link_pos_w(self) -> wp.array: + def body_link_pos_w(self) -> ProxyArray: """Positions of all bodies in simulation world frame. Shape is (num_instances, 1), dtype = wp.vec3f. In torch this resolves to (num_instances, 1, 3). This quantity is the position of the rigid bodies' actor frame relative to the world. """ - return self._get_pos_from_transform(self._body_link_pos_w, self.body_link_pose_w) + self._body_link_pos_w = self._get_pos_from_transform(self._body_link_pos_w, self.body_link_pose_w.warp) + if self._body_link_pos_w_ta is None: + self._body_link_pos_w_ta = ProxyArray(self._body_link_pos_w) + return self._body_link_pos_w_ta @property - def body_link_quat_w(self) -> wp.array: + def body_link_quat_w(self) -> ProxyArray: """Orientation (x, y, z, w) of all bodies in simulation world frame. Shape is (num_instances, 1), dtype = wp.quatf. In torch this resolves to (num_instances, 1, 4). This quantity is the orientation of the rigid bodies' actor frame relative to the world. """ - return self._get_quat_from_transform(self._body_link_quat_w, self.body_link_pose_w) + self._body_link_quat_w = self._get_quat_from_transform(self._body_link_quat_w, self.body_link_pose_w.warp) + if self._body_link_quat_w_ta is None: + self._body_link_quat_w_ta = ProxyArray(self._body_link_quat_w) + return self._body_link_quat_w_ta @property - def body_link_lin_vel_w(self) -> wp.array: + def body_link_lin_vel_w(self) -> ProxyArray: """Linear velocity of all bodies in simulation world frame. Shape is (num_instances, 1), dtype = wp.vec3f. In torch this resolves to (num_instances, 1, 3). This quantity is the linear velocity of the rigid bodies' actor frame relative to the world. """ - return self._get_top_from_spatial_vector(self._body_link_lin_vel_w, self.body_link_vel_w) + self._body_link_lin_vel_w = self._get_top_from_spatial_vector( + self._body_link_lin_vel_w, self.body_link_vel_w.warp + ) + if self._body_link_lin_vel_w_ta is None: + self._body_link_lin_vel_w_ta = ProxyArray(self._body_link_lin_vel_w) + return self._body_link_lin_vel_w_ta @property - def body_link_ang_vel_w(self) -> wp.array: + def body_link_ang_vel_w(self) -> ProxyArray: """Angular velocity of all bodies in simulation world frame. Shape is (num_instances, 1), dtype = wp.vec3f. In torch this resolves to (num_instances, 1, 3). This quantity is the angular velocity of the rigid bodies' actor frame relative to the world. """ - return self._get_bottom_from_spatial_vector(self._body_link_ang_vel_w, self.body_link_vel_w) + self._body_link_ang_vel_w = self._get_bottom_from_spatial_vector( + self._body_link_ang_vel_w, self.body_link_vel_w.warp + ) + if self._body_link_ang_vel_w_ta is None: + self._body_link_ang_vel_w_ta = ProxyArray(self._body_link_ang_vel_w) + return self._body_link_ang_vel_w_ta @property - def body_com_pos_w(self) -> wp.array: + def body_com_pos_w(self) -> ProxyArray: """Positions of all bodies' center of mass in simulation world frame. Shape is (num_instances, 1), dtype = wp.vec3f. In torch this resolves to (num_instances, 1, 3). This quantity is the position of the rigid bodies' center of mass frame. """ - return self._get_pos_from_transform(self._body_com_pos_w, self.body_com_pose_w) + self._body_com_pos_w = self._get_pos_from_transform(self._body_com_pos_w, self.body_com_pose_w.warp) + if self._body_com_pos_w_ta is None: + self._body_com_pos_w_ta = ProxyArray(self._body_com_pos_w) + return self._body_com_pos_w_ta @property - def body_com_quat_w(self) -> wp.array: + def body_com_quat_w(self) -> ProxyArray: """Orientation (x, y, z, w) of the principal axes of inertia of all bodies in simulation world frame. Shape is (num_instances, 1), dtype = wp.quatf. In torch this resolves to (num_instances, 1, 4). This quantity is the orientation of the principal axes of inertia of the rigid bodies. """ - return self._get_quat_from_transform(self._body_com_quat_w, self.body_com_pose_w) + self._body_com_quat_w = self._get_quat_from_transform(self._body_com_quat_w, self.body_com_pose_w.warp) + if self._body_com_quat_w_ta is None: + self._body_com_quat_w_ta = ProxyArray(self._body_com_quat_w) + return self._body_com_quat_w_ta @property - def body_com_lin_vel_w(self) -> wp.array: + def body_com_lin_vel_w(self) -> ProxyArray: """Linear velocity of all bodies in simulation world frame. Shape is (num_instances, 1), dtype = wp.vec3f. In torch this resolves to (num_instances, 1, 3). This quantity is the linear velocity of the rigid bodies' center of mass frame. """ - return self._get_top_from_spatial_vector(self._body_com_lin_vel_w, self.body_com_vel_w) + self._body_com_lin_vel_w = self._get_top_from_spatial_vector(self._body_com_lin_vel_w, self.body_com_vel_w.warp) + if self._body_com_lin_vel_w_ta is None: + self._body_com_lin_vel_w_ta = ProxyArray(self._body_com_lin_vel_w) + return self._body_com_lin_vel_w_ta @property - def body_com_ang_vel_w(self) -> wp.array: + def body_com_ang_vel_w(self) -> ProxyArray: """Angular velocity of all bodies in simulation world frame. Shape is (num_instances, 1), dtype = wp.vec3f. In torch this resolves to (num_instances, 1, 3). This quantity is the angular velocity of the rigid bodies' center of mass frame. """ - return self._get_bottom_from_spatial_vector(self._body_com_ang_vel_w, self.body_com_vel_w) + self._body_com_ang_vel_w = self._get_bottom_from_spatial_vector( + self._body_com_ang_vel_w, self.body_com_vel_w.warp + ) + if self._body_com_ang_vel_w_ta is None: + self._body_com_ang_vel_w_ta = ProxyArray(self._body_com_ang_vel_w) + return self._body_com_ang_vel_w_ta @property - def body_com_lin_acc_w(self) -> wp.array: + def body_com_lin_acc_w(self) -> ProxyArray: """Linear acceleration of all bodies in simulation world frame. Shape is (num_instances, 1), dtype = wp.vec3f. In torch this resolves to (num_instances, 1, 3). This quantity is the linear acceleration of the rigid bodies' center of mass frame. """ - return self._get_top_from_spatial_vector(self._body_com_lin_acc_w, self.body_com_acc_w) + self._body_com_lin_acc_w = self._get_top_from_spatial_vector(self._body_com_lin_acc_w, self.body_com_acc_w.warp) + if self._body_com_lin_acc_w_ta is None: + self._body_com_lin_acc_w_ta = ProxyArray(self._body_com_lin_acc_w) + return self._body_com_lin_acc_w_ta @property - def body_com_ang_acc_w(self) -> wp.array: + def body_com_ang_acc_w(self) -> ProxyArray: """Angular acceleration of all bodies in simulation world frame. Shape is (num_instances, 1), dtype = wp.vec3f. In torch this resolves to (num_instances, 1, 3). This quantity is the angular acceleration of the rigid bodies' center of mass frame. """ - return self._get_bottom_from_spatial_vector(self._body_com_ang_acc_w, self.body_com_acc_w) + self._body_com_ang_acc_w = self._get_bottom_from_spatial_vector( + self._body_com_ang_acc_w, self.body_com_acc_w.warp + ) + if self._body_com_ang_acc_w_ta is None: + self._body_com_ang_acc_w_ta = ProxyArray(self._body_com_ang_acc_w) + return self._body_com_ang_acc_w_ta @property - def body_com_quat_b(self) -> wp.array: + def body_com_quat_b(self) -> ProxyArray: """Orientation (x, y, z, w) of the principal axes of inertia of all of the bodies in their respective link frames. Shape is (num_instances, 1), dtype = wp.quatf. In torch this resolves to (num_instances, 1, 4). This quantity is the orientation of the principal axes of inertia relative to its body's link frame. """ - return self._get_quat_from_transform(self._body_com_quat_b, self.body_com_pose_b) + self._body_com_quat_b = self._get_quat_from_transform(self._body_com_quat_b, self.body_com_pose_b.warp) + if self._body_com_quat_b_ta is None: + self._body_com_quat_b_ta = ProxyArray(self._body_com_quat_b) + return self._body_com_quat_b_ta def _create_simulation_bindings(self) -> None: """Create simulation bindings for the root data. @@ -736,6 +831,11 @@ def _create_simulation_bindings(self) -> None: :, 0 ] + # Re-pin ProxyArray wrappers to the newly created sim bindings. + # On first init, _create_buffers() handles this after all buffers exist. + if hasattr(self, "_root_link_pose_w_ta"): + self._pin_proxy_arrays() + def _create_buffers(self) -> None: """Create buffers for the root data.""" super()._create_buffers() @@ -756,6 +856,7 @@ def _create_buffers(self) -> None: # -- default root pose and velocity self._default_root_pose = wp.zeros((self._num_instances,), dtype=wp.transformf, device=self.device) self._default_root_vel = wp.zeros((self._num_instances,), dtype=wp.spatial_vectorf, device=self.device) + self._default_root_state = None # lazily allocated by deprecated default_root_state property # Initialize history for finite differencing self._previous_body_com_vel = wp.clone(self._root_view.get_link_velocities(SimulationManager.get_state_0()))[ @@ -817,6 +918,108 @@ def _create_buffers(self) -> None: self._body_com_lin_acc_w = None self._body_com_ang_acc_w = None + # Pin all ProxyArray wrappers to current buffers. + self._pin_proxy_arrays() + + def _pin_proxy_arrays(self) -> None: + """Create or rebind all pinned ProxyArray wrappers. + + Called from :meth:`_create_buffers` on first initialization and from + :meth:`_create_simulation_bindings` after a full simulation reset when + the solver recreates its internal arrays. + """ + is_rebind = hasattr(self, "_root_link_pose_w_ta") + + if is_rebind: + # Rebind sim-bound ProxyArrays to new solver arrays + self._root_link_pose_w_ta = ProxyArray(self._sim_bind_root_link_pose_w) + self._root_com_vel_w_ta = ProxyArray(self._sim_bind_root_com_vel_w) + self._body_link_pose_w_ta = ProxyArray(self._sim_bind_body_link_pose_w) + self._body_com_vel_w_ta = ProxyArray(self._sim_bind_body_com_vel_w) + self._body_mass_ta = ProxyArray(self._sim_bind_body_mass) + self._body_inertia_ta = ProxyArray(self._sim_bind_body_inertia) + self._body_com_pos_b_ta = ProxyArray(self._sim_bind_body_com_pos_b) + else: + # First-time creation: pin ProxyArrays to current buffers + # Category 1: sim-bound and pre-allocated buffers + # Newton wp.array pointers are stable, so a ProxyArray wrapping them is valid forever. + self._root_link_pose_w_ta = ProxyArray(self._sim_bind_root_link_pose_w) + self._root_com_vel_w_ta = ProxyArray(self._sim_bind_root_com_vel_w) + self._body_link_pose_w_ta = ProxyArray(self._sim_bind_body_link_pose_w) + self._body_com_vel_w_ta = ProxyArray(self._sim_bind_body_com_vel_w) + self._default_root_pose_ta = ProxyArray(self._default_root_pose) + self._default_root_vel_ta = ProxyArray(self._default_root_vel) + self._body_mass_ta = ProxyArray(self._sim_bind_body_mass) + self._body_inertia_ta = ProxyArray(self._sim_bind_body_inertia) + self._body_com_pos_b_ta = ProxyArray(self._sim_bind_body_com_pos_b) + + # Category 2: TimestampedBuffer properties + self._root_link_vel_w_ta = ProxyArray(self._root_link_vel_w.data) + self._root_com_pose_w_ta = ProxyArray(self._root_com_pose_w.data) + self._body_com_acc_w_ta = ProxyArray(self._body_com_acc_w.data) + self._body_com_pose_b_ta = ProxyArray(self._body_com_pose_b.data) + self._projected_gravity_b_ta = ProxyArray(self._projected_gravity_b.data) + self._heading_w_ta = ProxyArray(self._heading_w.data) + + # -- deprecated state properties (lazy); type annotations declared once here + self._root_link_lin_vel_b_ta: ProxyArray | None = None + self._root_link_ang_vel_b_ta: ProxyArray | None = None + self._root_com_lin_vel_b_ta: ProxyArray | None = None + self._root_com_ang_vel_b_ta: ProxyArray | None = None + self._root_state_w_ta: ProxyArray | None = None + self._root_link_state_w_ta: ProxyArray | None = None + self._root_com_state_w_ta: ProxyArray | None = None + self._default_root_state_ta: ProxyArray | None = None + self._body_state_w_ta: ProxyArray | None = None + self._body_link_state_w_ta: ProxyArray | None = None + self._body_com_state_w_ta: ProxyArray | None = None + + # Invalidate lazy sliced ProxyArrays AND their backing wp.arrays so they are + # re-created from fresh data on next access. On first init the backing fields + # are already None (set by _create_buffers), so the assignments below are + # harmless no-ops. On rebind they reset stale pointers into freed transform + # memory after a sim reset. + self._root_link_pos_w_ta: ProxyArray | None = None + self._root_link_pos_w = None + self._root_link_quat_w_ta: ProxyArray | None = None + self._root_link_quat_w = None + self._root_link_lin_vel_w_ta: ProxyArray | None = None + self._root_link_lin_vel_w = None + self._root_link_ang_vel_w_ta: ProxyArray | None = None + self._root_link_ang_vel_w = None + self._root_com_pos_w_ta: ProxyArray | None = None + self._root_com_pos_w = None + self._root_com_quat_w_ta: ProxyArray | None = None + self._root_com_quat_w = None + self._root_com_lin_vel_w_ta: ProxyArray | None = None + self._root_com_lin_vel_w = None + self._root_com_ang_vel_w_ta: ProxyArray | None = None + self._root_com_ang_vel_w = None + self._body_link_pos_w_ta: ProxyArray | None = None + self._body_link_pos_w = None + self._body_link_quat_w_ta: ProxyArray | None = None + self._body_link_quat_w = None + self._body_link_vel_w_ta: ProxyArray | None = None + self._body_link_lin_vel_w_ta: ProxyArray | None = None + self._body_link_lin_vel_w = None + self._body_link_ang_vel_w_ta: ProxyArray | None = None + self._body_link_ang_vel_w = None + self._body_com_pose_w_ta: ProxyArray | None = None + self._body_com_pos_w_ta: ProxyArray | None = None + self._body_com_pos_w = None + self._body_com_quat_w_ta: ProxyArray | None = None + self._body_com_quat_w = None + self._body_com_lin_vel_w_ta: ProxyArray | None = None + self._body_com_lin_vel_w = None + self._body_com_ang_vel_w_ta: ProxyArray | None = None + self._body_com_ang_vel_w = None + self._body_com_lin_acc_w_ta: ProxyArray | None = None + self._body_com_lin_acc_w = None + self._body_com_ang_acc_w_ta: ProxyArray | None = None + self._body_com_ang_acc_w = None + self._body_com_quat_b_ta: ProxyArray | None = None + self._body_com_quat_b = None + """ Internal helpers. """ @@ -1021,7 +1224,7 @@ def _get_bottom_from_spatial_vector(self, source: wp.array | None, spatial_vecto """ @property - def root_state_w(self) -> wp.array: + def root_state_w(self) -> ProxyArray: """Deprecated, same as :attr:`root_link_pose_w` and :attr:`root_com_vel_w`.""" warnings.warn( "The `root_state_w` property will be deprecated in IsaacLab 4.0. Please use `root_link_pose_w` and " @@ -1033,13 +1236,14 @@ def root_state_w(self) -> wp.array: self._root_state_w = TimestampedBuffer( shape=(self._num_instances,), dtype=shared_kernels.vec13f, device=self.device ) + self._root_state_w_ta = ProxyArray(self._root_state_w.data) if self._root_state_w.timestamp < self._sim_timestamp: wp.launch( shared_kernels.concat_root_pose_and_vel_to_state, dim=self._num_instances, inputs=[ - self.root_link_pose_w, - self.root_com_vel_w, + self.root_link_pose_w.warp, + self.root_com_vel_w.warp, ], outputs=[ self._root_state_w.data, @@ -1048,10 +1252,10 @@ def root_state_w(self) -> wp.array: ) self._root_state_w.timestamp = self._sim_timestamp - return self._root_state_w.data + return self._root_state_w_ta @property - def root_link_state_w(self) -> wp.array: + def root_link_state_w(self) -> ProxyArray: """Deprecated, same as :attr:`root_link_pose_w` and :attr:`root_link_vel_w`.""" warnings.warn( "The `root_link_state_w` property will be deprecated in IsaacLab 4.0. Please use `root_link_pose_w` and " @@ -1063,13 +1267,14 @@ def root_link_state_w(self) -> wp.array: self._root_link_state_w = TimestampedBuffer( shape=(self._num_instances,), dtype=shared_kernels.vec13f, device=self.device ) + self._root_link_state_w_ta = ProxyArray(self._root_link_state_w.data) if self._root_link_state_w.timestamp < self._sim_timestamp: wp.launch( shared_kernels.concat_root_pose_and_vel_to_state, dim=self._num_instances, inputs=[ - self.root_link_pose_w, - self.root_link_vel_w, + self.root_link_pose_w.warp, + self.root_link_vel_w.warp, ], outputs=[ self._root_link_state_w.data, @@ -1078,10 +1283,10 @@ def root_link_state_w(self) -> wp.array: ) self._root_link_state_w.timestamp = self._sim_timestamp - return self._root_link_state_w.data + return self._root_link_state_w_ta @property - def root_com_state_w(self) -> wp.array: + def root_com_state_w(self) -> ProxyArray: """Deprecated, same as :attr:`root_com_pose_w` and :attr:`root_com_vel_w`.""" warnings.warn( "The `root_com_state_w` property will be deprecated in IsaacLab 4.0. Please use `root_com_pose_w` and " @@ -1093,13 +1298,14 @@ def root_com_state_w(self) -> wp.array: self._root_com_state_w = TimestampedBuffer( shape=(self._num_instances,), dtype=shared_kernels.vec13f, device=self.device ) + self._root_com_state_w_ta = ProxyArray(self._root_com_state_w.data) if self._root_com_state_w.timestamp < self._sim_timestamp: wp.launch( shared_kernels.concat_root_pose_and_vel_to_state, dim=self._num_instances, inputs=[ - self.root_com_pose_w, - self.root_com_vel_w, + self.root_com_pose_w.warp, + self.root_com_vel_w.warp, ], outputs=[ self._root_com_state_w.data, @@ -1108,10 +1314,10 @@ def root_com_state_w(self) -> wp.array: ) self._root_com_state_w.timestamp = self._sim_timestamp - return self._root_com_state_w.data + return self._root_com_state_w_ta @property - def default_root_state(self) -> wp.array: + def default_root_state(self) -> ProxyArray: """Default root state ``[pos, quat, lin_vel, ang_vel]`` in local environment frame. The position and quaternion are of the rigid body's actor frame. Meanwhile, the linear and angular velocities @@ -1125,6 +1331,7 @@ def default_root_state(self) -> wp.array: ) if self._default_root_state is None: self._default_root_state = wp.zeros((self._num_instances), dtype=shared_kernels.vec13f, device=self.device) + self._default_root_state_ta = ProxyArray(self._default_root_state) wp.launch( shared_kernels.concat_root_pose_and_vel_to_state, dim=self._num_instances, @@ -1137,10 +1344,10 @@ def default_root_state(self) -> wp.array: ], device=self.device, ) - return self._default_root_state + return self._default_root_state_ta @property - def body_state_w(self) -> wp.array: + def body_state_w(self) -> ProxyArray: """Deprecated, same as :attr:`body_link_pose_w` and :attr:`body_com_vel_w`.""" warnings.warn( "The `body_state_w` property will be deprecated in IsaacLab 4.0. Please use `body_link_pose_w` and " @@ -1153,13 +1360,14 @@ def body_state_w(self) -> wp.array: self._root_state_w = TimestampedBuffer( shape=(self._num_instances,), dtype=shared_kernels.vec13f, device=self.device ) + self._root_state_w_ta = ProxyArray(self._root_state_w.data) if self._root_state_w.timestamp < self._sim_timestamp: wp.launch( shared_kernels.concat_root_pose_and_vel_to_state, dim=self._num_instances, inputs=[ - self.root_link_pose_w, - self.root_com_vel_w, + self.root_link_pose_w.warp, + self.root_com_vel_w.warp, ], outputs=[ self._root_state_w.data, @@ -1167,10 +1375,12 @@ def body_state_w(self) -> wp.array: device=self.device, ) self._root_state_w.timestamp = self._sim_timestamp - return self._root_state_w.data.reshape((self._num_instances, 1)) + if self._body_state_w_ta is None: + self._body_state_w_ta = ProxyArray(self._root_state_w.data.reshape((self._num_instances, 1))) + return self._body_state_w_ta @property - def body_link_state_w(self) -> wp.array: + def body_link_state_w(self) -> ProxyArray: """Deprecated, same as :attr:`body_link_pose_w` and :attr:`body_link_vel_w`.""" warnings.warn( "The `body_link_state_w` property will be deprecated in IsaacLab 4.0. Please use `body_link_pose_w` and " @@ -1183,13 +1393,14 @@ def body_link_state_w(self) -> wp.array: self._root_link_state_w = TimestampedBuffer( shape=(self._num_instances,), dtype=shared_kernels.vec13f, device=self.device ) + self._root_link_state_w_ta = ProxyArray(self._root_link_state_w.data) if self._root_link_state_w.timestamp < self._sim_timestamp: wp.launch( shared_kernels.concat_root_pose_and_vel_to_state, dim=self._num_instances, inputs=[ - self.root_link_pose_w, - self.root_link_vel_w, + self.root_link_pose_w.warp, + self.root_link_vel_w.warp, ], outputs=[ self._root_link_state_w.data, @@ -1197,10 +1408,12 @@ def body_link_state_w(self) -> wp.array: device=self.device, ) self._root_link_state_w.timestamp = self._sim_timestamp - return self._root_link_state_w.data.reshape((self._num_instances, 1)) + if self._body_link_state_w_ta is None: + self._body_link_state_w_ta = ProxyArray(self._root_link_state_w.data.reshape((self._num_instances, 1))) + return self._body_link_state_w_ta @property - def body_com_state_w(self) -> wp.array: + def body_com_state_w(self) -> ProxyArray: """Deprecated, same as :attr:`body_com_pose_w` and :attr:`body_com_vel_w`.""" warnings.warn( "The `body_com_state_w` property will be deprecated in IsaacLab 4.0. Please use `body_com_pose_w` and " @@ -1212,13 +1425,14 @@ def body_com_state_w(self) -> wp.array: self._root_com_state_w = TimestampedBuffer( shape=(self._num_instances,), dtype=shared_kernels.vec13f, device=self.device ) + self._root_com_state_w_ta = ProxyArray(self._root_com_state_w.data) if self._root_com_state_w.timestamp < self._sim_timestamp: wp.launch( shared_kernels.concat_root_pose_and_vel_to_state, dim=self._num_instances, inputs=[ - self.root_com_pose_w, - self.root_com_vel_w, + self.root_com_pose_w.warp, + self.root_com_vel_w.warp, ], outputs=[ self._root_com_state_w.data, @@ -1226,4 +1440,6 @@ def body_com_state_w(self) -> wp.array: device=self.device, ) self._root_com_state_w.timestamp = self._sim_timestamp - return self._root_com_state_w.data.reshape((self._num_instances, 1)) + if self._body_com_state_w_ta is None: + self._body_com_state_w_ta = ProxyArray(self._root_com_state_w.data.reshape((self._num_instances, 1))) + return self._body_com_state_w_ta diff --git a/source/isaaclab_newton/isaaclab_newton/assets/rigid_object_collection/rigid_object_collection.py b/source/isaaclab_newton/isaaclab_newton/assets/rigid_object_collection/rigid_object_collection.py index 82bdf7a03003..8c499d75396c 100644 --- a/source/isaaclab_newton/isaaclab_newton/assets/rigid_object_collection/rigid_object_collection.py +++ b/source/isaaclab_newton/isaaclab_newton/assets/rigid_object_collection/rigid_object_collection.py @@ -21,6 +21,7 @@ import isaaclab.sim as sim_utils import isaaclab.utils.string as string_utils from isaaclab.assets.rigid_object_collection.base_rigid_object_collection import BaseRigidObjectCollection +from isaaclab.physics import PhysicsEvent from isaaclab.utils.wrench_composer import WrenchComposer from isaaclab_newton.assets import kernels as shared_kernels @@ -187,40 +188,23 @@ def write_data_to_sim(self) -> None: # write external wrench if self._instantaneous_wrench_composer.active or self._permanent_wrench_composer.active: if self._instantaneous_wrench_composer.active: - # Compose instantaneous wrench with permanent wrench - self._instantaneous_wrench_composer.add_forces_and_torques_index( - forces=self._permanent_wrench_composer.composed_force, - torques=self._permanent_wrench_composer.composed_torque, - body_ids=self._ALL_BODY_INDICES, - env_ids=self._ALL_ENV_INDICES, - ) - # Apply both instantaneous and permanent wrench to a consolidated 2D buffer - wp.launch( - shared_kernels.update_wrench_array_with_force_and_torque, - dim=(self.num_instances, self.num_bodies), - device=self.device, - inputs=[ - self._instantaneous_wrench_composer.composed_force, - self._instantaneous_wrench_composer.composed_torque, - self._wrench_buffer, - self._ALL_ENV_MASK, - self._ALL_BODY_MASK, - ], - ) + composer = self._instantaneous_wrench_composer + composer.add_raw_buffers_from(self._permanent_wrench_composer) else: - # Apply permanent wrench to a consolidated 2D buffer - wp.launch( - shared_kernels.update_wrench_array_with_force_and_torque, - dim=(self.num_instances, self.num_bodies), - device=self.device, - inputs=[ - self._permanent_wrench_composer.composed_force, - self._permanent_wrench_composer.composed_torque, - self._wrench_buffer, - self._ALL_ENV_MASK, - self._ALL_BODY_MASK, - ], - ) + composer = self._permanent_wrench_composer + composer.compose_to_body_frame() + wp.launch( + shared_kernels.update_wrench_array_with_force_and_torque, + dim=(self.num_instances, self.num_bodies), + device=self.device, + inputs=[ + composer.out_force_b, + composer.out_torque_b, + self._wrench_buffer, + self._ALL_ENV_MASK, + self._ALL_BODY_MASK, + ], + ) # Write the wrench buffer directly to the Newton binding (already 2D) wp.copy(self._data._sim_bind_body_external_wrench, self._wrench_buffer) self._instantaneous_wrench_composer.reset() @@ -417,6 +401,9 @@ def write_body_link_pose_to_sim_index( body_ids: Body indices. If None, then all indices are used. env_ids: Environment indices. If None, then all indices are used. full_data: Whether to expect full data. Defaults to False. + + Note: + Triggers per-environment FK recomputation and solver reset (Kamino) for the affected environments. """ env_ids = self._resolve_env_ids(env_ids) body_ids = self._resolve_body_ids(body_ids) @@ -446,6 +433,7 @@ def write_body_link_pose_to_sim_index( self.data._body_com_state_w.timestamp = -1.0 self.data._body_link_state_w.timestamp = -1.0 self.data._body_state_w.timestamp = -1.0 + SimulationManager.invalidate_fk(env_ids=env_ids, articulation_ids=self._root_view.articulation_ids) def write_body_link_pose_to_sim_mask( self, @@ -470,10 +458,14 @@ def write_body_link_pose_to_sim_mask( or (num_instances, num_bodies) with dtype wp.transformf. env_mask: Environment mask. If None, then all the instances are updated. Shape is (num_instances,). body_ids: Body indices. If None, then all indices are used. + + Note: + Triggers per-environment FK recomputation and solver reset (Kamino) for the affected environments. """ if env_mask is not None: env_ids = self._resolve_env_mask(env_mask) else: + env_mask = self._ALL_ENV_MASK env_ids = self._ALL_ENV_INDICES self.write_body_link_pose_to_sim_index( body_poses=body_poses, env_ids=env_ids, body_ids=body_ids, full_data=True @@ -506,6 +498,9 @@ def write_body_com_pose_to_sim_index( body_ids: Body indices. If None, then all indices are used. env_ids: Environment indices. If None, then all indices are used. full_data: Whether to expect full data. Defaults to False. + + Note: + Triggers per-environment FK recomputation and solver reset (Kamino) for the affected environments. """ env_ids = self._resolve_env_ids(env_ids) body_ids = self._resolve_body_ids(body_ids) @@ -537,6 +532,7 @@ def write_body_com_pose_to_sim_index( self.data._body_link_state_w.timestamp = -1.0 self.data._body_state_w.timestamp = -1.0 self.data._body_com_state_w.timestamp = -1.0 + SimulationManager.invalidate_fk(env_ids=env_ids, articulation_ids=self._root_view.articulation_ids) def write_body_com_pose_to_sim_mask( self, @@ -562,10 +558,14 @@ def write_body_com_pose_to_sim_mask( or (num_instances, num_bodies) with dtype wp.transformf. env_mask: Environment mask. If None, then all the instances are updated. Shape is (num_instances,). body_ids: Body indices. If None, then all indices are used. + + Note: + Triggers per-environment FK recomputation and solver reset (Kamino) for the affected environments. """ if env_mask is not None: env_ids = self._resolve_env_mask(env_mask) else: + env_mask = self._ALL_ENV_MASK env_ids = self._ALL_ENV_INDICES self.write_body_com_pose_to_sim_index(body_poses=body_poses, env_ids=env_ids, body_ids=body_ids, full_data=True) @@ -598,6 +598,9 @@ def write_body_com_velocity_to_sim_index( body_ids: Body indices. If None, then all indices are used. env_ids: Environment indices. If None, then all indices are used. full_data: Whether to expect full data. Defaults to False. + + Note: + Triggers per-environment FK recomputation and solver reset (Kamino) for the affected environments. """ env_ids = self._resolve_env_ids(env_ids) body_ids = self._resolve_body_ids(body_ids) @@ -632,6 +635,7 @@ def write_body_com_velocity_to_sim_index( self.data._body_state_w.timestamp = -1.0 self.data._body_com_state_w.timestamp = -1.0 self.data._body_link_state_w.timestamp = -1.0 + SimulationManager.invalidate_fk(env_ids=env_ids, articulation_ids=self._root_view.articulation_ids) def write_body_com_velocity_to_sim_mask( self, @@ -660,10 +664,14 @@ def write_body_com_velocity_to_sim_mask( or (num_instances, num_bodies) with dtype wp.spatial_vectorf. env_mask: Environment mask. If None, then all the instances are updated. Shape is (num_instances,). body_ids: Body indices. If None, then all indices are used. + + Note: + Triggers per-environment FK recomputation and solver reset (Kamino) for the affected environments. """ if env_mask is not None: env_ids = self._resolve_env_mask(env_mask) else: + env_mask = self._ALL_ENV_MASK env_ids = self._ALL_ENV_INDICES self.write_body_com_velocity_to_sim_index( body_velocities=body_velocities, env_ids=env_ids, body_ids=body_ids, full_data=True @@ -698,6 +706,9 @@ def write_body_link_velocity_to_sim_index( body_ids: Body indices. If None, then all indices are used. env_ids: Environment indices. If None, then all indices are used. full_data: Whether to expect full data. Defaults to False. + + Note: + Triggers per-environment FK recomputation and solver reset (Kamino) for the affected environments. """ env_ids = self._resolve_env_ids(env_ids) body_ids = self._resolve_body_ids(body_ids) @@ -735,6 +746,7 @@ def write_body_link_velocity_to_sim_index( self.data._body_link_state_w.timestamp = -1.0 self.data._body_state_w.timestamp = -1.0 self.data._body_com_state_w.timestamp = -1.0 + SimulationManager.invalidate_fk(env_ids=env_ids, articulation_ids=self._root_view.articulation_ids) def write_body_link_velocity_to_sim_mask( self, @@ -762,10 +774,14 @@ def write_body_link_velocity_to_sim_mask( or (num_instances, num_bodies) with dtype wp.spatial_vectorf. env_mask: Environment mask. If None, then all the instances are updated. Shape is (num_instances,). body_ids: Body indices. If None, then all indices are used. + + Note: + Triggers per-environment FK recomputation and solver reset (Kamino) for the affected environments. """ if env_mask is not None: env_ids = self._resolve_env_mask(env_mask) else: + env_mask = self._ALL_ENV_MASK env_ids = self._ALL_ENV_INDICES self.write_body_link_velocity_to_sim_index( body_velocities=body_velocities, env_ids=env_ids, body_ids=body_ids, full_data=True @@ -1119,6 +1135,13 @@ def _initialize_impl(self): # container for data access self._data = RigidObjectCollectionData(self._root_view, self.num_bodies, self.device) + # Register callback to rebind simulation data after a full reset (model/state recreation). + self._physics_ready_handle = SimulationManager.register_callback( + lambda _: self._data._create_simulation_bindings(), + PhysicsEvent.PHYSICS_READY, + name=f"rigid_object_collection_rebind_{self.cfg.rigid_objects}", + ) + # create buffers self._create_buffers() # process configuration @@ -1172,27 +1195,45 @@ def _process_cfg(self) -> None: self.data.default_body_vel = wp.array(default_body_vels, dtype=wp.spatial_vectorf, device=self.device) def _resolve_env_ids(self, env_ids) -> wp.array: - """Resolve environment indices to a warp array.""" - if isinstance(env_ids, list): - return wp.array(env_ids, dtype=wp.int32, device=self.device) + """Resolve environment indices to a warp array. + + Args: + env_ids: Environment indices. If None, then all indices are used. + + Returns: + A warp array of environment indices. + """ if (env_ids is None) or (env_ids == slice(None)): return self._ALL_ENV_INDICES if isinstance(env_ids, torch.Tensor): - return wp.from_torch(env_ids.to(torch.int32), dtype=wp.int32) + if env_ids.dtype == torch.int64: + env_ids = env_ids.to(torch.int32) + return wp.from_torch(env_ids, dtype=wp.int32) + if isinstance(env_ids, list): + return wp.array(env_ids, dtype=wp.int32, device=self.device) return env_ids def _resolve_body_ids(self, body_ids) -> wp.array: - """Resolve body indices to a warp array.""" - if body_ids is None or (body_ids == slice(None)): + """Resolve body indices to a warp array. + + Args: + body_ids: Body indices. If None, then all indices are used. + + Returns: + A warp array of body indices. + """ + if isinstance(body_ids, list): + return wp.array(body_ids, dtype=wp.int32, device=self.device) + if (body_ids is None) or (body_ids == slice(None)): return self._ALL_BODY_INDICES if isinstance(body_ids, slice): return wp.from_torch( torch.arange(self.num_bodies, dtype=torch.int32, device=self.device)[body_ids], dtype=wp.int32 ) - if isinstance(body_ids, list): - return wp.array(body_ids, dtype=wp.int32, device=self.device) if isinstance(body_ids, torch.Tensor): - return wp.from_torch(body_ids.to(torch.int32), dtype=wp.int32) + if body_ids.dtype == torch.int64: + body_ids = body_ids.to(torch.int32) + return wp.from_torch(body_ids, dtype=wp.int32) return body_ids def _resolve_env_mask(self, env_mask: wp.array | None) -> wp.array | torch.Tensor: diff --git a/source/isaaclab_newton/isaaclab_newton/assets/rigid_object_collection/rigid_object_collection_data.py b/source/isaaclab_newton/isaaclab_newton/assets/rigid_object_collection/rigid_object_collection_data.py index 3fbc1801322f..9fe3ec125de0 100644 --- a/source/isaaclab_newton/isaaclab_newton/assets/rigid_object_collection/rigid_object_collection_data.py +++ b/source/isaaclab_newton/isaaclab_newton/assets/rigid_object_collection/rigid_object_collection_data.py @@ -15,6 +15,7 @@ from isaaclab.assets.rigid_object_collection.base_rigid_object_collection_data import BaseRigidObjectCollectionData from isaaclab.utils.buffers import TimestampedBufferWarp as TimestampedBuffer from isaaclab.utils.math import normalize +from isaaclab.utils.warp import ProxyArray from isaaclab_newton.assets import kernels as shared_kernels from isaaclab_newton.physics import NewtonManager as SimulationManager @@ -75,10 +76,14 @@ def __init__(self, root_view: ArticulationView, num_bodies: int, device: str): gravity_dir = normalize(gravity_dir.unsqueeze(0)).squeeze(0) # Initialize constants - self.GRAVITY_VEC_W = wp.from_torch(gravity_dir.repeat(self.num_instances, self.num_bodies, 1), dtype=wp.vec3f) - self.FORWARD_VEC_B = wp.from_torch( - torch.tensor((1.0, 0.0, 0.0), device=self.device).repeat(self.num_instances, self.num_bodies, 1), - dtype=wp.vec3f, + self.GRAVITY_VEC_W = ProxyArray( + wp.from_torch(gravity_dir.repeat(self.num_instances, self.num_bodies, 1), dtype=wp.vec3f) + ) + self.FORWARD_VEC_B = ProxyArray( + wp.from_torch( + torch.tensor((1.0, 0.0, 0.0), device=self.device).repeat(self.num_instances, self.num_bodies, 1), + dtype=wp.vec3f, + ) ) self._create_simulation_bindings() @@ -130,14 +135,14 @@ def update(self, dt: float) -> None: """ @property - def default_body_pose(self) -> wp.array: + def default_body_pose(self) -> ProxyArray: """Default body pose ``[pos, quat]`` in local environment frame. The position and quaternion are of the rigid body's actor frame. Shape is (num_instances, num_bodies), dtype = wp.transformf. In torch this resolves to (num_instances, num_bodies, 7). """ - return self._default_body_pose + return self._default_body_pose_ta @default_body_pose.setter def default_body_pose(self, value: wp.array) -> None: @@ -154,14 +159,14 @@ def default_body_pose(self, value: wp.array) -> None: self._default_body_pose.assign(value) @property - def default_body_vel(self) -> wp.array: + def default_body_vel(self) -> ProxyArray: """Default body velocity ``[lin_vel, ang_vel]`` in local environment frame. The linear and angular velocities are of the rigid body's center of mass frame. Shape is (num_instances, num_bodies), dtype = wp.spatial_vectorf. In torch this resolves to (num_instances, num_bodies, 6). """ - return self._default_body_vel + return self._default_body_vel_ta @default_body_vel.setter def default_body_vel(self, value: wp.array) -> None: @@ -182,7 +187,7 @@ def default_body_vel(self, value: wp.array) -> None: """ @property - def body_link_pose_w(self) -> wp.array: + def body_link_pose_w(self) -> ProxyArray: """Body link pose ``[pos, quat]`` in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.transformf. In torch this resolves to @@ -190,10 +195,10 @@ def body_link_pose_w(self) -> wp.array: This quantity is the pose of the actor frame of the rigid body relative to the world. The orientation is provided in (x, y, z, w) format. """ - return self._sim_bind_body_link_pose_w + return self._body_link_pose_w_ta @property - def body_link_vel_w(self) -> wp.array: + def body_link_vel_w(self) -> ProxyArray: """Body link velocity ``[lin_vel, ang_vel]`` in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.spatial_vectorf. In torch this resolves to @@ -206,9 +211,9 @@ def body_link_vel_w(self) -> wp.array: shared_kernels.get_body_link_vel_from_body_com_vel, dim=(self.num_instances, self.num_bodies), inputs=[ - self.body_com_vel_w, - self.body_link_pose_w, - self.body_com_pos_b, + self.body_com_vel_w.warp, + self.body_link_pose_w.warp, + self.body_com_pos_b.warp, ], outputs=[ self._body_link_vel_w.data, @@ -217,10 +222,10 @@ def body_link_vel_w(self) -> wp.array: ) self._body_link_vel_w.timestamp = self._sim_timestamp - return self._body_link_vel_w.data + return self._body_link_vel_w_ta @property - def body_com_pose_w(self) -> wp.array: + def body_com_pose_w(self) -> ProxyArray: """Body center of mass pose ``[pos, quat]`` in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.transformf. In torch this resolves to @@ -233,8 +238,8 @@ def body_com_pose_w(self) -> wp.array: shared_kernels.get_body_com_pose_from_body_link_pose, dim=(self.num_instances, self.num_bodies), inputs=[ - self.body_link_pose_w, - self.body_com_pos_b, + self.body_link_pose_w.warp, + self.body_com_pos_b.warp, ], outputs=[ self._body_com_pose_w.data, @@ -243,10 +248,10 @@ def body_com_pose_w(self) -> wp.array: ) self._body_com_pose_w.timestamp = self._sim_timestamp - return self._body_com_pose_w.data + return self._body_com_pose_w_ta @property - def body_com_vel_w(self) -> wp.array: + def body_com_vel_w(self) -> ProxyArray: """Body center of mass velocity ``[lin_vel, ang_vel]`` in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.spatial_vectorf. In torch this resolves to @@ -254,10 +259,10 @@ def body_com_vel_w(self) -> wp.array: This quantity contains the linear and angular velocities of the root rigid body's center of mass frame relative to the world. """ - return self._sim_bind_body_com_vel_w + return self._body_com_vel_w_ta @property - def body_com_acc_w(self) -> wp.array: + def body_com_acc_w(self) -> ProxyArray: """Acceleration of all bodies ``[lin_acc, ang_acc]`` in the simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.spatial_vectorf. In torch this resolves to @@ -270,7 +275,7 @@ def body_com_acc_w(self) -> wp.array: dim=(self.num_instances, self.num_bodies), device=self.device, inputs=[ - self.body_com_vel_w, + self.body_com_vel_w.warp, SimulationManager.get_dt(), self._previous_body_com_vel, ], @@ -279,10 +284,10 @@ def body_com_acc_w(self) -> wp.array: ], ) self._body_com_acc_w.timestamp = self._sim_timestamp - return self._body_com_acc_w.data + return self._body_com_acc_w_ta @property - def body_com_pose_b(self) -> wp.array: + def body_com_pose_b(self) -> ProxyArray: """Center of mass pose ``[pos, quat]`` of all bodies in their respective body's link frames. Shape is (num_instances, num_bodies), dtype = wp.transformf. In torch this resolves to @@ -301,7 +306,7 @@ def body_com_pose_b(self) -> wp.array: shared_kernels.make_dummy_body_com_pose_b, dim=(self.num_instances, self.num_bodies), inputs=[ - self.body_com_pos_b, + self.body_com_pos_b.warp, ], outputs=[ self._body_com_pose_b.data, @@ -309,42 +314,42 @@ def body_com_pose_b(self) -> wp.array: device=self.device, ) self._body_com_pose_b.timestamp = self._sim_timestamp - return self._body_com_pose_b.data + return self._body_com_pose_b_ta @property - def body_com_pos_b(self) -> wp.array: + def body_com_pos_b(self) -> ProxyArray: """Center of mass position of all of the bodies in their respective link frames. Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to (num_instances, num_bodies, 3). This quantity is the center of mass location relative to its body's link frame. """ - return self._sim_bind_body_com_pos_b + return self._body_com_pos_b_ta @property - def body_mass(self) -> wp.array: + def body_mass(self) -> ProxyArray: """Mass of all bodies in the simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.float32. In torch this resolves to (num_instances, num_bodies). """ - return self._sim_bind_body_mass + return self._body_mass_ta @property - def body_inertia(self) -> wp.array: + def body_inertia(self) -> ProxyArray: """Inertia of all bodies in the simulation world frame. Shape is (num_instances, num_bodies, 9), dtype = wp.float32. In torch this resolves to (num_instances, num_bodies, 9). """ - return self._body_inertia + return self._body_inertia_ta """ Derived Properties. """ @property - def projected_gravity_b(self) -> wp.array: + def projected_gravity_b(self) -> ProxyArray: """Projection of the gravity direction on base frame. Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to @@ -354,15 +359,15 @@ def projected_gravity_b(self) -> wp.array: wp.launch( shared_kernels.quat_apply_inverse_2D_kernel, dim=(self.num_instances, self.num_bodies), - inputs=[self.GRAVITY_VEC_W, self.body_link_quat_w], + inputs=[self.GRAVITY_VEC_W.warp, self.body_link_quat_w.warp], outputs=[self._projected_gravity_b.data], device=self.device, ) self._projected_gravity_b.timestamp = self._sim_timestamp - return self._projected_gravity_b.data + return self._projected_gravity_b_ta @property - def heading_w(self) -> wp.array: + def heading_w(self) -> ProxyArray: """Yaw heading of the base frame (in radians). Shape is (num_instances, num_bodies), dtype = wp.float32. In torch this resolves to (num_instances, num_bodies). @@ -375,15 +380,15 @@ def heading_w(self) -> wp.array: wp.launch( shared_kernels.body_heading_w, dim=(self.num_instances, self.num_bodies), - inputs=[self.FORWARD_VEC_B, self.body_link_quat_w], + inputs=[self.FORWARD_VEC_B.warp, self.body_link_quat_w.warp], outputs=[self._heading_w.data], device=self.device, ) self._heading_w.timestamp = self._sim_timestamp - return self._heading_w.data + return self._heading_w_ta @property - def body_link_lin_vel_b(self) -> wp.array: + def body_link_lin_vel_b(self) -> ProxyArray: """Root link linear velocity in base frame. Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to @@ -395,15 +400,15 @@ def body_link_lin_vel_b(self) -> wp.array: wp.launch( shared_kernels.quat_apply_inverse_2D_kernel, dim=(self.num_instances, self.num_bodies), - inputs=[self.body_link_lin_vel_w, self.body_link_quat_w], + inputs=[self.body_link_lin_vel_w.warp, self.body_link_quat_w.warp], outputs=[self._body_link_lin_vel_b.data], device=self.device, ) self._body_link_lin_vel_b.timestamp = self._sim_timestamp - return self._body_link_lin_vel_b.data + return self._body_link_lin_vel_b_ta @property - def body_link_ang_vel_b(self) -> wp.array: + def body_link_ang_vel_b(self) -> ProxyArray: """Root link angular velocity in base frame. Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to @@ -415,15 +420,15 @@ def body_link_ang_vel_b(self) -> wp.array: wp.launch( shared_kernels.quat_apply_inverse_2D_kernel, dim=(self.num_instances, self.num_bodies), - inputs=[self.body_link_ang_vel_w, self.body_link_quat_w], + inputs=[self.body_link_ang_vel_w.warp, self.body_link_quat_w.warp], outputs=[self._body_link_ang_vel_b.data], device=self.device, ) self._body_link_ang_vel_b.timestamp = self._sim_timestamp - return self._body_link_ang_vel_b.data + return self._body_link_ang_vel_b_ta @property - def body_com_lin_vel_b(self) -> wp.array: + def body_com_lin_vel_b(self) -> ProxyArray: """Root center of mass linear velocity in base frame. Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to @@ -435,15 +440,15 @@ def body_com_lin_vel_b(self) -> wp.array: wp.launch( shared_kernels.quat_apply_inverse_2D_kernel, dim=(self.num_instances, self.num_bodies), - inputs=[self.body_com_lin_vel_w, self.body_link_quat_w], + inputs=[self.body_com_lin_vel_w.warp, self.body_link_quat_w.warp], outputs=[self._body_com_lin_vel_b.data], device=self.device, ) self._body_com_lin_vel_b.timestamp = self._sim_timestamp - return self._body_com_lin_vel_b.data + return self._body_com_lin_vel_b_ta @property - def body_com_ang_vel_b(self) -> wp.array: + def body_com_ang_vel_b(self) -> ProxyArray: """Root center of mass angular velocity in base frame. Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to @@ -455,119 +460,139 @@ def body_com_ang_vel_b(self) -> wp.array: wp.launch( shared_kernels.quat_apply_inverse_2D_kernel, dim=(self.num_instances, self.num_bodies), - inputs=[self.body_com_ang_vel_w, self.body_link_quat_w], + inputs=[self.body_com_ang_vel_w.warp, self.body_link_quat_w.warp], outputs=[self._body_com_ang_vel_b.data], device=self.device, ) self._body_com_ang_vel_b.timestamp = self._sim_timestamp - return self._body_com_ang_vel_b.data + return self._body_com_ang_vel_b_ta """ Sliced properties. """ @property - def body_link_pos_w(self) -> wp.array: + def body_link_pos_w(self) -> ProxyArray: """Positions of all bodies in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to (num_instances, num_bodies, 3). This quantity is the position of the rigid bodies' actor frame relative to the world. """ - return self._get_pos_from_transform(self.body_link_pose_w) + if self._body_link_pos_w_ta is None: + self._body_link_pos_w_ta = ProxyArray(self._get_pos_from_transform(self.body_link_pose_w.warp)) + return self._body_link_pos_w_ta @property - def body_link_quat_w(self) -> wp.array: + def body_link_quat_w(self) -> ProxyArray: """Orientation (x, y, z, w) of all bodies in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.quatf. In torch this resolves to (num_instances, num_bodies, 4). This quantity is the orientation of the rigid bodies' actor frame relative to the world. """ - return self._get_quat_from_transform(self.body_link_pose_w) + if self._body_link_quat_w_ta is None: + self._body_link_quat_w_ta = ProxyArray(self._get_quat_from_transform(self.body_link_pose_w.warp)) + return self._body_link_quat_w_ta @property - def body_link_lin_vel_w(self) -> wp.array: + def body_link_lin_vel_w(self) -> ProxyArray: """Linear velocity of all bodies in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to (num_instances, num_bodies, 3). This quantity is the linear velocity of the rigid bodies' actor frame relative to the world. """ - return self._get_lin_vel_from_spatial_vector(self.body_link_vel_w) + if self._body_link_lin_vel_w_ta is None: + self._body_link_lin_vel_w_ta = ProxyArray(self._get_lin_vel_from_spatial_vector(self.body_link_vel_w.warp)) + return self._body_link_lin_vel_w_ta @property - def body_link_ang_vel_w(self) -> wp.array: + def body_link_ang_vel_w(self) -> ProxyArray: """Angular velocity of all bodies in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to (num_instances, num_bodies, 3). This quantity is the angular velocity of the rigid bodies' actor frame relative to the world. """ - return self._get_ang_vel_from_spatial_vector(self.body_link_vel_w) + if self._body_link_ang_vel_w_ta is None: + self._body_link_ang_vel_w_ta = ProxyArray(self._get_ang_vel_from_spatial_vector(self.body_link_vel_w.warp)) + return self._body_link_ang_vel_w_ta @property - def body_com_pos_w(self) -> wp.array: + def body_com_pos_w(self) -> ProxyArray: """Positions of all bodies' center of mass in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to (num_instances, num_bodies, 3). This quantity is the position of the rigid bodies' center of mass frame. """ - return self._get_pos_from_transform(self.body_com_pose_w) + if self._body_com_pos_w_ta is None: + self._body_com_pos_w_ta = ProxyArray(self._get_pos_from_transform(self.body_com_pose_w.warp)) + return self._body_com_pos_w_ta @property - def body_com_quat_w(self) -> wp.array: + def body_com_quat_w(self) -> ProxyArray: """Orientation (x, y, z, w) of the principal axes of inertia of all bodies in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.quatf. In torch this resolves to (num_instances, num_bodies, 4). This quantity is the orientation of the principal axes of inertia of the rigid bodies. """ - return self._get_quat_from_transform(self.body_com_pose_w) + if self._body_com_quat_w_ta is None: + self._body_com_quat_w_ta = ProxyArray(self._get_quat_from_transform(self.body_com_pose_w.warp)) + return self._body_com_quat_w_ta @property - def body_com_lin_vel_w(self) -> wp.array: + def body_com_lin_vel_w(self) -> ProxyArray: """Linear velocity of all bodies in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to (num_instances, num_bodies, 3). This quantity is the linear velocity of the rigid bodies' center of mass frame. """ - return self._get_lin_vel_from_spatial_vector(self.body_com_vel_w) + if self._body_com_lin_vel_w_ta is None: + self._body_com_lin_vel_w_ta = ProxyArray(self._get_lin_vel_from_spatial_vector(self.body_com_vel_w.warp)) + return self._body_com_lin_vel_w_ta @property - def body_com_ang_vel_w(self) -> wp.array: + def body_com_ang_vel_w(self) -> ProxyArray: """Angular velocity of all bodies in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to (num_instances, num_bodies, 3). This quantity is the angular velocity of the rigid bodies' center of mass frame. """ - return self._get_ang_vel_from_spatial_vector(self.body_com_vel_w) + if self._body_com_ang_vel_w_ta is None: + self._body_com_ang_vel_w_ta = ProxyArray(self._get_ang_vel_from_spatial_vector(self.body_com_vel_w.warp)) + return self._body_com_ang_vel_w_ta @property - def body_com_lin_acc_w(self) -> wp.array: + def body_com_lin_acc_w(self) -> ProxyArray: """Linear acceleration of all bodies in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to (num_instances, num_bodies, 3). This quantity is the linear acceleration of the rigid bodies' center of mass frame. """ - return self._get_lin_vel_from_spatial_vector(self.body_com_acc_w) + if self._body_com_lin_acc_w_ta is None: + self._body_com_lin_acc_w_ta = ProxyArray(self._get_lin_vel_from_spatial_vector(self.body_com_acc_w.warp)) + return self._body_com_lin_acc_w_ta @property - def body_com_ang_acc_w(self) -> wp.array: + def body_com_ang_acc_w(self) -> ProxyArray: """Angular acceleration of all bodies in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to (num_instances, num_bodies, 3). This quantity is the angular acceleration of the rigid bodies' center of mass frame. """ - return self._get_ang_vel_from_spatial_vector(self.body_com_acc_w) + if self._body_com_ang_acc_w_ta is None: + self._body_com_ang_acc_w_ta = ProxyArray(self._get_ang_vel_from_spatial_vector(self.body_com_acc_w.warp)) + return self._body_com_ang_acc_w_ta @property - def body_com_quat_b(self) -> wp.array: + def body_com_quat_b(self) -> ProxyArray: """Orientation (x, y, z, w) of the principal axes of inertia of all of the bodies in their respective link frames. @@ -575,7 +600,9 @@ def body_com_quat_b(self) -> wp.array: (num_instances, num_bodies, 4). This quantity is the orientation of the principal axes of inertia relative to its body's link frame. """ - return self._get_quat_from_transform(self.body_com_pose_b) + if self._body_com_quat_b_ta is None: + self._body_com_quat_b_ta = ProxyArray(self._get_quat_from_transform(self.body_com_pose_b.warp)) + return self._body_com_quat_b_ta def _create_simulation_bindings(self) -> None: """Create simulation bindings for the body data. @@ -609,6 +636,11 @@ def _create_simulation_bindings(self) -> None: copy=False, ) + # Re-pin ProxyArray wrappers to the newly created sim bindings. + # On first init, _create_buffers() handles this after all buffers exist. + if hasattr(self, "_body_link_pose_w_ta"): + self._pin_proxy_arrays() + def _create_buffers(self) -> None: """Create buffers for computing and caching derived quantities.""" super()._create_buffers() @@ -654,6 +686,74 @@ def _create_buffers(self) -> None: # -- Initialize history for finite differencing self._previous_body_com_vel = wp.clone(self._sim_bind_body_com_vel_w) + # Pin all ProxyArray wrappers to current buffers. + self._pin_proxy_arrays() + + def _pin_proxy_arrays(self) -> None: + """Create or rebind all pinned ProxyArray wrappers. + + Called from :meth:`_create_buffers` on first initialization and from + :meth:`_create_simulation_bindings` after a full simulation reset when + the solver recreates its internal arrays. + """ + is_rebind = hasattr(self, "_body_link_pose_w_ta") + + if is_rebind: + # Rebind sim-bound ProxyArrays to new solver arrays + self._body_link_pose_w_ta = ProxyArray(self._sim_bind_body_link_pose_w) + self._body_com_vel_w_ta = ProxyArray(self._sim_bind_body_com_vel_w) + self._body_com_pos_b_ta = ProxyArray(self._sim_bind_body_com_pos_b) + self._body_mass_ta = ProxyArray(self._sim_bind_body_mass) + self._body_inertia_ta = ProxyArray(self._body_inertia) + else: + # First-time creation: pin ProxyArrays to current buffers + # Category 1: sim-bound and pre-allocated buffers + # Newton wp.array pointers are stable, so a ProxyArray wrapping them is valid forever. + self._body_link_pose_w_ta = ProxyArray(self._sim_bind_body_link_pose_w) + self._body_com_vel_w_ta = ProxyArray(self._sim_bind_body_com_vel_w) + self._body_com_pos_b_ta = ProxyArray(self._sim_bind_body_com_pos_b) + self._body_mass_ta = ProxyArray(self._sim_bind_body_mass) + self._body_inertia_ta = ProxyArray(self._body_inertia) + self._default_body_pose_ta = ProxyArray(self._default_body_pose) + self._default_body_vel_ta = ProxyArray(self._default_body_vel) + + # Category 2: TimestampedBuffer properties + self._body_link_vel_w_ta = ProxyArray(self._body_link_vel_w.data) + self._body_com_pose_w_ta = ProxyArray(self._body_com_pose_w.data) + self._body_com_acc_w_ta = ProxyArray(self._body_com_acc_w.data) + self._body_com_pose_b_ta = ProxyArray(self._body_com_pose_b.data) + self._projected_gravity_b_ta = ProxyArray(self._projected_gravity_b.data) + self._heading_w_ta = ProxyArray(self._heading_w.data) + self._body_link_lin_vel_b_ta = ProxyArray(self._body_link_lin_vel_b.data) + self._body_link_ang_vel_b_ta = ProxyArray(self._body_link_ang_vel_b.data) + self._body_com_lin_vel_b_ta = ProxyArray(self._body_com_lin_vel_b.data) + self._body_com_ang_vel_b_ta = ProxyArray(self._body_com_ang_vel_b.data) + self._body_state_w_ta = ProxyArray(self._body_state_w.data) + self._body_link_state_w_ta = ProxyArray(self._body_link_state_w.data) + self._body_com_state_w_ta = ProxyArray(self._body_com_state_w.data) + + # -- deprecated state properties (lazy); type annotation declared once here + self._default_body_state_ta: ProxyArray | None = None + + # Invalidate lazy sliced ProxyArrays AND their backing wp.arrays so they are + # re-created from fresh data on next access. On first init the backing fields + # are already None (set by _create_buffers), so the assignments below are + # harmless no-ops. On rebind they reset stale pointers into freed transform + # memory after a sim reset. + self._body_link_pos_w_ta: ProxyArray | None = None + self._body_link_quat_w_ta: ProxyArray | None = None + self._body_link_lin_vel_w_ta: ProxyArray | None = None + self._body_link_ang_vel_w_ta: ProxyArray | None = None + self._body_com_pos_w_ta: ProxyArray | None = None + self._body_com_quat_w_ta: ProxyArray | None = None + self._body_com_lin_vel_w_ta: ProxyArray | None = None + self._body_com_ang_vel_w_ta: ProxyArray | None = None + self._body_com_lin_acc_w_ta: ProxyArray | None = None + self._body_com_ang_acc_w_ta: ProxyArray | None = None + self._body_com_quat_b_ta: ProxyArray | None = None + self._default_body_state_ta: ProxyArray | None = None + self._default_body_state = None + """ Helpers. """ @@ -703,7 +803,7 @@ def _get_ang_vel_from_spatial_vector(self, spatial_vector: wp.array) -> wp.array """ @property - def default_body_state(self) -> wp.array: + def default_body_state(self) -> ProxyArray: """Default root state ``[pos, quat, lin_vel, ang_vel]`` in local environment frame. The position and quaternion are of the rigid body's actor frame. Meanwhile, the linear and angular velocities @@ -719,6 +819,7 @@ def default_body_state(self) -> wp.array: self._default_body_state = wp.zeros( (self.num_instances, self.num_bodies), dtype=shared_kernels.vec13f, device=self.device ) + self._default_body_state_ta = ProxyArray(self._default_body_state) wp.launch( shared_kernels.concat_body_pose_and_vel_to_state, dim=(self.num_instances, self.num_bodies), @@ -731,10 +832,10 @@ def default_body_state(self) -> wp.array: ], device=self.device, ) - return self._default_body_state + return self._default_body_state_ta @property - def body_state_w(self) -> wp.array: + def body_state_w(self) -> ProxyArray: """Deprecated, same as :attr:`body_link_pose_w` and :attr:`body_com_vel_w`.""" warnings.warn( "The `body_state_w` property will be deprecated in IsaacLab 4.0. Please use `body_link_pose_w` and " @@ -747,8 +848,8 @@ def body_state_w(self) -> wp.array: shared_kernels.concat_body_pose_and_vel_to_state, dim=(self.num_instances, self.num_bodies), inputs=[ - self.body_link_pose_w, - self.body_com_vel_w, + self.body_link_pose_w.warp, + self.body_com_vel_w.warp, ], outputs=[ self._body_state_w.data, @@ -757,10 +858,10 @@ def body_state_w(self) -> wp.array: ) self._body_state_w.timestamp = self._sim_timestamp - return self._body_state_w.data + return self._body_state_w_ta @property - def body_link_state_w(self) -> wp.array: + def body_link_state_w(self) -> ProxyArray: """Deprecated, same as :attr:`body_link_pose_w` and :attr:`body_link_vel_w`.""" warnings.warn( "The `body_link_state_w` property will be deprecated in IsaacLab 4.0. Please use `body_link_pose_w` and " @@ -773,8 +874,8 @@ def body_link_state_w(self) -> wp.array: shared_kernels.concat_body_pose_and_vel_to_state, dim=(self.num_instances, self.num_bodies), inputs=[ - self.body_link_pose_w, - self.body_link_vel_w, + self.body_link_pose_w.warp, + self.body_link_vel_w.warp, ], outputs=[ self._body_link_state_w.data, @@ -783,10 +884,10 @@ def body_link_state_w(self) -> wp.array: ) self._body_link_state_w.timestamp = self._sim_timestamp - return self._body_link_state_w.data + return self._body_link_state_w_ta @property - def body_com_state_w(self) -> wp.array: + def body_com_state_w(self) -> ProxyArray: """Deprecated, same as :attr:`body_com_pose_w` and :attr:`body_com_vel_w`.""" warnings.warn( "The `body_com_state_w` property will be deprecated in IsaacLab 4.0. Please use `body_com_pose_w` and " @@ -799,8 +900,8 @@ def body_com_state_w(self) -> wp.array: shared_kernels.concat_body_pose_and_vel_to_state, dim=(self.num_instances, self.num_bodies), inputs=[ - self.body_com_pose_w, - self.body_com_vel_w, + self.body_com_pose_w.warp, + self.body_com_vel_w.warp, ], outputs=[ self._body_com_state_w.data, @@ -809,4 +910,4 @@ def body_com_state_w(self) -> wp.array: ) self._body_com_state_w.timestamp = self._sim_timestamp - return self._body_com_state_w.data + return self._body_com_state_w_ta diff --git a/source/isaaclab_newton/isaaclab_newton/cloner/newton_replicate.py b/source/isaaclab_newton/isaaclab_newton/cloner/newton_replicate.py index 59e5d2476ccc..34cd35de4fa2 100644 --- a/source/isaaclab_newton/isaaclab_newton/cloner/newton_replicate.py +++ b/source/isaaclab_newton/isaaclab_newton/cloner/newton_replicate.py @@ -5,16 +5,12 @@ from __future__ import annotations -from collections.abc import Callable - import torch import warp as wp from newton import ModelBuilder, solvers from newton._src.usd.schemas import SchemaResolverNewton, SchemaResolverPhysx -from pxr import Usd, UsdGeom - -from isaaclab.physics.scene_data_requirements import VisualizerPrebuiltArtifacts +from pxr import Usd from isaaclab_newton.physics import NewtonManager @@ -28,7 +24,7 @@ def _build_newton_builder_from_mapping( quaternions: torch.Tensor | None = None, up_axis: str = "Z", simplify_meshes: bool = True, -) -> tuple[ModelBuilder, object]: +) -> tuple[ModelBuilder, object, dict]: """Build a Newton model builder from clone mapping inputs. Args: @@ -42,7 +38,9 @@ def _build_newton_builder_from_mapping( simplify_meshes: Whether to run convex-hull mesh approximation. Returns: - Tuple of the populated Newton model builder and stage metadata returned by ``add_usd``. + Tuple of the populated Newton model builder, stage metadata returned + by ``add_usd``, and a site index map for + :attr:`NewtonManager._cl_site_index_map`. """ if positions is None: positions = torch.zeros((mapping.size(1), 3), device=mapping.device, dtype=torch.float32) @@ -52,7 +50,7 @@ def _build_newton_builder_from_mapping( schema_resolvers = [SchemaResolverNewton(), SchemaResolverPhysx()] - builder = ModelBuilder(up_axis=up_axis) + builder = NewtonManager.create_builder(up_axis=up_axis) stage_info = builder.add_usd( stage, ignore_paths=["/World/envs"] + sources, @@ -64,7 +62,7 @@ def _build_newton_builder_from_mapping( env0_pos = positions[0] protos: dict[str, ModelBuilder] = {} for src_path in sources: - p = ModelBuilder(up_axis=up_axis) + p = NewtonManager.create_builder(up_axis=up_axis) solvers.SolverMuJoCo.register_custom_attributes(p) p.add_usd( stage, @@ -77,6 +75,16 @@ def _build_newton_builder_from_mapping( p.approximate_meshes("convex_hull", keep_visual_shapes=True) protos[src_path] = p + # Inject registered sites into prototypes (and global sites into main builder) + global_sites, proto_sites = NewtonManager._cl_inject_sites(builder, protos) + + # Global sites: (int, None) + global_site_map: dict[str, tuple[int, None]] = {label: (idx, None) for label, idx in global_sites.items()} + + # Local sites: per-world sublists, populated in the loop below + num_worlds = mapping.size(1) + local_site_map: dict[str, list[list[int]]] = {} + # create a separate world for each environment (heterogeneous spawning) # Newton assigns sequential world IDs (0, 1, 2, ...), so we need to track the mapping for col, _ in enumerate(env_ids.tolist()): @@ -85,14 +93,27 @@ def _build_newton_builder_from_mapping( # add all active sources for this world delta_pos = (positions[col] - env0_pos).tolist() for row in torch.nonzero(mapping[:, col], as_tuple=True)[0].tolist(): + proto = protos[sources[row]] + offset = builder.shape_count builder.add_builder( - protos[sources[row]], + proto, xform=wp.transform(delta_pos, quaternions[col].tolist()), ) + # Compute final shape indices for sites in this proto + for label, proto_shape_indices in proto_sites.get(id(proto), {}).items(): + if label not in local_site_map: + local_site_map[label] = [[] for _ in range(num_worlds)] + for proto_shape_idx in proto_shape_indices: + local_site_map[label][col].append(offset + proto_shape_idx) # end the world context builder.end_world() - return builder, stage_info + site_index_map = { + **global_site_map, + **{label: (None, per_world) for label, per_world in local_site_map.items()}, + } + + return builder, stage_info, site_index_map def _rename_builder_labels( @@ -155,7 +176,7 @@ def newton_physics_replicate( Returns: Tuple of the populated Newton model builder and stage metadata. """ - builder, stage_info = _build_newton_builder_from_mapping( + builder, stage_info, site_index_map = _build_newton_builder_from_mapping( stage=stage, sources=sources, env_ids=env_ids, @@ -166,6 +187,7 @@ def newton_physics_replicate( simplify_meshes=simplify_meshes, ) _rename_builder_labels(builder, sources, destinations, env_ids, mapping) + NewtonManager._cl_site_index_map = site_index_map NewtonManager.set_builder(builder) NewtonManager._num_envs = mapping.size(1) return builder, stage_info @@ -203,7 +225,7 @@ def newton_visualizer_prebuild( Returns: Tuple of finalized Newton model and state. """ - builder, _ = _build_newton_builder_from_mapping( + builder, _, _site_index_map = _build_newton_builder_from_mapping( stage=stage, sources=sources, env_ids=env_ids, @@ -217,55 +239,3 @@ def newton_visualizer_prebuild( model = builder.finalize(device=device) state = model.state() return model, state - - -def create_newton_visualizer_prebuild_clone_fn( - stage, - set_visualizer_artifact: Callable[[VisualizerPrebuiltArtifacts | None], None], -): - """Create a cloner callback that prebuilds Newton visualizer artifacts. - - Args: - stage: USD stage used by the clone callback. - set_visualizer_artifact: Callback used to store the produced prebuilt artifact. - - Returns: - Clone callback that builds and stores visualizer prebuilt artifacts. - """ - up_axis = UsdGeom.GetStageUpAxis(stage) - - def _visualizer_clone_fn( - stage, - sources, - destinations, - env_ids, - mapping, - positions=None, - quaternions=None, - device="cpu", - ): - """Prebuild Newton model/state and store visualizer artifacts for clone consumers.""" - model, state = newton_visualizer_prebuild( - stage=stage, - sources=sources, - destinations=destinations, - env_ids=env_ids, - mapping=mapping, - positions=positions, - quaternions=quaternions, - device=device, - up_axis=up_axis, - ) - set_visualizer_artifact( - VisualizerPrebuiltArtifacts( - model=model, - state=state, - rigid_body_paths=list(getattr(model, "body_label", None) or getattr(model, "body_key", [])), - articulation_paths=list( - getattr(model, "articulation_label", None) or getattr(model, "articulation_key", []) - ), - num_envs=int(mapping.size(1)), - ) - ) - - return _visualizer_clone_fn diff --git a/source/isaaclab_newton/isaaclab_newton/kernels/state_kernels.py b/source/isaaclab_newton/isaaclab_newton/kernels/state_kernels.py new file mode 100644 index 000000000000..9bb7a39e3b2c --- /dev/null +++ b/source/isaaclab_newton/isaaclab_newton/kernels/state_kernels.py @@ -0,0 +1,30 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Warp helper functions for body-frame state computations. + +These ``@wp.func`` helpers are used by warp-first MDP terms (observations, +rewards) that need to project root-frame quantities into body frames. +""" + +import warp as wp + + +@wp.func +def rotate_vec_to_body_frame(vec_w: wp.vec3f, pose_w: wp.transformf) -> wp.vec3f: + """Rotate a world-frame vector into the body frame defined by pose_w.""" + return wp.quat_rotate_inv(wp.transform_get_rotation(pose_w), vec_w) + + +@wp.func +def body_lin_vel_from_root(pose_w: wp.transformf, vel_w: wp.spatial_vectorf) -> wp.vec3f: + """Extract body-frame linear velocity from root pose and spatial velocity.""" + return wp.quat_rotate_inv(wp.transform_get_rotation(pose_w), wp.spatial_top(vel_w)) + + +@wp.func +def body_ang_vel_from_root(pose_w: wp.transformf, vel_w: wp.spatial_vectorf) -> wp.vec3f: + """Extract body-frame angular velocity from root pose and spatial velocity.""" + return wp.quat_rotate_inv(wp.transform_get_rotation(pose_w), wp.spatial_bottom(vel_w)) diff --git a/source/isaaclab_newton/isaaclab_newton/physics/__init__.pyi b/source/isaaclab_newton/isaaclab_newton/physics/__init__.pyi index 4e589e6f69d1..176973cd5400 100644 --- a/source/isaaclab_newton/isaaclab_newton/physics/__init__.pyi +++ b/source/isaaclab_newton/isaaclab_newton/physics/__init__.pyi @@ -4,13 +4,34 @@ # SPDX-License-Identifier: BSD-3-Clause __all__ = [ + "NewtonFeatherstoneManager", "FeatherstoneSolverCfg", + "HydroelasticSDFCfg", + "NewtonKaminoManager", + "KaminoSolverCfg", + "NewtonMJWarpManager", "MJWarpSolverCfg", "NewtonCfg", + "NewtonCollisionPipelineCfg", "NewtonManager", + "NewtonShapeCfg", "NewtonSolverCfg", + "NewtonXPBDManager", "XPBDSolverCfg", ] +from .featherstone_manager import NewtonFeatherstoneManager +from .featherstone_manager_cfg import FeatherstoneSolverCfg +from .kamino_manager import NewtonKaminoManager +from .kamino_manager_cfg import KaminoSolverCfg +from .mjwarp_manager import NewtonMJWarpManager +from .mjwarp_manager_cfg import MJWarpSolverCfg +from .newton_collision_cfg import HydroelasticSDFCfg, NewtonCollisionPipelineCfg from .newton_manager import NewtonManager -from .newton_manager_cfg import FeatherstoneSolverCfg, MJWarpSolverCfg, NewtonCfg, NewtonSolverCfg, XPBDSolverCfg +from .newton_manager_cfg import ( + NewtonCfg, + NewtonShapeCfg, + NewtonSolverCfg, +) +from .xpbd_manager import NewtonXPBDManager +from .xpbd_manager_cfg import XPBDSolverCfg diff --git a/source/isaaclab_newton/isaaclab_newton/physics/featherstone_manager.py b/source/isaaclab_newton/isaaclab_newton/physics/featherstone_manager.py new file mode 100644 index 000000000000..a1e918990c19 --- /dev/null +++ b/source/isaaclab_newton/isaaclab_newton/physics/featherstone_manager.py @@ -0,0 +1,36 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Featherstone Newton manager.""" + +from __future__ import annotations + +import inspect + +from newton import Model +from newton.solvers import SolverFeatherstone + +from .featherstone_manager_cfg import FeatherstoneSolverCfg +from .newton_manager import NewtonManager + + +class NewtonFeatherstoneManager(NewtonManager): + """:class:`NewtonManager` specialization for the Featherstone solver. + + Always uses Newton's :class:`CollisionPipeline` for contact handling. + """ + + @classmethod + def _build_solver(cls, model: Model, solver_cfg: FeatherstoneSolverCfg) -> None: + """Construct :class:`SolverFeatherstone` and populate the base-class slots. + + Featherstone always uses Newton's :class:`CollisionPipeline` and steps + with separate input/output states, so the flags are fixed. + """ + valid = set(inspect.signature(SolverFeatherstone.__init__).parameters) - {"self", "model"} + kwargs = {k: v for k, v in solver_cfg.to_dict().items() if k in valid} + NewtonManager._solver = SolverFeatherstone(model, **kwargs) + NewtonManager._use_single_state = False + NewtonManager._needs_collision_pipeline = True diff --git a/source/isaaclab_newton/isaaclab_newton/physics/featherstone_manager_cfg.py b/source/isaaclab_newton/isaaclab_newton/physics/featherstone_manager_cfg.py new file mode 100644 index 000000000000..fc4278b49788 --- /dev/null +++ b/source/isaaclab_newton/isaaclab_newton/physics/featherstone_manager_cfg.py @@ -0,0 +1,55 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Configuration for Newton physics manager.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from isaaclab.utils import configclass + +from .newton_manager_cfg import NewtonSolverCfg + +if TYPE_CHECKING: + from isaaclab_newton.physics import NewtonManager + + +@configclass +class FeatherstoneSolverCfg(NewtonSolverCfg): + """A semi-implicit integrator using symplectic Euler. + + It operates on reduced (also called generalized) coordinates to simulate articulated rigid body dynamics + based on Featherstone's composite rigid body algorithm (CRBA). + + See: Featherstone, Roy. Rigid Body Dynamics Algorithms. Springer US, 2014. + + Semi-implicit time integration is a variational integrator that + preserves energy, however it is not unconditionally stable, and requires a time-step + small enough to support the required stiffness and damping forces. + + See: https://en.wikipedia.org/wiki/Semi-implicit_Euler_method + """ + + class_type: type[NewtonManager] | str = "{DIR}.featherstone_manager:NewtonFeatherstoneManager" + """Manager class for the Featherstone solver.""" + + solver_type: str = "featherstone" + """Solver type. Can be "featherstone".""" + + angular_damping: float = 0.05 + """Angular damping parameter for rigid contact simulation.""" + + update_mass_matrix_interval: int = 1 + """Frequency (in simulation steps) at which to update the mass matrix.""" + + friction_smoothing: float = 1.0 + """Friction smoothing parameter.""" + + use_tile_gemm: bool = False + """Whether to use tile-based GEMM for the mass matrix.""" + + fuse_cholesky: bool = True + """Whether to fuse the Cholesky decomposition.""" diff --git a/source/isaaclab_newton/isaaclab_newton/physics/kamino_manager.py b/source/isaaclab_newton/isaaclab_newton/physics/kamino_manager.py new file mode 100644 index 000000000000..39d0fafbc1bb --- /dev/null +++ b/source/isaaclab_newton/isaaclab_newton/physics/kamino_manager.py @@ -0,0 +1,158 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Kamino Newton manager.""" + +from __future__ import annotations + +import logging + +import warp as wp +from newton import Model, eval_fk +from newton.solvers import SolverKamino + +from isaaclab.physics import PhysicsManager +from isaaclab.utils.timer import Timer + +from .kamino_manager_cfg import KaminoSolverCfg +from .newton_manager import NewtonManager + +logger = logging.getLogger(__name__) + + +class NewtonKaminoManager(NewtonManager): + """:class:`NewtonManager` specialization for the Kamino solver. + + Uses Newton's :class:`CollisionPipeline` unless + :attr:`KaminoSolverCfg.use_collision_detector` is ``True``, in which case + Kamino's internal collision detector handles contact generation. + """ + + @classmethod + def _forward_kamino(cls, world_mask: wp.array | None = None) -> None: + """Kamino-specific forward kinematics via ``solver.reset()``. + + Kamino's ``joint_q`` / ``joint_u`` include coordinates for **all** joints + (including free joints), so we pass Newton's full state arrays directly. + + Args: + world_mask: Per-world mask indicating which worlds to reset. + Shape ``(num_worlds,)``, dtype ``wp.int32``. If None, resets all worlds. + """ + cls._solver.reset( + state_out=cls._state_0, + joint_q=cls._state_0.joint_q, + joint_u=cls._state_0.joint_qd, + world_mask=world_mask, + ) + + @classmethod + def step(cls) -> None: + """Step the physics simulation.""" + sim = PhysicsManager._sim + if sim is None or not sim.is_playing(): + return + + # Kamino: run solver.reset() with the accumulated world mask to reinitialise + # internal state (warm-start containers, constraint multipliers) for reset worlds. + # Note: runs every step. solver.reset() with an all-False world_mask is a no-op + # (kernels check mask per-world and skip). The cost of a no-op launch is negligible + # compared to the complexity of maintaining a separate boolean guard. + cls._forward_kamino(world_mask=cls._world_reset_mask) + + # Notify solver of model changes + if cls._model_changes: + with wp.ScopedDevice(PhysicsManager._device): + for change in cls._model_changes: + cls._solver.notify_model_changed(change) + NewtonManager._model_changes = set() + + # Lazy CUDA graph capture: deferred from initialize_solver() when RTX was active. + # By the time step() is first called, RTX has fully initialized (all cudaImportExternalMemory + # calls are done) and is idle between render frames — giving us a clean capture window. + cfg = PhysicsManager._cfg + device = PhysicsManager._device + if cls._graph_capture_pending and cfg is not None and cfg.use_cuda_graph and "cuda" in device: # type: ignore[union-attr] + NewtonManager._graph_capture_pending = False + NewtonManager._graph = cls._capture_relaxed_graph(device) + if cls._graph is not None: + # Kamino: StateKamino.from_newton() lazily allocates body_f_total, + # joint_q_prev, and joint_lambdas via wp.clone/wp.zeros during the + # first step() inside graph capture. Replay once to pin those + # memory-pool addresses before any eager solver.reset() call. + wp.capture_launch(cls._graph) + logger.info("Newton CUDA graph captured (deferred relaxed mode, RTX-compatible)") + else: + logger.warning("Newton deferred CUDA graph capture failed; using eager execution") + + # Ensure body_q is up-to-date before collision detection. + # After env resets, joint_q is written but body_q (used by + # broadphase/narrowphase) is stale until FK runs. + # Only runs FK for dirtied articulations via the accumulated mask. + if cls._needs_collision_pipeline: + eval_fk(cls._model, cls._state_0.joint_q, cls._state_0.joint_qd, cls._state_0, cls._fk_reset_mask) + + # Zero both masks after consumption + NewtonManager._world_reset_mask.zero_() + NewtonManager._fk_reset_mask.zero_() + + # Step simulation (graphed or not; _graph is None when capture is disabled or failed) + if cfg is not None and cfg.use_cuda_graph and cls._graph is not None and "cuda" in device: # type: ignore[union-attr] + wp.capture_launch(cls._graph) + if cls._usdrt_stage is not None: + cls._mark_transforms_dirty() + else: + with wp.ScopedDevice(device): + cls._simulate() + + # Launch solver-specific debug logging after stepping. + cls._log_solver_debug() + + PhysicsManager._sim_time += cls._solver_dt * cls._num_substeps + + @classmethod + def _build_solver(cls, model: Model, solver_cfg: KaminoSolverCfg) -> None: + """Construct :class:`SolverKamino` and populate the base-class slots. + + Sets :attr:`NewtonManager._needs_collision_pipeline` to ``True`` only + when ``use_collision_detector=False`` (Kamino's internal detector + handles contacts otherwise). + """ + NewtonManager._solver = SolverKamino(model, solver_cfg.to_solver_config()) + NewtonManager._use_single_state = False + NewtonManager._needs_collision_pipeline = not solver_cfg.use_collision_detector + + @classmethod + def _capture_or_defer_cuda_graph(cls) -> None: + """Capture the physics CUDA graph, or defer if RTX is initializing.""" + cfg = PhysicsManager._cfg + device = PhysicsManager._device + use_cuda_graph = cfg is not None and cfg.use_cuda_graph and "cuda" in device # type: ignore[union-attr] + + with Timer(name="newton_cuda_graph", msg="CUDA graph took:"): + if not use_cuda_graph: + NewtonManager._graph = None + return + if cls._usdrt_stage is None: + # No RTX active — use standard Warp capture (cudaStreamCaptureModeGlobal). + with wp.ScopedCapture() as capture: + cls._simulate() + NewtonManager._graph = capture.graph + logger.info("Newton CUDA graph captured (standard Warp mode)") + + # TODO: streamline this with base NewtonManager + # Kamino: StateKamino.from_newton() lazily allocates body_f_total, + # joint_q_prev, and joint_lambdas via wp.clone/wp.zeros during the + # first step() inside graph capture. Replay once to pin those + # memory-pool addresses before any eager solver.reset() call. + wp.capture_launch(cls._graph) + else: + # RTX is active during initialization — cudaImportExternalMemory and other + # non-capturable RTX ops run on background CUDA streams right now. + # Defer capture to the first step() call, after RTX is fully initialized + # and idle between render frames (clean capture window). + NewtonManager._graph = None + NewtonManager._graph_capture_pending = True + logger.info("Newton CUDA graph capture deferred until first step() (RTX active)") diff --git a/source/isaaclab_newton/isaaclab_newton/physics/kamino_manager_cfg.py b/source/isaaclab_newton/isaaclab_newton/physics/kamino_manager_cfg.py new file mode 100644 index 000000000000..71c871f9d54d --- /dev/null +++ b/source/isaaclab_newton/isaaclab_newton/physics/kamino_manager_cfg.py @@ -0,0 +1,214 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Configuration for Newton physics manager.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from isaaclab.utils import configclass + +from .newton_manager_cfg import NewtonSolverCfg + +if TYPE_CHECKING: + from newton.solvers import SolverKamino + + from isaaclab_newton.physics import NewtonManager + + +@configclass +class KaminoSolverCfg(NewtonSolverCfg): + """Configuration for Kamino solver-related parameters. + + Kamino is a Proximal Alternating Direction Method of Multipliers (P-ADMM) based solver for + constrained multi-body dynamics. It operates in maximal coordinates and supports rigid bodies + and articulations with hard frictional contacts. + + .. note:: + + This solver is currently in **Beta**. Its API and behavior may change in future releases. + + For more information, see the `Newton Kamino documentation`_. + + .. _Newton Kamino documentation: https://newton.readthedocs.io/en/latest/ + """ + + class_type: type[NewtonManager] | str = "{DIR}.kamino_manager:NewtonKaminoManager" + """Manager class for the Kamino solver.""" + + solver_type: str = "kamino" + """Solver type. Can be "kamino".""" + + integrator: str = "euler" + """Integrator type. Can be "euler" or "moreau".""" + + use_collision_detector: bool = False + """Whether to use Kamino's internal collision detector instead of Newton's pipeline.""" + + use_fk_solver: bool = True + """Whether to enable the forward kinematics solver for state resets. + + Required for proper environment resets. The FK solver computes consistent body poses + from joint angles after state writes, which is essential for maximal-coordinate solvers. + """ + + sparse_jacobian: bool = False + """Whether to use sparse Jacobian computation.""" + + sparse_dynamics: bool = False + """Whether to use sparse dynamics computation.""" + + rotation_correction: str = "twopi" + """Rotation correction mode. Can be "twopi", "continuous", or "none".""" + + angular_velocity_damping: float = 0.0 + """Angular velocity damping factor. Valid range is [0.0, 1.0].""" + + constraints_alpha: float = 0.01 + """Baumgarte stabilization parameter for bilateral joint constraints. Valid range is [0, 1].""" + + constraints_beta: float = 0.01 + """Baumgarte stabilization parameter for unilateral joint-limit constraints. Valid range is [0, 1].""" + + constraints_gamma: float = 0.01 + """Baumgarte stabilization parameter for unilateral contact constraints. Valid range is [0, 1].""" + + constraints_delta: float = 1.0e-6 + """Contact penetration margin [m].""" + + padmm_max_iterations: int = 200 + """Maximum number of P-ADMM solver iterations.""" + + padmm_primal_tolerance: float = 1e-6 + """Primal residual convergence tolerance for P-ADMM.""" + + padmm_dual_tolerance: float = 1e-6 + """Dual residual convergence tolerance for P-ADMM.""" + + padmm_compl_tolerance: float = 1e-6 + """Complementarity residual convergence tolerance for P-ADMM.""" + + padmm_rho_0: float = 1.0 + """Initial penalty parameter for P-ADMM.""" + + padmm_use_acceleration: bool = True + """Whether to use acceleration in the P-ADMM solver.""" + + padmm_warmstart_mode: str = "containers" + """Warmstart mode for P-ADMM. Can be "none", "internal", or "containers".""" + + padmm_eta: float = 1e-5 + """Proximal regularization parameter for P-ADMM. Must be greater than zero.""" + + padmm_contact_warmstart_method: str = "key_and_position" + """Contact warm-start method for P-ADMM. + + Can be "key_and_position", "geom_pair_net_force", "geom_pair_net_wrench", + "key_and_position_with_net_force_backup", or "key_and_position_with_net_wrench_backup". + """ + + padmm_use_graph_conditionals: bool = True + """Whether to use CUDA graph conditional nodes in the P-ADMM iterative solver. + + When ``False``, replaces ``wp.capture_while`` with unrolled for-loops over max iterations. + """ + + collect_solver_info: bool = False + """Whether to collect solver convergence and performance info at each step. + + .. warning:: + + Enabling this significantly increases solver runtime and should only be used for debugging. + """ + + compute_solution_metrics: bool = False + """Whether to compute solution metrics at each step. + + .. warning:: + + Enabling this significantly increases solver runtime and should only be used for debugging. + """ + + collision_detector_pipeline: str | None = None + """Collision detection pipeline type. Can be "primitive" or "unified". + + Only used when :attr:`use_collision_detector` is ``True``. If ``None``, Newton's default + (``"unified"``) is used. + """ + + collision_detector_max_contacts_per_pair: int | None = None + """Maximum number of contacts to generate per candidate geometry pair. + + Only used when :attr:`use_collision_detector` is ``True``. If ``None``, Newton's default is used. + """ + + dynamics_preconditioning: bool = True + """Whether to use preconditioning in the constrained dynamics solver. + + Preconditioning improves convergence of the PADMM solver by rescaling the + problem. Disabling may be useful for debugging or profiling solver behavior. + """ + + def to_solver_config(self) -> SolverKamino.Config: + """Build a :class:`SolverKamino.Config` from this configuration. + + Converts the flat field layout of :class:`KaminoSolverCfg` into the + nested dataclass hierarchy expected by :class:`SolverKamino`. + + Returns: + A ``SolverKamino.Config`` instance ready for solver construction. + """ + from newton._src.solvers.kamino.config import ( + CollisionDetectorConfig, + ConstrainedDynamicsConfig, + ConstraintStabilizationConfig, + PADMMSolverConfig, + ) + from newton.solvers import SolverKamino + + # Build collision detector config if using Kamino's internal detector + collision_detector = None + if self.use_collision_detector: + cd_kwargs: dict = {} + if self.collision_detector_pipeline is not None: + cd_kwargs["pipeline"] = self.collision_detector_pipeline + if self.collision_detector_max_contacts_per_pair is not None: + cd_kwargs["max_contacts_per_pair"] = self.collision_detector_max_contacts_per_pair + collision_detector = CollisionDetectorConfig(**cd_kwargs) + + return SolverKamino.Config( + integrator=self.integrator, + use_collision_detector=self.use_collision_detector, + use_fk_solver=self.use_fk_solver, + sparse_jacobian=self.sparse_jacobian, + sparse_dynamics=self.sparse_dynamics, + rotation_correction=self.rotation_correction, + angular_velocity_damping=self.angular_velocity_damping, + collect_solver_info=self.collect_solver_info, + compute_solution_metrics=self.compute_solution_metrics, + collision_detector=collision_detector, + constraints=ConstraintStabilizationConfig( + alpha=self.constraints_alpha, + beta=self.constraints_beta, + gamma=self.constraints_gamma, + delta=self.constraints_delta, + ), + dynamics=ConstrainedDynamicsConfig( + preconditioning=self.dynamics_preconditioning, + ), + padmm=PADMMSolverConfig( + max_iterations=self.padmm_max_iterations, + primal_tolerance=self.padmm_primal_tolerance, + dual_tolerance=self.padmm_dual_tolerance, + compl_tolerance=self.padmm_compl_tolerance, + rho_0=self.padmm_rho_0, + eta=self.padmm_eta, + use_acceleration=self.padmm_use_acceleration, + use_graph_conditionals=self.padmm_use_graph_conditionals, + warmstart_mode=self.padmm_warmstart_mode, + contact_warmstart_method=self.padmm_contact_warmstart_method, + ), + ) diff --git a/source/isaaclab_newton/isaaclab_newton/physics/mjwarp_manager.py b/source/isaaclab_newton/isaaclab_newton/physics/mjwarp_manager.py new file mode 100644 index 000000000000..01cf6f1996e2 --- /dev/null +++ b/source/isaaclab_newton/isaaclab_newton/physics/mjwarp_manager.py @@ -0,0 +1,103 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""MuJoCo Warp Newton manager.""" + +from __future__ import annotations + +import inspect +import logging + +import numpy as np +from newton import Contacts, Model +from newton.solvers import SolverMuJoCo + +from isaaclab.physics import PhysicsManager + +from .mjwarp_manager_cfg import MJWarpSolverCfg +from .newton_manager import NewtonManager + +logger = logging.getLogger(__name__) + + +class NewtonMJWarpManager(NewtonManager): + """:class:`NewtonManager` specialization for the MuJoCo Warp solver. + + Owns construction of :class:`SolverMuJoCo`, contact-buffer allocation in + both internal-MuJoCo and Newton-pipeline contact modes, and the debug + convergence logging emitted from :meth:`_log_solver_debug` when + :attr:`NewtonCfg.debug_mode` is enabled. + """ + + @classmethod + def _build_solver(cls, model: Model, solver_cfg: MJWarpSolverCfg) -> None: + """Construct :class:`SolverMuJoCo` and populate the base-class slots. + + Filters cfg fields against the solver's ``__init__`` signature so + non-constructor metadata (``solver_type``, ``class_type``) is not + forwarded. Sets :attr:`NewtonManager._needs_collision_pipeline` to + ``True`` only when ``use_mujoco_contacts=False``. + """ + valid = set(inspect.signature(SolverMuJoCo.__init__).parameters) - {"self", "model"} + kwargs = {k: v for k, v in solver_cfg.to_dict().items() if k in valid} + NewtonManager._solver = SolverMuJoCo(model, **kwargs) + NewtonManager._use_single_state = True + NewtonManager._needs_collision_pipeline = not solver_cfg.use_mujoco_contacts + + cfg = PhysicsManager._cfg + # Cross-config validation that needs both halves. + if solver_cfg.use_mujoco_contacts and cfg.collision_cfg is not None: + raise ValueError( + "NewtonCfg: collision_cfg cannot be set when " + "solver_cfg.use_mujoco_contacts=True. Either set " + "use_mujoco_contacts=False or remove collision_cfg." + ) + + @classmethod + def _initialize_contacts(cls) -> None: + """Allocate contact buffers. + + Delegates to the base implementation when Newton's + :class:`CollisionPipeline` is active. When ``use_mujoco_contacts=True`` + the solver runs MuJoCo's internal collision detection, so this method + instead pre-allocates a :class:`Contacts` buffer sized to the solver's + maximum contact count; ``solver.update_contacts`` later populates it + from MuJoCo data for contact-sensor reporting. + """ + if cls._needs_collision_pipeline: + super()._initialize_contacts() + return + if cls._solver is not None: + NewtonManager._contacts = Contacts( + rigid_contact_max=cls._solver.get_max_contact_count(), + soft_contact_max=0, + device=PhysicsManager._device, + requested_attributes=cls._model.get_requested_contact_attributes(), + ) + + @classmethod + def _log_solver_debug(cls) -> None: + """Optionally log MuJoCo solver convergence at the end of step.""" + cfg = PhysicsManager._cfg + if cfg is not None and cfg.debug_mode: # type: ignore[union-attr] + data = cls._get_solver_convergence_steps() + logger.info(f"Solver convergence data: {data}") + if data["max"] == cls._solver.mjw_model.opt.iterations: + logger.warning(f"Solver didn't converge! max_iter={data['max']}") + + @classmethod + def _get_solver_convergence_steps(cls) -> dict[str, float | int]: + """Return MuJoCo Warp solver convergence statistics. + + Reads ``mjw_data.solver_niter`` (only available on + :class:`SolverMuJoCo`) and summarizes per-environment iteration counts. + """ + niter = cls._solver.mjw_data.solver_niter.numpy() + return { + "max": np.max(niter), + "mean": np.mean(niter), + "min": np.min(niter), + "std": np.std(niter), + } diff --git a/source/isaaclab_newton/isaaclab_newton/physics/mjwarp_manager_cfg.py b/source/isaaclab_newton/isaaclab_newton/physics/mjwarp_manager_cfg.py new file mode 100644 index 000000000000..673867902c2c --- /dev/null +++ b/source/isaaclab_newton/isaaclab_newton/physics/mjwarp_manager_cfg.py @@ -0,0 +1,115 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Configuration for Newton physics manager.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from isaaclab.utils import configclass + +from .newton_manager_cfg import NewtonSolverCfg + +if TYPE_CHECKING: + from isaaclab_newton.physics import NewtonManager + + +@configclass +class MJWarpSolverCfg(NewtonSolverCfg): + """Configuration for MuJoCo Warp solver-related parameters. + + These parameters are used to configure the MuJoCo Warp solver. For more information, see the + `MuJoCo Warp documentation`_. + + .. _MuJoCo Warp documentation: https://github.com/google-deepmind/mujoco_warp + """ + + class_type: type[NewtonManager] | str = "{DIR}.mjwarp_manager:NewtonMJWarpManager" + """Manager class for the MuJoCo Warp solver.""" + + solver_type: str = "mujoco_warp" + """Solver type. Can be "mujoco_warp".""" + + njmax: int = 300 + """Number of constraints per environment (world).""" + + nconmax: int | None = None + """Number of contact points per environment (world).""" + + iterations: int = 100 + """Number of solver iterations.""" + + ls_iterations: int = 50 + """Number of line search iterations for the solver.""" + + solver: str = "newton" + """Solver type. Can be "cg" or "newton", or their corresponding MuJoCo integer constants.""" + + integrator: str = "euler" + """Integrator type. Can be "euler", "rk4", or "implicitfast", or their corresponding MuJoCo integer constants.""" + + use_mujoco_cpu: bool = False + """Whether to use the pure MuJoCo backend instead of `mujoco_warp`.""" + + disable_contacts: bool = False + """Whether to disable contact computation in MuJoCo.""" + + default_actuator_gear: float | None = None + """Default gear ratio for all actuators.""" + + actuator_gears: dict[str, float] | None = None + """Dictionary mapping joint names to specific gear ratios, overriding the `default_actuator_gear`.""" + + update_data_interval: int = 1 + """Frequency (in simulation steps) at which to update the MuJoCo Data object from the Newton state. + + If 0, Data is never updated after initialization. + """ + + save_to_mjcf: str | None = None + """Optional path to save the generated MJCF model file. + + If None, the MJCF model is not saved. + """ + + impratio: float = 1.0 + """Frictional-to-normal constraint impedance ratio.""" + + cone: str = "pyramidal" + """The type of contact friction cone. Can be "pyramidal" or "elliptic".""" + + ccd_iterations: int = 35 + """Maximum iterations for convex collision detection (GJK/EPA). + + Increase this if you see warnings about ``opt.ccd_iterations`` needing to be increased, + which typically occurs with complex collision geometries (e.g. multi-finger hands). + """ + + ls_parallel: bool = False + """Whether to use parallel line search.""" + + use_mujoco_contacts: bool = True + """Whether to use MuJoCo's internal contact solver. + + If ``True`` (default), MuJoCo handles collision detection and contact resolution internally. + If ``False``, Newton's :class:`CollisionPipeline` is used instead. A default pipeline + (``broad_phase="explicit"``) is created automatically when :attr:`NewtonCfg.collision_cfg` + is ``None``. Set :attr:`NewtonCfg.collision_cfg` to a :class:`NewtonCollisionPipelineCfg` + to customize pipeline parameters (broad phase, contact limits, hydroelastic, etc.). + + .. note:: + Setting ``collision_cfg`` while ``use_mujoco_contacts=True`` raises + :class:`ValueError` because the two collision modes are mutually exclusive. + """ + + tolerance: float = 1e-6 + """Solver convergence tolerance for the constraint residual. + + The solver iterates until the residual drops below this threshold or + ``iterations`` is reached. Lower values give more precise constraint + satisfaction at the cost of more iterations. MuJoCo default is ``1e-8``; + Newton default is ``1e-6``. + """ diff --git a/source/isaaclab_newton/isaaclab_newton/physics/newton_collision_cfg.py b/source/isaaclab_newton/isaaclab_newton/physics/newton_collision_cfg.py new file mode 100644 index 000000000000..c8b0db0b3f4a --- /dev/null +++ b/source/isaaclab_newton/isaaclab_newton/physics/newton_collision_cfg.py @@ -0,0 +1,186 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Configuration for Newton collision pipeline.""" + +from __future__ import annotations + +from typing import Any, Literal + +from isaaclab.utils import configclass + + +@configclass +class HydroelasticSDFCfg: + """Configuration for SDF-based hydroelastic collision handling. + + Hydroelastic contacts generate distributed contact areas instead of point contacts, + providing more realistic force distribution for manipulation and compliant surfaces. + + For more details, see the `Newton Collisions Guide`_. + + .. _Newton Collisions Guide: https://newton-physics.github.io/newton/latest/concepts/collisions.html#hydroelastic-contacts + """ + + reduce_contacts: bool = True + """Whether to reduce contacts to a smaller representative set per shape pair. + + When False, all generated contacts are passed through without reduction. + + Defaults to ``True`` (same as Newton's default). + """ + + buffer_fraction: float = 1.0 + """Fraction of worst-case hydroelastic buffer allocations. Range: (0, 1]. + + Lower values reduce memory usage but may cause overflows in dense scenes. + Overflows are bounds-safe and emit warnings; increase this value when warnings appear. + + Defaults to ``1.0`` (same as Newton's default). + """ + + normal_matching: bool = True + """Whether to rotate reduced contact normals to align with aggregate force direction. + + Only active when ``reduce_contacts`` is True. + + Defaults to ``True`` (same as Newton's default). + """ + + anchor_contact: bool = False + """Whether to add an anchor contact at the center of pressure for each normal bin. + + The anchor contact helps preserve moment balance. Only active when ``reduce_contacts`` is True. + + Defaults to ``False`` (same as Newton's default). + """ + + margin_contact_area: float = 0.01 + """Contact area [m^2] used for non-penetrating contacts at the margin. + + Defaults to ``0.01`` (same as Newton's default). + """ + + output_contact_surface: bool = False + """Whether to output hydroelastic contact surface vertices for visualization. + + Defaults to ``False`` (same as Newton's default). + """ + + +@configclass +class NewtonCollisionPipelineCfg: + """Configuration for Newton collision pipeline. + + Full-featured collision pipeline with GJK/MPR narrow phase and pluggable broad phase. + When this config is set on :attr:`NewtonCfg.collision_cfg`: + + - **MJWarpSolverCfg**: Newton's collision pipeline replaces MuJoCo's internal contact solver. + - **Other solvers** (XPBD, Featherstone, etc.): Configures the collision pipeline parameters + (these solvers always use Newton's collision pipeline). + + Key features: + + - GJK/MPR algorithms for convex-convex collision detection + - Multiple broad phase options: NXN (all-pairs), SAP (sweep-and-prune), EXPLICIT (precomputed pairs) + - Mesh-mesh collision via SDF with contact reduction + - Optional hydroelastic contact model for compliant surfaces + + For more details, see the `Newton Collisions Guide`_ and `CollisionPipeline API`_. + + .. _Newton Collisions Guide: https://newton-physics.github.io/newton/latest/concepts/collisions.html + .. _CollisionPipeline API: https://newton-physics.github.io/newton/api/_generated/newton.CollisionPipeline.html + """ + + broad_phase: Literal["explicit", "nxn", "sap"] = "explicit" + """Broad phase algorithm for collision detection. + + Options: + + - ``"explicit"``: Use precomputed shape pairs from ``model.shape_contact_pairs``. + - ``"nxn"``: All-pairs brute force. Simple but O(n^2) complexity. + - ``"sap"``: Sweep-and-prune. Good for scenes with many dynamic objects. + + Defaults to ``"explicit"`` (same as Newton's default when ``broad_phase=None``). + """ + + reduce_contacts: bool = True + """Whether to reduce contacts for mesh-mesh collisions. + + When True, uses shared memory contact reduction to select representative contacts. + Improves performance and stability for meshes with many vertices. + + Defaults to ``True`` (same as Newton's default). + """ + + rigid_contact_max: int | None = None + """Maximum number of rigid contacts to allocate. + + Resolution order: + + 1. If provided, use this value. + 2. Else if ``model.rigid_contact_max > 0``, use the model value. + 3. Else estimate automatically from model shape and pair metadata. + + Defaults to ``None`` (auto-estimate, same as Newton's default). + """ + + max_triangle_pairs: int = 1_000_000 + """Maximum number of triangle pairs allocated by narrow phase for mesh and heightfield collisions. + + Increase this when scenes with large/complex meshes or heightfields report + triangle-pair overflow warnings. + + Defaults to ``1_000_000`` (same as Newton's default). + """ + + soft_contact_max: int | None = None + """Maximum number of soft contacts to allocate. + + If None, computed as ``shape_count * particle_count``. + + Defaults to ``None`` (auto-compute, same as Newton's default). + """ + + soft_contact_margin: float = 0.01 + """Margin [m] for soft contact generation. + + Defaults to ``0.01`` (same as Newton's default). + """ + + requires_grad: bool | None = None + """Whether to enable gradient computation for collision. + + If ``None``, uses ``model.requires_grad``. + + Defaults to ``None`` (same as Newton's default). + """ + + sdf_hydroelastic_config: HydroelasticSDFCfg | None = None + """Configuration for SDF-based hydroelastic collision handling. + + If ``None``, hydroelastic contacts are disabled. + If set, enables hydroelastic contacts with the specified parameters. + + Defaults to ``None`` (hydroelastic disabled, same as Newton's default). + """ + + def to_pipeline_args(self) -> dict[str, Any]: + """Build keyword arguments for :class:`newton.CollisionPipeline`. + + Converts this configuration into the dict expected by + ``CollisionPipeline.__init__``, handling nested config conversion + (e.g. :class:`HydroelasticSDFCfg` → ``HydroelasticSDF.Config``). + + Returns: + Keyword arguments suitable for ``CollisionPipeline(model, **args)``. + """ + from newton.geometry import HydroelasticSDF + + cfg_dict = self.to_dict() + hydro_cfg = cfg_dict.pop("sdf_hydroelastic_config", None) + if hydro_cfg is not None: + cfg_dict["sdf_hydroelastic_config"] = HydroelasticSDF.Config(**hydro_cfg) + return cfg_dict diff --git a/source/isaaclab_newton/isaaclab_newton/physics/newton_manager.py b/source/isaaclab_newton/isaaclab_newton/physics/newton_manager.py index a96749d7b3f3..2bb2f1f37397 100644 --- a/source/isaaclab_newton/isaaclab_newton/physics/newton_manager.py +++ b/source/isaaclab_newton/isaaclab_newton/physics/newton_manager.py @@ -9,11 +9,11 @@ import contextlib import ctypes -import inspect import logging +from abc import abstractmethod +from collections.abc import Callable from typing import TYPE_CHECKING -import numpy as np import warp as wp # Load CUDA runtime for relaxed-mode graph capture (RTX-compatible). @@ -29,17 +29,30 @@ from newton import Axis, CollisionPipeline, Contacts, Control, Model, ModelBuilder, State, eval_fk from newton._src.usd.schemas import SchemaResolverNewton, SchemaResolverPhysx from newton.sensors import SensorContact as NewtonContactSensor -from newton.solvers import SolverBase, SolverFeatherstone, SolverMuJoCo, SolverNotifyFlags, SolverXPBD +from newton.sensors import SensorFrameTransform +from newton.sensors import SensorIMU as NewtonSensorIMU +from newton.solvers import SolverBase, SolverNotifyFlags -from isaaclab.physics import PhysicsEvent, PhysicsManager +from isaaclab.physics import CallbackHandle, PhysicsEvent, PhysicsManager +from isaaclab.sim.utils.newton_model_utils import replace_newton_shape_colors from isaaclab.sim.utils.stage import get_current_stage +from isaaclab.utils import checked_apply +from isaaclab.utils.string import resolve_matching_names from isaaclab.utils.timer import Timer +from .newton_manager_cfg import NewtonCfg, NewtonShapeCfg, NewtonSolverCfg + if TYPE_CHECKING: from isaaclab.sim.simulation_context import SimulationContext + from .newton_collision_cfg import NewtonCollisionPipelineCfg + logger = logging.getLogger(__name__) +# Tagged union for entries in _cl_site_index_map. +# _GlobalSite: (global_shape_idx, None) — body_pattern was None +# _LocalSite: (None, [[env0_idx, ...], ...]) — per-world site indices + @wp.kernel(enable_backward=False) def _set_fabric_transforms( @@ -59,13 +72,58 @@ def _set_fabric_transforms( fabric_transforms[i] = wp.transpose(wp.mat44d(wp.math.transform_to_matrix(transform))) -class NewtonManager(PhysicsManager): - """Newton physics manager for Isaac Lab. +@wp.kernel(enable_backward=False) +def _or_reset_masks_from_mask( + env_mask: wp.array(dtype=wp.bool), + articulation_ids: wp.array2d(dtype=int), + world_mask: wp.array(dtype=wp.int32), + fk_mask: wp.array(dtype=wp.bool), +): + """OR env_mask into world_mask and set corresponding articulation bits in fk_mask.""" + world, arti = wp.tid() + if env_mask[world]: + world_mask[world] = wp.int32(1) + fk_mask[articulation_ids[world, arti]] = True - This is a class-level (singleton-like) manager for the Newton simulation. - It handles solver configuration, physics stepping, and reset. - Lifecycle: initialize() -> reset() -> step() (repeated) -> close() +@wp.kernel(enable_backward=False) +def _scatter_reset_masks_from_ids( + env_ids: wp.array(dtype=int), + articulation_ids: wp.array2d(dtype=int), + world_mask: wp.array(dtype=wp.int32), + fk_mask: wp.array(dtype=wp.bool), +): + """Scatter-set world_mask and fk_mask from sparse env_ids.""" + i, arti = wp.tid() + world = env_ids[i] + world_mask[world] = wp.int32(1) + fk_mask[articulation_ids[world, arti]] = True + + +class NewtonManager(PhysicsManager): + """Abstract Newton physics manager for Isaac Lab. + + Class-level (singleton-like) manager that owns simulation lifecycle, model + state, contacts/collision pipeline, sensors, replication, and CUDA-graph + orchestration. + Concrete subclasses (one per solver) implement :meth:`_build_solver` and + may extend :meth:`_initialize_contacts`, :meth:`_step_solver`, + :meth:`_solver_specific_clear`, and :meth:`_log_solver_debug`. + + Subclasses are selected via :attr:`NewtonSolverCfg.class_type`, which + :meth:`NewtonCfg.__post_init__` propagates onto :attr:`NewtonCfg.class_type` + so that ``SimulationContext`` resolves the matching subclass automatically. + + Lifecycle: ``initialize() -> reset() -> step()`` (repeated) ``-> close()``. + + .. note:: + Shared state lives on :class:`NewtonManager` (the base) by design — the + framework imports ``NewtonManager`` directly and reads attributes such + as ``_model`` / ``_state_0`` / ``_builder`` from many places. Lifecycle + methods therefore assign through the explicit base class + (``NewtonManager._foo = ...``) rather than through ``cls`` so that the + canonical state remains discoverable from external readers regardless of + which subclass is active. """ _solver_dt: float = 1.0 / 200.0 @@ -75,8 +133,7 @@ class NewtonManager(PhysicsManager): # Newton model and state _builder: ModelBuilder = None _model: Model = None - _solver: SolverBase = None - _solver_type: str = "mujoco_warp" + _solver: SolverBase | None = None _use_single_state: bool | None = None """Use only one state for both input and output for solver stepping. Requires solver support.""" _state_0: State = None @@ -91,8 +148,16 @@ class NewtonManager(PhysicsManager): _contacts: Contacts | None = None _needs_collision_pipeline: bool = False _collision_pipeline = None + _collision_cfg: NewtonCollisionPipelineCfg | None = None _newton_contact_sensors: dict = {} # Maps sensor_key to NewtonContactSensor + _newton_frame_transform_sensors: list = [] # List of SensorFrameTransform + _newton_imu_sensors: list = [] # List of NewtonSensorIMU + _pending_extended_state_attributes: set[str] = set() + _pending_extended_contact_attributes: set[str] = set() _report_contacts: bool = False + # Per-world reset masks (allocated in start_simulation, consumed in step) + _world_reset_mask: wp.array | None = None # (num_envs,) wp.int32 — for SolverKamino.reset(world_mask=...) + _fk_reset_mask: wp.array | None = None # (articulation_count,) wp.bool — for eval_fk(mask=...) # CUDA graphing _graph = None @@ -116,6 +181,19 @@ class NewtonManager(PhysicsManager): # Views list for assets to register their views _views: list = [] + # CL: Cloning / Replication logic + # TODO: These attributes support cloning-specific logic and should be moved into a cloner class + # Pending site requests from sensors. + # Key: (body_pattern, xform_floats), Value: (label, wp.transform) + # identical (body_pattern, transform) reuses the same site. + _cl_pending_sites: dict[tuple[str | None, tuple[float, ...]], tuple[str, wp.transform]] = {} + + # Maps each site label to its resolved global or local site entry. + _GlobalSite = tuple[int, None] + _LocalSite = tuple[None, list[list[int]]] + _SiteEntry = _GlobalSite | _LocalSite + _cl_site_index_map: dict[str, _SiteEntry] = {} + @classmethod def initialize(cls, sim_context: SimulationContext) -> None: """Initialize the manager with simulation context. @@ -128,7 +206,7 @@ def initialize(cls, sim_context: SimulationContext) -> None: # Newton-specific setup: get gravity from SimulationCfg (not physics manager cfg) sim = PhysicsManager._sim if sim is not None: - cls._gravity_vector = sim.cfg.gravity # type: ignore[union-attr] + NewtonManager._gravity_vector = sim.cfg.gravity # type: ignore[union-attr] # USD/Fabric sync for Omniverse rendering (visualizer) or Newton+RTX (Kit cameras) try: @@ -141,7 +219,7 @@ def initialize(cls, sim_context: SimulationContext) -> None: from isaaclab.app.settings_manager import get_settings_manager cameras_enabled = bool(get_settings_manager().get("/isaaclab/cameras_enabled", False)) - cls._clone_physics_only = "kit" not in requested and not cameras_enabled + NewtonManager._clone_physics_only = "kit" not in requested and not cameras_enabled @classmethod def reset(cls, soft: bool = False) -> None: @@ -156,7 +234,14 @@ def reset(cls, soft: bool = False) -> None: @classmethod def forward(cls) -> None: - """Update articulation kinematics without stepping physics.""" + """Update articulation kinematics without stepping physics. + + Runs Newton's generic forward kinematics (``eval_fk``) over **all** + articulations to compute body poses from joint coordinates. This is + the full (unmasked) FK path used during initial setup. For incremental + per-environment updates after resets, see :meth:`invalidate_fk` which + accumulates masks consumed by :meth:`step`. + """ eval_fk(cls._model, cls._state_0.joint_q, cls._state_0.joint_qd, cls._state_0, None) @classmethod @@ -197,12 +282,12 @@ def sync_transforms_to_usd(cls) -> None: # Lazy adapter creation: deferred from initialize_solver() to avoid # startup-ordering issues with the cubric plugin. if cls._cubric is not None and cls._cubric.available and cls._cubric_adapter is None: - cls._cubric_adapter = cls._cubric.create_adapter() + NewtonManager._cubric_adapter = cls._cubric.create_adapter() if cls._cubric_adapter is not None: logger.info("cubric GPU transform hierarchy enabled") else: logger.warning("cubric adapter creation failed; falling back to update_world_xforms()") - cls._cubric = None + NewtonManager._cubric = None use_cubric = cls._cubric is not None and cls._cubric_adapter is not None @@ -232,7 +317,7 @@ def sync_transforms_to_usd(cls) -> None: device=str(PhysicsManager._device), ) if selection.GetCount() == 0: - cls._transforms_dirty = False + NewtonManager._transforms_dirty = False return fabric_transforms = wp.fabricarray(selection, "omni:fabric:worldMatrix") @@ -245,13 +330,13 @@ def sync_transforms_to_usd(cls) -> None: ) wp.synchronize_device(PhysicsManager._device) - cls._transforms_dirty = False + NewtonManager._transforms_dirty = False if use_cubric and fabric_hierarchy is not None: fabric_id = cls._usdrt_stage.GetFabricId().id if fabric_id != cls._cubric_bound_fabric_id: cls._cubric.bind_to_stage(cls._cubric_adapter, fabric_id) - cls._cubric_bound_fabric_id = fabric_id + NewtonManager._cubric_bound_fabric_id = fabric_id cls._cubric.compute(cls._cubric_adapter) elif fabric_hierarchy is not None: fabric_hierarchy.update_world_xforms() @@ -269,7 +354,7 @@ def _mark_transforms_dirty(cls) -> None: Called by :meth:`_simulate` after stepping. The actual sync is deferred to :meth:`sync_transforms_to_usd`, which runs at render cadence. """ - cls._transforms_dirty = True + NewtonManager._transforms_dirty = True @classmethod def step(cls) -> None: @@ -283,7 +368,7 @@ def step(cls) -> None: with wp.ScopedDevice(PhysicsManager._device): for change in cls._model_changes: cls._solver.notify_model_changed(change) - cls._model_changes = set() + NewtonManager._model_changes = set() # Lazy CUDA graph capture: deferred from initialize_solver() when RTX was active. # By the time step() is first called, RTX has fully initialized (all cudaImportExternalMemory @@ -291,13 +376,24 @@ def step(cls) -> None: cfg = PhysicsManager._cfg device = PhysicsManager._device if cls._graph_capture_pending and cfg is not None and cfg.use_cuda_graph and "cuda" in device: # type: ignore[union-attr] - cls._graph_capture_pending = False - cls._graph = cls._capture_relaxed_graph(device) + NewtonManager._graph_capture_pending = False + NewtonManager._graph = cls._capture_relaxed_graph(device) if cls._graph is not None: logger.info("Newton CUDA graph captured (deferred relaxed mode, RTX-compatible)") else: logger.warning("Newton deferred CUDA graph capture failed; using eager execution") + # Ensure body_q is up-to-date before collision detection. + # After env resets, joint_q is written but body_q (used by + # broadphase/narrowphase) is stale until FK runs. + # Only runs FK for dirtied articulations via the accumulated mask. + if cls._needs_collision_pipeline: + eval_fk(cls._model, cls._state_0.joint_q, cls._state_0.joint_qd, cls._state_0, cls._fk_reset_mask) + + # Zero both masks after consumption + NewtonManager._world_reset_mask.zero_() + NewtonManager._fk_reset_mask.zero_() + # Step simulation (graphed or not; _graph is None when capture is disabled or failed) if cfg is not None and cfg.use_cuda_graph and cls._graph is not None and "cuda" in device: # type: ignore[union-attr] wp.capture_launch(cls._graph) @@ -307,12 +403,9 @@ def step(cls) -> None: with wp.ScopedDevice(device): cls._simulate() - # Debug convergence info - if cfg is not None and cfg.debug_mode: # type: ignore[union-attr] - convergence_data = cls.get_solver_convergence_steps() - logger.info(f"Solver convergence data: {convergence_data}") - if convergence_data["max"] == cls._solver.mjw_model.opt.iterations: - logger.warning(f"Solver didn't converge! max_iter={convergence_data['max']}") + # Launch solver-specific debug logging after stepping. + cls._log_solver_debug() + PhysicsManager._sim_time += cls._solver_dt * cls._num_substeps @classmethod @@ -321,6 +414,18 @@ def close(cls) -> None: cls.clear() super().close() + @classmethod + def register_callback( + cls, + callback: Callable, + event: PhysicsEvent, + order: int = 0, + name: str | None = None, + wrap_weak_ref: bool = True, + ) -> CallbackHandle: + """Register a callback. Passes event to parent class.""" + return PhysicsManager.register_callback(callback, event, order, name, wrap_weak_ref) + @classmethod def get_physics_sim_view(cls) -> list: """Get the list of registered views. @@ -340,43 +445,287 @@ def is_fabric_enabled(cls) -> bool: @classmethod def clear(cls): - """Clear all Newton-specific state (callbacks cleared by super().close()).""" + """Clear all Newton-specific state (callbacks cleared by super().close()). + Start with solver specific cleanup.""" + cls._solver_specific_clear() if cls._cubric is not None and cls._cubric_adapter is not None: cls._cubric.release_adapter(cls._cubric_adapter) - cls._cubric = None - cls._cubric_adapter = None - cls._cubric_bound_fabric_id = None - cls._builder = None - cls._model = None - cls._solver = None - cls._use_single_state = None - cls._state_0 = None - cls._state_1 = None - cls._control = None - cls._contacts = None - cls._needs_collision_pipeline = False - cls._collision_pipeline = None - cls._newton_contact_sensors = {} - cls._report_contacts = False - cls._graph = None - cls._graph_capture_pending = False - cls._newton_stage_path = None - cls._usdrt_stage = None - cls._transforms_dirty = False - cls._up_axis = "Z" - cls._model_changes = set() - cls._views = [] + NewtonManager._cubric = None + NewtonManager._cubric_adapter = None + NewtonManager._cubric_bound_fabric_id = None + NewtonManager._builder = None + NewtonManager._model = None + NewtonManager._solver = None + NewtonManager._use_single_state = None + NewtonManager._state_0 = None + NewtonManager._state_1 = None + NewtonManager._control = None + NewtonManager._contacts = None + NewtonManager._needs_collision_pipeline = False + NewtonManager._collision_pipeline = None + NewtonManager._collision_cfg = None + NewtonManager._newton_contact_sensors = {} + NewtonManager._newton_frame_transform_sensors = [] + NewtonManager._newton_imu_sensors = [] + NewtonManager._report_contacts = False + # Per-world reset masks + NewtonManager._world_reset_mask = None + NewtonManager._fk_reset_mask = None + NewtonManager._graph = None + NewtonManager._graph_capture_pending = False + NewtonManager._newton_stage_path = None + NewtonManager._usdrt_stage = None + NewtonManager._transforms_dirty = False + NewtonManager._up_axis = "Z" + NewtonManager._model_changes = set() + NewtonManager._cl_pending_sites = {} + NewtonManager._cl_site_index_map = {} + NewtonManager._pending_extended_state_attributes = set() + NewtonManager._pending_extended_contact_attributes = set() + NewtonManager._views = [] @classmethod def set_builder(cls, builder: ModelBuilder) -> None: """Set the Newton model builder.""" - cls._builder = builder + NewtonManager._builder = builder + + @classmethod + def create_builder(cls, up_axis: str | None = None, **kwargs) -> ModelBuilder: + """Create a :class:`ModelBuilder` configured with default settings. + + Forwards :class:`NewtonShapeCfg` defaults onto Newton's upstream + ``ModelBuilder.default_shape_cfg`` via :func:`~isaaclab.utils.checked_apply`. + Falls back to wrapper defaults when no Newton config is active so + rough-terrain margin/gap still apply during early construction. + + Args: + up_axis: Override for the up-axis. Defaults to ``None``, which uses + the manager's ``_up_axis``. + **kwargs: Forwarded to :class:`ModelBuilder`. + + Returns: + New builder with up-axis and per-shape defaults (gap, margin) applied. + """ + builder = ModelBuilder(up_axis=up_axis or cls._up_axis, **kwargs) + # Resolve which NewtonShapeCfg to apply: user override if active config + # is NewtonCfg, else the wrapper's own defaults so callers from non-Newton + # contexts (tests, early construction) still get the rough-terrain margin. + cfg = PhysicsManager._cfg + shape_cfg = cfg.default_shape_cfg if isinstance(cfg, NewtonCfg) else NewtonShapeCfg() + checked_apply(shape_cfg, builder.default_shape_cfg) + return builder + + @classmethod + def cl_register_site(cls, body_pattern: str | None, xform: wp.transform) -> str: + """Register a site request for injection into prototypes before replication. + + Sensors call this during ``__init__``. Sites are injected into prototype + builders by :meth:`_cl_inject_sites` (called from ``newton_replicate``) + before ``add_builder``, so they replicate correctly per-world. + + Identical ``(body_pattern, transform)`` registrations share sites. + + The *body_pattern* is matched against prototype-local body labels + (e.g. ``"Robot/link.*"``) when replication is active, or against the + flat builder's body labels in the fallback path. Wildcard patterns + that match multiple bodies create one site per matched body. + + Args: + body_pattern: Regex pattern matched against body labels in the + prototype builder (e.g. ``"Robot/link0"`` or ``"Robot/finger.*"`` + for multi-body wildcards), or ``None`` for global sites + (world-origin reference, etc.). + xform: Site transform relative to body. + + Returns: + Assigned site label suffix. + """ + xform_key = tuple(xform) + key = (body_pattern, xform_key) + if key in cls._cl_pending_sites: + return cls._cl_pending_sites[key][0] + label = f"ft_{len(cls._cl_pending_sites)}" + cls._cl_pending_sites[key] = (label, xform) + return label + + @classmethod + def request_extended_state_attribute(cls, attr: str) -> None: + """Request an extended state attribute (e.g. ``"body_qdd"``). + + Sensors call this during ``__init__``, before model finalization. + Attributes are forwarded to the builder in :meth:`start_simulation` + so that subsequent ``model.state()`` calls allocate them. + + Args: + attr: State attribute name (must be in ``State.EXTENDED_ATTRIBUTES``). + """ + cls._pending_extended_state_attributes.add(attr) + + @classmethod + def request_extended_contact_attribute(cls, attr: str) -> None: + """Request an extended contact attribute (e.g. ``"force"``). + + Sensors call this during ``__init__``, before model finalization. + Attributes are forwarded to the model in :meth:`start_simulation` + so that subsequent ``Contacts`` creation includes them. + + Args: + attr: Contact attribute name. + """ + cls._pending_extended_contact_attributes.add(attr) + + @classmethod + def _cl_inject_sites( + cls, + main_builder: ModelBuilder, + proto_builders: dict[str, ModelBuilder], + ) -> tuple[dict[str, int], dict[int, dict[str, list[int]]]]: + """Inject registered sites into prototype builders before replication. + + Non-global sites are matched against prototype body labels using + :func:`resolve_matching_names` (regex). Global sites + (``body_pattern is None``) are added to *main_builder* with + ``body=-1``. + + Returns proto-local shape indices so that ``newton_replicate`` can + compute final indices during replication without a second pattern match. + + Pending requests are cleared after processing. + + Args: + main_builder: Top-level builder that receives global sites. + proto_builders: ``{src_path: ModelBuilder}`` prototype builders. + + Returns: + Tuple of ``(global_sites, proto_sites)`` where *global_sites* maps + ``{label: main_builder_shape_idx}`` and *proto_sites* maps + ``{id(proto): {label: [proto_local_shape_idx, ...]}}``. + """ + global_sites: dict[str, int] = {} + proto_sites: dict[int, dict[str, list[int]]] = {} + + for (body_pattern, _xform_key), (label, xform) in cls._cl_pending_sites.items(): + if body_pattern is None: + site_idx = main_builder.add_site(body=-1, xform=xform, label=label) + global_sites[label] = site_idx + continue + + any_matched = False + for src_prefix, proto in proto_builders.items(): + body_labels = list(proto.body_label) + matched_indices, matched_names = resolve_matching_names( + body_pattern, body_labels, raise_when_no_match=False + ) + if not matched_indices: # Pattern has no matches in this prototype + continue + + any_matched = True + proto_id = id(proto) + site_indices: list[int] = [] + for body_idx, body_name in zip(matched_indices, matched_names): + site_label = f"{body_name}/{label}" + proto_site_idx = proto.add_site(body=body_idx, xform=xform, label=site_label) + site_indices.append(proto_site_idx) + logger.debug(f"Injected site '{site_label}' into prototype") + proto_sites.setdefault(proto_id, {})[label] = site_indices + + if not any_matched: + raise ValueError( + f"Site '{label}' with body_pattern '{body_pattern}' matched no prototype bodies " + f"across {len(proto_builders)} prototype(s). " + f"Check that the pattern matches a body label in the prototype builder." + ) + + cls._cl_pending_sites.clear() + return global_sites, proto_sites + + @classmethod + def _cl_inject_sites_fallback(cls) -> None: + """Inject pending sites into the flat builder (no-replication path). + + Populates :attr:`_cl_site_index_map` with the unified per-world structure: + + - Global sites (``body_pattern is None``): ``(shape_idx, None)`` + - Local sites: ``(None, [[idx, ...]])`` — one sublist for the single world. + """ + builder = cls._builder + body_labels = list(builder.body_label) + + for (body_pattern, _xform_key), (label, xform) in cls._cl_pending_sites.items(): + if body_pattern is None: + site_idx = builder.add_site(body=-1, xform=xform, label=label) + cls._cl_site_index_map[label] = (site_idx, None) + else: + try: + matched_indices, matched_names = resolve_matching_names(body_pattern, body_labels) + except ValueError as e: + raise ValueError( + f"Site '{label}' with body_pattern '{body_pattern}' matched no bodies " + f"in the flat builder. Available body labels: {body_labels}." + ) from e + + site_indices: list[int] = [] + for body_idx in matched_indices: + site_label = f"{builder.body_label[body_idx]}/{label}" + site_idx = builder.add_site(body=body_idx, xform=xform, label=site_label) + site_indices.append(site_idx) + + # Single world (no replication): one-element outer list + cls._cl_site_index_map[label] = (None, [site_indices]) + + cls._cl_pending_sites.clear() @classmethod def add_model_change(cls, change: SolverNotifyFlags) -> None: """Register a model change to notify the solver.""" cls._model_changes.add(change) + @classmethod + def invalidate_fk( + cls, + env_mask: wp.array | None = None, + env_ids: wp.array | None = None, + articulation_ids: wp.array | None = None, + ) -> None: + """Mark environments as needing FK recomputation and solver reset. + + Called by asset write methods that modify joint coordinates or root + transforms. The masks are consumed in :meth:`step` before physics + stepping. + + Args: + env_mask: Boolean mask of dirtied environments. Shape ``(num_envs,)``. + Used by ``_mask`` write methods. + env_ids: Integer indices of dirtied environments. + Used by ``_index`` write methods. + articulation_ids: Mapping from ``(world, arti)`` to model articulation + index. Shape ``(world_count, count_per_world)``. Obtained from + ``ArticulationView.articulation_ids``. + """ + if cls._world_reset_mask is None or cls._fk_reset_mask is None: + return + + if articulation_ids is not None and env_mask is not None: + wp.launch( + _or_reset_masks_from_mask, + dim=articulation_ids.shape, + inputs=[env_mask, articulation_ids], + outputs=[NewtonManager._world_reset_mask, NewtonManager._fk_reset_mask], + device=PhysicsManager._device, + ) + elif articulation_ids is not None and env_ids is not None: + wp.launch( + _scatter_reset_masks_from_ids, + dim=(env_ids.shape[0], articulation_ids.shape[1]), + inputs=[env_ids, articulation_ids], + outputs=[NewtonManager._world_reset_mask, NewtonManager._fk_reset_mask], + device=PhysicsManager._device, + ) + else: + # Fallback: no topology info — mark everything dirty + NewtonManager._world_reset_mask.fill_(1) + NewtonManager._fk_reset_mask.fill_(True) + @classmethod def start_simulation(cls) -> None: """Start simulation by finalizing model and initializing state. @@ -394,20 +743,36 @@ def start_simulation(cls) -> None: logger.info("Dispatching MODEL_INIT callbacks") cls.dispatch_event(PhysicsEvent.MODEL_INIT) + # Inject any pending site requests (no-replication fallback path). + # In the replication path, _cl_inject_sites() already ran from newton_replicate. + cls._cl_inject_sites_fallback() + device = PhysicsManager._device logger.info(f"Finalizing model on device: {device}") cls._builder.up_axis = Axis.from_string(cls._up_axis) - # Set smaller contact margin for manipulation examples (default 10cm is too large) + # Forward pending extended attribute requests to builder and clear them + if cls._pending_extended_state_attributes: + cls._builder.request_state_attributes(*cls._pending_extended_state_attributes) + NewtonManager._pending_extended_state_attributes = set() with Timer(name="newton_finalize_builder", msg="Finalize builder took:"): - cls._model = cls._builder.finalize(device=device) + NewtonManager._model = cls._builder.finalize(device=device) cls._model.set_gravity(cls._gravity_vector) cls._model.num_envs = cls._num_envs - cls._state_0 = cls._model.state() - cls._state_1 = cls._model.state() - cls._control = cls._model.control() + replace_newton_shape_colors(cls._model) + + if cls._pending_extended_contact_attributes: + cls._model.request_contact_attributes(*cls._pending_extended_contact_attributes) + NewtonManager._pending_extended_contact_attributes = set() + NewtonManager._state_0 = cls._model.state() + NewtonManager._state_1 = cls._model.state() + NewtonManager._control = cls._model.control() eval_fk(cls._model, cls._state_0.joint_q, cls._state_0.joint_qd, cls._state_0, None) + # Allocate per-world reset masks (used by all solvers for masked FK, and by Kamino for masked reset) + NewtonManager._world_reset_mask = wp.zeros(cls._model.world_count, dtype=wp.int32, device=device) + NewtonManager._fk_reset_mask = wp.zeros(cls._model.articulation_count, dtype=wp.bool, device=device) + logger.info("Dispatching PHYSICS_READY callbacks") cls.dispatch_event(PhysicsEvent.PHYSICS_READY) @@ -418,7 +783,7 @@ def start_simulation(cls) -> None: body_paths = getattr(cls._model, "body_label", None) or getattr(cls._model, "body_key", None) if body_paths is None: raise RuntimeError("NewtonManager: model has no body_label/body_key, skipping USD/Fabric sync for RTX.") - cls._usdrt_stage = get_current_stage(fabric=True) + NewtonManager._usdrt_stage = get_current_stage(fabric=True) for i, prim_path in enumerate(body_paths): prim = cls._usdrt_stage.GetPrimAtPath(prim_path) prim.CreateAttribute(cls._newton_index_attr, usdrt.Sdf.ValueTypeNames.UInt, True) @@ -441,6 +806,7 @@ def instantiate_builder_from_stage(cls): Detects env Xforms (e.g. ``/World/Env_0``, ``/World/Env_1``) and builds each as a separate Newton world via ``begin_world``/``end_world``. Falls back to a flat ``add_usd`` when no env Xforms are found. + """ import re @@ -481,10 +847,18 @@ def instantiate_builder_from_stage(cls): schema_resolvers=schema_resolvers, ) + # Inject registered sites into the proto before replication + global_sites, proto_sites = cls._cl_inject_sites(builder, {proto_path: proto}) + global_site_map: dict[str, tuple[int, None]] = {label: (idx, None) for label, idx in global_sites.items()} + num_worlds = len(env_paths) + local_site_map: dict[str, list[list[int]]] = {} + site_entries = proto_sites.get(id(proto), {}) + # Add each env as a separate Newton world xform_cache = UsdGeom.XformCache() - for _, env_path in env_paths: + for col, (_, env_path) in enumerate(env_paths): builder.begin_world() + offset = builder.shape_count world_xform = xform_cache.GetLocalToWorldTransform(stage.GetPrimAtPath(env_path)) translation = world_xform.ExtractTranslation() rotation = world_xform.ExtractRotationQuat() @@ -496,137 +870,192 @@ def instantiate_builder_from_stage(cls): rotation.GetReal(), ) builder.add_builder(proto, xform=wp.transform(pos, quat)) + for label, proto_shape_indices in site_entries.items(): + if label not in local_site_map: + local_site_map[label] = [[] for _ in range(num_worlds)] + for proto_shape_idx in proto_shape_indices: + local_site_map[label][col].append(offset + proto_shape_idx) builder.end_world() - cls._num_envs = len(env_paths) + NewtonManager._cl_site_index_map = { + **global_site_map, + **{label: (None, per_world) for label, per_world in local_site_map.items()}, + } + NewtonManager._num_envs = len(env_paths) cls.set_builder(builder) @classmethod def _initialize_contacts(cls) -> None: - """Unified method to initialize contacts and collision pipeline. + """Initialize contacts using Newton's :class:`CollisionPipeline`. + + This default implementation handles solvers that rely on Newton's + unified collision pipeline (XPBD, Featherstone, and MuJoCo with + ``use_mujoco_contacts=False``). Solver subclasses with internal + contact handling (e.g. :class:`NewtonMJWarpManager` when + ``use_mujoco_contacts=True``) override this method to allocate a + :class:`Contacts` object sized to the solver's internal contact buffer. + """ + if not cls._needs_collision_pipeline: + return + if cls._collision_pipeline is None: + if cls._collision_cfg is not None: + NewtonManager._collision_pipeline = CollisionPipeline( + cls._model, **cls._collision_cfg.to_pipeline_args() + ) + else: + NewtonManager._collision_pipeline = CollisionPipeline(cls._model, broad_phase="explicit") + if cls._contacts is None: + NewtonManager._contacts = cls._collision_pipeline.contacts() + + # ----- Solver construction (subclass contract) ------------------------ + + @classmethod + @abstractmethod + def _build_solver(cls, model: Model, solver_cfg: NewtonSolverCfg) -> None: + """Construct the solver this manager owns and assign it onto the base class. + + Subclasses must populate the canonical :class:`NewtonManager` slots: + + * :attr:`NewtonManager._solver` — the constructed :class:`SolverBase` + instance. + * :attr:`NewtonManager._use_single_state` — ``True`` if the solver + steps in-place on a single :class:`State` (e.g. MuJoCo); ``False`` + if it needs separate input/output states (e.g. XPBD, Featherstone, + Kamino). + * :attr:`NewtonManager._needs_collision_pipeline` — ``True`` if the + manager owns Newton's :class:`CollisionPipeline` for contact + generation; ``False`` if the solver runs internal collision + detection (MuJoCo internal contacts, Kamino with its own detector). + + Writing through ``NewtonManager._foo`` (rather than ``cls._foo``) + keeps the canonical state visible to external readers regardless of + which subclass is active. - This method handles both Newton collision pipeline and MuJoCo contact modes. - It ensures contacts are properly initialized with force attributes if sensors are registered. + Args: + model: Finalized Newton model the solver should run on. + solver_cfg: The manager-specific :class:`NewtonSolverCfg` + subclass (i.e. the inner ``cfg.solver_cfg``, not the outer + :class:`NewtonCfg`). """ - if cls._needs_collision_pipeline: - # Newton collision pipeline: create pipeline and generate contacts - if cls._collision_pipeline is None: - cls._collision_pipeline = CollisionPipeline(cls._model, broad_phase="explicit") - if cls._contacts is None: - cls._contacts = cls._collision_pipeline.contacts() - - elif cls._solver is not None and isinstance(cls._solver, SolverMuJoCo): - # MuJoCo contacts mode: create properly sized Contacts object - # The solver's update_contacts() will populate this from MuJoCo data - rigid_contact_max = cls._solver.get_max_contact_count() - cls._contacts = Contacts( - rigid_contact_max=rigid_contact_max, - soft_contact_max=0, - device=PhysicsManager._device, - requested_attributes=cls._model.get_requested_contact_attributes(), - ) + raise NotImplementedError("NewtonManager subclasses must implement _build_solver()") + + @classmethod + def _step_solver(cls, state_0: State, state_1: State, control: Control, substep_dt: float) -> None: + """Run one solver substep. + + Default invokes :attr:`_solver` once. Subclasses can override to + batch multiple solvers within a single substep. + """ + # Only solvers that consume Newton collision-pipeline contacts receive ``_contacts`` here. Solvers with + # internal contact handling receive ``None`` even when ``_contacts`` is allocated for later reporting via + # ``solver.update_contacts`` (e.g. MuJoCo with ``use_mujoco_contacts=True``). + contacts = cls._contacts if cls._needs_collision_pipeline else None + cls._solver.step(state_0, state_1, control, contacts, substep_dt) + + @classmethod + def _solver_specific_clear(cls) -> None: + """Solver-specific cleanup hook called from :meth:`clear`. + + Default no-op. Subclasses override to release sub-solver references + or other solver-specific resources. + """ + + @classmethod + def _log_solver_debug(cls) -> None: + """Solver-specific debug logging after stepping. + + Default no-op. Subclasses override to log solver-specific debug info + (e.g. constraint violations, contact forces, etc.) after stepping. + """ + + # ----- Lifecycle orchestration ---------------------------------------- @classmethod def initialize_solver(cls) -> None: """Initialize the solver and collision pipeline. - This function initializes the solver based on the specified solver type. Currently, only XPBD and MuJoCoWarp - are supported. If the solver requires external collision detection (i.e., not using MuJoCo's internal - contacts), a unified collision pipeline is created. - - The graphing of the simulation is performed in this function if the simulation is ran using - a CUDA enabled device. + Thin orchestrator: delegates solver construction to + :meth:`_build_solver` (overridden by each solver subclass), allocates + the collision pipeline (when applicable) via + :meth:`_initialize_contacts`, then sets up cubric bindings and either + captures the CUDA graph immediately or defers capture until the + first :meth:`step` call (RTX-active path). .. warning:: - When using a CUDA enabled device, the simulation will be graphed. This means that this function steps the - simulation once to capture the graph. Hence, this function should only be called after everything else in - the simulation is initialized. + When using a CUDA-enabled device, the simulation is graphed. + This means the function steps the simulation once to capture the + graph, so it should only be called after everything else in the + simulation is initialized. """ cfg = PhysicsManager._cfg if cfg is None: return with Timer(name="newton_initialize_solver", msg="Initialize solver took:"): - cls._num_substeps = cfg.num_substeps # type: ignore[union-attr] - cls._solver_dt = cls.get_physics_dt() / cls._num_substeps - - # Create solver from config - solver_cfg = cfg.solver_cfg # type: ignore[union-attr] - cfg_dict = solver_cfg.to_dict() if hasattr(solver_cfg, "to_dict") else {} - cls._solver_type = cfg_dict.pop("solver_type", "mujoco_warp") - - if cls._solver_type == "mujoco_warp": - # SolverMuJoCo does not require distinct input & output states - cls._use_single_state = True - solver_sig = inspect.signature(SolverMuJoCo.__init__) - valid_solver_args = set(solver_sig.parameters.keys()) - {"self", "model"} - cfg_dict = {k: v for k, v in cfg_dict.items() if k in valid_solver_args} - cls._solver = SolverMuJoCo(cls._model, **cfg_dict) - elif cls._solver_type == "xpbd": - cls._use_single_state = False - cls._solver = SolverXPBD(cls._model, **cfg_dict) - elif cls._solver_type == "featherstone": - cls._use_single_state = False - cls._solver = SolverFeatherstone(cls._model, **cfg_dict) - else: - raise ValueError(f"Invalid solver type: {cls._solver_type}") - - # Determine if we need external collision detection - # - SolverMuJoCo with use_mujoco_contacts=True: uses internal MuJoCo collision detection - # - SolverMuJoCo with use_mujoco_contacts=False: needs Newton's unified collision pipeline - # - Other solvers (XPBD, Featherstone): always need Newton's unified collision pipeline - if isinstance(cls._solver, SolverMuJoCo): - # Handle both dict and object configs - if hasattr(solver_cfg, "use_mujoco_contacts"): - use_mujoco_contacts = solver_cfg.use_mujoco_contacts - elif isinstance(solver_cfg, dict): - use_mujoco_contacts = solver_cfg.get("use_mujoco_contacts", False) - else: - use_mujoco_contacts = getattr(solver_cfg, "use_mujoco_contacts", False) - cls._needs_collision_pipeline = not use_mujoco_contacts - else: - cls._needs_collision_pipeline = True + NewtonManager._num_substeps = cfg.num_substeps # type: ignore[union-attr] + NewtonManager._solver_dt = cls.get_physics_dt() / cls._num_substeps + NewtonManager._collision_cfg = cfg.collision_cfg # type: ignore[union-attr] + + cls._build_solver( + cls._model, + cfg.solver_cfg, # type: ignore[union-attr] + ) + if NewtonManager._solver is None: + raise RuntimeError( + f"{cls.__name__}._build_solver did not assign NewtonManager._solver. " + "Subclasses of NewtonManager must populate NewtonManager._solver, " + "NewtonManager._use_single_state, and NewtonManager._needs_collision_pipeline." + ) - # Initialize contacts and collision pipeline cls._initialize_contacts() - # Prepare cubric ctypes bindings (acquires IAdapter from carb framework). - # Adapter creation is deferred to the first sync_transforms_to_usd() call - # at render time to avoid any startup-ordering issues with the cubric - # plugin initialisation. if cls._usdrt_stage is not None: - from isaaclab_newton.physics._cubric import CubricBindings - - cls._cubric = CubricBindings() - if cls._cubric.initialize(): - logger.info("cubric bindings ready (adapter deferred to first render)") - else: - logger.warning("cubric bindings init failed; falling back to update_world_xforms()") - cls._cubric = None + cls._setup_cubric_bindings() device = PhysicsManager._device - use_cuda_graph = cfg.use_cuda_graph and "cuda" in device # type: ignore[union-attr] + if use_cuda_graph: + cls._capture_or_defer_cuda_graph() + else: + NewtonManager._graph = None + + @classmethod + def _setup_cubric_bindings(cls) -> None: + """Initialize cubric ctypes bindings when the Kit viewport is active. + Adapter creation itself is deferred to the first + :meth:`sync_transforms_to_usd` call to avoid startup-ordering issues + with the cubric plugin. + """ + from isaaclab_newton.physics._cubric import CubricBindings + + bindings = CubricBindings() + if bindings.initialize(): + NewtonManager._cubric = bindings + logger.info("cubric bindings ready (adapter deferred to first render)") + else: + NewtonManager._cubric = None + logger.warning("cubric bindings init failed; falling back to update_world_xforms()") + + @classmethod + def _capture_or_defer_cuda_graph(cls) -> None: + """Capture the physics CUDA graph, or defer if RTX is initializing.""" with Timer(name="newton_cuda_graph", msg="CUDA graph took:"): - if use_cuda_graph: - if cls._usdrt_stage is None: - # No RTX active — use standard Warp capture (cudaStreamCaptureModeGlobal). - with wp.ScopedCapture() as capture: - cls._simulate() - cls._graph = capture.graph - logger.info("Newton CUDA graph captured (standard Warp mode)") - else: - # RTX is active during initialization — cudaImportExternalMemory and other - # non-capturable RTX ops run on background CUDA streams right now. - # Defer capture to the first step() call, after RTX is fully initialized - # and idle between render frames (clean capture window). - cls._graph = None - cls._graph_capture_pending = True - logger.info("Newton CUDA graph capture deferred until first step() (RTX active)") + if cls._usdrt_stage is None: + # No RTX active — use standard Warp capture (cudaStreamCaptureModeGlobal). + with wp.ScopedCapture() as capture: + cls._simulate() + NewtonManager._graph = capture.graph + logger.info("Newton CUDA graph captured (standard Warp mode)") else: - cls._graph = None + # RTX is active during initialization — cudaImportExternalMemory and other + # non-capturable RTX ops run on background CUDA streams right now. + # Defer capture to the first step() call, after RTX is fully initialized + # and idle between render frames (clean capture window). + NewtonManager._graph = None + NewtonManager._graph_capture_pending = True + logger.info("Newton CUDA graph capture deferred until first step() (RTX active)") @classmethod def _capture_relaxed_graph(cls, device: str): @@ -663,7 +1092,7 @@ def _capture_relaxed_graph(cls, device: str): - Call ``wp.capture_end(stream=fresh_stream)`` to finalise the Warp-level capture. - Call ``cudaStreamEndCapture`` to close the CUDA stream capture and get the graph. - Warmup run pre-allocates all MuJoCo-Warp scratch buffers so no ``cudaMalloc`` occurs during + Warmup run pre-allocates all solver scratch buffers so no ``cudaMalloc`` occurs during capture. ``sync_transforms_to_usd`` (which calls ``wp.synchronize_device``) is excluded from the capture and runs eagerly in ``step()`` after ``wp.capture_launch``. @@ -673,7 +1102,7 @@ def _capture_relaxed_graph(cls, device: str): logger.warning("libcudart not available; cannot use relaxed graph capture") return None - # Warmup: pre-allocate all MuJoCo-Warp scratch buffers so the capture window has + # Warmup: pre-allocate all solver scratch buffers so the capture window has # no new cudaMalloc calls (which are forbidden inside graph capture). with wp.ScopedDevice(device): cls._simulate_physics_only() @@ -761,30 +1190,35 @@ def _simulate_physics_only(cls) -> None: """ if cls._needs_collision_pipeline: cls._collision_pipeline.collide(cls._state_0, cls._contacts) - contacts = cls._contacts - else: - contacts = None - - def step_fn(state_0, state_1): - cls._solver.step(state_0, state_1, cls._control, contacts, cls._solver_dt) if cls._use_single_state: - for i in range(cls._num_substeps): - step_fn(cls._state_0, cls._state_0) + for _ in range(cls._num_substeps): + cls._step_solver(cls._state_0, cls._state_0, cls._control, cls._solver_dt) cls._state_0.clear_forces() else: cfg = PhysicsManager._cfg need_copy_on_last_substep = (cfg is not None and cfg.use_cuda_graph) and cls._num_substeps % 2 == 1 # type: ignore[union-attr] for i in range(cls._num_substeps): - step_fn(cls._state_0, cls._state_1) + cls._step_solver(cls._state_0, cls._state_1, cls._control, cls._solver_dt) if need_copy_on_last_substep and i == cls._num_substeps - 1: cls._state_0.assign(cls._state_1) else: - cls._state_0, cls._state_1 = cls._state_1, cls._state_0 + NewtonManager._state_0, NewtonManager._state_1 = cls._state_1, cls._state_0 cls._state_0.clear_forces() + # Update frame transform sensors + if cls._newton_frame_transform_sensors: + for sensor in cls._newton_frame_transform_sensors: + sensor.update(cls._state_0) + + # Update IMU sensors + if cls._newton_imu_sensors: + for sensor in cls._newton_imu_sensors: + sensor.update(cls._state_0) + + # Populate contacts for contact sensors if cls._report_contacts: - eval_contacts = contacts if contacts is not None else cls._contacts + eval_contacts = cls._contacts cls._solver.update_contacts(eval_contacts, cls._state_0) for sensor in cls._newton_contact_sensors.values(): sensor.update(cls._state_0, eval_contacts) @@ -803,14 +1237,11 @@ def _simulate(cls) -> None: @classmethod def get_solver_convergence_steps(cls) -> dict[str, float | int]: - """Get solver convergence statistics.""" - niter = cls._solver.mjw_data.solver_niter.numpy() - return { - "max": np.max(niter), - "mean": np.mean(niter), - "min": np.min(niter), - "std": np.std(niter), - } + """Get the solver convergence steps. Needs to be implemented in solver-specific managers.""" + if hasattr(cls, "_get_solver_convergence_steps"): + return cls._get_solver_convergence_steps() + else: + raise NotImplementedError("NewtonManager subclasses must implement _get_solver_convergence_steps()") # State accessors (used extensively by articulation/rigid object data) @classmethod @@ -925,9 +1356,58 @@ def _normalize_for_labels(expr: str | list[str] | None, labels: list[str]) -> st ) cls._newton_contact_sensors[sensor_key] = sensor - cls._report_contacts = True + NewtonManager._report_contacts = True if cls._solver is not None and cls._contacts is not None and cls._contacts.force is None: cls._initialize_contacts() return sensor_key + + @classmethod + def add_frame_transform_sensor(cls, shapes: list[int], reference_sites: list[int]) -> int: + """Add a frame transform sensor for measuring relative transforms. + + Creates a :class:`SensorFrameTransform` from pre-resolved shape and reference + site indices, appends it to the internal list, and returns its index. + + Args: + shapes: Ordered list of shape indices to measure. + reference_sites: 1:1 list of reference site indices (same length as shapes). + + Returns: + Index of the newly created sensor in :attr:`_newton_frame_transform_sensors`. + """ + sensor = SensorFrameTransform( + cls._model, + shapes=shapes, + reference_sites=reference_sites, + ) + idx = len(cls._newton_frame_transform_sensors) + cls._newton_frame_transform_sensors.append(sensor) + logger.info(f"Added frame transform sensor (index={idx}, shapes={len(shapes)})") + return idx + + @classmethod + def add_imu_sensor(cls, sites: list[int]) -> int: + """Add an IMU sensor for measuring acceleration and angular velocity at sites. + + Creates a ``newton.sensors.SensorIMU`` from pre-resolved site indices, + appends it to the internal list, and returns its index. + + Args: + sites: Ordered list of site indices (one per environment). + + Returns: + Index of the newly created sensor in the internal IMU sensor list. + """ + if cls._model is None: + raise RuntimeError("add_imu_sensor called before model finalization (start_simulation).") + sensor = NewtonSensorIMU( + cls._model, + sites=sites, + request_state_attributes=False, # Already requested via NewtonManager + ) + idx = len(cls._newton_imu_sensors) + cls._newton_imu_sensors.append(sensor) + logger.info(f"Added IMU sensor (index={idx}, sites={len(sites)})") + return idx diff --git a/source/isaaclab_newton/isaaclab_newton/physics/newton_manager_cfg.py b/source/isaaclab_newton/isaaclab_newton/physics/newton_manager_cfg.py index afbf7f54ba0c..85e4061ab911 100644 --- a/source/isaaclab_newton/isaaclab_newton/physics/newton_manager_cfg.py +++ b/source/isaaclab_newton/isaaclab_newton/physics/newton_manager_cfg.py @@ -12,8 +12,10 @@ from isaaclab.physics import PhysicsCfg from isaaclab.utils import configclass +from .newton_collision_cfg import NewtonCollisionPipelineCfg + if TYPE_CHECKING: - from .newton_manager import NewtonManager + from isaaclab_newton.physics import NewtonManager @configclass @@ -22,176 +24,53 @@ class NewtonSolverCfg: These parameters are used to configure the Newton solver. For more information, see the `Newton documentation`_. - .. _Newton documentation: https://newton.readthedocs.io/en/latest/ - """ - - solver_type: str = "None" - """Solver type. - - Used to select the right solver class. - """ - - -@configclass -class MJWarpSolverCfg(NewtonSolverCfg): - """Configuration for MuJoCo Warp solver-related parameters. - - These parameters are used to configure the MuJoCo Warp solver. For more information, see the - `MuJoCo Warp documentation`_. - - .. _MuJoCo Warp documentation: https://github.com/google-deepmind/mujoco_warp - """ - - solver_type: str = "mujoco_warp" - """Solver type. Can be "mujoco_warp".""" - - njmax: int = 300 - """Number of constraints per environment (world).""" - - nconmax: int | None = None - """Number of contact points per environment (world).""" - - iterations: int = 100 - """Number of solver iterations.""" - - ls_iterations: int = 50 - """Number of line search iterations for the solver.""" + Subclasses set :attr:`class_type` to their matching :class:`NewtonManager` + subclass; :class:`NewtonCfg` propagates that to its own + :attr:`NewtonCfg.class_type` in :meth:`NewtonCfg.__post_init__` so that + ``SimulationContext`` resolves the correct manager via the existing + dispatch path. - solver: str = "newton" - """Solver type. Can be "cg" or "newton", or their corresponding MuJoCo integer constants.""" - - integrator: str = "euler" - """Integrator type. Can be "euler", "rk4", or "implicitfast", or their corresponding MuJoCo integer constants.""" - - use_mujoco_cpu: bool = False - """Whether to use the pure MuJoCo backend instead of `mujoco_warp`.""" - - disable_contacts: bool = False - """Whether to disable contact computation in MuJoCo.""" - - default_actuator_gear: float | None = None - """Default gear ratio for all actuators.""" - - actuator_gears: dict[str, float] | None = None - """Dictionary mapping joint names to specific gear ratios, overriding the `default_actuator_gear`.""" - - update_data_interval: int = 1 - """Frequency (in simulation steps) at which to update the MuJoCo Data object from the Newton state. - - If 0, Data is never updated after initialization. + .. _Newton documentation: https://newton.readthedocs.io/en/latest/ """ - save_to_mjcf: str | None = None - """Optional path to save the generated MJCF model file. + class_type: type[NewtonManager] | str = "{DIR}.newton_manager:NewtonManager" + """Manager class for this solver. - If None, the MJCF model is not saved. + Default points at the abstract :class:`NewtonManager`; concrete subclasses + override it. """ - impratio: float = 1.0 - """Frictional-to-normal constraint impedance ratio.""" - - cone: str = "pyramidal" - """The type of contact friction cone. Can be "pyramidal" or "elliptic".""" - - ccd_iterations: int = 35 - """Maximum iterations for convex collision detection (GJK/EPA). + solver_type: str = "None" + """Solver type metadata (deprecated). - Increase this if you see warnings about ``opt.ccd_iterations`` needing to be increased, - which typically occurs with complex collision geometries (e.g. multi-finger hands). + .. deprecated:: + Manager dispatch is now driven by :attr:`class_type`; this field is + retained as metadata for logging and debugging only. Do not branch on + ``solver_type`` in new code. """ - ls_parallel: bool = False - """Whether to use parallel line search.""" - - use_mujoco_contacts: bool = True - """Whether to use MuJoCo's contact solver.""" - @configclass -class XPBDSolverCfg(NewtonSolverCfg): - """An implicit integrator using eXtended Position-Based Dynamics (XPBD) for rigid and soft body simulation. - - References: - - Miles Macklin, Matthias Müller, and Nuttapong Chentanez. 2016. XPBD: position-based simulation of compliant - constrained dynamics. In Proceedings of the 9th International Conference on Motion in Games (MIG '16). - Association for Computing Machinery, New York, NY, USA, 49-54. https://doi.org/10.1145/2994258.2994272 - - Matthias Müller, Miles Macklin, Nuttapong Chentanez, Stefan Jeschke, and Tae-Yong Kim. 2020. Detailed rigid - body simulation with extended position based dynamics. In Proceedings of the ACM SIGGRAPH/Eurographics - Symposium on Computer Animation (SCA '20). Eurographics Association, Goslar, DEU, - Article 10, 1-12. https://doi.org/10.1111/cgf.14105 - +class NewtonShapeCfg: + """Default per-shape collision properties applied to all shapes in a Newton scene. + + Mirrors Newton's :attr:`ModelBuilder.default_shape_cfg`. Only fields Isaac + Lab actually overrides are declared here; unspecified fields keep Newton's + upstream default. The struct is forwarded onto Newton's upstream + ``ShapeConfig`` via :func:`~isaaclab.utils.checked_apply` at builder + construction. """ - solver_type: str = "xpbd" - """Solver type. Can be "xpbd".""" - - iterations: int = 2 - """Number of solver iterations.""" - - soft_body_relaxation: float = 0.9 - """Relaxation parameter for soft body simulation.""" + margin: float = 0.0 + """Default per-shape collision margin [m]. - soft_contact_relaxation: float = 0.9 - """Relaxation parameter for soft contact simulation.""" - - joint_linear_relaxation: float = 0.7 - """Relaxation parameter for joint linear simulation.""" - - joint_angular_relaxation: float = 0.4 - """Relaxation parameter for joint angular simulation.""" - - joint_linear_compliance: float = 0.0 - """Compliance parameter for joint linear simulation.""" - - joint_angular_compliance: float = 0.0 - """Compliance parameter for joint angular simulation.""" - - rigid_contact_relaxation: float = 0.8 - """Relaxation parameter for rigid contact simulation.""" - - rigid_contact_con_weighting: bool = True - """Whether to use contact constraint weighting for rigid contact simulation.""" - - angular_damping: float = 0.0 - """Angular damping parameter for rigid contact simulation.""" - - enable_restitution: bool = False - """Whether to enable restitution for rigid contact simulation.""" - - -@configclass -class FeatherstoneSolverCfg(NewtonSolverCfg): - """A semi-implicit integrator using symplectic Euler. - - It operates on reduced (also called generalized) coordinates to simulate articulated rigid body dynamics - based on Featherstone's composite rigid body algorithm (CRBA). - - See: Featherstone, Roy. Rigid Body Dynamics Algorithms. Springer US, 2014. - - Semi-implicit time integration is a variational integrator that - preserves energy, however it not unconditionally stable, and requires a time-step - small enough to support the required stiffness and damping forces. - - See: https://en.wikipedia.org/wiki/Semi-implicit_Euler_method + A nonzero margin (e.g. ``0.01``) is required for stable contact on + triangle-mesh terrain — without it, lightweight robots fail to learn + rough-terrain locomotion on Newton. Newton's upstream default is ``0.0``. """ - solver_type: str = "featherstone" - """Solver type. Can be "featherstone".""" - - angular_damping: float = 0.05 - """Angular damping parameter for rigid contact simulation.""" - - update_mass_matrix_interval: int = 1 - """Frequency (in simulation steps) at which to update the mass matrix.""" - - friction_smoothing: float = 1.0 - """Friction smoothing parameter.""" - - use_tile_gemm: bool = False - """Whether to use tile-based GEMM for the mass matrix.""" - - fuse_cholesky: bool = True - """Whether to fuse the Cholesky decomposition.""" + gap: float = 0.01 + """Default per-shape contact gap [m]. Newton's upstream default is ``None``.""" @configclass @@ -199,10 +78,21 @@ class NewtonCfg(PhysicsCfg): """Configuration for Newton physics manager. This configuration includes Newton-specific simulation settings and solver configuration. + + The active :class:`NewtonManager` subclass is determined by + :attr:`solver_cfg.class_type`, which :meth:`__post_init__` propagates to + :attr:`class_type` so that ``SimulationContext`` resolves the right + manager subclass automatically. User code keeps the existing two-level + shape ``NewtonCfg(solver_cfg=...)`` and does not need to set + :attr:`class_type` explicitly. """ - class_type: type[NewtonManager] | str = "{DIR}.newton_manager:NewtonManager" - """The class type of the NewtonManager.""" + class_type: type[NewtonManager] | str | None = None + """The class type of the :class:`NewtonManager`. + + Auto-set in :meth:`__post_init__` from :attr:`solver_cfg.class_type`. + Users normally do not set this directly. + """ num_substeps: int = 1 """Number of substeps to use for the solver.""" @@ -216,5 +106,46 @@ class NewtonCfg(PhysicsCfg): If set to False, the simulation performance will be severely degraded. """ - solver_cfg: NewtonSolverCfg = MJWarpSolverCfg() - """Solver configuration. Default is MJWarpSolverCfg().""" + solver_cfg: NewtonSolverCfg | None = None + """Solver configuration. If None (default), MJWarpSolverCfg is used by default.""" + + collision_cfg: NewtonCollisionPipelineCfg | None = None + """Newton collision pipeline configuration. + + Controls how Newton's :class:`CollisionPipeline` is configured when it is active. + The pipeline is active when the solver delegates collision detection to Newton: + + - :class:`MJWarpSolverCfg` with ``use_mujoco_contacts=False``, + - :class:`KaminoSolverCfg` with ``use_collision_detector=False``, + - :class:`XPBDSolverCfg` (always), + - :class:`FeatherstoneSolverCfg` (always). + + If ``None`` (default), a pipeline with ``broad_phase="explicit"`` is created + automatically. Set this to a :class:`NewtonCollisionPipelineCfg` to customize + parameters such as broad phase algorithm, contact limits, or hydroelastic mode. + + .. note:: + Setting this while ``MJWarpSolverCfg.use_mujoco_contacts=True`` raises + :class:`ValueError`. When ``KaminoSolverCfg.use_collision_detector=True``, + the field is ignored because Kamino's internal detector handles contacts. + """ + + default_shape_cfg: NewtonShapeCfg = NewtonShapeCfg() + """Default per-shape collision properties applied to every shape in the scene. + + Forwarded to Newton's :attr:`ModelBuilder.default_shape_cfg` at builder + construction via :func:`~isaaclab.utils.checked_apply`. See + :class:`NewtonShapeCfg` for the declared fields. + """ + + def __post_init__(self): + # NewtonCfg.class_type is auto-derived from solver_cfg.class_type. + # Refuse a user-set value: setting both is ambiguous and was + # previously silently overwritten. + if self.class_type is not None: + raise TypeError("Cannot manually set NewtonCfg.class_type; it is auto-derived from solver_cfg.class_type.") + if self.solver_cfg is None: + from .mjwarp_manager_cfg import MJWarpSolverCfg + + self.solver_cfg = MJWarpSolverCfg() + self.class_type = self.solver_cfg.class_type diff --git a/source/isaaclab_newton/isaaclab_newton/physics/xpbd_manager.py b/source/isaaclab_newton/isaaclab_newton/physics/xpbd_manager.py new file mode 100644 index 000000000000..40022ef7e0d2 --- /dev/null +++ b/source/isaaclab_newton/isaaclab_newton/physics/xpbd_manager.py @@ -0,0 +1,36 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""XPBD Newton manager.""" + +from __future__ import annotations + +import inspect + +from newton import Model +from newton.solvers import SolverXPBD + +from .newton_manager import NewtonManager +from .xpbd_manager_cfg import XPBDSolverCfg + + +class NewtonXPBDManager(NewtonManager): + """:class:`NewtonManager` specialization for the XPBD solver. + + Always uses Newton's :class:`CollisionPipeline` for contact handling. + """ + + @classmethod + def _build_solver(cls, model: Model, solver_cfg: XPBDSolverCfg) -> None: + """Construct :class:`SolverXPBD` and populate the base-class slots. + + XPBD always uses Newton's :class:`CollisionPipeline` and steps with + separate input/output states, so the flags are fixed. + """ + valid = set(inspect.signature(SolverXPBD.__init__).parameters) - {"self", "model"} + kwargs = {k: v for k, v in solver_cfg.to_dict().items() if k in valid} + NewtonManager._solver = SolverXPBD(model, **kwargs) + NewtonManager._use_single_state = False + NewtonManager._needs_collision_pipeline = True diff --git a/source/isaaclab_newton/isaaclab_newton/physics/xpbd_manager_cfg.py b/source/isaaclab_newton/isaaclab_newton/physics/xpbd_manager_cfg.py new file mode 100644 index 000000000000..0555bd95a412 --- /dev/null +++ b/source/isaaclab_newton/isaaclab_newton/physics/xpbd_manager_cfg.py @@ -0,0 +1,72 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Configuration for Newton physics manager.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from isaaclab.utils import configclass + +from .newton_manager_cfg import NewtonSolverCfg + +if TYPE_CHECKING: + from isaaclab_newton.physics import NewtonManager + + +@configclass +class XPBDSolverCfg(NewtonSolverCfg): + """An implicit integrator using eXtended Position-Based Dynamics (XPBD) for rigid and soft body simulation. + + References: + - Miles Macklin, Matthias Müller, and Nuttapong Chentanez. 2016. XPBD: position-based simulation of compliant + constrained dynamics. In Proceedings of the 9th International Conference on Motion in Games (MIG '16). + Association for Computing Machinery, New York, NY, USA, 49-54. https://doi.org/10.1145/2994258.2994272 + - Matthias Müller, Miles Macklin, Nuttapong Chentanez, Stefan Jeschke, and Tae-Yong Kim. 2020. Detailed rigid + body simulation with extended position based dynamics. In Proceedings of the ACM SIGGRAPH/Eurographics + Symposium on Computer Animation (SCA '20). Eurographics Association, Goslar, DEU, + Article 10, 1-12. https://doi.org/10.1111/cgf.14105 + + """ + + class_type: type[NewtonManager] | str = "{DIR}.xpbd_manager:NewtonXPBDManager" + """Manager class for the XPBD solver.""" + + solver_type: str = "xpbd" + """Solver type. Can be "xpbd".""" + + iterations: int = 2 + """Number of solver iterations.""" + + soft_body_relaxation: float = 0.9 + """Relaxation parameter for soft body simulation.""" + + soft_contact_relaxation: float = 0.9 + """Relaxation parameter for soft contact simulation.""" + + joint_linear_relaxation: float = 0.7 + """Relaxation parameter for joint linear simulation.""" + + joint_angular_relaxation: float = 0.4 + """Relaxation parameter for joint angular simulation.""" + + joint_linear_compliance: float = 0.0 + """Compliance parameter for joint linear simulation.""" + + joint_angular_compliance: float = 0.0 + """Compliance parameter for joint angular simulation.""" + + rigid_contact_relaxation: float = 0.8 + """Relaxation parameter for rigid contact simulation.""" + + rigid_contact_con_weighting: bool = True + """Whether to use contact constraint weighting for rigid contact simulation.""" + + angular_damping: float = 0.0 + """Angular damping parameter for rigid contact simulation.""" + + enable_restitution: bool = False + """Whether to enable restitution for rigid contact simulation.""" diff --git a/source/isaaclab_newton/isaaclab_newton/renderers/newton_warp_renderer.py b/source/isaaclab_newton/isaaclab_newton/renderers/newton_warp_renderer.py index 4fdee1041256..a02d820f2951 100644 --- a/source/isaaclab_newton/isaaclab_newton/renderers/newton_warp_renderer.py +++ b/source/isaaclab_newton/isaaclab_newton/renderers/newton_warp_renderer.py @@ -8,7 +8,6 @@ from __future__ import annotations import logging -import weakref from dataclasses import dataclass from typing import TYPE_CHECKING, Any @@ -16,7 +15,8 @@ import torch import warp as wp -from isaaclab.renderers import BaseRenderer +from isaaclab.renderers import BaseRenderer, RenderBufferKind, RenderBufferSpec +from isaaclab.renderers.camera_render_spec import CameraRenderSpec from isaaclab.sim import SimulationContext from isaaclab.utils.math import convert_camera_frame_orientation_convention @@ -24,19 +24,14 @@ if TYPE_CHECKING: from isaaclab.physics import BaseSceneDataProvider - from isaaclab.sensors import SensorBase + from isaaclab.sensors.camera.camera_data import CameraData logger = logging.getLogger(__name__) class RenderData: - class OutputNames: - RGB = "rgb" - RGBA = "rgba" - ALBEDO = "albedo" - DEPTH = "depth" - NORMALS = "normals" - INSTANCE_SEGMENTATION = "instance_segmentation_fast" + # Back-compat alias for callers of ``RenderData.OutputNames``. + OutputNames = RenderBufferKind @dataclass class CameraOutputs: @@ -46,49 +41,44 @@ class CameraOutputs: normals_image: wp.array(dtype=wp.vec3f, ndim=4) = None instance_segmentation_image: wp.array(dtype=wp.uint32, ndim=4) = None - def __init__(self, newton_sensor: newton.sensors.SensorTiledCamera, sensor: SensorBase): + def __init__(self, newton_sensor: newton.sensors.SensorTiledCamera, spec: CameraRenderSpec): self.newton_sensor = newton_sensor - # Currently camera owns the renderer and render data. By holding full - # reference of the sensor, we create a circular reference between the - # sensor and the render data. Weak reference ensures proper garbage - # collection. - self.sensor = weakref.ref(sensor) self.num_cameras = 1 self.camera_rays: wp.array(dtype=wp.vec3f, ndim=4) = None self.camera_transforms: wp.array(dtype=wp.transformf, ndim=2) = None self.outputs = RenderData.CameraOutputs() - self.width = getattr(sensor.cfg, "width", 100) - self.height = getattr(sensor.cfg, "height", 100) + self.width = getattr(spec.cfg, "width", 100) + self.height = getattr(spec.cfg, "height", 100) def set_outputs(self, output_data: dict[str, torch.Tensor]): for output_name, tensor_data in output_data.items(): - if output_name == RenderData.OutputNames.RGBA: + if output_name == RenderBufferKind.RGBA: self.outputs.color_image = self._from_torch(tensor_data, dtype=wp.uint32) - elif output_name == RenderData.OutputNames.ALBEDO: + elif output_name == RenderBufferKind.ALBEDO: self.outputs.albedo_image = self._from_torch(tensor_data, dtype=wp.uint32) - elif output_name == RenderData.OutputNames.DEPTH: + elif output_name == RenderBufferKind.DEPTH: self.outputs.depth_image = self._from_torch(tensor_data, dtype=wp.float32) - elif output_name == RenderData.OutputNames.NORMALS: + elif output_name == RenderBufferKind.NORMALS: self.outputs.normals_image = self._from_torch(tensor_data, dtype=wp.vec3f) - elif output_name == RenderData.OutputNames.INSTANCE_SEGMENTATION: + elif output_name == RenderBufferKind.INSTANCE_SEGMENTATION_FAST: self.outputs.instance_segmentation_image = self._from_torch(tensor_data, dtype=wp.uint32) - elif output_name == RenderData.OutputNames.RGB: + elif output_name == RenderBufferKind.RGB: pass else: logger.warning(f"NewtonWarpRenderer - output type {output_name} is not yet supported") def get_output(self, output_name: str) -> wp.array: - if output_name == RenderData.OutputNames.RGBA: + if output_name == RenderBufferKind.RGBA: return self.outputs.color_image - elif output_name == RenderData.OutputNames.ALBEDO: + elif output_name == RenderBufferKind.ALBEDO: return self.outputs.albedo_image - elif output_name == RenderData.OutputNames.DEPTH: + elif output_name == RenderBufferKind.DEPTH: return self.outputs.depth_image - elif output_name == RenderData.OutputNames.NORMALS: + elif output_name == RenderBufferKind.NORMALS: return self.outputs.normals_image - elif output_name == RenderData.OutputNames.INSTANCE_SEGMENTATION: + elif output_name == RenderBufferKind.INSTANCE_SEGMENTATION_FAST: return self.outputs.instance_segmentation_image return None @@ -116,13 +106,13 @@ def update(self, positions: torch.Tensor, orientations: torch.Tensor, intrinsics ) def _from_torch(self, tensor: torch.Tensor, dtype) -> wp.array: - torch_array = wp.from_torch(tensor) + proxy_array = wp.from_torch(tensor) if tensor.is_contiguous(): return wp.array( - ptr=torch_array.ptr, + ptr=proxy_array.ptr, dtype=dtype, shape=(self.newton_sensor.model.world_count, self.num_cameras, self.height, self.width), - device=torch_array.device, + device=proxy_array.device, copy=False, ) @@ -130,7 +120,7 @@ def _from_torch(self, tensor: torch.Tensor, dtype) -> wp.array: return wp.zeros( (self.newton_sensor.model.world_count, self.num_cameras, self.height, self.width), dtype=dtype, - device=torch_array.device, + device=proxy_array.device, ) @wp.kernel @@ -154,6 +144,7 @@ def __init__(self, cfg: NewtonWarpRendererCfg): requirement_for_renderer_type, ) + self.cfg = cfg sim = SimulationContext.instance() current_req = sim.get_scene_data_requirements() renderer_req = requirement_for_renderer_type("newton_warp") @@ -184,15 +175,32 @@ def __init__(self, cfg: NewtonWarpRendererCfg): if cfg.create_default_light: self.newton_sensor.utils.create_default_light(enable_shadows=cfg.enable_shadows) + def supported_output_types(self) -> dict[RenderBufferKind, RenderBufferSpec]: + """Publish the per-output layout this Newton Warp backend writes. + See :meth:`~isaaclab.renderers.base_renderer.BaseRenderer.supported_output_types`.""" + seg_spec = ( + RenderBufferSpec(4, torch.uint8) + if self.cfg.colorize_instance_segmentation + else RenderBufferSpec(1, torch.int32) + ) + return { + RenderBufferKind.RGBA: RenderBufferSpec(4, torch.uint8), + RenderBufferKind.RGB: RenderBufferSpec(3, torch.uint8), + RenderBufferKind.ALBEDO: RenderBufferSpec(4, torch.uint8), + RenderBufferKind.DEPTH: RenderBufferSpec(1, torch.float32), + RenderBufferKind.NORMALS: RenderBufferSpec(3, torch.float32), + RenderBufferKind.INSTANCE_SEGMENTATION_FAST: seg_spec, + } + def prepare_stage(self, stage: Any, num_envs: int) -> None: """No-op for Newton Warp - uses Newton scene directly without stage export. See :meth:`~isaaclab.renderers.base_renderer.BaseRenderer.prepare_stage`.""" pass - def create_render_data(self, sensor: SensorBase) -> RenderData: + def create_render_data(self, spec: CameraRenderSpec) -> RenderData: """Create render data for the Newton tiled camera. See :meth:`~isaaclab.renderers.base_renderer.BaseRenderer.create_render_data`.""" - return RenderData(self.newton_sensor, sensor) + return RenderData(self.newton_sensor, spec) def set_outputs(self, render_data: RenderData, output_data: dict[str, torch.Tensor]): """Store output buffers. See :meth:`~isaaclab.renderers.base_renderer.BaseRenderer.set_outputs`.""" @@ -221,21 +229,26 @@ def render(self, render_data: RenderData): depth_image=render_data.outputs.depth_image, normal_image=render_data.outputs.normals_image, shape_index_image=render_data.outputs.instance_segmentation_image, + # ARGB 93% gray to improve visibility of dark objects and align with RTX renderer background + clear_data=newton.sensors.SensorTiledCamera.ClearData(clear_color=0xFFEEEEEE), ) - def write_output(self, render_data: RenderData, output_name: str, output_data: torch.Tensor): - """Copy a specific output to the given buffer. - See :meth:`~isaaclab.renderers.base_renderer.BaseRenderer.write_output`.""" - image_data = render_data.get_output(output_name) - if image_data is not None: - if image_data.ptr != output_data.data_ptr(): - wp.copy(wp.from_torch(output_data), image_data) + def read_output(self, render_data: RenderData, camera_data: CameraData) -> None: + """Copy rendered outputs to the camera data buffers. + See :meth:`~isaaclab.renderers.base_renderer.BaseRenderer.read_output`.""" + for output_name in camera_data.output: + if output_name == "rgb": + continue + image_data = render_data.get_output(output_name) + if image_data is not None: + output_data = camera_data.output[output_name] + if image_data.ptr != output_data.data_ptr(): + wp.copy(wp.from_torch(output_data), image_data) def cleanup(self, render_data: RenderData | None): """Release resources. No-op for Newton Warp. See :meth:`~isaaclab.renderers.base_renderer.BaseRenderer.cleanup`.""" - if render_data: - render_data.sensor = None + pass def get_scene_data_provider(self) -> BaseSceneDataProvider: return SimulationContext.instance().initialize_scene_data_provider() diff --git a/source/isaaclab_newton/isaaclab_newton/renderers/newton_warp_renderer_cfg.py b/source/isaaclab_newton/isaaclab_newton/renderers/newton_warp_renderer_cfg.py index f6a5ce559af7..96db9ca41fd1 100644 --- a/source/isaaclab_newton/isaaclab_newton/renderers/newton_warp_renderer_cfg.py +++ b/source/isaaclab_newton/isaaclab_newton/renderers/newton_warp_renderer_cfg.py @@ -33,3 +33,6 @@ class NewtonWarpRendererCfg(RendererCfg): create_default_light: bool = True """Create a default directional light source in the scene.""" + + colorize_instance_segmentation: bool = True + """Expose ``instance_segmentation_fast`` as ``(N, H, W, 4) uint8`` if True, else ``(N, H, W, 1) int32``.""" diff --git a/source/isaaclab_newton/isaaclab_newton/scene_data_providers/newton_scene_data_provider.py b/source/isaaclab_newton/isaaclab_newton/scene_data_providers/newton_scene_data_provider.py index f3b10dc40044..ba19f4e7c63a 100644 --- a/source/isaaclab_newton/isaaclab_newton/scene_data_providers/newton_scene_data_provider.py +++ b/source/isaaclab_newton/isaaclab_newton/scene_data_providers/newton_scene_data_provider.py @@ -96,7 +96,7 @@ def _determine_num_envs_in_scene(self) -> int: # ---- Core provider API ------------------------------------------------------------------- - def update(self, env_ids: list[int] | None = None) -> None: + def update(self) -> None: """Sync Newton body transforms to USD Fabric when a Kit viewport is active. Called at render cadence by :meth:`~isaaclab.sim.SimulationContext.update_scene_data_provider`, @@ -104,9 +104,6 @@ def update(self, env_ids: list[int] | None = None) -> None: :meth:`~isaaclab_newton.physics.NewtonManager.sync_transforms_to_usd` when a Kit (or other USD-based) visualizer is in use. When both sim and rendering backend are Newton (or Rerun), the sync is skipped to avoid unnecessary slowdown. - - Args: - env_ids: Optional environment id selection. Unused in this provider. """ if not self._needs_usd_sync: return @@ -127,13 +124,9 @@ def get_newton_model(self) -> Any | None: return NewtonManager.get_model() - def get_newton_state(self, env_ids: list[int] | None = None) -> Any | None: + def get_newton_state(self) -> Any | None: """Return Newton state from NewtonManager. - Args: - env_ids: Optional list of environment IDs. Currently returns the full - state for all environments (env_ids filtering is not yet implemented). - Returns: The current Newton state (state_0) from NewtonManager. """ @@ -149,16 +142,9 @@ def get_model(self) -> Any | None: """ return self.get_newton_model() - def get_state(self, env_ids: list[int] | None = None) -> Any | None: - """Alias for :meth:`get_newton_state` for visualizer compatibility. - - Args: - env_ids: Optional list of environment ids. - - Returns: - Newton state object, or ``None`` when unavailable. - """ - return self.get_newton_state(env_ids) + def get_state(self) -> Any | None: + """Alias for :meth:`get_newton_state` for visualizer compatibility.""" + return self.get_newton_state() def get_usd_stage(self) -> Any | None: """Return the USD stage handle. diff --git a/source/isaaclab_newton/isaaclab_newton/sensors/__init__.pyi b/source/isaaclab_newton/isaaclab_newton/sensors/__init__.pyi index 88c5925d55c7..e536b281952b 100644 --- a/source/isaaclab_newton/isaaclab_newton/sensors/__init__.pyi +++ b/source/isaaclab_newton/isaaclab_newton/sensors/__init__.pyi @@ -9,7 +9,16 @@ __all__ = [ "ContactSensorCfg", "FrameTransformer", "FrameTransformerData", + "Imu", + "ImuData", + "JointWrenchSensor", + "JointWrenchSensorData", + "Pva", + "PvaData", ] from .contact_sensor import ContactSensor, ContactSensorData, ContactSensorCfg from .frame_transformer import FrameTransformer, FrameTransformerData +from .imu import Imu, ImuData +from .joint_wrench import JointWrenchSensor, JointWrenchSensorData +from .pva import Pva, PvaData diff --git a/source/isaaclab_newton/isaaclab_newton/sensors/contact_sensor/contact_sensor.py b/source/isaaclab_newton/isaaclab_newton/sensors/contact_sensor/contact_sensor.py index 5517b845438b..02850e9cc903 100644 --- a/source/isaaclab_newton/isaaclab_newton/sensors/contact_sensor/contact_sensor.py +++ b/source/isaaclab_newton/isaaclab_newton/sensors/contact_sensor/contact_sensor.py @@ -20,6 +20,7 @@ import isaaclab.utils.string as string_utils from isaaclab.sensors.contact_sensor.base_contact_sensor import BaseContactSensor +from isaaclab.utils.warp import ProxyArray from isaaclab_newton.physics import NewtonManager @@ -207,7 +208,7 @@ def find_sensors(self, name_keys: str | Sequence[str], preserve_order: bool = Fa ) return string_utils.resolve_matching_names(name_keys, sensor_names, preserve_order) - def compute_first_contact(self, dt: float, abs_tol: float = 1.0e-8) -> wp.array: + def compute_first_contact(self, dt: float, abs_tol: float = 1.0e-8) -> ProxyArray: """Checks if sensors that have established contact within the last :attr:`dt` seconds. This function checks if the sensors have established contact within the last :attr:`dt` seconds @@ -246,9 +247,9 @@ def compute_first_contact(self, dt: float, abs_tol: float = 1.0e-8) -> wp.array: outputs=[self._data._first_transition], device=self._device, ) - return self._data._first_transition + return self._data._first_transition_ta - def compute_first_air(self, dt: float, abs_tol: float = 1.0e-8) -> wp.array: + def compute_first_air(self, dt: float, abs_tol: float = 1.0e-8) -> ProxyArray: """Checks if sensors that have broken contact within the last :attr:`dt` seconds. This function checks if the sensors have broken contact within the last :attr:`dt` seconds @@ -288,7 +289,7 @@ def compute_first_air(self, dt: float, abs_tol: float = 1.0e-8) -> wp.array: outputs=[self._data._first_transition], device=self._device, ) - return self._data._first_transition + return self._data._first_transition_ta """ Implementation. diff --git a/source/isaaclab_newton/isaaclab_newton/sensors/contact_sensor/contact_sensor_data.py b/source/isaaclab_newton/isaaclab_newton/sensors/contact_sensor/contact_sensor_data.py index 7c8250ee808a..8ed00b91eab8 100644 --- a/source/isaaclab_newton/isaaclab_newton/sensors/contact_sensor/contact_sensor_data.py +++ b/source/isaaclab_newton/isaaclab_newton/sensors/contact_sensor/contact_sensor_data.py @@ -11,6 +11,7 @@ import warp as wp from isaaclab.sensors.contact_sensor.base_contact_sensor_data import BaseContactSensorData +from isaaclab.utils.warp import ProxyArray logger = logging.getLogger(__name__) @@ -32,12 +33,12 @@ class ContactSensorData(BaseContactSensorData): _first_transition: wp.array | None @property - def pose_w(self) -> wp.array | None: + def pose_w(self) -> ProxyArray | None: """Not supported by Newton contact sensor.""" raise NotImplementedError("pose_w is not supported by the Newton contact sensor.") @property - def pos_w(self) -> wp.array | None: + def pos_w(self) -> ProxyArray | None: """Position of the sensor origin in world frame. `wp.vec3f` array whose shape is (N,) where N is the number of sensors. Note, that when casted to as a @@ -46,10 +47,14 @@ def pos_w(self) -> wp.array | None: Note: If the :attr:`ContactSensorCfg.track_pose` is False, then this quantity is None. """ - return self._pos_w + if self._pos_w is None: + return None + if self._pos_w_ta is None: + self._pos_w_ta = ProxyArray(self._pos_w) + return self._pos_w_ta @property - def quat_w(self) -> wp.array | None: + def quat_w(self) -> ProxyArray | None: """Orientation of the sensor origin in quaternion (x, y, z, w) in world frame. `wp.quatf` whose shape is (N,) where N is the number of sensors. Note, that when casted to as a `torch.Tensor`, @@ -58,10 +63,14 @@ def quat_w(self) -> wp.array | None: Note: If the :attr:`ContactSensorCfg.track_pose` is False, then this quantity is None. """ - return self._quat_w + if self._quat_w is None: + return None + if self._quat_w_ta is None: + self._quat_w_ta = ProxyArray(self._quat_w) + return self._quat_w_ta @property - def net_forces_w(self) -> wp.array2d | None: + def net_forces_w(self) -> ProxyArray | None: """The net (total) contact forces in world frame. `wp.vec3f` array whose shape is (N, S) where N is the number of environments and S is the number of sensors. @@ -71,10 +80,12 @@ def net_forces_w(self) -> wp.array2d | None: This quantity is the sum of the contact forces acting on each sensor. It must not be confused with the total contact forces acting on the sensors (which also includes the tangential forces). """ - return self._net_forces_w + if self._net_forces_w is None: + return None + return self._net_forces_w_ta @property - def net_forces_w_history(self) -> wp.array3d | None: + def net_forces_w_history(self) -> ProxyArray | None: """The net (total) contact forces in world frame. `wp.vec3f` array whose shape is (N, T, S) where N is the number of environments, T is the configured history @@ -87,10 +98,12 @@ def net_forces_w_history(self) -> wp.array3d | None: This quantity is the sum of the contact forces acting on each sensor. It must not be confused with the total contact forces acting on the sensors (which also includes the tangential forces). """ - return self._net_forces_w_history + if self._net_forces_w_history is None: + return None + return self._net_forces_w_history_ta @property - def force_matrix_w(self) -> wp.array3d | None: + def force_matrix_w(self) -> ProxyArray | None: """The contact forces between sensors and filter objects in world frame. `wp.vec3f` array whose shape is (N, S, F) where N is the number of environments, S is number of sensors @@ -100,10 +113,14 @@ def force_matrix_w(self) -> wp.array3d | None: Note: If the :attr:`ContactSensorCfg.filter_prim_paths_expr` is empty, then this quantity is None. """ - return self._force_matrix_w + if self._force_matrix_w is None: + return None + if self._force_matrix_w_ta is None: + self._force_matrix_w_ta = ProxyArray(self._force_matrix_w) + return self._force_matrix_w_ta @property - def force_matrix_w_history(self) -> wp.array4d | None: + def force_matrix_w_history(self) -> ProxyArray | None: """The contact forces between sensors and filter objects in world frame. `wp.vec3f` array whose shape is (N, T, S, F) where N is the number of environments, T is the configured history @@ -115,20 +132,24 @@ def force_matrix_w_history(self) -> wp.array4d | None: Note: If the :attr:`ContactSensorCfg.filter_prim_paths_expr` is empty, then this quantity is None. """ - return self._force_matrix_w_history + if self._force_matrix_w_history is None: + return None + if self._force_matrix_w_history_ta is None: + self._force_matrix_w_history_ta = ProxyArray(self._force_matrix_w_history) + return self._force_matrix_w_history_ta @property - def contact_pos_w(self) -> wp.array | None: + def contact_pos_w(self) -> ProxyArray | None: """Not supported by Newton contact sensor.""" raise NotImplementedError("contact_pos_w is not supported by the Newton contact sensor.") @property - def friction_forces_w(self) -> wp.array | None: + def friction_forces_w(self) -> ProxyArray | None: """Not supported by Newton contact sensor.""" raise NotImplementedError("friction_forces_w is not supported by the Newton contact sensor.") @property - def last_air_time(self) -> wp.array2d | None: + def last_air_time(self) -> ProxyArray | None: """Time spent (in s) in the air before the last contact. `wp.float32` array whose shape is (N, S) where N is the number of environments and S is the number of sensors. @@ -137,10 +158,12 @@ def last_air_time(self) -> wp.array2d | None: Note: If the :attr:`ContactSensorCfg.track_air_time` is False, then this quantity is None. """ - return self._last_air_time + if self._last_air_time is None: + return None + return self._last_air_time_ta @property - def current_air_time(self) -> wp.array2d | None: + def current_air_time(self) -> ProxyArray | None: """Time spent (in s) in the air since the last detach. `wp.float32` array whose shape is (N, S) where N is the number of environments and S is the number of sensors. @@ -149,10 +172,12 @@ def current_air_time(self) -> wp.array2d | None: Note: If the :attr:`ContactSensorCfg.track_air_time` is False, then this quantity is None. """ - return self._current_air_time + if self._current_air_time is None: + return None + return self._current_air_time_ta @property - def last_contact_time(self) -> wp.array2d | None: + def last_contact_time(self) -> ProxyArray | None: """Time spent (in s) in contact before the last detach. `wp.float32` array whose shape is (N, S) where N is the number of environments and S is the number of sensors. @@ -161,10 +186,12 @@ def last_contact_time(self) -> wp.array2d | None: Note: If the :attr:`ContactSensorCfg.track_air_time` is False, then this quantity is None. """ - return self._last_contact_time + if self._last_contact_time is None: + return None + return self._last_contact_time_ta @property - def current_contact_time(self) -> wp.array2d | None: + def current_contact_time(self) -> ProxyArray | None: """Time spent (in s) in contact since the last contact. `wp.float32` array whose shape is (N, S) where N is the number of environments and S is the number of sensors. @@ -173,7 +200,9 @@ def current_contact_time(self) -> wp.array2d | None: Note: If the :attr:`ContactSensorCfg.track_air_time` is False, then this quantity is None. """ - return self._current_contact_time + if self._current_contact_time is None: + return None + return self._current_contact_time_ta def create_buffers( self, @@ -240,9 +269,31 @@ def create_buffers( self._last_contact_time = wp.zeros((num_envs, num_sensors), dtype=wp.float32, device=device) self._current_contact_time = wp.zeros((num_envs, num_sensors), dtype=wp.float32, device=device) self._first_transition = wp.zeros((num_envs, num_sensors), dtype=wp.float32, device=device) + self._first_transition_ta = ProxyArray(self._first_transition) else: self._last_air_time = None self._current_air_time = None self._last_contact_time = None self._current_contact_time = None self._first_transition = None + self._first_transition_ta = None + + # -- Pin ProxyArray instances for pre-allocated buffers + self._net_forces_w_ta = ProxyArray(self._net_forces_w) + self._net_forces_w_history_ta = ( + ProxyArray(self._net_forces_w_history) if self._net_forces_w_history is not None else None + ) + # -- Lazy ProxyArray instances for nullable buffers (pinned on first access) + self._pos_w_ta: ProxyArray | None = None + self._quat_w_ta: ProxyArray | None = None + self._force_matrix_w_ta: ProxyArray | None = None + self._force_matrix_w_history_ta: ProxyArray | None = None + # -- Pin ProxyArray instances for air/contact time buffers (eagerly when allocated) + self._last_air_time_ta = ProxyArray(self._last_air_time) if self._last_air_time is not None else None + self._current_air_time_ta = ProxyArray(self._current_air_time) if self._current_air_time is not None else None + self._last_contact_time_ta = ( + ProxyArray(self._last_contact_time) if self._last_contact_time is not None else None + ) + self._current_contact_time_ta = ( + ProxyArray(self._current_contact_time) if self._current_contact_time is not None else None + ) diff --git a/source/isaaclab_newton/isaaclab_newton/sensors/frame_transformer/frame_transformer.py b/source/isaaclab_newton/isaaclab_newton/sensors/frame_transformer/frame_transformer.py index 27abc2007d7b..e9150b63174b 100644 --- a/source/isaaclab_newton/isaaclab_newton/sensors/frame_transformer/frame_transformer.py +++ b/source/isaaclab_newton/isaaclab_newton/sensors/frame_transformer/frame_transformer.py @@ -5,158 +5,36 @@ from __future__ import annotations +import logging from typing import TYPE_CHECKING -import torch import warp as wp -import isaaclab.sim as sim_utils from isaaclab.sensors.frame_transformer.base_frame_transformer import BaseFrameTransformer -from isaaclab.utils.math import normalize, quat_from_angle_axis from isaaclab_newton.physics import NewtonManager from .frame_transformer_data import FrameTransformerData +from .frame_transformer_kernels import compose_target_world_kernel, copy_from_newton_kernel if TYPE_CHECKING: from isaaclab.sensors.frame_transformer.frame_transformer_cfg import FrameTransformerCfg -""" -Warp kernels -""" - - -@wp.kernel -def set_env_mask(env_mask: wp.array(dtype=bool), env_ids: wp.array(dtype=wp.int32)): - """Create an environment mask from the environment ids. - - Args: - env_mask: The environment mask (num_envs,). (modified) - env_ids: The environment ids. - """ - idx = wp.tid() - env_mask[env_ids[idx]] = True - - -@wp.func -def split_transform_to_quat4lab(transform: wp.transformf) -> wp.vec4f: - """Split a frame transform into a quaternion in wxyz order. - - Args: - transform: The frame transform in xyzw order. - - Returns: - The quaternion in wxyz order. - """ - quat = wp.transform_get_rotation(transform) - return wp.vec4f(quat[3], quat[0], quat[1], quat[2]) - - -@wp.kernel -def update_source_transform( - offset: wp.transformf, - source_index: int, - source_transforms: wp.array2d(dtype=wp.transformf), - output_transforms: wp.array(dtype=wp.transformf), - output_pos: wp.array(dtype=wp.vec3f), - output_quat: wp.array(dtype=wp.vec4f), - env_mask: wp.array(dtype=bool), -): - """Update the source transform. - - This kernel applies the offset to the source frame transform and outputs the results - in the output transforms, positions, and quaternions. - - Args: - offset: The offset of the source frame. - source_index: The index of the source frame. - source_transforms: The source frame transforms. - output_transforms: The output transforms (modified). - output_pos: The output positions (modified). - output_quat: The output quaternions (modified). - env_mask: The environment mask. - """ - idx = wp.tid() - if env_mask[idx]: - output_transforms[idx] = source_transforms[idx, source_index] * offset - output_pos[idx] = wp.transform_get_translation(output_transforms[idx]) - output_quat[idx] = split_transform_to_quat4lab(output_transforms[idx]) - - -@wp.kernel -def update_frame_transforms( - frame_offsets: wp.array(dtype=wp.transformf), - origin_transforms: wp.array(dtype=wp.transformf), - frames_transforms_world: wp.array2d(dtype=wp.transformf), - frames_transforms_origin: wp.array2d(dtype=wp.transformf), - frames_pos_world: wp.array2d(dtype=wp.vec3f), - frames_quat_world: wp.array2d(dtype=wp.vec4f), - frames_pos_origin: wp.array2d(dtype=wp.vec3f), - frames_quat_origin: wp.array2d(dtype=wp.vec4f), - frame_to_view_ids: wp.array(dtype=wp.int32), - body_to_view_ids: wp.array(dtype=wp.int32), - env_mask: wp.array(dtype=bool), -): - """Update the frame transforms. - - This kernel updates the frame transforms in the origin frame and the world frame. - - Args: - frame_offsets: The offsets of the frames. - origin_transforms: The origin transforms. - frames_transforms_world: The frame transforms in world frame. - frames_transforms_origin: The frame transforms in origin frame (modified). - frames_pos_world: The frame positions in world frame (modified). - frames_quat_world: The frame quaternions in world frame (modified). - frames_pos_origin: The frame positions in origin frame (modified). - frames_quat_origin: The frame quaternions in origin frame (modified). - frame_to_view_ids: The mapping from frame to view ids. - body_to_view_ids: The mapping from body to view ids. - env_mask: The environment mask. - """ - env_idx, frame_idx = wp.tid() - - if env_mask[env_idx]: - frames_transforms_origin[env_idx][frame_to_view_ids[frame_idx]] = ( - frames_transforms_world[env_idx][body_to_view_ids[frame_idx]] * frame_offsets[frame_to_view_ids[frame_idx]] - ) - frames_pos_world[env_idx][frame_to_view_ids[frame_idx]] = wp.transform_get_translation( - frames_transforms_origin[env_idx][frame_to_view_ids[frame_idx]] - ) - frames_quat_world[env_idx][frame_to_view_ids[frame_idx]] = split_transform_to_quat4lab( - frames_transforms_origin[env_idx][frame_to_view_ids[frame_idx]] - ) - frames_transforms_origin[env_idx][frame_to_view_ids[frame_idx]] = ( - wp.transform_inverse(origin_transforms[env_idx]) - * frames_transforms_origin[env_idx][frame_to_view_ids[frame_idx]] - ) - frames_pos_origin[env_idx][frame_to_view_ids[frame_idx]] = wp.transform_get_translation( - frames_transforms_origin[env_idx][frame_to_view_ids[frame_idx]] - ) - frames_quat_origin[env_idx][frame_to_view_ids[frame_idx]] = split_transform_to_quat4lab( - frames_transforms_origin[env_idx][frame_to_view_ids[frame_idx]] - ) - - -""" -FrameTransformer class -""" +logger = logging.getLogger(__name__) class FrameTransformer(BaseFrameTransformer): - """A sensor for reporting frame transforms using the Newton physics backend. + """Newton frame transformer wrapping :class:`newton.sensors.SensorFrameTransform`. - This class provides an interface for reporting the transform of one or more frames (target frames) - with respect to another frame (source frame). The source frame is specified by the user as a prim path - (:attr:`FrameTransformerCfg.prim_path`) and the target frames are specified by the user as a list of - prim paths (:attr:`FrameTransformerCfg.target_frames`). + Creates per-env sites for the source and all target frames, backed by a single + :class:`SensorFrameTransform` with 1:1 shape/reference pairs: - The source frame and target frames are assumed to be rigid bodies. The transform of the target frames - with respect to the source frame is computed by first extracting the transform of the source frame - and target frames from the Newton physics engine and then computing the relative transform between the two. + * Entry 0 per env — source site measured w.r.t. a world-origin site. + * Entries 1..M per env — target sites measured w.r.t. source site. - Additionally, the user can specify an offset for the source frame and each target frame. This is useful - for specifying the transform of the desired frame with respect to the body's center of mass, for instance. + Flat sensor output is indexed with stride ``1 + num_targets``: + ``[i * stride]`` is the source world transform, ``[i * stride + 1 + j]`` + is target *j* relative to source in env *i*. """ cfg: FrameTransformerCfg @@ -166,27 +44,54 @@ class FrameTransformer(BaseFrameTransformer): """The name of the backend for the frame transformer sensor.""" def __init__(self, cfg: FrameTransformerCfg): - """Initializes the frame transformer object. + """Initializes the frame transformer. + + Registers site requests via :meth:`NewtonManager.cl_register_site` for + the source frame, each target frame, and a shared world-origin reference. + Sites are injected into prototype builders by ``newton_replicate`` before + replication, so they end up correctly in each world. Args: - cfg: The configuration parameters. + cfg: Configuration parameters. """ - # initialize base class + # initialize base class (registers PHYSICS_READY callback for _initialize_impl) super().__init__(cfg) - # Create empty data container + self._data: FrameTransformerData = FrameTransformerData() - # Internal warp buffers (allocated in _initialize_impl) - self._warp_source_transforms_w = None - self._warp_target_transform_source = None - - def __str__(self) -> str: - """Returns: A string containing information about the instance.""" - return ( - f"FrameTransformer @ '{self.cfg.prim_path}': \n" - f"\ttracked body frames: {[self._source_frame_body_name] + self._target_frame_body_names} \n" - f"\tnumber of envs: {self._num_envs}\n" - f"\tsource body frame: {self._source_frame_body_name}\n" - f"\ttarget frames (count: {len(self._target_frame_names)}): {self._target_frame_names}\n" + self._newton_transforms = None + self._stride: int = 0 + + self._sensor_index: int | None = None + self._source_frame_body_name: str = cfg.prim_path.rsplit("/", 1)[-1] + + # Register world-origin reference site + self._world_origin_label = NewtonManager.cl_register_site(None, wp.transform()) + + # Register source site + source_offset = wp.transform(cfg.source_frame_offset.pos, cfg.source_frame_offset.rot) + self._source_label = NewtonManager.cl_register_site(cfg.prim_path, source_offset) + + # Register target sites + self._target_labels: list[str] = [] + self._target_frame_body_names: list[str] = [] + self._num_targets: int = 0 + + for target_frame in cfg.target_frames: + target_offset = wp.transform(target_frame.offset.pos, target_frame.offset.rot) + label = NewtonManager.cl_register_site(target_frame.prim_path, target_offset) + + self._target_labels.append(label) + body_name = target_frame.prim_path.rsplit("/", 1)[-1] + self._target_frame_body_names.append(target_frame.name or body_name) + self._num_targets += 1 + + # Set target frame names for base class find_bodies() and data container + self._target_frame_names = [t.name or t.prim_path.rsplit("/", 1)[-1] for t in cfg.target_frames] + self._data._target_frame_names = self._target_frame_names + + logger.info( + f"FrameTransformer '{cfg.prim_path}': source='{self._source_frame_body_name}', " + f"{self._num_targets} target(s) registered" ) """ @@ -197,7 +102,6 @@ def __str__(self) -> str: def data(self) -> FrameTransformerData: # update sensors if needed self._update_outdated_buffers() - # return the data return self._data @property @@ -211,231 +115,240 @@ def body_names(self) -> list[str]: return self._target_frame_body_names """ - Implementation. + Implementation """ def _initialize_impl(self): + """PHYSICS_READY callback: resolves site indices and creates the SensorFrameTransform.""" super()._initialize_impl() - # Collect all target frames, their associated body prim paths and their offsets - frames = [target_frame.name for target_frame in self.cfg.target_frames] - frame_prim_paths = [target_frame.prim_path for target_frame in self.cfg.target_frames] - # First element is None because source frame offset is handled separately - frame_offsets = [target_frame.offset for target_frame in self.cfg.target_frames] - - # Loop through all the views attached to the Newton manager to find the source frame body - # and set view id and the id of the body within that view. - source_frame_prim_path = self.cfg.prim_path - frame_found = False - body_name = source_frame_prim_path.rsplit("/", 1)[-1] - for view_id, view in enumerate(NewtonManager.get_physics_sim_view()): - for body_id, view_body_name in enumerate(view.link_names): - if body_name == view_body_name: - self._warp_source_body_id = body_id - self._warp_source_view_id = view_id - # Convert the offset to a wp.transformf - self._warp_source_offset = wp.transformf( - self.cfg.source_frame_offset.pos[0], - self.cfg.source_frame_offset.pos[1], - self.cfg.source_frame_offset.pos[2], - self.cfg.source_frame_offset.rot[1], - self.cfg.source_frame_offset.rot[2], - self.cfg.source_frame_offset.rot[3], - self.cfg.source_frame_offset.rot[0], - ) - frame_found = True - break - if frame_found: - break - # Raise an error if the source frame body is not found - if not frame_found: - raise ValueError(f"Source frame '{body_name}' not found.") - self._source_frame_body_name = body_name - print("[INFO]: Initializing FrameTransformer!") - print(f"[INFO]: Using source body: {body_name} as reference frame.") - print(f"[INFO]: + Body found in view id: {self._warp_source_view_id}.") - print(f"[INFO]: + Body id in view {self._warp_source_view_id}: {self._warp_source_body_id}.") - - # Go through all the target frames and find the bodies matching the regex - matching_prims = [] - offsets = [] - self._target_frame_names = [] - for prim_path, offset, frame_name in zip(frame_prim_paths, frame_offsets, frames): - # Find the matching prims - prims = sim_utils.find_matching_prims(prim_path) - # Duplicate the target frame names if more than one prim is found - self._target_frame_names.extend([frame_name] * len(prims)) - # Add to the list all the matching prims - matching_prims.extend(prims) - # Duplicate the offsets if more than one prim is found - offsets.extend([offset] * len(prims)) - # Convert the matching prims to a list of prim paths - matching_prims = [prim.GetPath().pathString for prim in matching_prims] - - # Set the number of bodies/frames found in the scene - self._num_frames = len(matching_prims) - # Create a buffer to store the pose of the target frames - pose = torch.zeros((self._num_frames, 7), dtype=torch.float32, device=self._device) - # Set the default to identity transform - pose[:, -1] = 1.0 - - # Create a dictionary to store the body id, frame id and body name for each view - self._warp_view_body_id = {} - self._warp_view_frame_id = {} - self._warp_view_body_name = {} - self._target_frame_body_names = [] - - # Loop through all the matching prims and offsets to find the bodies in the scene - for frame_id, (prim_path, offset) in enumerate(zip(matching_prims, offsets)): - frame_found = False - # Go through all the views to find the requested bodies - body_name = prim_path.rsplit("/", 1)[-1] - for view_id, view in enumerate(NewtonManager.get_physics_sim_view()): - # Get the body names from the view - view_body_names = view.link_names - for body_id, view_body_name in enumerate(view_body_names): - if body_name == view_body_name: - frame_found = True - if view_id not in self._warp_view_body_id.keys(): - self._warp_view_body_id[view_id] = [body_id] - self._warp_view_frame_id[view_id] = [frame_id] - self._warp_view_body_name[view_id] = [body_name] - else: - self._warp_view_body_id[view_id].append(body_id) - self._warp_view_frame_id[view_id].append(frame_id) - self._warp_view_body_name[view_id].append(body_name) - self._target_frame_body_names.append(body_name) - break - if frame_found: - break - # If the offset is not None, then set the pose of the target frame - if offset is not None: - pose[frame_id, :3] = torch.tensor(offset.pos, device=self._device) - # Warp wants quaternions in xyzw order - pose[frame_id, 3] = offset.rot[1] - pose[frame_id, 4] = offset.rot[2] - pose[frame_id, 5] = offset.rot[3] - pose[frame_id, 6] = offset.rot[0] - # Raise an error if the frame is not found - if not frame_found: - raise ValueError(f"Frame '{body_name}' not found.") - # Set the target frame names - self._data.create_buffers(self._num_envs, self._num_frames, self._target_frame_names, self._device) - print(f"[INFO]: Found {self._num_frames} target frames.") - for key in self._warp_view_body_name: - print(f"[INFO]: + Found {len(self._warp_view_body_name[key])} bodies in view {key}.") - for body_name, body_id, frame_id in zip( - self._warp_view_body_name[key], self._warp_view_body_id[key], self._warp_view_frame_id[key] - ): - print(f"[INFO]: + Found {body_name} in view {key} with body id {body_id} and frame id {frame_id}.") - print("[INFO]: FrameTransformer initialized!") - # Convert the pose to a wp.array - self._warp_offset_buffer = wp.from_torch(pose, dtype=wp.transformf) - - for key in self._warp_view_body_id.keys(): - self._warp_view_body_id[key] = wp.array(self._warp_view_body_id[key], dtype=wp.int32) - for key in self._warp_view_frame_id.keys(): - self._warp_view_frame_id[key] = wp.array(self._warp_view_frame_id[key], dtype=wp.int32) - - # Allocate intermediate buffers (not exposed through data class) - self._warp_source_transforms_w = wp.zeros((self._num_envs,), dtype=wp.transformf, device=self._device) - self._warp_target_transform_source = wp.zeros( - (self._num_envs, self._num_frames), dtype=wp.transformf, device=self._device + num_envs = self._num_envs + site_map = NewtonManager._cl_site_index_map + + # Resolve and validate per-env site indices + assert self._world_origin_label in site_map + world_origin_idx, _ = site_map[self._world_origin_label] + source_indices, target_per_world = self._validate_site_map( + self._source_label, + self.cfg.prim_path, + self._target_labels, + [t.prim_path for t in self.cfg.target_frames], + site_map, + num_envs, + ) + + # Expand targets and build sensor index lists + expanded_names, target_indices_per_target, shapes_list, references_list = self._build_sensor_index_lists( + source_indices, + target_per_world, + self._target_frame_body_names, + NewtonManager._builder.shape_label, + world_origin_idx, + num_envs, + ) + + # Update instance state with expanded values + self._num_targets = len(target_indices_per_target) + self._target_frame_names = expanded_names + self._target_frame_body_names = expanded_names + self._data._target_frame_names = expanded_names + + # Create SensorFrameTransform via NewtonManager + self._sensor_index = NewtonManager.add_frame_transform_sensor(shapes_list, references_list) + + # Store reference to Newton sensor's flat transforms array + sensor = NewtonManager._newton_frame_transform_sensors[self._sensor_index] + self._newton_transforms = sensor.transforms + self._stride = 1 + self._num_targets + + # Allocate owned buffers + self._data._create_buffers(num_envs, self._num_targets, self._device) + + logger.info( + f"FrameTransformer initialized: {num_envs} envs, " + f"{self._num_targets} targets, sensor_index={self._sensor_index}" ) - # Bind Newton views - self._warp_views = {} - for key in self._warp_view_body_id: - view = NewtonManager.get_physics_sim_view()[key].get_link_transforms(NewtonManager.get_state_0())[:, 0] - if len(view.shape) == 1: - view = view.reshape((-1, 1)) - self._warp_views[key] = view + @staticmethod + def _validate_site_map( + source_label: str, + source_prim_path: str, + target_labels: list[str], + target_prim_paths: list[str], + site_map: dict, + num_envs: int, + ) -> tuple[list[int], list[list[list[int]]]]: + """Validate per-env site counts and return resolved index arrays. + + Args: + source_label: Site label for the source frame. + source_prim_path: Config prim path used in error messages. + target_labels: Site labels for each target frame (in order). + target_prim_paths: Config prim paths used in error messages. + site_map: ``NewtonManager._cl_site_index_map``. + num_envs: Expected number of environments. + + Returns: + ``(source_indices, target_per_world)`` where ``source_indices[e]`` is the + single source site index for env ``e``, and ``target_per_world[t][e]`` is + the list of site indices for target ``t`` in env ``e``. + + Raises: + ValueError: If the source has the wrong world count, or any env has a + count other than 1. If any target has zero matches, non-uniform + counts across envs, or a world-count mismatch. + """ + assert source_label in site_map, ( + f"FrameTransformer source '{source_prim_path}' (site label '{source_label}') " + "not found in NewtonManager._cl_site_index_map." + ) + _, source_per_world = site_map[source_label] + if len(source_per_world) != num_envs: + raise ValueError( + f"FrameTransformer source '{source_prim_path}' has {len(source_per_world)} " + f"world entries in the site map, expected {num_envs}." + ) + for env_idx, world_sites in enumerate(source_per_world): + if len(world_sites) != 1: + raise ValueError( + f"FrameTransformer source pattern '{source_prim_path}' matched " + f"{len(world_sites)} bodies in env {env_idx}, expected exactly 1. " + f"Source patterns must resolve to a single rigid body per environment." + ) + source_indices: list[int] = [w[0] for w in source_per_world] + + target_per_world: list[list[list[int]]] = [] + for tgt_idx, label in enumerate(target_labels): + assert label in site_map, ( + f"FrameTransformer target '{target_prim_paths[tgt_idx]}' (site label '{label}') " + "not found in NewtonManager._cl_site_index_map." + ) + _, per_world = site_map[label] + if len(per_world) != num_envs: + raise ValueError( + f"FrameTransformer target '{target_prim_paths[tgt_idx]}' has " + f"{len(per_world)} world entries, expected {num_envs}." + ) + lengths = [len(w) for w in per_world] + if len(set(lengths)) != 1: + raise ValueError( + f"FrameTransformer target pattern '{target_prim_paths[tgt_idx]}' matched " + f"different numbers of bodies across envs: {lengths}. " + f"All environments must have the same number of matches." + ) + if lengths[0] == 0: + raise ValueError( + f"FrameTransformer target pattern '{target_prim_paths[tgt_idx]}' " + f"matched no bodies in any environment." + ) + target_per_world.append(per_world) + + return source_indices, target_per_world + + @staticmethod + def _build_sensor_index_lists( + source_indices: list[int], + target_per_world: list[list[list[int]]], + target_frame_body_names: list[str], + shape_labels: list[str], + world_origin_idx: int, + num_envs: int, + ) -> tuple[list[str], list[list[int]], list[int], list[int]]: + """Expand per-world target sublists and build sensor index lists. + + Args: + source_indices: Per-env source site indices, length ``num_envs``. + target_per_world: Per-target-config, per-world, per-body site indices. + Shape: ``[num_target_cfgs][num_envs][n_bodies_per_env]``. + target_frame_body_names: Config-level name for each target config entry. + shape_labels: ``builder.shape_label`` — maps shape index to its label string. + Site labels have the form ``"{body_name}/{site_label}"``; the body name + is extracted for wildcard expansion. + world_origin_idx: Global world-origin site index. + num_envs: Number of environments. + + Returns: + ``(expanded_names, target_indices_per_target, shapes_list, references_list)`` + where ``expanded_names[k]`` is the resolved name for expanded target ``k``, + ``target_indices_per_target[k][e]`` is the site index for expanded target ``k`` + in env ``e``, ``shapes_list`` and ``references_list`` are 1:1 sensor inputs. + """ + target_indices_per_target: list[list[int]] = [] + expanded_names: list[str] = [] + + for tgt_idx, per_world in enumerate(target_per_world): + n_bodies = len(per_world[0]) # uniform across envs (validated) + for k in range(n_bodies): + per_env = [per_world[env_idx][k] for env_idx in range(num_envs)] + target_indices_per_target.append(per_env) + # For wildcards (n_bodies > 1), derive the bare body name from the + # site label ("{body_path}/{site_label}") using env 0. + if n_bodies > 1: + site_idx = per_world[0][k] + expanded_names.append(shape_labels[site_idx].rsplit("/", 2)[-2]) + else: + expanded_names.append(target_frame_body_names[tgt_idx]) + + num_targets = len(target_indices_per_target) + shapes_list: list[int] = [] + references_list: list[int] = [] + + for env_idx in range(num_envs): + source_idx = source_indices[env_idx] + shapes_list.append(source_idx) + references_list.append(world_origin_idx) + for tgt_idx in range(num_targets): + target_idx = target_indices_per_target[tgt_idx][env_idx] + shapes_list.append(target_idx) + references_list.append(source_idx) + + return expanded_names, target_indices_per_target, shapes_list, references_list def _update_buffers_impl(self, env_mask: wp.array): - """Fills the buffers of the sensor data.""" - # Update the source frame transform + """Copies transforms from Newton sensor into owned buffers.""" + if self._newton_transforms is None: + raise RuntimeError(f"FrameTransformer '{self.cfg.prim_path}': sensor is not initialized") wp.launch( - update_source_transform, - dim=self._num_envs, - inputs=[ - self._warp_source_offset, - self._warp_source_body_id, - self._warp_views[self._warp_source_view_id], - self._warp_source_transforms_w, - self._data._source_pos_w, - self._data._source_quat_w, - env_mask, - ], + copy_from_newton_kernel, + dim=(self._num_envs, 1 + self._num_targets), + inputs=[env_mask, self._newton_transforms, self._stride], + outputs=[self._data._source_transforms, self._data._target_transforms], + device=self._device, ) - # Update the frame transforms in the origin frame and the world frame - for view_id in self._warp_view_body_id.keys(): + + # Compose target world transforms: source_world * target_relative + if self._num_targets > 0: wp.launch( - update_frame_transforms, - dim=(self._num_envs, self._warp_view_frame_id[view_id].shape[0]), - inputs=[ - self._warp_offset_buffer, - self._warp_source_transforms_w, - self._warp_views[view_id], - self._warp_target_transform_source, - self._data._target_pos_w, - self._data._target_quat_w, - self._data._target_pos_source, - self._data._target_quat_source, - self._warp_view_frame_id[view_id], - self._warp_view_body_id[view_id], - env_mask, - ], + compose_target_world_kernel, + dim=(self._num_envs, self._num_targets), + inputs=[env_mask, self._data._source_transforms, self._data._target_transforms], + outputs=[self._data._target_transforms_w], + device=self._device, ) - def _invalidate_initialize_callback(self, event): - """Invalidates the scene elements.""" - super()._invalidate_initialize_callback(event) - self._warp_views = None - """ - Internal helpers. + Internal simulation callbacks. """ - def _get_connecting_lines( - self, start_pos: torch.Tensor, end_pos: torch.Tensor - ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: - """Given start and end points, compute positions, orientations, and lengths of connecting lines. - - Args: - start_pos: The start positions of the connecting lines. Shape is (N, 3). - end_pos: The end positions of the connecting lines. Shape is (N, 3). + def _invalidate_initialize_callback(self, event): + """Clears references to the native sensor and re-registers sites. - Returns: - positions: The position of each connecting line. Shape is (N, 3). - orientations: The orientation of each connecting line in quaternion. Shape is (N, 4). - lengths: The length of each connecting line. Shape is (N,). + ``NewtonManager.close()`` calls ``clear()`` before dispatching ``STOP``, + so ``_cl_pending_sites`` is already empty when this callback fires. + Re-registering here ensures sites survive a close/reinit cycle. """ - direction = end_pos - start_pos - lengths = torch.norm(direction, dim=-1) - positions = (start_pos + end_pos) / 2 - - # Get default direction (along z-axis) - default_direction = torch.tensor([0.0, 0.0, 1.0], device=self.device).expand(start_pos.size(0), -1) - - # Normalize direction vector - direction_norm = normalize(direction) - - # Calculate rotation from default direction to target direction - rotation_axis = torch.linalg.cross(default_direction, direction_norm) - rotation_axis_norm = torch.norm(rotation_axis, dim=-1) - - # Handle case where vectors are parallel - mask = rotation_axis_norm > 1e-6 - rotation_axis = torch.where( - mask.unsqueeze(-1), - normalize(rotation_axis), - torch.tensor([1.0, 0.0, 0.0], device=self.device).expand(start_pos.size(0), -1), - ) + super()._invalidate_initialize_callback(event) + self._newton_transforms = None + self._sensor_index = None + + # Re-register sites so a subsequent start_simulation picks them up. + self._world_origin_label = NewtonManager.cl_register_site(None, wp.transform()) - # Calculate rotation angle - cos_angle = torch.sum(default_direction * direction_norm, dim=-1) - cos_angle = torch.clamp(cos_angle, -1.0, 1.0) - angle = torch.acos(cos_angle) - orientations = quat_from_angle_axis(angle, rotation_axis) + source_offset = wp.transform(self.cfg.source_frame_offset.pos, self.cfg.source_frame_offset.rot) + self._source_label = NewtonManager.cl_register_site(self.cfg.prim_path, source_offset) - return positions, orientations, lengths + self._target_labels = [] + for target_frame in self.cfg.target_frames: + target_offset = wp.transform(target_frame.offset.pos, target_frame.offset.rot) + label = NewtonManager.cl_register_site(target_frame.prim_path, target_offset) + self._target_labels.append(label) diff --git a/source/isaaclab_newton/isaaclab_newton/sensors/frame_transformer/frame_transformer_data.py b/source/isaaclab_newton/isaaclab_newton/sensors/frame_transformer/frame_transformer_data.py index 4abfa2451d02..2b5f4f48006b 100644 --- a/source/isaaclab_newton/isaaclab_newton/sensors/frame_transformer/frame_transformer_data.py +++ b/source/isaaclab_newton/isaaclab_newton/sensors/frame_transformer/frame_transformer_data.py @@ -7,114 +7,90 @@ import warp as wp -from isaaclab.sensors.frame_transformer import BaseFrameTransformerData +from isaaclab.sensors.frame_transformer.base_frame_transformer_data import BaseFrameTransformerData +from isaaclab.utils.warp import ProxyArray +from isaaclab.utils.warp.math_ops import transform_to_vec_quat class FrameTransformerData(BaseFrameTransformerData): """Data container for the Newton frame transformer sensor. - The quaternion fields store components in (w, x, y, z) order as :class:`wp.vec4f` arrays. + Transform buffers are populated from the Newton sensor via + :func:`copy_from_newton_kernel`. """ - @property - def target_frame_names(self) -> list[str]: - """Target frame names (order matches data ordering).""" - return self._target_frame_names + _source_transforms: wp.array | None + """Source world transforms — ``(num_envs,)`` array of ``wp.transformf``.""" - @property - def target_pose_source(self) -> wp.array | None: - """Pose of target frame(s) relative to source frame. + _target_transforms: wp.array | None + """Target-relative transforms — ``(num_envs, num_targets)`` array of ``wp.transformf``.""" - Not computed for the Newton backend. Returns ``None``. - """ - return None + _target_transforms_w: wp.array | None + """Target world transforms — ``(num_envs, num_targets)`` array of ``wp.transformf``.""" - @property - def target_pos_source(self) -> wp.array: - """Position of target frame(s) relative to source frame. - - Shape is (num_instances, num_target_frames), dtype = :class:`wp.vec3f`. - """ - return self._target_pos_source + def __init__(self): + self._target_frame_names: list[str] | None = None + self._source_transforms = None + self._target_transforms = None + self._target_transforms_w = None - @property - def target_quat_source(self) -> wp.array: - """Orientation of target frame(s) relative to source frame. + def _create_buffers(self, num_envs: int, num_targets: int, device: str): + """Allocates transform buffers and zero-copy views.""" + self._source_transforms = wp.zeros(num_envs, dtype=wp.transformf, device=device) + self._target_transforms = wp.zeros((num_envs, num_targets), dtype=wp.transformf, device=device) + self._target_transforms_w = wp.zeros((num_envs, num_targets), dtype=wp.transformf, device=device) - Shape is (num_instances, num_target_frames), dtype = :class:`wp.vec4f` in (w, x, y, z) order. - """ - return self._target_quat_source + # Zero-copy views — auto-reflect kernel writes to underlying transforms + self._source_pos_w, self._source_quat_w = transform_to_vec_quat(self._source_transforms) + self._target_pos_source, self._target_quat_source = transform_to_vec_quat(self._target_transforms) + self._target_pos_w, self._target_quat_w = transform_to_vec_quat(self._target_transforms_w) @property - def target_pose_w(self) -> wp.array | None: - """Pose of target frame(s) after offset in world frame. - - Not computed for the Newton backend. Returns ``None``. - """ - return None + def target_frame_names(self) -> list[str]: + """Names of the target frames.""" + return self._target_frame_names @property - def target_pos_w(self) -> wp.array: - """Position of target frame(s) after offset in world frame. + def target_pose_source(self) -> ProxyArray: + """Target poses relative to source frame, shape ``(num_envs, num_targets)``, dtype ``wp.transformf``.""" + return ProxyArray(self._target_transforms) - Shape is (num_instances, num_target_frames), dtype = :class:`wp.vec3f`. - """ - return self._target_pos_w + @property + def target_pos_source(self) -> ProxyArray: + """Position of target frames relative to source frame [m], shape ``(num_envs, num_targets, 3)``.""" + return ProxyArray(self._target_pos_source) @property - def target_quat_w(self) -> wp.array: - """Orientation of target frame(s) after offset in world frame. + def target_quat_source(self) -> ProxyArray: + """Orientation of target frames relative to source frame (xyzw), shape ``(num_envs, num_targets, 4)``.""" + return ProxyArray(self._target_quat_source) - Shape is (num_instances, num_target_frames), dtype = :class:`wp.vec4f` in (w, x, y, z) order. - """ - return self._target_quat_w + @property + def target_pose_w(self) -> ProxyArray: + """Target poses in world frame, shape ``(num_envs, num_targets)``, dtype ``wp.transformf``.""" + return ProxyArray(self._target_transforms_w) @property - def source_pose_w(self) -> wp.array | None: - """Pose of source frame after offset in world frame. + def target_pos_w(self) -> ProxyArray: + """Position of target frames in world frame [m], shape ``(num_envs, num_targets, 3)``.""" + return ProxyArray(self._target_pos_w) - Not computed for the Newton backend. Returns ``None``. - """ - return None + @property + def target_quat_w(self) -> ProxyArray: + """Orientation of target frames in world frame (xyzw), shape ``(num_envs, num_targets, 4)``.""" + return ProxyArray(self._target_quat_w) @property - def source_pos_w(self) -> wp.array: - """Position of source frame after offset in world frame. + def source_pose_w(self) -> ProxyArray: + """Source pose in world frame, shape ``(num_envs,)``, dtype ``wp.transformf``.""" + return ProxyArray(self._source_transforms) - Shape is (num_instances,), dtype = :class:`wp.vec3f`. - """ - return self._source_pos_w + @property + def source_pos_w(self) -> ProxyArray: + """Position of source frame in world frame [m], shape ``(num_envs, 3)``.""" + return ProxyArray(self._source_pos_w) @property - def source_quat_w(self) -> wp.array: - """Orientation of source frame after offset in world frame. - - Shape is (num_instances,), dtype = :class:`wp.vec4f` in (w, x, y, z) order. - """ - return self._source_quat_w - - def create_buffers( - self, - num_envs: int, - num_target_frames: int, - target_frame_names: list[str], - device: str, - ) -> None: - """Allocate internal warp buffers. - - Args: - num_envs: Number of parallel environments. - num_target_frames: Number of tracked target frames. - target_frame_names: Ordered list of target frame names. - device: Warp device string (e.g. ``"cuda:0"``). - """ - self._num_envs = num_envs - self._device = device - self._num_target_frames = num_target_frames - self._target_frame_names = target_frame_names - self._source_pos_w = wp.zeros(num_envs, dtype=wp.vec3f, device=device) - self._source_quat_w = wp.zeros(num_envs, dtype=wp.vec4f, device=device) - self._target_pos_w = wp.zeros((num_envs, num_target_frames), dtype=wp.vec3f, device=device) - self._target_quat_w = wp.zeros((num_envs, num_target_frames), dtype=wp.vec4f, device=device) - self._target_pos_source = wp.zeros((num_envs, num_target_frames), dtype=wp.vec3f, device=device) - self._target_quat_source = wp.zeros((num_envs, num_target_frames), dtype=wp.vec4f, device=device) + def source_quat_w(self) -> ProxyArray: + """Orientation of source frame in world frame (xyzw), shape ``(num_envs, 4)``.""" + return ProxyArray(self._source_quat_w) diff --git a/source/isaaclab_newton/isaaclab_newton/sensors/frame_transformer/frame_transformer_kernels.py b/source/isaaclab_newton/isaaclab_newton/sensors/frame_transformer/frame_transformer_kernels.py new file mode 100644 index 000000000000..26004b8a1d7c --- /dev/null +++ b/source/isaaclab_newton/isaaclab_newton/sensors/frame_transformer/frame_transformer_kernels.py @@ -0,0 +1,60 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +# Ignore optional memory usage warning globally +# pyright: reportOptionalSubscript=false + +import warp as wp + + +@wp.kernel +def copy_from_newton_kernel( + # in + env_mask: wp.array(dtype=wp.bool), + newton_transforms: wp.array(dtype=wp.transformf), # flat (num_envs * stride,) + stride: int, + # outputs + source_transforms: wp.array(dtype=wp.transformf), # (num_envs,) + target_transforms: wp.array2d(dtype=wp.transformf), # (num_envs, num_targets) +): + """Copy frame transform data from Newton sensor into owned buffers. + + Deinterleaves the flat strided Newton output into separate source and target buffers. + Launch with dim=(num_envs, 1 + num_targets). + """ + env, idx = wp.tid() + + if env_mask: + if not env_mask[env]: + return + + t = newton_transforms[env * stride + idx] + + if idx == 0: + source_transforms[env] = t + else: + target_transforms[env, idx - 1] = t + + +@wp.kernel +def compose_target_world_kernel( + # in + env_mask: wp.array(dtype=wp.bool), + source_transforms: wp.array(dtype=wp.transformf), # (num_envs,) + target_transforms: wp.array2d(dtype=wp.transformf), # (num_envs, num_targets) + # outputs + target_transforms_w: wp.array2d(dtype=wp.transformf), # (num_envs, num_targets) +): + """Compute target world transforms: source_world * target_relative. + + Launch with dim=(num_envs, num_targets). + """ + env, tgt = wp.tid() + + if env_mask: + if not env_mask[env]: + return + + target_transforms_w[env, tgt] = source_transforms[env] * target_transforms[env, tgt] diff --git a/source/isaaclab_newton/isaaclab_newton/sensors/imu/__init__.py b/source/isaaclab_newton/isaaclab_newton/sensors/imu/__init__.py new file mode 100644 index 000000000000..4d0042be743c --- /dev/null +++ b/source/isaaclab_newton/isaaclab_newton/sensors/imu/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Sub-module for the Newton IMU sensor.""" + +from isaaclab.utils.module import lazy_export + +lazy_export() diff --git a/source/isaaclab_newton/isaaclab_newton/sensors/imu/__init__.pyi b/source/isaaclab_newton/isaaclab_newton/sensors/imu/__init__.pyi new file mode 100644 index 000000000000..b5d6077112f3 --- /dev/null +++ b/source/isaaclab_newton/isaaclab_newton/sensors/imu/__init__.pyi @@ -0,0 +1,9 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +__all__ = ["Imu", "ImuData"] + +from .imu import Imu +from .imu_data import ImuData diff --git a/source/isaaclab_newton/isaaclab_newton/sensors/imu/imu.py b/source/isaaclab_newton/isaaclab_newton/sensors/imu/imu.py new file mode 100644 index 000000000000..1c25f4550932 --- /dev/null +++ b/source/isaaclab_newton/isaaclab_newton/sensors/imu/imu.py @@ -0,0 +1,187 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from __future__ import annotations + +import logging +from collections.abc import Sequence +from typing import TYPE_CHECKING + +import warp as wp + +from isaaclab.sensors.imu import BaseImu + +from isaaclab_newton.physics import NewtonManager + +from .imu_data import ImuData +from .kernels import imu_copy_kernel, imu_reset_kernel + +if TYPE_CHECKING: + from newton.sensors import SensorIMU as NewtonSensorIMU + + from isaaclab.sensors.imu import ImuCfg + +logger = logging.getLogger(__name__) + + +class Imu(BaseImu): + """Newton Inertial Measurement Unit (IMU) sensor. + + Wrapper around ``newton.sensors.SensorIMU`` providing angular velocity + (gyroscope) and linear acceleration (accelerometer) in the sensor's + body frame. + """ + + cfg: ImuCfg + """The configuration parameters.""" + + __backend_name__: str = "newton" + """The name of the backend for the IMU sensor.""" + + def __init__(self, cfg: ImuCfg): + """Initializes the Newton IMU sensor. + + Registers a site request and the ``body_qdd`` state attribute with + :class:`NewtonManager`. The site is injected into prototype builders + before replication so it ends up in each world. + + Args: + cfg: The configuration parameters. + """ + super().__init__(cfg) + + self._data = ImuData() + self._sensor_index: int | None = None + self._newton_sensor: NewtonSensorIMU | None = None + + offset_xform = wp.transform(cfg.offset.pos, cfg.offset.rot) + self._site_label: str = NewtonManager.cl_register_site(cfg.prim_path, offset_xform) + NewtonManager.request_extended_state_attribute("body_qdd") + + logger.info(f"IMU '{cfg.prim_path}': site registered (label='{self._site_label}')") + + def __str__(self) -> str: + """String representation of the sensor instance.""" + return ( + f"IMU sensor @ '{self.cfg.prim_path}': \n" + f"\tbackend : newton\n" + f"\tupdate period (s) : {self.cfg.update_period}\n" + f"\tnumber of sensors : {self._num_envs}\n" + ) + + """ + Properties + """ + + @property + def data(self) -> ImuData: + """The IMU sensor data.""" + self._update_outdated_buffers() + return self._data + + """ + Operations + """ + + def reset(self, env_ids: Sequence[int] | None = None, env_mask: wp.array | None = None): + """Reset the sensor for the given environments. + + Zeroes out angular velocity and linear acceleration buffers for the + specified environments. + + Args: + env_ids: Environment indices to reset. Defaults to all environments. + env_mask: Boolean mask of environments to reset. Mutually exclusive with *env_ids*. + """ + env_mask = self._resolve_indices_and_mask(env_ids, env_mask) + super().reset(None, env_mask) + wp.launch( + imu_reset_kernel, + dim=self._num_envs, + inputs=[env_mask, self._data._lin_acc_b, self._data._ang_vel_b], + device=self._device, + ) + + """ + Implementation + """ + + def _initialize_impl(self): + """PHYSICS_READY callback: resolves site indices and creates the native SensorIMU.""" + super()._initialize_impl() + + site_map = NewtonManager._cl_site_index_map + num_envs = self._num_envs + + if self._site_label not in site_map: + raise ValueError( + f"IMU '{self.cfg.prim_path}': site label '{self._site_label}' " + "not found in NewtonManager._cl_site_index_map." + ) + + global_idx, per_world = site_map[self._site_label] + + if per_world is None: + # Global site (body=-1, i.e. world frame): replicate across envs. + site_indices = [global_idx] * num_envs + else: + if len(per_world) != num_envs: + raise ValueError( + f"IMU '{self.cfg.prim_path}': site has {len(per_world)} world entries, expected {num_envs}." + ) + + site_indices: list[int] = [] + for env_idx, world_sites in enumerate(per_world): + if len(world_sites) != 1: + raise ValueError( + f"IMU '{self.cfg.prim_path}': pattern matched {len(world_sites)} " + f"bodies in env {env_idx}, expected exactly 1." + ) + site_indices.append(world_sites[0]) + + self._sensor_index = NewtonManager.add_imu_sensor(site_indices) + self._newton_sensor = NewtonManager._newton_imu_sensors[self._sensor_index] + + self._data.create_buffers(num_envs=num_envs, device=self._device) + + logger.info(f"IMU initialized: {num_envs} envs, sensor_index={self._sensor_index}") + + def _update_buffers_impl(self, env_mask: wp.array): + """Copies accelerometer/gyroscope data from native Newton sensor into owned buffers.""" + if self._newton_sensor is None: + raise RuntimeError( + f"IMU '{self.cfg.prim_path}': sensor not initialized. " + "Access sensor data only after sim.reset() has been called." + ) + wp.launch( + imu_copy_kernel, + dim=self._num_envs, + inputs=[env_mask, self._newton_sensor.accelerometer, self._newton_sensor.gyroscope], + outputs=[self._data._lin_acc_b, self._data._ang_vel_b], + device=self._device, + ) + + def _invalidate_initialize_callback(self, event): + """Clears references to the native Newton sensor and re-registers site/attributes. + + ``NewtonManager.close()`` calls ``clear()`` before dispatching ``STOP``, + so ``_cl_pending_sites`` and ``_pending_extended_state_attributes`` are + already empty when this callback fires. Re-registering here ensures the + site and ``body_qdd`` attribute survive a close/reinit cycle. + """ + super()._invalidate_initialize_callback(event) + self._newton_sensor = None + self._sensor_index = None + + # Zero out data buffers so stale data is not served between STOP and reinit. + if self._data._ang_vel_b is not None: + self._data._ang_vel_b.zero_() + if self._data._lin_acc_b is not None: + self._data._lin_acc_b.zero_() + + # Re-register so a subsequent start_simulation picks them up. + offset_xform = wp.transform(self.cfg.offset.pos, self.cfg.offset.rot) + self._site_label = NewtonManager.cl_register_site(self.cfg.prim_path, offset_xform) + NewtonManager.request_extended_state_attribute("body_qdd") diff --git a/source/isaaclab_newton/isaaclab_newton/sensors/imu/imu_data.py b/source/isaaclab_newton/isaaclab_newton/sensors/imu/imu_data.py new file mode 100644 index 000000000000..f288df131a2f --- /dev/null +++ b/source/isaaclab_newton/isaaclab_newton/sensors/imu/imu_data.py @@ -0,0 +1,63 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from __future__ import annotations + +import warp as wp + +from isaaclab.sensors.imu import BaseImuData +from isaaclab.utils.warp import ProxyArray + + +class ImuData(BaseImuData): + """Data container for the Newton IMU sensor.""" + + def __init__(self): + self._ang_vel_b: wp.array | None = None + self._lin_acc_b: wp.array | None = None + self._ang_vel_b_ta: ProxyArray | None = None + self._lin_acc_b_ta: ProxyArray | None = None + + @property + def ang_vel_b(self) -> ProxyArray | None: + """IMU frame angular velocity relative to the world expressed in IMU frame [rad/s]. + + Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). + + ``None`` before the simulation is initialized. + """ + if self._ang_vel_b is None: + return None + if self._ang_vel_b_ta is None: + self._ang_vel_b_ta = ProxyArray(self._ang_vel_b) + return self._ang_vel_b_ta + + @property + def lin_acc_b(self) -> ProxyArray | None: + """Linear acceleration (proper) in the IMU frame [m/s^2]. + + Zero in freefall, +g upward at rest. + + Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). + + ``None`` before the simulation is initialized. + """ + if self._lin_acc_b is None: + return None + if self._lin_acc_b_ta is None: + self._lin_acc_b_ta = ProxyArray(self._lin_acc_b) + return self._lin_acc_b_ta + + def create_buffers(self, num_envs: int, device: str) -> None: + """Create internal buffers for sensor data. + + Args: + num_envs: Number of environments. + device: Device for array storage. + """ + self._ang_vel_b = wp.zeros(num_envs, dtype=wp.vec3f, device=device) + self._lin_acc_b = wp.zeros(num_envs, dtype=wp.vec3f, device=device) + self._ang_vel_b_ta = None + self._lin_acc_b_ta = None diff --git a/source/isaaclab_newton/isaaclab_newton/sensors/imu/kernels.py b/source/isaaclab_newton/isaaclab_newton/sensors/imu/kernels.py new file mode 100644 index 000000000000..7c4716fd55c9 --- /dev/null +++ b/source/isaaclab_newton/isaaclab_newton/sensors/imu/kernels.py @@ -0,0 +1,34 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +import warp as wp + + +@wp.kernel +def imu_copy_kernel( + env_mask: wp.array(dtype=wp.bool), + accelerometer: wp.array(dtype=wp.vec3f), + gyroscope: wp.array(dtype=wp.vec3f), + out_lin_acc_b: wp.array(dtype=wp.vec3f), + out_ang_vel_b: wp.array(dtype=wp.vec3f), +): + idx = wp.tid() + if not env_mask[idx]: + return + out_lin_acc_b[idx] = accelerometer[idx] + out_ang_vel_b[idx] = gyroscope[idx] + + +@wp.kernel +def imu_reset_kernel( + env_mask: wp.array(dtype=wp.bool), + out_lin_acc_b: wp.array(dtype=wp.vec3f), + out_ang_vel_b: wp.array(dtype=wp.vec3f), +): + idx = wp.tid() + if not env_mask[idx]: + return + out_lin_acc_b[idx] = wp.vec3f(0.0, 0.0, 0.0) + out_ang_vel_b[idx] = wp.vec3f(0.0, 0.0, 0.0) diff --git a/source/isaaclab_newton/isaaclab_newton/sensors/joint_wrench/__init__.py b/source/isaaclab_newton/isaaclab_newton/sensors/joint_wrench/__init__.py new file mode 100644 index 000000000000..fb10acc86182 --- /dev/null +++ b/source/isaaclab_newton/isaaclab_newton/sensors/joint_wrench/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Sub-module for the Newton joint-wrench sensor.""" + +from isaaclab.utils.module import lazy_export + +lazy_export() diff --git a/source/isaaclab_newton/isaaclab_newton/sensors/joint_wrench/__init__.pyi b/source/isaaclab_newton/isaaclab_newton/sensors/joint_wrench/__init__.pyi new file mode 100644 index 000000000000..b2bcd3582d44 --- /dev/null +++ b/source/isaaclab_newton/isaaclab_newton/sensors/joint_wrench/__init__.pyi @@ -0,0 +1,9 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +__all__ = ["JointWrenchSensor", "JointWrenchSensorData"] + +from .joint_wrench_sensor import JointWrenchSensor +from .joint_wrench_sensor_data import JointWrenchSensorData diff --git a/source/isaaclab_newton/isaaclab_newton/sensors/joint_wrench/joint_wrench_sensor.py b/source/isaaclab_newton/isaaclab_newton/sensors/joint_wrench/joint_wrench_sensor.py new file mode 100644 index 000000000000..bd53751d6a5f --- /dev/null +++ b/source/isaaclab_newton/isaaclab_newton/sensors/joint_wrench/joint_wrench_sensor.py @@ -0,0 +1,247 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from __future__ import annotations + +import logging +from collections.abc import Sequence +from typing import TYPE_CHECKING + +import warp as wp +from newton import JointType +from newton.selection import ArticulationView + +from pxr import UsdPhysics + +from isaaclab.sensors.joint_wrench import BaseJointWrenchSensor +from isaaclab.sim.utils.queries import find_first_matching_prim, get_all_matching_child_prims + +from isaaclab_newton.physics import NewtonManager + +from .joint_wrench_sensor_data import JointWrenchSensorData +from .kernels import joint_wrench_reset_kernel, joint_wrench_to_incoming_joint_frame_kernel + +if TYPE_CHECKING: + from isaaclab.sensors.joint_wrench import JointWrenchSensorCfg + +logger = logging.getLogger(__name__) + + +class JointWrenchSensor(BaseJointWrenchSensor): + """Newton joint reaction wrench sensor. + + Reads Newton's ``body_parent_f`` (world-frame wrench at child COM) and + converts each entry to the ``INCOMING_JOINT_FRAME`` convention + (child-side joint frame, child-side joint anchor as reference point) + before storing it in per-joint force / torque buffers. + + :attr:`~isaaclab.sensors.SensorBaseCfg.prim_path` must point at either + the articulation root prim or a parent prim containing a single + articulation root in every environment. ``FREE`` and ``FIXED`` joints are + excluded — neither has a meaningful joint anchor. + """ + + cfg: JointWrenchSensorCfg + """The configuration parameters.""" + + __backend_name__: str = "newton" + """The name of the backend for the joint wrench sensor.""" + + def __init__(self, cfg: JointWrenchSensorCfg): + """Initialize the Newton joint-wrench sensor. + + Requests the ``body_parent_f`` extended state attribute from :class:`NewtonManager` so the + model builder allocates it during simulation startup. + + Args: + cfg: The configuration parameters. + """ + super().__init__(cfg) + + self._data = JointWrenchSensorData() + self._root_view: ArticulationView | None = None + self._sim_bind_body_parent_f: wp.array | None = None + self._sim_bind_body_q: wp.array | None = None + self._sim_bind_body_com: wp.array | None = None + self._sim_bind_joint_X_c: wp.array | None = None + self._joint_child: wp.array | None = None + self._num_joints: int = 0 + + NewtonManager.request_extended_state_attribute("body_parent_f") + + def __str__(self) -> str: + """String representation of the sensor instance.""" + return ( + f"Joint wrench sensor @ '{self.cfg.prim_path}': \n" + f"\tbackend : newton\n" + f"\tupdate period (s) : {self.cfg.update_period}\n" + f"\tnumber of joints : {self._num_joints}\n" + ) + + """ + Properties + """ + + @property + def body_names(self) -> list[str]: + """Ordered names of the bodies whose incoming joint wrench is reported.""" + return self._data._body_names + + @property + def data(self) -> JointWrenchSensorData: + """The joint-wrench sensor data.""" + self._update_outdated_buffers() + return self._data + + """ + Operations + """ + + def reset(self, env_ids: Sequence[int] | None = None, env_mask: wp.array | None = None) -> None: + """Reset the sensor buffers for the given environments. + + Args: + env_ids: the environment ids to reset. + env_mask: the mask used to reset the environments. Shape is (num_envs).""" + if self._data._force is None or self._data._torque is None: + return + env_mask = self._resolve_indices_and_mask(env_ids, env_mask) + super().reset(None, env_mask) + wp.launch( + joint_wrench_reset_kernel, + dim=(self._num_envs, self._num_joints), + inputs=[env_mask, self._data._force, self._data._torque], + device=self._device, + ) + + """ + Implementation + """ + + def _initialize_impl(self) -> None: + """PHYSICS_READY callback: builds the articulation view and binds model / state arrays.""" + super()._initialize_impl() + + model = NewtonManager.get_model() + state_0 = NewtonManager.get_state_0() + + root_prim_path_expr = self._resolve_articulation_root_prim_path() + self._root_view = ArticulationView( + model, + root_prim_path_expr.replace(".*", "*"), + verbose=False, + exclude_joint_types=[JointType.FREE, JointType.FIXED], + ) + self._num_joints = self._root_view.joint_count + if self._num_joints == 0: + raise RuntimeError( + "Joint wrench sensor matched zero reportable joints (all joints are FREE or FIXED)." + f" Check the articulation at '{root_prim_path_expr}'." + ) + + try: + body_parent_f = self._root_view.get_attribute("body_parent_f", state_0) + except AttributeError as err: + raise RuntimeError( + f"Joint wrench sensor '{self.cfg.prim_path}': Newton state does not expose" + " 'body_parent_f'. Construct the sensor before sim startup so the extended-state" + " request is forwarded to the model builder." + ) from err + + self._sim_bind_body_parent_f = body_parent_f[:, 0] + self._sim_bind_body_q = self._root_view.get_link_transforms(state_0)[:, 0] + self._sim_bind_body_com = self._root_view.get_attribute("body_com", model)[:, 0] + self._sim_bind_joint_X_c = self._root_view.get_attribute("joint_X_c", model)[:, 0] + + # joint_child is per-articulation; topology is identical across envs, + # so we take the first-env mapping as the 1-D kernel input. + joint_child_full = self._root_view.get_attribute("joint_child", model)[:, 0] + joint_child_np = joint_child_full.numpy()[0] + if not all(0 <= b < self._sim_bind_body_parent_f.shape[1] for b in joint_child_np): + raise RuntimeError(f"joint_child contains out-of-range body indices for '{self.cfg.prim_path}'") + self._joint_child = wp.array(joint_child_np, dtype=wp.int32, device=self._device) + + link_names = list(self._root_view.link_names) + self._data._body_names = [link_names[int(b)] for b in joint_child_np] + + self._data.create_buffers(num_envs=self._num_envs, num_joints=self._num_joints, device=self._device) + + logger.info(f"Joint wrench sensor initialized: {self._num_envs} envs, {self._num_joints} joints") + + def _resolve_articulation_root_prim_path(self) -> str: + """Resolve the articulation root prim path expression from the configured asset prim path.""" + first_env_matching_prim = find_first_matching_prim(self.cfg.prim_path) + if first_env_matching_prim is None: + raise RuntimeError(f"Failed to find prim for expression: '{self.cfg.prim_path}'.") + first_env_matching_prim_path = first_env_matching_prim.GetPath().pathString + + first_env_root_prims = get_all_matching_child_prims( + first_env_matching_prim_path, + predicate=lambda prim: prim.HasAPI(UsdPhysics.ArticulationRootAPI) + and prim.GetAttribute("physxArticulation:articulationEnabled").Get() is not False, + traverse_instance_prims=False, + ) + if len(first_env_root_prims) == 0: + raise RuntimeError( + f"Failed to find an articulation when resolving '{first_env_matching_prim_path}'." + " Please ensure that the prim has 'USD ArticulationRootAPI' applied." + ) + if len(first_env_root_prims) > 1: + raise RuntimeError( + f"Failed to find a single articulation when resolving '{first_env_matching_prim_path}'." + f" Found multiple '{first_env_root_prims}' under '{first_env_matching_prim_path}'." + " Please ensure that there is only one articulation in the prim path tree." + ) + + first_env_root_prim_path = first_env_root_prims[0].GetPath().pathString + root_prim_path_relative_to_prim_path = first_env_root_prim_path[len(first_env_matching_prim_path) :] + return self.cfg.prim_path + root_prim_path_relative_to_prim_path + + def _update_buffers_impl(self, env_mask: wp.array) -> None: + """Convert Newton's body_parent_f into INCOMING_JOINT_FRAME force and torque buffers. + + Args: + env_mask: A mask containing which environments need to be updated. Shape is (num_envs) + """ + if self._sim_bind_body_parent_f is None: + raise RuntimeError( + f"Joint wrench sensor '{self.cfg.prim_path}': not initialized." + " Access sensor data only after sim.reset() has been called." + ) + wp.launch( + joint_wrench_to_incoming_joint_frame_kernel, + dim=(self._num_envs, self._num_joints), + inputs=[ + env_mask, + self._sim_bind_body_parent_f, + self._sim_bind_body_q, + self._sim_bind_body_com, + self._sim_bind_joint_X_c, + self._joint_child, + ], + outputs=[self._data._force, self._data._torque], + device=self._device, + ) + + def _invalidate_initialize_callback(self, event) -> None: + """Drop view, cached sizes, and buffers; re-register the extended-state request. + + Args: + event: An invalidate event. + """ + super()._invalidate_initialize_callback(event) + self._root_view = None + self._sim_bind_body_parent_f = None + self._sim_bind_body_q = None + self._sim_bind_body_com = None + self._sim_bind_joint_X_c = None + self._joint_child = None + self._num_joints = 0 + self._data._force = None + self._data._torque = None + self._data._body_names = [] + self._data._force_ta = None + self._data._torque_ta = None + NewtonManager.request_extended_state_attribute("body_parent_f") diff --git a/source/isaaclab_newton/isaaclab_newton/sensors/joint_wrench/joint_wrench_sensor_data.py b/source/isaaclab_newton/isaaclab_newton/sensors/joint_wrench/joint_wrench_sensor_data.py new file mode 100644 index 000000000000..76c5a565bdfb --- /dev/null +++ b/source/isaaclab_newton/isaaclab_newton/sensors/joint_wrench/joint_wrench_sensor_data.py @@ -0,0 +1,67 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from __future__ import annotations + +import warp as wp + +from isaaclab.sensors.joint_wrench import BaseJointWrenchSensorData +from isaaclab.utils.warp import ProxyArray + + +class JointWrenchSensorData(BaseJointWrenchSensorData): + """Data container for the Newton joint-wrench sensor.""" + + def __init__(self): + self._force: wp.array | None = None + self._torque: wp.array | None = None + self._body_names: list[str] = [] + self._force_ta: ProxyArray | None = None + self._torque_ta: ProxyArray | None = None + + @property + def force(self) -> ProxyArray | None: + """Linear component of the joint reaction wrench [N]. + + Expressed in the frame selected by + :attr:`~isaaclab.sensors.JointWrenchSensorCfg.convention`. Shape is + ``(num_envs, num_bodies)``, dtype ``wp.vec3f``. In torch this resolves + to ``(num_envs, num_bodies, 3)``. ``None`` before the simulation is + initialized. + """ + if self._force is None: + return None + if self._force_ta is None: + self._force_ta = ProxyArray(self._force) + return self._force_ta + + @property + def torque(self) -> ProxyArray | None: + """Angular component of the joint reaction wrench [N·m]. + + Expressed in the frame selected by + :attr:`~isaaclab.sensors.JointWrenchSensorCfg.convention`. Shape is + ``(num_envs, num_bodies)``, dtype ``wp.vec3f``. In torch this resolves + to ``(num_envs, num_bodies, 3)``. ``None`` before the simulation is + initialized. + """ + if self._torque is None: + return None + if self._torque_ta is None: + self._torque_ta = ProxyArray(self._torque) + return self._torque_ta + + def create_buffers(self, num_envs: int, num_joints: int, device: str) -> None: + """Allocate internal buffers. + + Args: + num_envs: Number of environments. + num_joints: Number of reported joints (excludes FREE and FIXED joint types). + device: Device for array storage. + """ + self._force = wp.zeros((num_envs, num_joints), dtype=wp.vec3f, device=device) + self._torque = wp.zeros((num_envs, num_joints), dtype=wp.vec3f, device=device) + self._force_ta = None + self._torque_ta = None diff --git a/source/isaaclab_newton/isaaclab_newton/sensors/joint_wrench/kernels.py b/source/isaaclab_newton/isaaclab_newton/sensors/joint_wrench/kernels.py new file mode 100644 index 000000000000..64a0b4f0dda2 --- /dev/null +++ b/source/isaaclab_newton/isaaclab_newton/sensors/joint_wrench/kernels.py @@ -0,0 +1,80 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +import warp as wp + + +@wp.kernel +def joint_wrench_to_incoming_joint_frame_kernel( + env_mask: wp.array(dtype=wp.bool), + body_parent_f: wp.array(dtype=wp.spatial_vectorf, ndim=2), + body_q: wp.array(dtype=wp.transformf, ndim=2), + body_com: wp.array(dtype=wp.vec3f, ndim=2), + joint_X_c: wp.array(dtype=wp.transformf, ndim=2), + joint_child: wp.array(dtype=wp.int32), + out_force: wp.array(dtype=wp.vec3f, ndim=2), + out_torque: wp.array(dtype=wp.vec3f, ndim=2), +): + """Convert Newton's ``body_parent_f`` to the INCOMING_JOINT_FRAME convention. + + Newton reports ``body_parent_f[env, body]`` as a spatial wrench in world frame, referenced at + the child body's centre of mass. The output is that same wrench re-expressed in the child-side + joint frame and with the child-side joint anchor as the reference point — matching what a 6-axis + force/torque sensor mounted at the joint would measure. + + Args: + env_mask: Boolean mask selecting which environments to update. + body_parent_f: Newton state — world-frame spatial wrench at child COM ``(num_envs, num_bodies)``. + body_q: Newton state — child link transforms in world frame ``(num_envs, num_bodies)``. + body_com: Newton model — COM offset in link-local frame ``(num_envs, num_bodies)``. + joint_X_c: Newton model — child-side joint frame relative to child link ``(num_envs, num_joints)``. + joint_child: Newton model — body index of each joint's child link ``(num_joints,)``. + out_force: Output force in joint frame [N] ``(num_envs, num_joints)``. + out_torque: Output torque in joint frame [N·m] ``(num_envs, num_joints)``. + """ + env, j = wp.tid() + if not env_mask[env]: + return + + body_idx = joint_child[j] + + # Source wrench in world frame. Newton's body_parent_f stores (force, torque-about-COM). + src = body_parent_f[env, body_idx] + f_world = wp.spatial_top(src) + tau_world_com = wp.spatial_bottom(src) + + # Child link transform in world and COM offset in link frame. + link_xform = body_q[env, body_idx] + link_quat = wp.transform_get_rotation(link_xform) + link_pos = wp.transform_get_translation(link_xform) + com_world = link_pos + wp.quat_rotate(link_quat, body_com[env, body_idx]) + + # Child-side joint frame in world = body link pose composed with joint_X_c. + joint_xform_world = link_xform * joint_X_c[env, j] + anchor_world = wp.transform_get_translation(joint_xform_world) + joint_quat_world = wp.transform_get_rotation(joint_xform_world) + + # Shift torque reference from COM to joint anchor: + # tau_anchor = tau_com + (com - anchor) x f = tau_com + r_anchor_to_com x f. + r_anchor_to_com = com_world - anchor_world + tau_world_anchor = tau_world_com + wp.cross(r_anchor_to_com, f_world) + + # Rotate both components into the child-side joint frame. + out_force[env, j] = wp.quat_rotate_inv(joint_quat_world, f_world) + out_torque[env, j] = wp.quat_rotate_inv(joint_quat_world, tau_world_anchor) + + +@wp.kernel +def joint_wrench_reset_kernel( + env_mask: wp.array(dtype=wp.bool), + out_force: wp.array(dtype=wp.vec3f, ndim=2), + out_torque: wp.array(dtype=wp.vec3f, ndim=2), +): + """Zero force / torque entries for the environments selected by ``env_mask``.""" + env, joint = wp.tid() + if not env_mask[env]: + return + out_force[env, joint] = wp.vec3f(0.0, 0.0, 0.0) + out_torque[env, joint] = wp.vec3f(0.0, 0.0, 0.0) diff --git a/source/isaaclab_newton/isaaclab_newton/sensors/pva/__init__.py b/source/isaaclab_newton/isaaclab_newton/sensors/pva/__init__.py new file mode 100644 index 000000000000..257e5b627f83 --- /dev/null +++ b/source/isaaclab_newton/isaaclab_newton/sensors/pva/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Sub-module for Newton PVA sensor.""" + +from isaaclab.utils.module import lazy_export + +lazy_export() diff --git a/source/isaaclab_newton/isaaclab_newton/sensors/pva/__init__.pyi b/source/isaaclab_newton/isaaclab_newton/sensors/pva/__init__.pyi new file mode 100644 index 000000000000..bba750977ae1 --- /dev/null +++ b/source/isaaclab_newton/isaaclab_newton/sensors/pva/__init__.pyi @@ -0,0 +1,9 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +__all__ = ["Pva", "PvaData"] + +from .pva import Pva +from .pva_data import PvaData diff --git a/source/isaaclab_newton/isaaclab_newton/sensors/pva/kernels.py b/source/isaaclab_newton/isaaclab_newton/sensors/pva/kernels.py new file mode 100644 index 000000000000..8ea779284058 --- /dev/null +++ b/source/isaaclab_newton/isaaclab_newton/sensors/pva/kernels.py @@ -0,0 +1,108 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +import warp as wp + + +@wp.kernel +def pva_update_kernel( + # indexing + env_mask: wp.array(dtype=wp.bool), + site_indices: wp.array(dtype=int), + # model arrays + shape_body: wp.array(dtype=int), + shape_transform: wp.array(dtype=wp.transform), + body_com: wp.array(dtype=wp.vec3), + gravity: wp.array(dtype=wp.vec3), + body_world: wp.array(dtype=wp.int32), + # state arrays + body_q: wp.array(dtype=wp.transform), + body_qd: wp.array(dtype=wp.spatial_vector), + body_qdd: wp.array(dtype=wp.spatial_vector), + # outputs + out_pose_w: wp.array(dtype=wp.transformf), + out_pos_w: wp.array(dtype=wp.vec3f), + out_quat_w: wp.array(dtype=wp.quatf), + out_projected_gravity_b: wp.array(dtype=wp.vec3f), + out_lin_vel_b: wp.array(dtype=wp.vec3f), + out_ang_vel_b: wp.array(dtype=wp.vec3f), + out_lin_acc_b: wp.array(dtype=wp.vec3f), + out_ang_acc_b: wp.array(dtype=wp.vec3f), +): + idx = wp.tid() + if not env_mask[idx]: + return + + site_idx = site_indices[idx] + body_idx = shape_body[site_idx] + site_xform = shape_transform[site_idx] + + # 1. World-frame pose at sensor site + body_xform = body_q[body_idx] + body_quat = wp.transform_get_rotation(body_xform) + sensor_pos = wp.transform_get_translation(body_xform) + wp.quat_rotate(body_quat, site_xform.p) + sensor_quat = body_quat * site_xform.q + + # 2. Projected gravity (normalized to unit vector) + world_idx = body_world[body_idx] + g = gravity[wp.max(world_idx, 0)] + projected_gravity_b = wp.quat_rotate_inv(sensor_quat, wp.normalize(g)) + + # 3. Velocity at sensor site: v_site = v_com + omega x r + # r = lever arm from body COM to sensor site, in world frame. + # body_qd stores the spatial velocity at the COM, so the linear + # velocity at the site requires the cross-product correction. + r = wp.quat_rotate(body_quat, site_xform.p - body_com[body_idx]) + ang_vel_w = wp.spatial_bottom(body_qd[body_idx]) + lin_vel_w = wp.spatial_top(body_qd[body_idx]) + wp.cross(ang_vel_w, r) + + lin_vel_b = wp.quat_rotate_inv(sensor_quat, lin_vel_w) + ang_vel_b = wp.quat_rotate_inv(sensor_quat, ang_vel_w) + + # 4. Acceleration at sensor site via rigid-body transport (from body_qdd): + # a_site = a_com + alpha x r + omega x (omega x r) + ang_acc_w = wp.spatial_bottom(body_qdd[body_idx]) + lin_acc_w = ( + wp.spatial_top(body_qdd[body_idx]) + wp.cross(ang_acc_w, r) + wp.cross(ang_vel_w, wp.cross(ang_vel_w, r)) + ) + + lin_acc_b = wp.quat_rotate_inv(sensor_quat, lin_acc_w) + ang_acc_b = wp.quat_rotate_inv(sensor_quat, ang_acc_w) + + # 5. Write outputs + out_pose_w[idx] = wp.transform(sensor_pos, sensor_quat) + out_pos_w[idx] = sensor_pos + out_quat_w[idx] = sensor_quat + out_projected_gravity_b[idx] = projected_gravity_b + out_lin_vel_b[idx] = lin_vel_b + out_ang_vel_b[idx] = ang_vel_b + out_lin_acc_b[idx] = lin_acc_b + out_ang_acc_b[idx] = ang_acc_b + + +@wp.kernel +def pva_reset_kernel( + env_mask: wp.array(dtype=wp.bool), + out_pose_w: wp.array(dtype=wp.transformf), + out_pos_w: wp.array(dtype=wp.vec3f), + out_quat_w: wp.array(dtype=wp.quatf), + out_projected_gravity_b: wp.array(dtype=wp.vec3f), + out_lin_vel_b: wp.array(dtype=wp.vec3f), + out_ang_vel_b: wp.array(dtype=wp.vec3f), + out_lin_acc_b: wp.array(dtype=wp.vec3f), + out_ang_acc_b: wp.array(dtype=wp.vec3f), +): + idx = wp.tid() + if not env_mask[idx]: + return + + out_pose_w[idx] = wp.transform(wp.vec3f(0.0, 0.0, 0.0), wp.quatf(0.0, 0.0, 0.0, 1.0)) + out_pos_w[idx] = wp.vec3f(0.0, 0.0, 0.0) + out_quat_w[idx] = wp.quatf(0.0, 0.0, 0.0, 1.0) + out_projected_gravity_b[idx] = wp.vec3f(0.0, 0.0, -1.0) + out_lin_vel_b[idx] = wp.vec3f(0.0, 0.0, 0.0) + out_ang_vel_b[idx] = wp.vec3f(0.0, 0.0, 0.0) + out_lin_acc_b[idx] = wp.vec3f(0.0, 0.0, 0.0) + out_ang_acc_b[idx] = wp.vec3f(0.0, 0.0, 0.0) diff --git a/source/isaaclab_newton/isaaclab_newton/sensors/pva/pva.py b/source/isaaclab_newton/isaaclab_newton/sensors/pva/pva.py new file mode 100644 index 000000000000..c000e17c437a --- /dev/null +++ b/source/isaaclab_newton/isaaclab_newton/sensors/pva/pva.py @@ -0,0 +1,256 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from __future__ import annotations + +import logging +from collections.abc import Sequence +from typing import TYPE_CHECKING + +import torch +import warp as wp + +from pxr import UsdGeom + +import isaaclab.utils.math as math_utils +from isaaclab.markers import VisualizationMarkers +from isaaclab.sensors.pva import BasePva + +from isaaclab_newton.physics import NewtonManager + +from .kernels import pva_reset_kernel, pva_update_kernel +from .pva_data import PvaData + +if TYPE_CHECKING: + from isaaclab.sensors.pva import PvaCfg + +logger = logging.getLogger(__name__) + + +class Pva(BasePva): + """Newton Pose Velocity Acceleration (PVA) sensor. + + Reads body transforms, velocities, and accelerations directly from + Newton's simulation state (``body_q``, ``body_qd``, ``body_qdd``) to + provide world-frame pose and body-frame velocities/accelerations. + """ + + cfg: PvaCfg + """The configuration parameters.""" + + __backend_name__: str = "newton" + """The name of the backend for the PVA sensor.""" + + def __init__(self, cfg: PvaCfg): + """Initializes the Newton PVA sensor. + + Registers a site request and the ``body_qdd`` state attribute with + :class:`NewtonManager`. The site is injected into prototype builders + before replication so it ends up in each world. + + Args: + cfg: The configuration parameters. + """ + super().__init__(cfg) + + self._data = PvaData() + self._site_indices: wp.array | None = None + self._newton_model = None + + offset_xform = wp.transform(cfg.offset.pos, cfg.offset.rot) + self._site_label = NewtonManager.cl_register_site(cfg.prim_path, offset_xform) + NewtonManager.request_extended_state_attribute("body_qdd") + + logger.info(f"Pva '{cfg.prim_path}': site registered (label='{self._site_label}')") + + def __str__(self) -> str: + """String representation of the sensor instance.""" + return ( + f"Pva sensor @ '{self.cfg.prim_path}': \n" + f"\tbackend : newton\n" + f"\tupdate period (s) : {self.cfg.update_period}\n" + f"\tnumber of sensors : {self._num_envs}\n" + ) + + """ + Properties + """ + + @property + def data(self) -> PvaData: + """The PVA sensor data.""" + self._update_outdated_buffers() + return self._data + + """ + Operations + """ + + def reset(self, env_ids: Sequence[int] | None = None, env_mask: wp.array | None = None): + """Reset the sensor for the given environments. + + Zeroes out all PVA buffers for the specified environments. + + Args: + env_ids: Environment indices to reset. Defaults to all environments. + env_mask: Boolean mask of environments to reset. Mutually exclusive with *env_ids*. + """ + env_mask = self._resolve_indices_and_mask(env_ids, env_mask) + super().reset(None, env_mask) + wp.launch( + pva_reset_kernel, + dim=self._num_envs, + inputs=[ + env_mask, + self._data._pose_w, + self._data._pos_w, + self._data._quat_w, + self._data._projected_gravity_b, + self._data._lin_vel_b, + self._data._ang_vel_b, + self._data._lin_acc_b, + self._data._ang_acc_b, + ], + device=self._device, + ) + + """ + Implementation + """ + + def _initialize_impl(self): + """PHYSICS_READY callback: resolves site indices and stores model reference.""" + super()._initialize_impl() + + site_map = NewtonManager._cl_site_index_map + num_envs = self._num_envs + + if self._site_label not in site_map: + raise ValueError( + f"Pva '{self.cfg.prim_path}': site label '{self._site_label}' " + "not found in NewtonManager._cl_site_index_map." + ) + + global_idx, per_world = site_map[self._site_label] + + if per_world is None: + site_indices = [global_idx] * num_envs + else: + if len(per_world) != num_envs: + raise ValueError( + f"Pva '{self.cfg.prim_path}': site has {len(per_world)} world entries, expected {num_envs}." + ) + + site_indices: list[int] = [] + for env_idx, world_sites in enumerate(per_world): + if len(world_sites) != 1: + raise ValueError( + f"Pva '{self.cfg.prim_path}': pattern matched {len(world_sites)} " + f"bodies in env {env_idx}, expected exactly 1." + ) + site_indices.append(world_sites[0]) + + self._site_indices = wp.array(site_indices, dtype=int, device=self._device) + self._newton_model = NewtonManager._model + + self._data.create_buffers(num_envs=num_envs, device=self._device) + + logger.info(f"Pva initialized: {num_envs} envs") + + def _update_buffers_impl(self, env_mask: wp.array): + """Reads Newton body state and computes all PVA quantities.""" + if self._newton_model is None: + raise RuntimeError( + f"Pva '{self.cfg.prim_path}': sensor not initialized. " + "Access sensor data only after sim.reset() has been called." + ) + state = NewtonManager._state_0 + + wp.launch( + pva_update_kernel, + dim=self._num_envs, + inputs=[ + env_mask, + self._site_indices, + self._newton_model.shape_body, + self._newton_model.shape_transform, + self._newton_model.body_com, + self._newton_model.gravity, + self._newton_model.body_world, + state.body_q, + state.body_qd, + state.body_qdd, + ], + outputs=[ + self._data._pose_w, + self._data._pos_w, + self._data._quat_w, + self._data._projected_gravity_b, + self._data._lin_vel_b, + self._data._ang_vel_b, + self._data._lin_acc_b, + self._data._ang_acc_b, + ], + device=self._device, + ) + + def _set_debug_vis_impl(self, debug_vis: bool): + if debug_vis: + if not hasattr(self, "acceleration_visualizer"): + self.acceleration_visualizer = VisualizationMarkers(self.cfg.visualizer_cfg) + self.acceleration_visualizer.set_visibility(True) + else: + if hasattr(self, "acceleration_visualizer"): + self.acceleration_visualizer.set_visibility(False) + + def _debug_vis_callback(self, event): + if self._newton_model is None: + return + # base position (offset upward for visibility) + base_pos_w = self._data.pos_w.torch.clone() + base_pos_w[:, 2] += 0.5 + # arrow scale + default_scale = self.acceleration_visualizer.cfg.markers["arrow"].scale + arrow_scale = torch.tensor(default_scale, device=self.device).repeat(self._data.lin_acc_b.torch.shape[0], 1) + # arrow direction from acceleration + up_axis = UsdGeom.GetStageUpAxis(self.stage) + pos_w_torch = self._data.pos_w.torch + quat_w_torch = self._data.quat_w.torch + lin_acc_b_torch = self._data.lin_acc_b.torch + quat_opengl = math_utils.quat_from_matrix( + math_utils.create_rotation_matrix_from_view( + pos_w_torch, + pos_w_torch + math_utils.quat_apply(quat_w_torch, lin_acc_b_torch), + up_axis=up_axis, + device=self._device, + ) + ) + quat_w = math_utils.convert_camera_frame_orientation_convention(quat_opengl, "opengl", "world") + self.acceleration_visualizer.visualize(base_pos_w, quat_w, arrow_scale) + + def _invalidate_initialize_callback(self, event): + """Clears references for re-initialization and re-registers with NewtonManager.""" + super()._invalidate_initialize_callback(event) + self._newton_model = None + self._site_indices = None + + # Zero out data buffers so stale data is not served between STOP and reinit. + for buf in [ + self._data._pose_w, + self._data._pos_w, + self._data._quat_w, + self._data._projected_gravity_b, + self._data._lin_vel_b, + self._data._ang_vel_b, + self._data._lin_acc_b, + self._data._ang_acc_b, + ]: + if buf is not None: + buf.zero_() + + # Re-register so a subsequent start_simulation picks them up. + offset_xform = wp.transform(self.cfg.offset.pos, self.cfg.offset.rot) + self._site_label = NewtonManager.cl_register_site(self.cfg.prim_path, offset_xform) + NewtonManager.request_extended_state_attribute("body_qdd") diff --git a/source/isaaclab_newton/isaaclab_newton/sensors/pva/pva_data.py b/source/isaaclab_newton/isaaclab_newton/sensors/pva/pva_data.py new file mode 100644 index 000000000000..5b75a0087a26 --- /dev/null +++ b/source/isaaclab_newton/isaaclab_newton/sensors/pva/pva_data.py @@ -0,0 +1,175 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from __future__ import annotations + +import warp as wp + +from isaaclab.sensors.pva import BasePvaData +from isaaclab.utils.warp import ProxyArray + + +class PvaData(BasePvaData): + """Data container for the Newton PVA sensor.""" + + def __init__(self): + self._pose_w: wp.array | None = None + self._pos_w: wp.array | None = None + self._quat_w: wp.array | None = None + self._projected_gravity_b: wp.array | None = None + self._lin_vel_b: wp.array | None = None + self._ang_vel_b: wp.array | None = None + self._lin_acc_b: wp.array | None = None + self._ang_acc_b: wp.array | None = None + # ProxyArray caches + self._pose_w_ta: ProxyArray | None = None + self._pos_w_ta: ProxyArray | None = None + self._quat_w_ta: ProxyArray | None = None + self._projected_gravity_b_ta: ProxyArray | None = None + self._lin_vel_b_ta: ProxyArray | None = None + self._ang_vel_b_ta: ProxyArray | None = None + self._lin_acc_b_ta: ProxyArray | None = None + self._ang_acc_b_ta: ProxyArray | None = None + + @property + def pose_w(self) -> ProxyArray | None: + """Pose of the sensor origin in world frame [m, unitless]. + + Shape is (num_instances,), dtype = wp.transformf. In torch this resolves to (num_instances, 7). + The pose is provided in (x, y, z, qx, qy, qz, qw) format. + + ``None`` before the simulation is initialized. + """ + if self._pose_w is None: + return None + if self._pose_w_ta is None: + self._pose_w_ta = ProxyArray(self._pose_w) + return self._pose_w_ta + + @property + def pos_w(self) -> ProxyArray | None: + """Position of the sensor origin in world frame [m]. + + Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). + + ``None`` before the simulation is initialized. + """ + if self._pos_w is None: + return None + if self._pos_w_ta is None: + self._pos_w_ta = ProxyArray(self._pos_w) + return self._pos_w_ta + + @property + def quat_w(self) -> ProxyArray | None: + """Orientation of the sensor origin in world frame. + + Shape is (num_instances,), dtype = wp.quatf. In torch this resolves to (num_instances, 4). + The orientation is provided in (x, y, z, w) format. + + ``None`` before the simulation is initialized. + """ + if self._quat_w is None: + return None + if self._quat_w_ta is None: + self._quat_w_ta = ProxyArray(self._quat_w) + return self._quat_w_ta + + @property + def projected_gravity_b(self) -> ProxyArray | None: + """Gravity direction unit vector projected on the PVA frame [unitless]. + + Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). + + ``None`` before the simulation is initialized. + """ + if self._projected_gravity_b is None: + return None + if self._projected_gravity_b_ta is None: + self._projected_gravity_b_ta = ProxyArray(self._projected_gravity_b) + return self._projected_gravity_b_ta + + @property + def lin_vel_b(self) -> ProxyArray | None: + """PVA frame linear velocity relative to the world expressed in PVA frame [m/s]. + + Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). + + ``None`` before the simulation is initialized. + """ + if self._lin_vel_b is None: + return None + if self._lin_vel_b_ta is None: + self._lin_vel_b_ta = ProxyArray(self._lin_vel_b) + return self._lin_vel_b_ta + + @property + def ang_vel_b(self) -> ProxyArray | None: + """PVA frame angular velocity relative to the world expressed in PVA frame [rad/s]. + + Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). + + ``None`` before the simulation is initialized. + """ + if self._ang_vel_b is None: + return None + if self._ang_vel_b_ta is None: + self._ang_vel_b_ta = ProxyArray(self._ang_vel_b) + return self._ang_vel_b_ta + + @property + def lin_acc_b(self) -> ProxyArray | None: + """Linear acceleration (coordinate) in the PVA frame [m/s^2]. + + Equal to -g in freefall, zero at rest. + + Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). + + ``None`` before the simulation is initialized. + """ + if self._lin_acc_b is None: + return None + if self._lin_acc_b_ta is None: + self._lin_acc_b_ta = ProxyArray(self._lin_acc_b) + return self._lin_acc_b_ta + + @property + def ang_acc_b(self) -> ProxyArray | None: + """PVA frame angular acceleration relative to the world expressed in PVA frame [rad/s^2]. + + Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). + + ``None`` before the simulation is initialized. + """ + if self._ang_acc_b is None: + return None + if self._ang_acc_b_ta is None: + self._ang_acc_b_ta = ProxyArray(self._ang_acc_b) + return self._ang_acc_b_ta + + def create_buffers(self, num_envs: int, device: str) -> None: + """Create internal buffers for sensor data. + + Args: + num_envs: Number of environments. + device: Device for array storage. + """ + self._pose_w = wp.zeros(num_envs, dtype=wp.transformf, device=device) + self._pos_w = wp.zeros(num_envs, dtype=wp.vec3f, device=device) + self._quat_w = wp.zeros(num_envs, dtype=wp.quatf, device=device) + self._projected_gravity_b = wp.zeros(num_envs, dtype=wp.vec3f, device=device) + self._lin_vel_b = wp.zeros(num_envs, dtype=wp.vec3f, device=device) + self._ang_vel_b = wp.zeros(num_envs, dtype=wp.vec3f, device=device) + self._lin_acc_b = wp.zeros(num_envs, dtype=wp.vec3f, device=device) + self._ang_acc_b = wp.zeros(num_envs, dtype=wp.vec3f, device=device) + # Reset ProxyArray caches + self._pose_w_ta = None + self._pos_w_ta = None + self._quat_w_ta = None + self._projected_gravity_b_ta = None + self._lin_vel_b_ta = None + self._ang_vel_b_ta = None + self._lin_acc_b_ta = None + self._ang_acc_b_ta = None diff --git a/source/isaaclab_newton/isaaclab_newton/sim/__init__.py b/source/isaaclab_newton/isaaclab_newton/sim/__init__.py new file mode 100644 index 000000000000..b4646aabbd0a --- /dev/null +++ b/source/isaaclab_newton/isaaclab_newton/sim/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Newton simulation utilities.""" + +from isaaclab.utils.module import lazy_export + +lazy_export() diff --git a/source/isaaclab_newton/isaaclab_newton/sim/__init__.pyi b/source/isaaclab_newton/isaaclab_newton/sim/__init__.pyi new file mode 100644 index 000000000000..aac4c8327ccb --- /dev/null +++ b/source/isaaclab_newton/isaaclab_newton/sim/__init__.pyi @@ -0,0 +1,10 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +__all__ = [ + "views", +] + +from . import views diff --git a/source/isaaclab_newton/isaaclab_newton/sim/views/__init__.py b/source/isaaclab_newton/isaaclab_newton/sim/views/__init__.py new file mode 100644 index 000000000000..44e8303bcedf --- /dev/null +++ b/source/isaaclab_newton/isaaclab_newton/sim/views/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Newton simulation views.""" + +from isaaclab.utils.module import lazy_export + +lazy_export() diff --git a/source/isaaclab_newton/isaaclab_newton/sim/views/__init__.pyi b/source/isaaclab_newton/isaaclab_newton/sim/views/__init__.pyi new file mode 100644 index 000000000000..433dfc1e8b6a --- /dev/null +++ b/source/isaaclab_newton/isaaclab_newton/sim/views/__init__.pyi @@ -0,0 +1,10 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +__all__ = [ + "NewtonSiteFrameView", +] + +from .newton_site_frame_view import NewtonSiteFrameView diff --git a/source/isaaclab_newton/isaaclab_newton/sim/views/newton_site_frame_view.py b/source/isaaclab_newton/isaaclab_newton/sim/views/newton_site_frame_view.py new file mode 100644 index 000000000000..c7758f0cbe42 --- /dev/null +++ b/source/isaaclab_newton/isaaclab_newton/sim/views/newton_site_frame_view.py @@ -0,0 +1,951 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Newton-backed FrameView — Warp-native, GPU-resident pose queries.""" + +from __future__ import annotations + +import logging + +import warp as wp + +from pxr import Gf, Usd, UsdGeom + +import isaaclab.sim as sim_utils +from isaaclab.physics import PhysicsEvent +from isaaclab.sim.views.base_frame_view import BaseFrameView +from isaaclab.utils.warp import ProxyArray + +from isaaclab_newton.physics.newton_manager import NewtonManager + +logger = logging.getLogger(__name__) + +WORLD_BODY_INDEX = -1 + + +# ------------------------------------------------------------------ +# Warp kernels +# ------------------------------------------------------------------ + + +@wp.kernel +def _compute_site_world_transforms( + body_q: wp.array(dtype=wp.transformf), + site_body: wp.array(dtype=wp.int32), + site_local: wp.array(dtype=wp.transformf), + out_pos: wp.array(dtype=wp.vec3f), + out_quat: wp.array(dtype=wp.vec4f), +): + """Compute world-space transforms for every site in the view. + + For each site *i*, computes ``world = body_q[site_body[i]] * site_local[i]`` + and splits the result into position and quaternion outputs. When + ``site_body[i] == -1`` the site is world-attached and ``site_local[i]`` is + returned directly. + + Args: + body_q: Rigid-body world transforms from the Newton state, shape ``[num_bodies]``. + site_body: Per-site body index (flat model-level), shape ``[num_sites]``. + A value of ``-1`` indicates a world-attached site. + site_local: Per-site local offset relative to its parent body, shape ``[num_sites]``. + out_pos: Output world positions [m], shape ``[num_sites]``. + out_quat: Output world orientations as ``(qx, qy, qz, qw)``, shape ``[num_sites]``. + """ + i = wp.tid() + bid = site_body[i] + if bid == -1: + world = site_local[i] + else: + world = wp.transform_multiply(body_q[bid], site_local[i]) + out_pos[i] = wp.transform_get_translation(world) + q = wp.transform_get_rotation(world) + out_quat[i] = wp.vec4f(q[0], q[1], q[2], q[3]) + + +@wp.kernel +def _compute_site_world_transforms_indexed( + body_q: wp.array(dtype=wp.transformf), + site_body: wp.array(dtype=wp.int32), + site_local: wp.array(dtype=wp.transformf), + indices: wp.array(dtype=wp.int32), + out_pos: wp.array(dtype=wp.vec3f), + out_quat: wp.array(dtype=wp.vec4f), +): + """Indexed variant of :func:`_compute_site_world_transforms`. + + Only computes world transforms for the subset of sites selected by + ``indices``. Thread *i* reads ``indices[i]`` to obtain the site index, + then writes the result to ``out_pos[i]`` / ``out_quat[i]``. + + Args: + body_q: Rigid-body world transforms from the Newton state, shape ``[num_bodies]``. + site_body: Per-site body index (flat model-level), shape ``[num_sites]``. + site_local: Per-site local offset relative to its parent body, shape ``[num_sites]``. + indices: Site indices to query, shape ``[M]``. + out_pos: Output world positions [m], shape ``[M]``. + out_quat: Output world orientations as ``(qx, qy, qz, qw)``, shape ``[M]``. + """ + i = wp.tid() + si = indices[i] + bid = site_body[si] + if bid == -1: + world = site_local[si] + else: + world = wp.transform_multiply(body_q[bid], site_local[si]) + out_pos[i] = wp.transform_get_translation(world) + q = wp.transform_get_rotation(world) + out_quat[i] = wp.vec4f(q[0], q[1], q[2], q[3]) + + +@wp.kernel +def _gather_scales( + shape_scale: wp.array(dtype=wp.vec3f), + shape_body: wp.array(dtype=wp.int32), + site_body: wp.array(dtype=wp.int32), + num_shapes: wp.int32, + out_scales: wp.array(dtype=wp.vec3f), +): + """Gather per-site scales from collision shapes on the same body. + + For each site *i*, linearly scans all shapes to find the first one whose + ``shape_body`` matches ``site_body[i]`` and copies its scale. Falls back + to ``(1, 1, 1)`` if no shape is found on that body. + + Args: + shape_scale: Per-shape scale vectors from the Newton model, shape ``[num_shapes]``. + shape_body: Per-shape parent body index, shape ``[num_shapes]``. + site_body: Per-site body index, shape ``[num_sites]``. + num_shapes: Total number of shapes in the model. + out_scales: Output scale per site, shape ``[num_sites]``. + """ + i = wp.tid() + bid = site_body[i] + found = int(0) + for s in range(num_shapes): + if shape_body[s] == bid and found == 0: + out_scales[i] = shape_scale[s] + found = 1 + if found == 0: + out_scales[i] = wp.vec3f(1.0, 1.0, 1.0) + + +@wp.kernel +def _gather_scales_indexed( + shape_scale: wp.array(dtype=wp.vec3f), + shape_body: wp.array(dtype=wp.int32), + site_body: wp.array(dtype=wp.int32), + indices: wp.array(dtype=wp.int32), + num_shapes: wp.int32, + out_scales: wp.array(dtype=wp.vec3f), +): + """Indexed variant of :func:`_gather_scales`. + + Args: + shape_scale: Per-shape scale vectors from the Newton model, shape ``[num_shapes]``. + shape_body: Per-shape parent body index, shape ``[num_shapes]``. + site_body: Per-site body index, shape ``[num_sites]``. + indices: Site indices to query, shape ``[M]``. + num_shapes: Total number of shapes in the model. + out_scales: Output scale per queried site, shape ``[M]``. + """ + i = wp.tid() + si = indices[i] + bid = site_body[si] + found = int(0) + for s in range(num_shapes): + if shape_body[s] == bid and found == 0: + out_scales[i] = shape_scale[s] + found = 1 + if found == 0: + out_scales[i] = wp.vec3f(1.0, 1.0, 1.0) + + +@wp.kernel +def _scatter_scales( + site_body: wp.array(dtype=wp.int32), + new_scales: wp.array(dtype=wp.vec3f), + shape_body: wp.array(dtype=wp.int32), + num_shapes: wp.int32, + shape_scale: wp.array(dtype=wp.vec3f), +): + """Scatter per-site scales to all collision shapes on the same body. + + For each site *i*, writes ``new_scales[i]`` to every shape whose + ``shape_body`` matches ``site_body[i]``. Multiple shapes on the same + body all receive the same scale. + + Args: + site_body: Per-site body index, shape ``[num_sites]``. + new_scales: New scale to apply per site, shape ``[num_sites]``. + shape_body: Per-shape parent body index, shape ``[num_shapes]``. + num_shapes: Total number of shapes in the model. + shape_scale: Per-shape scale vectors to write into (modified in-place), + shape ``[num_shapes]``. + """ + i = wp.tid() + bid = site_body[i] + for s in range(num_shapes): + if shape_body[s] == bid: + shape_scale[s] = new_scales[i] + + +@wp.kernel +def _scatter_scales_indexed( + site_body: wp.array(dtype=wp.int32), + indices: wp.array(dtype=wp.int32), + new_scales: wp.array(dtype=wp.vec3f), + shape_body: wp.array(dtype=wp.int32), + num_shapes: wp.int32, + shape_scale: wp.array(dtype=wp.vec3f), +): + """Indexed variant of :func:`_scatter_scales`. + + Args: + site_body: Per-site body index, shape ``[num_sites]``. + indices: Site indices to update, shape ``[M]``. + new_scales: New scale to apply per selected site, shape ``[M]``. + shape_body: Per-shape parent body index, shape ``[num_shapes]``. + num_shapes: Total number of shapes in the model. + shape_scale: Per-shape scale vectors to write into (modified in-place), + shape ``[num_shapes]``. + """ + i = wp.tid() + si = indices[i] + bid = site_body[si] + for s in range(num_shapes): + if shape_body[s] == bid: + shape_scale[s] = new_scales[i] + + +# ------------------------------------------------------------------ +# World-pose site_local write kernels +# ------------------------------------------------------------------ + + +@wp.kernel +def _write_site_local_from_world_poses( + body_q: wp.array(dtype=wp.transformf), + site_body: wp.array(dtype=wp.int32), + world_pos: wp.array(dtype=wp.vec3f), + world_quat: wp.array(dtype=wp.vec4f), + site_local: wp.array(dtype=wp.transformf), +): + """Update site local offsets so that the sites reach desired world poses. + + For each site *i*, computes + ``site_local[i] = inv(body_q[site_body[i]]) * desired_world`` so that + a subsequent ``body_q[bid] * site_local[i]`` yields the requested world + pose. For world-attached sites (``site_body[i] == -1``) the desired world + transform is written directly into ``site_local[i]``. + + Does **not** modify ``body_q``. + + Args: + body_q: Rigid-body world transforms from the Newton state, shape ``[num_bodies]``. + site_body: Per-site body index (flat model-level), shape ``[num_sites]``. + world_pos: Desired world positions [m], shape ``[num_sites]``. + world_quat: Desired world orientations as ``(qx, qy, qz, qw)``, shape ``[num_sites]``. + site_local: Per-site local offset (modified in-place), shape ``[num_sites]``. + """ + i = wp.tid() + w_pos = world_pos[i] + w_q = world_quat[i] + desired_world = wp.transform(w_pos, wp.quatf(w_q[0], w_q[1], w_q[2], w_q[3])) + + bid = site_body[i] + if bid == -1: + site_local[i] = desired_world + else: + site_local[i] = wp.transform_multiply(wp.transform_inverse(body_q[bid]), desired_world) + + +@wp.kernel +def _write_site_local_from_world_poses_indexed( + body_q: wp.array(dtype=wp.transformf), + site_body: wp.array(dtype=wp.int32), + indices: wp.array(dtype=wp.int32), + world_pos: wp.array(dtype=wp.vec3f), + world_quat: wp.array(dtype=wp.vec4f), + site_local: wp.array(dtype=wp.transformf), +): + """Indexed variant of :func:`_write_site_local_from_world_poses`. + + Args: + body_q: Rigid-body world transforms from the Newton state, shape ``[num_bodies]``. + site_body: Per-site body index (flat model-level), shape ``[num_sites]``. + indices: Site indices to update, shape ``[M]``. + world_pos: Desired world positions [m], shape ``[M]``. + world_quat: Desired world orientations as ``(qx, qy, qz, qw)``, shape ``[M]``. + site_local: Per-site local offset (modified in-place), shape ``[num_sites]``. + """ + i = wp.tid() + si = indices[i] + w_pos = world_pos[i] + w_q = world_quat[i] + desired_world = wp.transform(w_pos, wp.quatf(w_q[0], w_q[1], w_q[2], w_q[3])) + + bid = site_body[si] + if bid == -1: + site_local[si] = desired_world + else: + site_local[si] = wp.transform_multiply(wp.transform_inverse(body_q[bid]), desired_world) + + +# ------------------------------------------------------------------ +# Local-pose Warp kernels +# ------------------------------------------------------------------ + + +@wp.kernel +def _compute_site_local_transforms( + body_q: wp.array(dtype=wp.transformf), + site_body: wp.array(dtype=wp.int32), + site_local: wp.array(dtype=wp.transformf), + parent_site_body: wp.array(dtype=wp.int32), + parent_site_local: wp.array(dtype=wp.transformf), + out_pos: wp.array(dtype=wp.vec3f), + out_quat: wp.array(dtype=wp.vec4f), +): + """Compute parent-relative transforms for every site in the view. + + For each site *i*, computes the world pose of both the site and its USD + parent, then returns ``inv(parent_world) * prim_world``. When + ``site_body[i] == -1`` the site is world-attached and ``site_local[i]`` + is used as the world transform directly. The same convention applies to + the parent arrays. + + Args: + body_q: Rigid-body world transforms from the Newton state, shape ``[num_bodies]``. + site_body: Per-site body index (flat model-level), shape ``[num_sites]``. + site_local: Per-site local offset relative to its parent body, shape ``[num_sites]``. + parent_site_body: Per-site USD-parent body index, shape ``[num_sites]``. + parent_site_local: Per-site USD-parent local offset, shape ``[num_sites]``. + out_pos: Output parent-relative positions [m], shape ``[num_sites]``. + out_quat: Output parent-relative orientations as ``(qx, qy, qz, qw)``, + shape ``[num_sites]``. + """ + i = wp.tid() + prim_bid = site_body[i] + if prim_bid == -1: + prim_world = site_local[i] + else: + prim_world = wp.transform_multiply(body_q[prim_bid], site_local[i]) + + parent_bid = parent_site_body[i] + if parent_bid == -1: + parent_world = parent_site_local[i] + else: + parent_world = wp.transform_multiply(body_q[parent_bid], parent_site_local[i]) + + local_tf = wp.transform_multiply(wp.transform_inverse(parent_world), prim_world) + out_pos[i] = wp.transform_get_translation(local_tf) + q = wp.transform_get_rotation(local_tf) + out_quat[i] = wp.vec4f(q[0], q[1], q[2], q[3]) + + +@wp.kernel +def _compute_site_local_transforms_indexed( + body_q: wp.array(dtype=wp.transformf), + site_body: wp.array(dtype=wp.int32), + site_local: wp.array(dtype=wp.transformf), + parent_site_body: wp.array(dtype=wp.int32), + parent_site_local: wp.array(dtype=wp.transformf), + indices: wp.array(dtype=wp.int32), + out_pos: wp.array(dtype=wp.vec3f), + out_quat: wp.array(dtype=wp.vec4f), +): + """Indexed variant of :func:`_compute_site_local_transforms`. + + Args: + body_q: Rigid-body world transforms from the Newton state, shape ``[num_bodies]``. + site_body: Per-site body index (flat model-level), shape ``[num_sites]``. + site_local: Per-site local offset relative to its parent body, shape ``[num_sites]``. + parent_site_body: Per-site USD-parent body index, shape ``[num_sites]``. + parent_site_local: Per-site USD-parent local offset, shape ``[num_sites]``. + indices: Site indices to query, shape ``[M]``. + out_pos: Output parent-relative positions [m], shape ``[M]``. + out_quat: Output parent-relative orientations as ``(qx, qy, qz, qw)``, + shape ``[M]``. + """ + i = wp.tid() + si = indices[i] + prim_bid = site_body[si] + if prim_bid == -1: + prim_world = site_local[si] + else: + prim_world = wp.transform_multiply(body_q[prim_bid], site_local[si]) + + parent_bid = parent_site_body[si] + if parent_bid == -1: + parent_world = parent_site_local[si] + else: + parent_world = wp.transform_multiply(body_q[parent_bid], parent_site_local[si]) + + local_tf = wp.transform_multiply(wp.transform_inverse(parent_world), prim_world) + out_pos[i] = wp.transform_get_translation(local_tf) + q = wp.transform_get_rotation(local_tf) + out_quat[i] = wp.vec4f(q[0], q[1], q[2], q[3]) + + +@wp.kernel +def _write_site_local_from_local_poses( + body_q: wp.array(dtype=wp.transformf), + site_body: wp.array(dtype=wp.int32), + parent_site_body: wp.array(dtype=wp.int32), + parent_site_local: wp.array(dtype=wp.transformf), + local_pos: wp.array(dtype=wp.vec3f), + local_quat: wp.array(dtype=wp.vec4f), + site_local: wp.array(dtype=wp.transformf), +): + """Update site local offsets so that sites reach desired parent-relative poses. + + For each site *i*, reconstructs the desired world pose as + ``parent_world * desired_local``, then solves for the body-relative offset: + ``site_local[i] = inv(body_q[bid]) * desired_world``. For world-attached + sites (``site_body[i] == -1``) the world transform is written directly. + + Does **not** modify ``body_q``. + + Args: + body_q: Rigid-body world transforms from the Newton state, shape ``[num_bodies]``. + site_body: Per-site body index (flat model-level), shape ``[num_sites]``. + parent_site_body: Per-site USD-parent body index, shape ``[num_sites]``. + parent_site_local: Per-site USD-parent local offset, shape ``[num_sites]``. + local_pos: Desired parent-relative positions [m], shape ``[num_sites]``. + local_quat: Desired parent-relative orientations as ``(qx, qy, qz, qw)``, + shape ``[num_sites]``. + site_local: Per-site local offset (modified in-place), shape ``[num_sites]``. + """ + i = wp.tid() + parent_bid = parent_site_body[i] + if parent_bid == -1: + parent_world = parent_site_local[i] + else: + parent_world = wp.transform_multiply(body_q[parent_bid], parent_site_local[i]) + + l_pos = local_pos[i] + l_q = local_quat[i] + local_tf = wp.transform(l_pos, wp.quatf(l_q[0], l_q[1], l_q[2], l_q[3])) + desired_world = wp.transform_multiply(parent_world, local_tf) + + bid = site_body[i] + if bid == -1: + site_local[i] = desired_world + else: + site_local[i] = wp.transform_multiply(wp.transform_inverse(body_q[bid]), desired_world) + + +@wp.kernel +def _write_site_local_from_local_poses_indexed( + body_q: wp.array(dtype=wp.transformf), + site_body: wp.array(dtype=wp.int32), + parent_site_body: wp.array(dtype=wp.int32), + parent_site_local: wp.array(dtype=wp.transformf), + indices: wp.array(dtype=wp.int32), + local_pos: wp.array(dtype=wp.vec3f), + local_quat: wp.array(dtype=wp.vec4f), + site_local: wp.array(dtype=wp.transformf), +): + """Indexed variant of :func:`_write_site_local_from_local_poses`. + + Args: + body_q: Rigid-body world transforms from the Newton state, shape ``[num_bodies]``. + site_body: Per-site body index (flat model-level), shape ``[num_sites]``. + parent_site_body: Per-site USD-parent body index, shape ``[num_sites]``. + parent_site_local: Per-site USD-parent local offset, shape ``[num_sites]``. + indices: Site indices to update, shape ``[M]``. + local_pos: Desired parent-relative positions [m], shape ``[M]``. + local_quat: Desired parent-relative orientations as ``(qx, qy, qz, qw)``, + shape ``[M]``. + site_local: Per-site local offset (modified in-place), shape ``[num_sites]``. + """ + i = wp.tid() + si = indices[i] + parent_bid = parent_site_body[si] + if parent_bid == -1: + parent_world = parent_site_local[si] + else: + parent_world = wp.transform_multiply(body_q[parent_bid], parent_site_local[si]) + + l_pos = local_pos[i] + l_q = local_quat[i] + local_tf = wp.transform(l_pos, wp.quatf(l_q[0], l_q[1], l_q[2], l_q[3])) + desired_world = wp.transform_multiply(parent_world, local_tf) + + bid = site_body[si] + if bid == -1: + site_local[si] = desired_world + else: + site_local[si] = wp.transform_multiply(wp.transform_inverse(body_q[bid]), desired_world) + + +# ------------------------------------------------------------------ +# View class +# ------------------------------------------------------------------ + + +class NewtonSiteFrameView(BaseFrameView): + """Batched prim view for non-physics prims tracked as sites on Newton bodies. + + Each matched USD prim must be a **non-physics** prim (camera, sensor, + Xform marker, etc.) that sits as a child of a Newton rigid body in the + USD hierarchy. The prim path must **not** resolve directly to a physics + body or collision shape -- those are owned by Newton and should be + accessed through :class:`~isaaclab_newton.assets.Articulation` or + :class:`~isaaclab_newton.assets.RigidObject` instead. + + At init time each prim is resolved to a ``(body_index, site_local)`` + pair via ancestor walk: the nearest ancestor that appears in + ``model.body_label`` becomes the attachment body, and the relative USD + transform becomes the site offset. If no body ancestor exists the prim + is attached to the world frame (``body_index = -1``). + + World poses are computed on GPU as + ``body_q[body_index] * site_local`` via a Warp kernel. Both + ``set_world_poses`` and ``set_local_poses`` update ``site_local`` -- + neither touches ``body_q``. + + Pose getters return :class:`~isaaclab.utils.warp.ProxyArray`. Setters accept ``wp.array``. + + Raises: + ValueError: If any matched prim resolves to a Newton physics body + or collision shape. + """ + + def __init__(self, prim_path: str, device: str = "cpu", stage: Usd.Stage | None = None, **kwargs): + """Initialize the Newton site-based frame view. + + Resolves all USD prims matching ``prim_path`` and, for each one, walks + the USD ancestor hierarchy to find the nearest Newton rigid body. The + relative transform between the prim and its ancestor body becomes the + site's local offset. + + If the Newton model is already finalized the view initializes + immediately; otherwise initialization is deferred to a + :attr:`PhysicsEvent.PHYSICS_READY` callback. + + Args: + prim_path: USD prim path pattern (may contain regex). + device: Warp device for GPU arrays (e.g. ``"cuda:0"``). + stage: USD stage to search. Defaults to the current stage. + **kwargs: Unused; accepted for interface compatibility with other + :class:`~isaaclab.sim.views.BaseFrameView` backends. + """ + self._prim_path = prim_path + self._device = device + + stage = sim_utils.get_current_stage() if stage is None else stage + self._prims: list[Usd.Prim] = sim_utils.find_matching_prims(prim_path, stage=stage) + + model = NewtonManager.get_model() + if model is not None: + self._initialize_impl(model) + else: + self._physics_ready_handle = NewtonManager.register_callback( + self._on_physics_ready, PhysicsEvent.PHYSICS_READY, name=f"site_view_{prim_path}" + ) + + def _on_physics_ready(self, _event) -> None: + """Callback invoked when the Newton model becomes available.""" + self._initialize_impl(NewtonManager.get_model()) + + def _initialize_impl(self, model) -> None: + """Resolve USD prims to Newton body indices and allocate GPU buffers.""" + body_labels = list(model.body_label) + body_label_set = set(body_labels) + body_label_to_idx = {path: idx for idx, path in enumerate(body_labels)} + shape_label_set = set(model.shape_label) + + xform_cache = UsdGeom.XformCache(Usd.TimeCode.Default()) + + site_bodies: list[int] = [] + site_locals: list[list[float]] = [] + parent_bodies: list[int] = [] + parent_locals: list[list[float]] = [] + + identity_xform = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0] + resolve_cache: dict[str, tuple[int, list[float]]] = {} + + for prim in self._prims: + pp = prim.GetPath().pathString + if pp in body_label_set: + raise ValueError( + f"FrameView prim '{pp}' is a Newton physics body. " + "FrameView should only be used for non-physics prims (cameras, sensors, Xform markers). " + "Use Articulation or RigidObject APIs to control physics bodies." + ) + if pp in shape_label_set: + raise ValueError( + f"FrameView prim '{pp}' is a Newton collision shape. " + "FrameView should only be used for non-physics prims (cameras, sensors, Xform markers). " + "Use Articulation or RigidObject APIs to control collision shapes." + ) + + body_idx, local_xform = self._resolve_ancestor_body(prim, body_label_to_idx, xform_cache) + site_bodies.append(body_idx) + site_locals.append(local_xform) + + parent = prim.GetParent() + if not parent or not parent.IsValid() or parent.GetPath().pathString == "/": + parent_bodies.append(WORLD_BODY_INDEX) + parent_locals.append(identity_xform) + else: + parent_path = parent.GetPath().pathString + if parent_path in resolve_cache: + pb_idx, pb_local = resolve_cache[parent_path] + elif parent_path in body_label_to_idx: + pb_idx = body_label_to_idx[parent_path] + pb_local = identity_xform + resolve_cache[parent_path] = (pb_idx, pb_local) + else: + pb_idx, pb_local = self._resolve_ancestor_body(parent, body_label_to_idx, xform_cache) + resolve_cache[parent_path] = (pb_idx, pb_local) + parent_bodies.append(pb_idx) + parent_locals.append(pb_local) + + device = self._device + self._site_body = wp.array(site_bodies, dtype=wp.int32, device=device) + self._site_local = wp.array( + [wp.transform(*x) for x in site_locals], + dtype=wp.transformf, + device=device, + ) + self._parent_site_body = wp.array(parent_bodies, dtype=wp.int32, device=device) + self._parent_site_local = wp.array( + [wp.transform(*x) for x in parent_locals], + dtype=wp.transformf, + device=device, + ) + + self._pos_buf = wp.zeros(self.count, dtype=wp.vec3f, device=device) + self._quat_buf = wp.zeros(self.count, dtype=wp.vec4f, device=device) + self._local_pos_buf = wp.zeros(self.count, dtype=wp.vec3f, device=device) + self._local_quat_buf = wp.zeros(self.count, dtype=wp.vec4f, device=device) + self._pos_ta = ProxyArray(self._pos_buf) + self._quat_ta = ProxyArray(self._quat_buf) + self._local_pos_ta = ProxyArray(self._local_pos_buf) + self._local_quat_ta = ProxyArray(self._local_quat_buf) + + @staticmethod + def _resolve_ancestor_body( + prim: Usd.Prim, + body_label_to_idx: dict[str, int], + xform_cache: UsdGeom.XformCache, + ) -> tuple[int, list[float]]: + """Walk USD ancestors to find the nearest Newton body and compute the relative local transform. + + Args: + prim: The USD prim to resolve. + body_label_to_idx: Dict mapping body prim paths to their Newton body indices. + xform_cache: USD xform cache for efficient transform lookups. + + Returns: + A tuple ``(body_index, local_xform_7)`` where *local_xform_7* is + ``[tx, ty, tz, qx, qy, qz, qw]``. If no body ancestor exists, + ``body_index`` is :data:`WORLD_BODY_INDEX` and the local transform + is the prim's world transform. + """ + prim_world_tf = xform_cache.GetLocalToWorldTransform(prim) + prim_world_tf.Orthonormalize() + + ancestor = prim.GetParent() + while ancestor and ancestor.IsValid() and ancestor.GetPath().pathString != "/": + ancestor_path = ancestor.GetPath().pathString + body_idx = body_label_to_idx.get(ancestor_path) + if body_idx is not None: + ancestor_world_tf = xform_cache.GetLocalToWorldTransform(ancestor) + ancestor_world_tf.Orthonormalize() + local_tf = prim_world_tf * ancestor_world_tf.GetInverse() + return body_idx, _gf_matrix_to_xform7(local_tf) + ancestor = ancestor.GetParent() + + return WORLD_BODY_INDEX, _gf_matrix_to_xform7(prim_world_tf) + + @property + def prims(self) -> list: + """List of USD prims being managed by this view.""" + return self._prims + + @property + def count(self) -> int: + """Number of prims in this view.""" + return len(self._prims) + + @property + def device(self) -> str: + """Device where arrays are allocated (cpu or cuda).""" + return self._device + + # ------------------------------------------------------------------ + # World poses + # ------------------------------------------------------------------ + + def get_world_poses(self, indices: wp.array | None = None) -> tuple[ProxyArray, ProxyArray]: + """Get world-space positions and orientations. + + Args: + indices: Subset of sites to query. ``None`` means all sites. + + Returns: + A tuple ``(positions, orientations)`` of :class:`~isaaclab.utils.warp.ProxyArray` + wrappers. Use ``.warp`` for the underlying ``wp.array`` or ``.torch`` for a + cached zero-copy ``torch.Tensor`` view. + """ + state = NewtonManager.get_state_0() + + if indices is not None: + n = len(indices) + pos_buf = wp.zeros(n, dtype=wp.vec3f, device=self._device) + quat_buf = wp.zeros(n, dtype=wp.vec4f, device=self._device) + wp.launch( + _compute_site_world_transforms_indexed, + dim=n, + inputs=[state.body_q, self._site_body, self._site_local, indices], + outputs=[pos_buf, quat_buf], + device=self._device, + ) + return ProxyArray(pos_buf), ProxyArray(quat_buf) + + wp.launch( + _compute_site_world_transforms, + dim=self.count, + inputs=[state.body_q, self._site_body, self._site_local], + outputs=[self._pos_buf, self._quat_buf], + device=self._device, + ) + return self._pos_ta, self._quat_ta + + def set_world_poses( + self, + positions: wp.array | None = None, + orientations: wp.array | None = None, + indices: wp.array | None = None, + ) -> None: + """Set world-space positions and/or orientations. + + Updates the internal ``site_local`` offsets so that + ``body_q[body] * new_site_local`` yields the desired world pose. + Does **not** modify ``body_q``. + + Args: + positions: Desired world positions ``(M, 3)``. ``None`` leaves + positions unchanged. + orientations: Desired world quaternions ``(M, 4)`` as + ``(qx, qy, qz, qw)``. ``None`` leaves orientations unchanged. + indices: Subset of sites to update. ``None`` means all sites. + """ + if positions is None and orientations is None: + return + + state = NewtonManager.get_state_0() + + if positions is None or orientations is None: + cur_pos_ta, cur_quat_ta = self.get_world_poses(indices) + if positions is None: + positions = cur_pos_ta.warp + if orientations is None: + orientations = cur_quat_ta.warp + + if indices is not None: + wp.launch( + _write_site_local_from_world_poses_indexed, + dim=len(indices), + inputs=[state.body_q, self._site_body, indices, positions, orientations, self._site_local], + device=self._device, + ) + else: + wp.launch( + _write_site_local_from_world_poses, + dim=self.count, + inputs=[state.body_q, self._site_body, positions, orientations, self._site_local], + device=self._device, + ) + + # ------------------------------------------------------------------ + # Local poses (parent-relative) + # ------------------------------------------------------------------ + + def get_local_poses(self, indices: wp.array | None = None) -> tuple[ProxyArray, ProxyArray]: + """Get parent-relative positions and orientations. + + Computes ``inv(parent_world) * prim_world`` for each site. + + Args: + indices: Subset of sites to query. ``None`` means all sites. + + Returns: + A tuple ``(translations, orientations)`` of :class:`~isaaclab.utils.warp.ProxyArray` + wrappers. Use ``.warp`` for the underlying ``wp.array`` or ``.torch`` for a + cached zero-copy ``torch.Tensor`` view. + """ + state = NewtonManager.get_state_0() + + if indices is not None: + n = len(indices) + pos_buf = wp.zeros(n, dtype=wp.vec3f, device=self._device) + quat_buf = wp.zeros(n, dtype=wp.vec4f, device=self._device) + wp.launch( + _compute_site_local_transforms_indexed, + dim=n, + inputs=[ + state.body_q, + self._site_body, + self._site_local, + self._parent_site_body, + self._parent_site_local, + indices, + ], + outputs=[pos_buf, quat_buf], + device=self._device, + ) + return ProxyArray(pos_buf), ProxyArray(quat_buf) + + wp.launch( + _compute_site_local_transforms, + dim=self.count, + inputs=[ + state.body_q, + self._site_body, + self._site_local, + self._parent_site_body, + self._parent_site_local, + ], + outputs=[self._local_pos_buf, self._local_quat_buf], + device=self._device, + ) + return self._local_pos_ta, self._local_quat_ta + + def set_local_poses( + self, + translations: wp.array | None = None, + orientations: wp.array | None = None, + indices: wp.array | None = None, + ) -> None: + """Set parent-relative translations and/or orientations. + + Updates the internal ``site_local`` offsets so that + ``inv(parent_world) * (body_q[bid] * site_local)`` yields the desired + local pose. Does **not** modify ``body_q``. + + Args: + translations: Desired parent-relative translations ``(M, 3)``. + ``None`` leaves translations unchanged. + orientations: Desired parent-relative quaternions ``(M, 4)`` as + ``(qx, qy, qz, qw)``. ``None`` leaves orientations unchanged. + indices: Subset of sites to update. ``None`` means all sites. + """ + if translations is None and orientations is None: + return + + state = NewtonManager.get_state_0() + + if translations is None or orientations is None: + cur_pos_ta, cur_quat_ta = self.get_local_poses(indices) + if translations is None: + translations = cur_pos_ta.warp + if orientations is None: + orientations = cur_quat_ta.warp + + if indices is not None: + wp.launch( + _write_site_local_from_local_poses_indexed, + dim=len(indices), + inputs=[ + state.body_q, + self._site_body, + self._parent_site_body, + self._parent_site_local, + indices, + translations, + orientations, + self._site_local, + ], + device=self._device, + ) + else: + wp.launch( + _write_site_local_from_local_poses, + dim=self.count, + inputs=[ + state.body_q, + self._site_body, + self._parent_site_body, + self._parent_site_local, + translations, + orientations, + self._site_local, + ], + device=self._device, + ) + + # ------------------------------------------------------------------ + # Scales + # ------------------------------------------------------------------ + + def get_scales(self, indices: wp.array | None = None) -> wp.array: + """Get per-site scales by reading from the first collision shape on the same body. + + Args: + indices: Subset of sites to query. ``None`` means all sites. + + Returns: + A ``wp.array`` of shape ``(M, 3)``. + """ + model = NewtonManager.get_model() + num_shapes = model.shape_count + + if indices is not None: + n = len(indices) + out = wp.zeros(n, dtype=wp.vec3f, device=self._device) + wp.launch( + _gather_scales_indexed, + dim=n, + inputs=[model.shape_scale, model.shape_body, self._site_body, indices, num_shapes], + outputs=[out], + device=self._device, + ) + else: + out = wp.zeros(self.count, dtype=wp.vec3f, device=self._device) + wp.launch( + _gather_scales, + dim=self.count, + inputs=[model.shape_scale, model.shape_body, self._site_body, num_shapes], + outputs=[out], + device=self._device, + ) + return out + + def set_scales(self, scales: wp.array, indices: wp.array | None = None) -> None: + """Set per-site scales by writing to all collision shapes on the same body. + + Args: + scales: New scales ``(M, 3)`` as ``wp.array``. + indices: Subset of sites to update. ``None`` means all sites. + """ + model = NewtonManager.get_model() + num_shapes = model.shape_count + + if indices is not None: + wp.launch( + _scatter_scales_indexed, + dim=len(indices), + inputs=[self._site_body, indices, scales, model.shape_body, num_shapes, model.shape_scale], + device=self._device, + ) + else: + wp.launch( + _scatter_scales, + dim=self.count, + inputs=[self._site_body, scales, model.shape_body, num_shapes, model.shape_scale], + device=self._device, + ) + + +def _gf_matrix_to_xform7(mat: Gf.Matrix4d) -> list[float]: + """Convert a ``Gf.Matrix4d`` to ``[tx, ty, tz, qx, qy, qz, qw]``.""" + t = mat.ExtractTranslation() + q = mat.ExtractRotationQuat() + imag = q.GetImaginary() + return [float(t[0]), float(t[1]), float(t[2]), float(imag[0]), float(imag[1]), float(imag[2]), float(q.GetReal())] diff --git a/source/isaaclab_newton/isaaclab_newton/test/mock_interfaces/views/mock_articulation_view.py b/source/isaaclab_newton/isaaclab_newton/test/mock_interfaces/views/mock_articulation_view.py index dc698e97d223..26761937667e 100644 --- a/source/isaaclab_newton/isaaclab_newton/test/mock_interfaces/views/mock_articulation_view.py +++ b/source/isaaclab_newton/isaaclab_newton/test/mock_interfaces/views/mock_articulation_view.py @@ -49,6 +49,7 @@ def __init__( # Internal state (lazily initialised) self._root_transforms: wp.array | None = None self._root_velocities: wp.array | None = None + self._articulation_ids: wp.array | None = None self._attributes: dict[str, wp.array | None] = { "body_com": None, "body_mass": None, @@ -67,6 +68,16 @@ def count(self) -> int: def body_names(self) -> list[str]: return self._body_names + @property + def articulation_ids(self) -> wp.array: + """Mapping from ``(world, arti)`` to model articulation index. Shape ``(N, B)`` dtype=int.""" + if self._articulation_ids is None: + ids_np = np.arange(self._num_envs * self._num_bodies, dtype=np.int32).reshape( + self._num_envs, self._num_bodies + ) + self._articulation_ids = wp.array(ids_np, dtype=int, device=self._device) + return self._articulation_ids + # -- Lazy init helpers ------------------------------------------------- def _ensure_root_transforms(self) -> wp.array: @@ -222,6 +233,7 @@ def __init__( self._link_velocities: wp.array | None = None self._dof_positions: wp.array | None = None self._dof_velocities: wp.array | None = None + self._articulation_ids: wp.array | None = None # Attributes dict (lazily initialized) self._attributes: dict[str, wp.array | None] = { @@ -281,6 +293,14 @@ def link_names(self) -> list[str]: """Alias for body_names (Newton calls bodies 'links').""" return self._body_names + @property + def articulation_ids(self) -> wp.array: + """Mapping from ``(world, arti)`` to model articulation index. Shape ``(N, 1)`` dtype=int.""" + if self._articulation_ids is None: + ids_np = np.arange(self._count, dtype=np.int32).reshape(self._count, 1) + self._articulation_ids = wp.array(ids_np, dtype=int, device=self._device) + return self._articulation_ids + # -- Lazy Initialization Helpers -- def _ensure_root_transforms(self) -> wp.array: diff --git a/source/isaaclab_newton/isaaclab_newton/video_recording/__init__.py b/source/isaaclab_newton/isaaclab_newton/video_recording/__init__.py new file mode 100644 index 000000000000..1d5cb96e0ef3 --- /dev/null +++ b/source/isaaclab_newton/isaaclab_newton/video_recording/__init__.py @@ -0,0 +1,11 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Newton GL perspective video recording.""" + +from .newton_gl_perspective_video import NewtonGlPerspectiveVideo +from .newton_gl_perspective_video_cfg import NewtonGlPerspectiveVideoCfg + +__all__ = ["NewtonGlPerspectiveVideo", "NewtonGlPerspectiveVideoCfg"] diff --git a/source/isaaclab_newton/isaaclab_newton/video_recording/newton_gl_perspective_video.py b/source/isaaclab_newton/isaaclab_newton/video_recording/newton_gl_perspective_video.py new file mode 100644 index 000000000000..9c440a657981 --- /dev/null +++ b/source/isaaclab_newton/isaaclab_newton/video_recording/newton_gl_perspective_video.py @@ -0,0 +1,128 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Newton GL perspective RGB capture via headless ``newton.viewer.ViewerGL``.""" + +from __future__ import annotations + +import logging +import math +from typing import TYPE_CHECKING + +import numpy as np + +if TYPE_CHECKING: + from .newton_gl_perspective_video_cfg import NewtonGlPerspectiveVideoCfg + +logger = logging.getLogger(__name__) + + +class NewtonGlPerspectiveVideo: + """Lazy-initialised ViewerGL; one RGB frame per :meth:`render_rgb_array` call.""" + + def __init__(self, cfg: NewtonGlPerspectiveVideoCfg): + self.cfg = cfg + self._viewer = None + self._init_attempted = False + + def _ensure_viewer(self) -> None: + if self._init_attempted: + return + self._init_attempted = True + from isaaclab.sim import SimulationContext + + sdp = SimulationContext.instance().initialize_scene_data_provider() + model = sdp.get_newton_model() + if model is None: + raise RuntimeError( + "Newton GL perspective video requires a Newton model on the scene data provider. " + "Do not use --video for this setup." + ) + + import pyglet + + pyglet.options["headless"] = True + from newton.viewer import ViewerGL + + w, h = self.cfg.window_width, self.cfg.window_height + viewer = ViewerGL(width=w, height=h, headless=True) + viewer.set_model(model) + viewer.set_world_offsets((0.0, 0.0, 0.0)) + viewer.up_axis = 2 + + aspect = w / h + h_fov = math.radians(self.cfg.horiz_fov_deg) + v_fov_deg = math.degrees(2.0 * math.atan(math.tan(h_fov / 2.0) / aspect)) + viewer.camera.fov = v_fov_deg + + self._viewer = viewer + self._apply_camera(self.cfg.eye, self.cfg.lookat) + logger.info("[NewtonGlPerspectiveVideo] ViewerGL ready (%dx%d).", w, h) + + def _apply_camera( + self, + position: tuple[float, float, float], + target: tuple[float, float, float], + ) -> None: + """Point the recorder's ViewerGL at ``position`` looking toward ``target``.""" + if self._viewer is None: + return + import warp as wp + + ex, ey, ez = position + lx, ly, lz = target + dx, dy, dz = lx - ex, ly - ey, lz - ez + length = math.sqrt(dx**2 + dy**2 + dz**2) + if length > 1e-9: + dx, dy, dz = dx / length, dy / length, dz / length + pitch = math.degrees(math.asin(max(-1.0, min(1.0, dz)))) + yaw = math.degrees(math.atan2(dy, dx)) + self._viewer.set_camera(pos=wp.vec3(ex, ey, ez), pitch=pitch, yaw=yaw) + + def update_camera( + self, + position: tuple[float, float, float], + target: tuple[float, float, float], + ) -> None: + """Update the recorder camera to match ``position`` / ``target``. + + Safe to call before the first :meth:`render_rgb_array` (the viewer is + created lazily; the values will be applied immediately after creation). + When the viewer is already live the camera is repositioned in-place so + the next frame reflects the new viewpoint. + + Args: + position: Camera eye position ``(x, y, z)``. + target: Camera look-at target ``(x, y, z)``. + """ + self._ensure_viewer() + self._apply_camera(position, target) + + def render_rgb_array(self) -> np.ndarray: + """Return one RGB frame from the Newton GL viewer. Raises on failure.""" + self._ensure_viewer() + from isaaclab.sim import SimulationContext + + sim = SimulationContext.instance() + sdp = sim.initialize_scene_data_provider() + state = sdp.get_newton_state() + dt = sim.get_physics_dt() + + viewer = self._viewer + viewer.begin_frame(dt) + viewer.log_state(state) + viewer.end_frame() + return viewer.get_frame().numpy() + + +def create_newton_gl_perspective_video(cfg: NewtonGlPerspectiveVideoCfg) -> NewtonGlPerspectiveVideo: + """Instantiate the Newton GL perspective capture from ``cfg.class_type``.""" + ct = cfg.class_type + if isinstance(ct, type): + return ct(cfg) + from isaaclab.utils.string import string_to_callable + + cls = string_to_callable(str(ct)) + return cls(cfg) diff --git a/source/isaaclab_newton/isaaclab_newton/video_recording/newton_gl_perspective_video_cfg.py b/source/isaaclab_newton/isaaclab_newton/video_recording/newton_gl_perspective_video_cfg.py new file mode 100644 index 000000000000..6408b2ac0e53 --- /dev/null +++ b/source/isaaclab_newton/isaaclab_newton/video_recording/newton_gl_perspective_video_cfg.py @@ -0,0 +1,39 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Configuration for Newton GL perspective RGB capture (headless ViewerGL).""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +from isaaclab.utils import configclass + +if TYPE_CHECKING: + pass + + +@configclass +class NewtonGlPerspectiveVideoCfg: + """Settings for capturing a perspective RGB frame via ``newton.viewer.ViewerGL``.""" + + class_type: type[Any] | str = "isaaclab_newton.video_recording.newton_gl_perspective_video:NewtonGlPerspectiveVideo" + """Implementation class; default is + :class:`~isaaclab_newton.video_recording.newton_gl_perspective_video.NewtonGlPerspectiveVideo`.""" + + window_width: int = 1280 + """Viewer width in pixels.""" + + window_height: int = 720 + """Viewer height in pixels.""" + + eye: tuple[float, float, float] = (7.5, 7.5, 7.5) + """Camera position in world space (metres).""" + + lookat: tuple[float, float, float] = (0.0, 0.0, 0.0) + """Camera look-at target in world space (metres).""" + + horiz_fov_deg: float = 60.0 + """Horizontal FOV assumed for Kit ``/OmniverseKit_Persp``; converted to vertical FOV for GL viewer.""" diff --git a/source/isaaclab_newton/isaaclab_newton/video_recording/recording_hooks.py b/source/isaaclab_newton/isaaclab_newton/video_recording/recording_hooks.py new file mode 100644 index 000000000000..7efcae7b5500 --- /dev/null +++ b/source/isaaclab_newton/isaaclab_newton/video_recording/recording_hooks.py @@ -0,0 +1,30 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Hooks for Newton-based video recording after visualizers have stepped.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from isaaclab.sim import SimulationContext + + +def recording_followup_after_visualizers(sim: SimulationContext) -> None: + """Newton extension hook: recording pipeline after visualizers have stepped. + + Called from :func:`isaaclab.envs.utils.recording_hooks.run_recording_hooks_after_visualizers`. + Wire **Newton GL** / Newton-specific video capture here (e.g. perspective video, + frame sync with ``NewtonVisualizer``). Stay lightweight and no-op when Newton + recording is inactive. + + The Isaac Sim / RTX path (``omni.kit.app`` pump for Replicator ``rgb_array``) lives in + :mod:`isaaclab_physx.renderers.isaac_rtx_renderer_utils` — not here. + + Args: + sim: Active simulation context. + """ + _ = sim # Reserved until Newton GL video paths are hooked up. diff --git a/source/isaaclab_newton/setup.py b/source/isaaclab_newton/setup.py index c15812f8282a..2e0b87f17543 100644 --- a/source/isaaclab_newton/setup.py +++ b/source/isaaclab_newton/setup.py @@ -33,19 +33,15 @@ def run(self): # Read the extension.toml file EXTENSION_TOML_DATA = toml.load(os.path.join(EXTENSION_PATH, "config", "extension.toml")) -INSTALL_REQUIRES = [ - # INTENTIONALLY disabled to avoid circular dependency with isaaclab_physx, which also depends on isaaclab_newton. - # This will be re-enabled once we move to UV and pyproject.toml-based packaging. - # f"isaaclab_physx @ file://{os.path.join(os.path.dirname(EXTENSION_PATH), 'isaaclab_physx')}", -] +INSTALL_REQUIRES = [] EXTRAS_REQUIRE = { "all": [ "prettytable==3.3.0", - "mujoco==3.5.0", - "mujoco-warp==3.5.0.2", + "mujoco==3.6.0", + "mujoco-warp==3.6.0", "PyOpenGL-accelerate==3.1.10", - "newton @ git+https://github.com/newton-physics/newton.git@2684d75bfa4bb8b058a93b81c458a74b7701c997", + "newton @ git+https://github.com/newton-physics/newton.git@a27277ed49d6f307b8a1e4c394be7e1d14965a62", ], } @@ -61,7 +57,7 @@ def run(self): license="BSD-3-Clause", include_package_data=True, package_data={"": ["*.pyi"]}, - python_requires=">=3.11", + python_requires=">=3.12", install_requires=INSTALL_REQUIRES, extras_require=EXTRAS_REQUIRE, packages=[ @@ -83,10 +79,7 @@ def run(self): ], classifiers=[ "Natural Language :: English", - "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", - "Isaac Sim :: 5.0.0", - "Isaac Sim :: 5.1.0", "Isaac Sim :: 6.0.0", ], zip_safe=False, diff --git a/source/isaaclab_newton/test/assets/test_articulation.py b/source/isaaclab_newton/test/assets/test_articulation.py index 3a90bf203b37..a5eacf95045e 100644 --- a/source/isaaclab_newton/test/assets/test_articulation.py +++ b/source/isaaclab_newton/test/assets/test_articulation.py @@ -379,11 +379,11 @@ def sim(request): yield sim +@pytest.mark.isaacsim_ci @pytest.mark.parametrize("num_articulations", [1, 2]) @pytest.mark.parametrize("device", ["cuda:0", "cpu"]) @pytest.mark.parametrize("add_ground_plane", [True]) @pytest.mark.parametrize("articulation_type", ["humanoid"]) -@pytest.mark.isaacsim_ci def test_initialization_floating_base_non_root(sim, num_articulations, device, add_ground_plane, articulation_type): """Test initialization for a floating-base with articulation root on a rigid body. @@ -412,9 +412,9 @@ def test_initialization_floating_base_non_root(sim, num_articulations, device, a # Check that is fixed base assert not articulation.is_fixed_base # Check buffers that exists and have correct shapes - assert wp.to_torch(articulation.data.root_pos_w).shape == (num_articulations, 3) - assert wp.to_torch(articulation.data.root_quat_w).shape == (num_articulations, 4) - assert wp.to_torch(articulation.data.joint_pos).shape == (num_articulations, 21) + assert articulation.data.root_pos_w.torch.shape == (num_articulations, 3) + assert articulation.data.root_quat_w.torch.shape == (num_articulations, 4) + assert articulation.data.joint_pos.torch.shape == (num_articulations, 21) # -- actuator type for actuator_name, actuator in articulation.actuators.items(): @@ -429,11 +429,11 @@ def test_initialization_floating_base_non_root(sim, num_articulations, device, a articulation.update(sim.cfg.dt) +@pytest.mark.isaacsim_ci @pytest.mark.parametrize("num_articulations", [1, 2]) @pytest.mark.parametrize("device", ["cuda:0", "cpu"]) @pytest.mark.parametrize("add_ground_plane", [True]) @pytest.mark.parametrize("articulation_type", ["anymal"]) -@pytest.mark.isaacsim_ci def test_initialization_floating_base(sim, num_articulations, device, add_ground_plane, articulation_type): """Test initialization for a floating-base with articulation root on provided prim path. @@ -461,11 +461,11 @@ def test_initialization_floating_base(sim, num_articulations, device, add_ground # Check that floating base assert not articulation.is_fixed_base # Check buffers that exists and have correct shapes - assert wp.to_torch(articulation.data.root_pos_w).shape == (num_articulations, 3) - assert wp.to_torch(articulation.data.root_quat_w).shape == (num_articulations, 4) - assert wp.to_torch(articulation.data.joint_pos).shape == (num_articulations, 12) - assert wp.to_torch(articulation.data.body_mass).shape == (num_articulations, articulation.num_bodies) - assert wp.to_torch(articulation.data.body_inertia).shape == (num_articulations, articulation.num_bodies, 9) + assert articulation.data.root_pos_w.torch.shape == (num_articulations, 3) + assert articulation.data.root_quat_w.torch.shape == (num_articulations, 4) + assert articulation.data.joint_pos.torch.shape == (num_articulations, 12) + assert articulation.data.body_mass.torch.shape == (num_articulations, articulation.num_bodies) + assert articulation.data.body_inertia.torch.shape == (num_articulations, articulation.num_bodies, 9) # -- actuator type for actuator_name, actuator in articulation.actuators.items(): @@ -480,10 +480,10 @@ def test_initialization_floating_base(sim, num_articulations, device, add_ground articulation.update(sim.cfg.dt) +@pytest.mark.isaacsim_ci @pytest.mark.parametrize("num_articulations", [1, 2]) @pytest.mark.parametrize("device", ["cuda:0", "cpu"]) @pytest.mark.parametrize("articulation_type", ["panda"]) -@pytest.mark.isaacsim_ci def test_initialization_fixed_base(sim, num_articulations, device, articulation_type): """Test initialization for fixed base. @@ -511,11 +511,11 @@ def test_initialization_fixed_base(sim, num_articulations, device, articulation_ # Check that fixed base assert articulation.is_fixed_base # Check buffers that exists and have correct shapes - assert wp.to_torch(articulation.data.root_pos_w).shape == (num_articulations, 3) - assert wp.to_torch(articulation.data.root_quat_w).shape == (num_articulations, 4) - assert wp.to_torch(articulation.data.joint_pos).shape == (num_articulations, 9) - assert wp.to_torch(articulation.data.body_mass).shape == (num_articulations, articulation.num_bodies) - assert wp.to_torch(articulation.data.body_inertia).shape == (num_articulations, articulation.num_bodies, 9) + assert articulation.data.root_pos_w.torch.shape == (num_articulations, 3) + assert articulation.data.root_quat_w.torch.shape == (num_articulations, 4) + assert articulation.data.joint_pos.torch.shape == (num_articulations, 9) + assert articulation.data.body_mass.torch.shape == (num_articulations, articulation.num_bodies) + assert articulation.data.body_inertia.torch.shape == (num_articulations, articulation.num_bodies, 9) # -- actuator type for actuator_name, actuator in articulation.actuators.items(): @@ -530,19 +530,19 @@ def test_initialization_fixed_base(sim, num_articulations, device, articulation_ articulation.update(sim.cfg.dt) # check that the root is at the correct state - its default state as it is fixed base - default_root_pose = wp.to_torch(articulation.data.default_root_pose).clone() - default_root_vel = wp.to_torch(articulation.data.default_root_vel).clone() + default_root_pose = articulation.data.default_root_pose.torch.clone() + default_root_vel = articulation.data.default_root_vel.torch.clone() default_root_pose[:, :3] = default_root_pose[:, :3] + translations - torch.testing.assert_close(wp.to_torch(articulation.data.root_link_pose_w), default_root_pose) - torch.testing.assert_close(wp.to_torch(articulation.data.root_com_vel_w), default_root_vel) + torch.testing.assert_close(articulation.data.root_link_pose_w.torch, default_root_pose) + torch.testing.assert_close(articulation.data.root_com_vel_w.torch, default_root_vel) +@pytest.mark.isaacsim_ci @pytest.mark.parametrize("num_articulations", [1, 2]) @pytest.mark.parametrize("device", ["cuda:0", "cpu"]) @pytest.mark.parametrize("add_ground_plane", [True]) @pytest.mark.parametrize("articulation_type", ["single_joint_implicit"]) -@pytest.mark.isaacsim_ci def test_initialization_fixed_base_single_joint(sim, num_articulations, device, add_ground_plane, articulation_type): """Test initialization for fixed base articulation with a single joint. @@ -570,11 +570,11 @@ def test_initialization_fixed_base_single_joint(sim, num_articulations, device, # Check that fixed base assert articulation.is_fixed_base # Check buffers that exists and have correct shapes - assert wp.to_torch(articulation.data.root_pos_w).shape == (num_articulations, 3) - assert wp.to_torch(articulation.data.root_quat_w).shape == (num_articulations, 4) - assert wp.to_torch(articulation.data.joint_pos).shape == (num_articulations, 1) - assert wp.to_torch(articulation.data.body_mass).shape == (num_articulations, articulation.num_bodies) - assert wp.to_torch(articulation.data.body_inertia).shape == (num_articulations, articulation.num_bodies, 9) + assert articulation.data.root_pos_w.torch.shape == (num_articulations, 3) + assert articulation.data.root_quat_w.torch.shape == (num_articulations, 4) + assert articulation.data.joint_pos.torch.shape == (num_articulations, 1) + assert articulation.data.body_mass.torch.shape == (num_articulations, articulation.num_bodies) + assert articulation.data.body_inertia.torch.shape == (num_articulations, articulation.num_bodies, 9) # -- actuator type for actuator_name, actuator in articulation.actuators.items(): @@ -589,18 +589,18 @@ def test_initialization_fixed_base_single_joint(sim, num_articulations, device, articulation.update(sim.cfg.dt) # check that the root is at the correct state - its default state as it is fixed base - default_root_pose = wp.to_torch(articulation.data.default_root_pose).clone() - default_root_vel = wp.to_torch(articulation.data.default_root_vel).clone() + default_root_pose = articulation.data.default_root_pose.torch.clone() + default_root_vel = articulation.data.default_root_vel.torch.clone() default_root_pose[:, :3] = default_root_pose[:, :3] + translations - torch.testing.assert_close(wp.to_torch(articulation.data.root_link_pose_w), default_root_pose) - torch.testing.assert_close(wp.to_torch(articulation.data.root_com_vel_w), default_root_vel) + torch.testing.assert_close(articulation.data.root_link_pose_w.torch, default_root_pose) + torch.testing.assert_close(articulation.data.root_com_vel_w.torch, default_root_vel) +@pytest.mark.isaacsim_ci @pytest.mark.parametrize("num_articulations", [1, 2]) @pytest.mark.parametrize("device", ["cuda:0", "cpu"]) @pytest.mark.parametrize("articulation_type", ["shadow_hand"]) -@pytest.mark.isaacsim_ci def test_initialization_hand_with_tendons(sim, num_articulations, device, articulation_type): """Test initialization for fixed base articulated hand with tendons. @@ -628,11 +628,11 @@ def test_initialization_hand_with_tendons(sim, num_articulations, device, articu # Check that fixed base assert articulation.is_fixed_base # Check buffers that exists and have correct shapes - assert wp.to_torch(articulation.data.root_pos_w).shape == (num_articulations, 3) - assert wp.to_torch(articulation.data.root_quat_w).shape == (num_articulations, 4) - assert wp.to_torch(articulation.data.joint_pos).shape == (num_articulations, 24) - assert wp.to_torch(articulation.data.body_mass).shape == (num_articulations, articulation.num_bodies) - assert wp.to_torch(articulation.data.body_inertia).shape == (num_articulations, articulation.num_bodies, 9) + assert articulation.data.root_pos_w.torch.shape == (num_articulations, 3) + assert articulation.data.root_quat_w.torch.shape == (num_articulations, 4) + assert articulation.data.joint_pos.torch.shape == (num_articulations, 24) + assert articulation.data.body_mass.torch.shape == (num_articulations, articulation.num_bodies) + assert articulation.data.body_inertia.torch.shape == (num_articulations, articulation.num_bodies, 9) # -- actuator type for actuator_name, actuator in articulation.actuators.items(): @@ -647,11 +647,11 @@ def test_initialization_hand_with_tendons(sim, num_articulations, device, articu articulation.update(sim.cfg.dt) +@pytest.mark.isaacsim_ci @pytest.mark.parametrize("num_articulations", [1, 2]) @pytest.mark.parametrize("device", ["cuda:0", "cpu"]) @pytest.mark.parametrize("add_ground_plane", [True]) @pytest.mark.parametrize("articulation_type", ["anymal"]) -@pytest.mark.isaacsim_ci def test_initialization_floating_base_made_fixed_base( sim, num_articulations, device, add_ground_plane, articulation_type ): @@ -682,9 +682,9 @@ def test_initialization_floating_base_made_fixed_base( # Check that is fixed base assert articulation.is_fixed_base # Check buffers that exists and have correct shapes - assert wp.to_torch(articulation.data.root_pos_w).shape == (num_articulations, 3) - assert wp.to_torch(articulation.data.root_quat_w).shape == (num_articulations, 4) - assert wp.to_torch(articulation.data.joint_pos).shape == (num_articulations, 12) + assert articulation.data.root_pos_w.torch.shape == (num_articulations, 3) + assert articulation.data.root_quat_w.torch.shape == (num_articulations, 4) + assert articulation.data.joint_pos.torch.shape == (num_articulations, 12) # Simulate physics for _ in range(10): @@ -694,19 +694,19 @@ def test_initialization_floating_base_made_fixed_base( articulation.update(sim.cfg.dt) # check that the root is at the correct state - its default state as it is fixed base - default_root_pose = wp.to_torch(articulation.data.default_root_pose).clone() - default_root_vel = wp.to_torch(articulation.data.default_root_vel).clone() + default_root_pose = articulation.data.default_root_pose.torch.clone() + default_root_vel = articulation.data.default_root_vel.torch.clone() default_root_pose[:, :3] = default_root_pose[:, :3] + translations - torch.testing.assert_close(wp.to_torch(articulation.data.root_link_pose_w), default_root_pose) - torch.testing.assert_close(wp.to_torch(articulation.data.root_com_vel_w), default_root_vel) + torch.testing.assert_close(articulation.data.root_link_pose_w.torch, default_root_pose) + torch.testing.assert_close(articulation.data.root_com_vel_w.torch, default_root_vel) +@pytest.mark.isaacsim_ci @pytest.mark.parametrize("num_articulations", [1, 2]) @pytest.mark.parametrize("device", ["cuda:0", "cpu"]) @pytest.mark.parametrize("add_ground_plane", [True]) @pytest.mark.parametrize("articulation_type", ["panda"]) -@pytest.mark.isaacsim_ci def test_initialization_fixed_base_made_floating_base( sim, num_articulations, device, add_ground_plane, articulation_type ): @@ -737,9 +737,9 @@ def test_initialization_fixed_base_made_floating_base( # Check that is floating base assert not articulation.is_fixed_base # Check buffers that exists and have correct shapes - assert wp.to_torch(articulation.data.root_pos_w).shape == (num_articulations, 3) - assert wp.to_torch(articulation.data.root_quat_w).shape == (num_articulations, 4) - assert wp.to_torch(articulation.data.joint_pos).shape == (num_articulations, 9) + assert articulation.data.root_pos_w.torch.shape == (num_articulations, 3) + assert articulation.data.root_quat_w.torch.shape == (num_articulations, 4) + assert articulation.data.joint_pos.torch.shape == (num_articulations, 9) # Simulate physics for _ in range(10): @@ -749,11 +749,11 @@ def test_initialization_fixed_base_made_floating_base( articulation.update(sim.cfg.dt) +@pytest.mark.isaacsim_ci @pytest.mark.parametrize("num_articulations", [1, 2]) @pytest.mark.parametrize("device", ["cuda:0", "cpu"]) @pytest.mark.parametrize("add_ground_plane", [True]) @pytest.mark.parametrize("articulation_type", ["panda"]) -@pytest.mark.isaacsim_ci def test_out_of_range_default_joint_pos(sim, num_articulations, device, add_ground_plane, articulation_type): """Test that the default joint position from configuration is out of range. @@ -782,9 +782,9 @@ def test_out_of_range_default_joint_pos(sim, num_articulations, device, add_grou sim.reset() +@pytest.mark.isaacsim_ci @pytest.mark.parametrize("device", ["cuda:0", "cpu"]) @pytest.mark.parametrize("articulation_type", ["panda"]) -@pytest.mark.isaacsim_ci def test_out_of_range_default_joint_vel(sim, device, articulation_type): """Test that the default joint velocity from configuration is out of range. @@ -807,11 +807,11 @@ def test_out_of_range_default_joint_vel(sim, device, articulation_type): sim.reset() +@pytest.mark.isaacsim_ci @pytest.mark.parametrize("num_articulations", [1, 2]) @pytest.mark.parametrize("device", ["cuda:0", "cpu"]) @pytest.mark.parametrize("add_ground_plane", [True]) @pytest.mark.parametrize("articulation_type", ["panda"]) -@pytest.mark.isaacsim_ci def test_joint_pos_limits(sim, num_articulations, device, add_ground_plane, articulation_type): """Test write_joint_limits_to_sim API and when default pos falls outside of the new limits. @@ -835,7 +835,7 @@ def test_joint_pos_limits(sim, num_articulations, device, add_ground_plane, arti assert articulation.is_initialized # Get current default joint pos - default_joint_pos = wp.to_torch(articulation._data.default_joint_pos).clone() + default_joint_pos = articulation._data.default_joint_pos.torch.clone() # Set new joint limits limits = torch.zeros(num_articulations, articulation.num_joints, 2, device=device) @@ -844,8 +844,8 @@ def test_joint_pos_limits(sim, num_articulations, device, add_ground_plane, arti articulation.write_joint_position_limit_to_sim_index(limits=limits) # Check new limits are in place - torch.testing.assert_close(wp.to_torch(articulation._data.joint_pos_limits), limits) - torch.testing.assert_close(wp.to_torch(articulation._data.default_joint_pos), default_joint_pos) + torch.testing.assert_close(articulation._data.joint_pos_limits.torch, limits) + torch.testing.assert_close(articulation._data.default_joint_pos.torch, default_joint_pos) # Set new joint limits with indexing env_ids = torch.arange(1, device=device, dtype=torch.int32) @@ -856,8 +856,8 @@ def test_joint_pos_limits(sim, num_articulations, device, add_ground_plane, arti articulation.write_joint_position_limit_to_sim_index(limits=limits, env_ids=env_ids, joint_ids=joint_ids) # Check new limits are in place - torch.testing.assert_close(wp.to_torch(articulation._data.joint_pos_limits)[env_ids][:, joint_ids], limits) - torch.testing.assert_close(wp.to_torch(articulation._data.default_joint_pos), default_joint_pos) + torch.testing.assert_close(articulation._data.joint_pos_limits.torch[env_ids][:, joint_ids], limits) + torch.testing.assert_close(articulation._data.default_joint_pos.torch, default_joint_pos) # Set new joint limits that invalidate default joint pos limits = torch.zeros(num_articulations, articulation.num_joints, 2, device=device) @@ -866,7 +866,7 @@ def test_joint_pos_limits(sim, num_articulations, device, add_ground_plane, arti articulation.write_joint_position_limit_to_sim_index(limits=limits) # Check if all values are within the bounds - default_joint_pos_torch = wp.to_torch(articulation._data.default_joint_pos) + default_joint_pos_torch = articulation._data.default_joint_pos.torch within_bounds = (default_joint_pos_torch >= limits[..., 0]) & (default_joint_pos_torch <= limits[..., 1]) assert torch.all(within_bounds) @@ -877,7 +877,7 @@ def test_joint_pos_limits(sim, num_articulations, device, add_ground_plane, arti articulation.write_joint_position_limit_to_sim_index(limits=limits, env_ids=env_ids, joint_ids=joint_ids) # Check if all values are within the bounds - default_joint_pos_torch = wp.to_torch(articulation._data.default_joint_pos) + default_joint_pos_torch = articulation._data.default_joint_pos.torch within_bounds = (default_joint_pos_torch[env_ids][:, joint_ids] >= limits[..., 0]) & ( default_joint_pos_torch[env_ids][:, joint_ids] <= limits[..., 1] ) @@ -888,7 +888,6 @@ def test_joint_pos_limits(sim, num_articulations, device, add_ground_plane, arti @pytest.mark.parametrize("device", ["cuda:0", "cpu"]) @pytest.mark.parametrize("add_ground_plane", [True]) @pytest.mark.parametrize("articulation_type", ["panda"]) -@pytest.mark.isaacsim_ci def test_joint_effort_limits(sim, num_articulations, device, add_ground_plane, articulation_type): """Validate joint effort limits via joint_effort_out_of_limit().""" # Create articulation @@ -907,22 +906,22 @@ def __init__(self, art): assert articulation.is_initialized # Case A: no clipping → should NOT terminate - wp.to_torch(articulation._data.computed_torque).zero_() - wp.to_torch(articulation._data.applied_torque).zero_() + articulation._data.computed_torque.torch.zero_() + articulation._data.applied_torque.torch.zero_() out = joint_effort_out_of_limit(env, robot_all) # [N] assert torch.all(~out) # Case B: simulate clipping → should terminate - wp.to_torch(articulation._data.computed_torque).fill_(100.0) # pretend controller commanded 100 - wp.to_torch(articulation._data.applied_torque).fill_(50.0) # pretend actuator clipped to 50 + articulation._data.computed_torque.torch.fill_(100.0) # pretend controller commanded 100 + articulation._data.applied_torque.torch.fill_(50.0) # pretend actuator clipped to 50 out = joint_effort_out_of_limit(env, robot_all) # [N] assert torch.all(out) +@pytest.mark.isaacsim_ci @pytest.mark.parametrize("num_articulations", [1, 2]) @pytest.mark.parametrize("device", ["cuda:0", "cpu"]) @pytest.mark.parametrize("articulation_type", ["anymal"]) -@pytest.mark.isaacsim_ci def test_external_force_buffer(sim, num_articulations, device, articulation_type): """Test if external force buffer correctly updates in the force value is zero case. @@ -945,13 +944,13 @@ def test_external_force_buffer(sim, num_articulations, device, articulation_type body_ids, _ = articulation.find_bodies("base") # reset root state - articulation.write_root_pose_to_sim_index(root_pose=wp.to_torch(articulation.data.default_root_pose).clone()) - articulation.write_root_velocity_to_sim_index(root_velocity=wp.to_torch(articulation.data.default_root_vel).clone()) + articulation.write_root_pose_to_sim_index(root_pose=articulation.data.default_root_pose.torch.clone()) + articulation.write_root_velocity_to_sim_index(root_velocity=articulation.data.default_root_vel.torch.clone()) # reset dof state joint_pos, joint_vel = ( - wp.to_torch(articulation.data.default_joint_pos), - wp.to_torch(articulation.data.default_joint_vel), + articulation.data.default_joint_pos.torch, + articulation.data.default_joint_vel.torch, ) articulation.write_joint_position_to_sim_index(position=joint_pos) articulation.write_joint_velocity_to_sim_index(velocity=joint_vel) @@ -984,8 +983,8 @@ def test_external_force_buffer(sim, num_articulations, device, articulation_type # check if the articulation's force and torque buffers are correctly updated for i in range(num_articulations): - assert wp.to_torch(articulation.permanent_wrench_composer.composed_force)[i, 0, 0].item() == force - assert wp.to_torch(articulation.permanent_wrench_composer.composed_torque)[i, 0, 0].item() == force + assert articulation.permanent_wrench_composer.composed_force.torch[i, 0, 0].item() == force + assert articulation.permanent_wrench_composer.composed_torque.torch[i, 0, 0].item() == force # Check if the instantaneous wrench is correctly added to the permanent wrench articulation.instantaneous_wrench_composer.add_forces_and_torques_index( @@ -995,7 +994,7 @@ def test_external_force_buffer(sim, num_articulations, device, articulation_type ) # apply action to the articulation - articulation.set_joint_position_target_index(target=wp.to_torch(articulation.data.default_joint_pos).clone()) + articulation.set_joint_position_target_index(target=articulation.data.default_joint_pos.torch.clone()) articulation.write_data_to_sim() # perform step @@ -1005,10 +1004,10 @@ def test_external_force_buffer(sim, num_articulations, device, articulation_type articulation.update(sim.cfg.dt) +@pytest.mark.isaacsim_ci @pytest.mark.parametrize("num_articulations", [1, 2]) @pytest.mark.parametrize("device", ["cuda:0", "cpu"]) @pytest.mark.parametrize("articulation_type", ["anymal"]) -@pytest.mark.isaacsim_ci def test_external_force_on_single_body(sim, num_articulations, device, articulation_type): """Test application of external force on the base of the articulation. @@ -1035,14 +1034,12 @@ def test_external_force_on_single_body(sim, num_articulations, device, articulat # Now we are ready! for _ in range(5): # reset root state - articulation.write_root_pose_to_sim_index(root_pose=wp.to_torch(articulation.data.default_root_pose).clone()) - articulation.write_root_velocity_to_sim_index( - root_velocity=wp.to_torch(articulation.data.default_root_vel).clone() - ) + articulation.write_root_pose_to_sim_index(root_pose=articulation.data.default_root_pose.torch.clone()) + articulation.write_root_velocity_to_sim_index(root_velocity=articulation.data.default_root_vel.torch.clone()) # reset dof state joint_pos, joint_vel = ( - wp.to_torch(articulation.data.default_joint_pos), - wp.to_torch(articulation.data.default_joint_vel), + articulation.data.default_joint_pos.torch, + articulation.data.default_joint_vel.torch, ) articulation.write_joint_position_to_sim_index(position=joint_pos) articulation.write_joint_velocity_to_sim_index(velocity=joint_vel) @@ -1055,9 +1052,7 @@ def test_external_force_on_single_body(sim, num_articulations, device, articulat # perform simulation for _ in range(100): # apply action to the articulation - articulation.set_joint_position_target_index( - target=wp.to_torch(articulation.data.default_joint_pos).clone() - ) + articulation.set_joint_position_target_index(target=articulation.data.default_joint_pos.torch.clone()) articulation.write_data_to_sim() # perform step sim.step() @@ -1065,13 +1060,13 @@ def test_external_force_on_single_body(sim, num_articulations, device, articulat articulation.update(sim.cfg.dt) # check condition that the articulations have fallen down for i in range(num_articulations): - assert wp.to_torch(articulation.data.root_pos_w)[i, 2].item() < 0.2 + assert articulation.data.root_pos_w.torch[i, 2].item() < 0.2 +@pytest.mark.isaacsim_ci @pytest.mark.parametrize("num_articulations", [1, 2]) @pytest.mark.parametrize("device", ["cuda:0", "cpu"]) @pytest.mark.parametrize("articulation_type", ["anymal"]) -@pytest.mark.isaacsim_ci def test_external_force_on_single_body_at_position(sim, num_articulations, device, articulation_type): """Test application of external force on the base of the articulation at a given position. @@ -1107,17 +1102,15 @@ def test_external_force_on_single_body_at_position(sim, num_articulations, devic # Now we are ready! for i in range(5): # reset root state - root_pose = wp.to_torch(articulation.data.default_root_pose).clone() + root_pose = articulation.data.default_root_pose.torch.clone() root_pose[0, 0] = 2.5 # space them apart by 2.5m articulation.write_root_pose_to_sim_index(root_pose=root_pose) - articulation.write_root_velocity_to_sim_index( - root_velocity=wp.to_torch(articulation.data.default_root_vel).clone() - ) + articulation.write_root_velocity_to_sim_index(root_velocity=articulation.data.default_root_vel.torch.clone()) # reset dof state joint_pos, joint_vel = ( - wp.to_torch(articulation.data.default_joint_pos), - wp.to_torch(articulation.data.default_joint_vel), + articulation.data.default_joint_pos.torch, + articulation.data.default_joint_vel.torch, ) articulation.write_joint_position_to_sim_index(position=joint_pos) articulation.write_joint_velocity_to_sim_index(velocity=joint_vel) @@ -1127,7 +1120,7 @@ def test_external_force_on_single_body_at_position(sim, num_articulations, devic is_global = False if i % 2 == 0: - body_com_pos_w = wp.to_torch(articulation.data.body_com_pos_w)[:, body_ids, :3] + body_com_pos_w = articulation.data.body_com_pos_w.torch[:, body_ids, :3] # is_global = True external_wrench_positions_b[..., 0] = 0.0 external_wrench_positions_b[..., 1] = 1.0 @@ -1155,9 +1148,7 @@ def test_external_force_on_single_body_at_position(sim, num_articulations, devic # perform simulation for _ in range(100): # apply action to the articulation - articulation.set_joint_position_target_index( - target=wp.to_torch(articulation.data.default_joint_pos).clone() - ) + articulation.set_joint_position_target_index(target=articulation.data.default_joint_pos.torch.clone()) articulation.write_data_to_sim() # perform step sim.step() @@ -1165,13 +1156,13 @@ def test_external_force_on_single_body_at_position(sim, num_articulations, devic articulation.update(sim.cfg.dt) # check condition that the articulations have fallen down for i in range(num_articulations): - assert wp.to_torch(articulation.data.root_pos_w)[i, 2].item() < 0.2 + assert articulation.data.root_pos_w.torch[i, 2].item() < 0.2 +@pytest.mark.isaacsim_ci @pytest.mark.parametrize("num_articulations", [1, 2]) @pytest.mark.parametrize("device", ["cuda:0", "cpu"]) @pytest.mark.parametrize("articulation_type", ["anymal"]) -@pytest.mark.isaacsim_ci def test_external_force_on_multiple_bodies(sim, num_articulations, device, articulation_type): """Test application of external force on the legs of the articulation. @@ -1199,14 +1190,12 @@ def test_external_force_on_multiple_bodies(sim, num_articulations, device, artic # Now we are ready! for _ in range(5): # reset root state - articulation.write_root_pose_to_sim_index(root_pose=wp.to_torch(articulation.data.default_root_pose).clone()) - articulation.write_root_velocity_to_sim_index( - root_velocity=wp.to_torch(articulation.data.default_root_vel).clone() - ) + articulation.write_root_pose_to_sim_index(root_pose=articulation.data.default_root_pose.torch.clone()) + articulation.write_root_velocity_to_sim_index(root_velocity=articulation.data.default_root_vel.torch.clone()) # reset dof state joint_pos, joint_vel = ( - wp.to_torch(articulation.data.default_joint_pos), - wp.to_torch(articulation.data.default_joint_vel), + articulation.data.default_joint_pos.torch, + articulation.data.default_joint_vel.torch, ) articulation.write_joint_position_to_sim_index(position=joint_pos) articulation.write_joint_velocity_to_sim_index(velocity=joint_vel) @@ -1219,9 +1208,7 @@ def test_external_force_on_multiple_bodies(sim, num_articulations, device, artic # perform simulation for _ in range(100): # apply action to the articulation - articulation.set_joint_position_target_index( - target=wp.to_torch(articulation.data.default_joint_pos).clone() - ) + articulation.set_joint_position_target_index(target=articulation.data.default_joint_pos.torch.clone()) articulation.write_data_to_sim() # perform step sim.step() @@ -1230,13 +1217,13 @@ def test_external_force_on_multiple_bodies(sim, num_articulations, device, artic # check condition for i in range(num_articulations): # since there is a moment applied on the articulation, the articulation should rotate - assert wp.to_torch(articulation.data.root_ang_vel_w)[i, 2].item() > 0.1 + assert articulation.data.root_ang_vel_w.torch[i, 2].item() > 0.1 +@pytest.mark.isaacsim_ci @pytest.mark.parametrize("num_articulations", [1, 2]) @pytest.mark.parametrize("device", ["cuda:0", "cpu"]) @pytest.mark.parametrize("articulation_type", ["anymal"]) -@pytest.mark.isaacsim_ci def test_external_force_on_multiple_bodies_at_position(sim, num_articulations, device, articulation_type): """Test application of external force on the legs of the articulation at a given position. @@ -1273,14 +1260,12 @@ def test_external_force_on_multiple_bodies_at_position(sim, num_articulations, d # Now we are ready! for i in range(5): # reset root state - articulation.write_root_pose_to_sim_index(root_pose=wp.to_torch(articulation.data.default_root_pose).clone()) - articulation.write_root_velocity_to_sim_index( - root_velocity=wp.to_torch(articulation.data.default_root_vel).clone() - ) + articulation.write_root_pose_to_sim_index(root_pose=articulation.data.default_root_pose.torch.clone()) + articulation.write_root_velocity_to_sim_index(root_velocity=articulation.data.default_root_vel.torch.clone()) # reset dof state joint_pos, joint_vel = ( - wp.to_torch(articulation.data.default_joint_pos), - wp.to_torch(articulation.data.default_joint_vel), + articulation.data.default_joint_pos.torch, + articulation.data.default_joint_vel.torch, ) articulation.write_joint_position_to_sim_index(position=joint_pos) articulation.write_joint_velocity_to_sim_index(velocity=joint_vel) @@ -1289,7 +1274,7 @@ def test_external_force_on_multiple_bodies_at_position(sim, num_articulations, d is_global = False if i % 2 == 0: - body_com_pos_w = wp.to_torch(articulation.data.body_com_pos_w)[:, body_ids, :3] + body_com_pos_w = articulation.data.body_com_pos_w.torch[:, body_ids, :3] is_global = True external_wrench_positions_b[..., 0] = 0.0 external_wrench_positions_b[..., 1] = 1.0 @@ -1318,9 +1303,7 @@ def test_external_force_on_multiple_bodies_at_position(sim, num_articulations, d # perform simulation for _ in range(100): # apply action to the articulation - articulation.set_joint_position_target_index( - target=wp.to_torch(articulation.data.default_joint_pos).clone() - ) + articulation.set_joint_position_target_index(target=articulation.data.default_joint_pos.torch.clone()) articulation.write_data_to_sim() # perform step sim.step() @@ -1329,13 +1312,13 @@ def test_external_force_on_multiple_bodies_at_position(sim, num_articulations, d # check condition for i in range(num_articulations): # since there is a moment applied on the articulation, the articulation should rotate - assert torch.abs(wp.to_torch(articulation.data.root_ang_vel_w)[i, 2]).item() > 0.1 + assert torch.abs(articulation.data.root_ang_vel_w.torch[i, 2]).item() > 0.1 +@pytest.mark.isaacsim_ci @pytest.mark.parametrize("num_articulations", [1, 2]) @pytest.mark.parametrize("device", ["cuda:0", "cpu"]) @pytest.mark.parametrize("articulation_type", ["humanoid"]) -@pytest.mark.isaacsim_ci def test_loading_gains_from_usd(sim, num_articulations, device, articulation_type): """Test that gains are loaded from USD file if actuator model has them as None. @@ -1395,11 +1378,11 @@ def test_loading_gains_from_usd(sim, num_articulations, device, articulation_typ torch.testing.assert_close(articulation.actuators["body"].damping, expected_damping) +@pytest.mark.isaacsim_ci @pytest.mark.parametrize("num_articulations", [1, 2]) @pytest.mark.parametrize("device", ["cuda:0", "cpu"]) @pytest.mark.parametrize("add_ground_plane", [True]) @pytest.mark.parametrize("articulation_type", ["humanoid"]) -@pytest.mark.isaacsim_ci def test_setting_gains_from_cfg(sim, num_articulations, device, add_ground_plane, articulation_type): """Test that gains are loaded from the configuration correctly. @@ -1431,10 +1414,10 @@ def test_setting_gains_from_cfg(sim, num_articulations, device, add_ground_plane torch.testing.assert_close(articulation.actuators["body"].damping, expected_damping) +@pytest.mark.isaacsim_ci @pytest.mark.parametrize("num_articulations", [1, 2]) @pytest.mark.parametrize("device", ["cuda:0", "cpu"]) @pytest.mark.parametrize("articulation_type", ["humanoid"]) -@pytest.mark.isaacsim_ci def test_setting_gains_from_cfg_dict(sim, num_articulations, device, articulation_type): """Test that gains are loaded from the configuration dictionary correctly. @@ -1465,13 +1448,13 @@ def test_setting_gains_from_cfg_dict(sim, num_articulations, device, articulatio torch.testing.assert_close(articulation.actuators["body"].damping, expected_damping) +@pytest.mark.isaacsim_ci @pytest.mark.parametrize("num_articulations", [1, 2]) @pytest.mark.parametrize("device", ["cuda:0", "cpu"]) @pytest.mark.parametrize("vel_limit_sim", [1e5, None]) @pytest.mark.parametrize("vel_limit", [1e2, None]) @pytest.mark.parametrize("add_ground_plane", [False]) @pytest.mark.parametrize("articulation_type", ["single_joint_implicit"]) -@pytest.mark.isaacsim_ci def test_setting_velocity_limit_implicit( sim, num_articulations, device, vel_limit_sim, vel_limit, add_ground_plane, articulation_type ): @@ -1512,7 +1495,7 @@ def test_setting_velocity_limit_implicit( articulation.root_view.get_attribute("joint_velocity_limit", SimulationManager.get_model()) ).to(device)[:, 0, :] # check data buffer - torch.testing.assert_close(wp.to_torch(articulation.data.joint_velocity_limits), newton_vel_limit) + torch.testing.assert_close(articulation.data.joint_velocity_limits.torch, newton_vel_limit) # check actuator has simulation velocity limit torch.testing.assert_close(articulation.actuators["joint"].velocity_limit_sim, newton_vel_limit) # check that both values match for velocity limit @@ -1538,12 +1521,12 @@ def test_setting_velocity_limit_implicit( torch.testing.assert_close(newton_vel_limit, expected_velocity_limit) +@pytest.mark.isaacsim_ci @pytest.mark.parametrize("num_articulations", [1, 2]) @pytest.mark.parametrize("device", ["cuda:0", "cpu"]) @pytest.mark.parametrize("vel_limit_sim", [1e5, None]) @pytest.mark.parametrize("vel_limit", [1e2, None]) @pytest.mark.parametrize("articulation_type", ["single_joint_explicit"]) -@pytest.mark.isaacsim_ci def test_setting_velocity_limit_explicit(sim, num_articulations, device, vel_limit_sim, vel_limit, articulation_type): """Test setting of velocity limit for explicit actuators.""" articulation_cfg = generate_articulation_cfg( @@ -1567,7 +1550,7 @@ def test_setting_velocity_limit_explicit(sim, num_articulations, device, vel_lim actuator_vel_limit_sim = articulation.actuators["joint"].velocity_limit_sim # check data buffer for joint_velocity_limits_sim - torch.testing.assert_close(wp.to_torch(articulation.data.joint_velocity_limits), newton_vel_limit) + torch.testing.assert_close(articulation.data.joint_velocity_limits.torch, newton_vel_limit) # check actuator velocity_limit_sim is set to physx torch.testing.assert_close(actuator_vel_limit_sim, newton_vel_limit) @@ -1595,12 +1578,12 @@ def test_setting_velocity_limit_explicit(sim, num_articulations, device, vel_lim torch.testing.assert_close(newton_vel_limit, expected_vel_limit) +@pytest.mark.isaacsim_ci @pytest.mark.parametrize("num_articulations", [1, 2]) @pytest.mark.parametrize("device", ["cuda:0", "cpu"]) @pytest.mark.parametrize("effort_limit_sim", [1e5, None]) @pytest.mark.parametrize("effort_limit", [1e2, 80.0, None]) @pytest.mark.parametrize("articulation_type", ["single_joint_implicit"]) -@pytest.mark.isaacsim_ci def test_setting_effort_limit_implicit( sim, num_articulations, device, effort_limit_sim, effort_limit, articulation_type ): @@ -1653,12 +1636,12 @@ def test_setting_effort_limit_implicit( torch.testing.assert_close(newton_effort_limit, expected_effort_limit) +@pytest.mark.isaacsim_ci @pytest.mark.parametrize("num_articulations", [1, 2]) @pytest.mark.parametrize("device", ["cuda:0", "cpu"]) @pytest.mark.parametrize("effort_limit_sim", [1e5, None]) @pytest.mark.parametrize("effort_limit", [80.0, 1e2, None]) @pytest.mark.parametrize("articulation_type", ["single_joint_explicit"]) -@pytest.mark.isaacsim_ci def test_setting_effort_limit_explicit( sim, num_articulations, device, effort_limit_sim, effort_limit, articulation_type ): @@ -1720,10 +1703,10 @@ def test_setting_effort_limit_explicit( torch.testing.assert_close(newton_effort_limit, expected_effort_limit) +@pytest.mark.isaacsim_ci @pytest.mark.parametrize("num_articulations", [1, 2]) @pytest.mark.parametrize("device", ["cuda:0", "cpu"]) @pytest.mark.parametrize("articulation_type", ["humanoid"]) -@pytest.mark.isaacsim_ci def test_reset(sim, num_articulations, device, articulation_type): """Test that reset method works properly.""" articulation_cfg = generate_articulation_cfg(articulation_type=articulation_type) @@ -1741,10 +1724,10 @@ def test_reset(sim, num_articulations, device, articulation_type): # Reset should zero external forces and torques assert not articulation._instantaneous_wrench_composer.active assert not articulation._permanent_wrench_composer.active - assert torch.count_nonzero(wp.to_torch(articulation._instantaneous_wrench_composer.composed_force)) == 0 - assert torch.count_nonzero(wp.to_torch(articulation._instantaneous_wrench_composer.composed_torque)) == 0 - assert torch.count_nonzero(wp.to_torch(articulation._permanent_wrench_composer.composed_force)) == 0 - assert torch.count_nonzero(wp.to_torch(articulation._permanent_wrench_composer.composed_torque)) == 0 + assert torch.count_nonzero(articulation._instantaneous_wrench_composer.composed_force.torch) == 0 + assert torch.count_nonzero(articulation._instantaneous_wrench_composer.composed_torque.torch) == 0 + assert torch.count_nonzero(articulation._permanent_wrench_composer.composed_force.torch) == 0 + assert torch.count_nonzero(articulation._permanent_wrench_composer.composed_torque.torch) == 0 if num_articulations > 1: num_bodies = articulation.num_bodies @@ -1759,27 +1742,17 @@ def test_reset(sim, num_articulations, device, articulation_type): articulation.reset(env_ids=torch.tensor([0], device=device)) assert articulation._instantaneous_wrench_composer.active assert articulation._permanent_wrench_composer.active - assert ( - torch.count_nonzero(wp.to_torch(articulation._instantaneous_wrench_composer.composed_force)) - == num_bodies * 3 - ) - assert ( - torch.count_nonzero(wp.to_torch(articulation._instantaneous_wrench_composer.composed_torque)) - == num_bodies * 3 - ) - assert ( - torch.count_nonzero(wp.to_torch(articulation._permanent_wrench_composer.composed_force)) == num_bodies * 3 - ) - assert ( - torch.count_nonzero(wp.to_torch(articulation._permanent_wrench_composer.composed_torque)) == num_bodies * 3 - ) + assert torch.count_nonzero(articulation._instantaneous_wrench_composer.composed_force.torch) == num_bodies * 3 + assert torch.count_nonzero(articulation._instantaneous_wrench_composer.composed_torque.torch) == num_bodies * 3 + assert torch.count_nonzero(articulation._permanent_wrench_composer.composed_force.torch) == num_bodies * 3 + assert torch.count_nonzero(articulation._permanent_wrench_composer.composed_torque.torch) == num_bodies * 3 +@pytest.mark.isaacsim_ci @pytest.mark.parametrize("num_articulations", [1, 2]) @pytest.mark.parametrize("device", ["cuda:0", "cpu"]) @pytest.mark.parametrize("add_ground_plane", [True]) @pytest.mark.parametrize("articulation_type", ["panda"]) -@pytest.mark.isaacsim_ci def test_apply_joint_command(sim, num_articulations, device, add_ground_plane, articulation_type): """Test applying of joint position target functions correctly for a robotic arm.""" articulation_cfg = generate_articulation_cfg(articulation_type=articulation_type) @@ -1797,7 +1770,7 @@ def test_apply_joint_command(sim, num_articulations, device, add_ground_plane, a articulation.update(sim.cfg.dt) # reset dof state - joint_pos = wp.to_torch(articulation.data.default_joint_pos).clone() + joint_pos = articulation.data.default_joint_pos.torch.clone() joint_pos[:, 3] = 0.0 # apply action to the articulation @@ -1813,14 +1786,14 @@ def test_apply_joint_command(sim, num_articulations, device, add_ground_plane, a # Check that current joint position is not the same as default joint position, meaning # the articulation moved. We can't check that it reached its desired joint position as the gains # are not properly tuned - assert not torch.allclose(wp.to_torch(articulation.data.joint_pos), joint_pos) + assert not torch.allclose(articulation.data.joint_pos.torch, joint_pos) +@pytest.mark.isaacsim_ci @pytest.mark.parametrize("num_articulations", [1, 2]) @pytest.mark.parametrize("device", ["cuda:0", "cpu"]) @pytest.mark.parametrize("with_offset", [True, False]) @pytest.mark.parametrize("articulation_type", ["single_joint_implicit"]) -@pytest.mark.isaacsim_ci def test_body_root_state(sim, num_articulations, device, with_offset, articulation_type): """Test for reading the `body_state_w` property. @@ -1879,19 +1852,19 @@ def test_body_root_state(sim, num_articulations, device, with_offset, articulati articulation.update(sim.cfg.dt) # get state properties - root_link_pose_w = wp.to_torch(articulation.data.root_link_pose_w) - root_link_vel_w = wp.to_torch(articulation.data.root_link_vel_w) - root_com_pose_w = wp.to_torch(articulation.data.root_com_pose_w) - root_com_vel_w = wp.to_torch(articulation.data.root_com_vel_w) - body_link_pose_w = wp.to_torch(articulation.data.body_link_pose_w) - body_link_vel_w = wp.to_torch(articulation.data.body_link_vel_w) - body_com_pose_w = wp.to_torch(articulation.data.body_com_pose_w) - body_com_vel_w = wp.to_torch(articulation.data.body_com_vel_w) + root_link_pose_w = articulation.data.root_link_pose_w.torch + root_link_vel_w = articulation.data.root_link_vel_w.torch + root_com_pose_w = articulation.data.root_com_pose_w.torch + root_com_vel_w = articulation.data.root_com_vel_w.torch + body_link_pose_w = articulation.data.body_link_pose_w.torch + body_link_vel_w = articulation.data.body_link_vel_w.torch + body_com_pose_w = articulation.data.body_com_pose_w.torch + body_com_vel_w = articulation.data.body_com_vel_w.torch if with_offset: # get joint state - joint_pos = wp.to_torch(articulation.data.joint_pos).unsqueeze(-1) - joint_vel = wp.to_torch(articulation.data.joint_vel).unsqueeze(-1) + joint_pos = articulation.data.joint_pos.torch.unsqueeze(-1) + joint_vel = articulation.data.joint_vel.torch.unsqueeze(-1) # LINK state # angular velocity should be the same for both COM and link frames @@ -1926,7 +1899,7 @@ def test_body_root_state(sim, num_articulations, device, with_offset, articulati torch.testing.assert_close(pos_gt, body_com_pose_w[..., :3], atol=1e-3, rtol=1e-1) # orientation - com_quat_b = wp.to_torch(articulation.data.body_com_quat_b) + com_quat_b = articulation.data.body_com_quat_b.torch com_quat_w = math_utils.quat_mul(body_link_pose_w[..., 3:], com_quat_b) torch.testing.assert_close(com_quat_w, body_com_pose_w[..., 3:]) torch.testing.assert_close(com_quat_w[:, root_idx, :], root_com_pose_w[..., 3:]) @@ -1942,13 +1915,13 @@ def test_body_root_state(sim, num_articulations, device, with_offset, articulati torch.testing.assert_close(body_com_vel_w, body_link_vel_w) +@pytest.mark.isaacsim_ci @pytest.mark.parametrize("num_articulations", [1, 2]) @pytest.mark.parametrize("device", ["cuda:0", "cpu"]) @pytest.mark.parametrize("with_offset", [True, False]) @pytest.mark.parametrize("state_location", ["com", "link"]) @pytest.mark.parametrize("gravity_enabled", [False]) @pytest.mark.parametrize("articulation_type", ["anymal"]) -@pytest.mark.isaacsim_ci def test_write_root_state( sim, num_articulations, device, with_offset, state_location, gravity_enabled, articulation_type ): @@ -1998,7 +1971,7 @@ def test_write_root_state( ) rand_state = torch.zeros(num_articulations, 13, device=device) - rand_state[..., :7] = wp.to_torch(articulation.data.default_root_pose) + rand_state[..., :7] = articulation.data.default_root_pose.torch rand_state[..., :3] += env_pos # make quaternion a unit vector rand_state[..., 3:7] = torch.nn.functional.normalize(rand_state[..., 3:7], dim=-1) @@ -2026,118 +1999,16 @@ def test_write_root_state( articulation.write_root_link_velocity_to_sim_index(root_velocity=rand_state[..., 7:], env_ids=env_idx) if state_location == "com": - torch.testing.assert_close(rand_state[..., :7], wp.to_torch(articulation.data.root_com_pose_w)) - torch.testing.assert_close(rand_state[..., 7:], wp.to_torch(articulation.data.root_com_vel_w)) + torch.testing.assert_close(rand_state[..., :7], articulation.data.root_com_pose_w.torch) + torch.testing.assert_close(rand_state[..., 7:], articulation.data.root_com_vel_w.torch) elif state_location == "link": - torch.testing.assert_close(rand_state[..., :7], wp.to_torch(articulation.data.root_link_pose_w)) - torch.testing.assert_close(rand_state[..., 7:], wp.to_torch(articulation.data.root_link_vel_w)) + torch.testing.assert_close(rand_state[..., :7], articulation.data.root_link_pose_w.torch) + torch.testing.assert_close(rand_state[..., 7:], articulation.data.root_link_vel_w.torch) -@pytest.mark.parametrize("num_articulations", [1, 2]) -@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) -@pytest.mark.parametrize("articulation_type", ["single_joint_implicit"]) -@pytest.mark.xfail(reason="Newton body_parent_f uses different convention than PhysX get_link_incoming_joint_force") @pytest.mark.isaacsim_ci -def test_body_incoming_joint_wrench_b_single_joint(sim, num_articulations, device, articulation_type): - """Test the data.body_incoming_joint_wrench_b buffer is populated correctly and statically correct for single joint. - - This test verifies that: - 1. The body incoming joint wrench buffer has correct shape - 2. The wrench values are statically correct for a single joint - 3. The wrench values match expected values from gravity and external forces - - Args: - sim: The simulation fixture - num_articulations: Number of articulations to test - device: The device to run the simulation on - """ - articulation_cfg = generate_articulation_cfg(articulation_type=articulation_type) - articulation, _ = generate_articulation( - articulation_cfg=articulation_cfg, num_articulations=num_articulations, device=device - ) - - # Play the simulator - sim.reset() - - # Resolve body indices by name (ordering may differ across physics backends) - arm_idx = articulation.body_names.index("Arm") - root_idx = articulation.body_names.index("CenterPivot") - # apply external force - external_force_vector_b = torch.zeros((num_articulations, articulation.num_bodies, 3), device=device) - external_force_vector_b[:, arm_idx, 1] = 10.0 # 10 N in Y direction - external_torque_vector_b = torch.zeros((num_articulations, articulation.num_bodies, 3), device=device) - external_torque_vector_b[:, arm_idx, 2] = 10.0 # 10 Nm in z direction - - # apply action to the articulation - joint_pos = torch.ones_like(wp.to_torch(articulation.data.joint_pos)) * 1.5708 / 2.0 - articulation.write_joint_position_to_sim_index( - position=torch.ones_like(wp.to_torch(articulation.data.joint_pos)), - ) - articulation.write_joint_velocity_to_sim_index( - velocity=torch.zeros_like(wp.to_torch(articulation.data.joint_vel)), - ) - articulation.set_joint_position_target_index(target=joint_pos) - articulation.write_data_to_sim() - for _ in range(50): - articulation.permanent_wrench_composer.set_forces_and_torques_index( - forces=external_force_vector_b, torques=external_torque_vector_b - ) - articulation.write_data_to_sim() - # perform step - sim.step() - # update buffers - articulation.update(sim.cfg.dt) - - # check shape - assert wp.to_torch(articulation.data.body_incoming_joint_wrench_b).shape == ( - num_articulations, - articulation.num_bodies, - 6, - ) - - # calculate expected static - mass = wp.to_torch(articulation.data.body_mass).to("cpu") - pos_w = wp.to_torch(articulation.data.body_pos_w) - quat_w = wp.to_torch(articulation.data.body_quat_w) - - mass_link2 = mass[:, arm_idx].view(num_articulations, -1) - gravity = torch.tensor(sim.cfg.gravity, device="cpu").repeat(num_articulations, 1).view((num_articulations, 3)) - - # NOTE: the com and link pose for single joint are colocated - weight_vector_w = mass_link2 * gravity - # expected wrench from link mass and external wrench - # The incoming joint wrench is the constraint/support force from parent onto child (body1=Arm), - # expressed in Arm's frame. In static equilibrium this equals -(gravity + external forces on Arm). - total_force_w = weight_vector_w.to(device) + math_utils.quat_apply( - quat_w[:, arm_idx, :], external_force_vector_b[:, arm_idx, :] - ) - total_torque_w = torch.cross( - pos_w[:, arm_idx, :].to(device) - pos_w[:, root_idx, :].to(device), - total_force_w, - dim=-1, - ) + math_utils.quat_apply(quat_w[:, arm_idx, :], external_torque_vector_b[:, arm_idx, :]) - expected_wrench = torch.zeros((num_articulations, 6), device=device) - expected_wrench[:, :3] = math_utils.quat_apply( - math_utils.quat_conjugate(quat_w[:, arm_idx, :]), - -total_force_w, - ) - expected_wrench[:, 3:] = math_utils.quat_apply( - math_utils.quat_conjugate(quat_w[:, arm_idx, :]), - -total_torque_w, - ) - - # check value of last joint wrench - torch.testing.assert_close( - expected_wrench, - wp.to_torch(articulation.data.body_incoming_joint_wrench_b)[:, arm_idx, :].squeeze(1), - atol=1e-2, - rtol=1e-3, - ) - - @pytest.mark.parametrize("device", ["cuda:0", "cpu"]) @pytest.mark.parametrize("articulation_type", ["humanoid"]) -@pytest.mark.isaacsim_ci def test_setting_articulation_root_prim_path(sim, device, articulation_type): """Test that the articulation root prim path can be set explicitly.""" sim._app_control_on_stop_handle = None @@ -2155,9 +2026,9 @@ def test_setting_articulation_root_prim_path(sim, device, articulation_type): assert articulation._is_initialized +@pytest.mark.isaacsim_ci @pytest.mark.parametrize("device", ["cuda:0", "cpu"]) @pytest.mark.parametrize("articulation_type", ["humanoid"]) -@pytest.mark.isaacsim_ci def test_setting_invalid_articulation_root_prim_path(sim, device, articulation_type): """Test that the articulation root prim path can be set explicitly.""" sim._app_control_on_stop_handle = None @@ -2174,11 +2045,11 @@ def test_setting_invalid_articulation_root_prim_path(sim, device, articulation_t sim.reset() +@pytest.mark.isaacsim_ci @pytest.mark.parametrize("num_articulations", [1, 2]) @pytest.mark.parametrize("device", ["cuda:0", "cpu"]) @pytest.mark.parametrize("gravity_enabled", [False]) @pytest.mark.parametrize("articulation_type", ["anymal"]) -@pytest.mark.isaacsim_ci def test_write_joint_state_data_consistency(sim, num_articulations, device, gravity_enabled, articulation_type): """Test the setters for root_state using both the link frame and center of mass as reference frame. @@ -2205,13 +2076,13 @@ def test_write_joint_state_data_consistency(sim, num_articulations, device, grav from torch.distributions import Uniform - joint_pos_limits = wp.to_torch(articulation.data.joint_pos_limits) - joint_vel_limits = wp.to_torch(articulation.data.joint_vel_limits) + joint_pos_limits = articulation.data.joint_pos_limits.torch + joint_vel_limits = articulation.data.joint_vel_limits.torch pos_dist = Uniform(joint_pos_limits[..., 0], joint_pos_limits[..., 1]) vel_dist = Uniform(-joint_vel_limits, joint_vel_limits) - original_body_link_pose_w = wp.to_torch(articulation.data.body_link_pose_w).clone() - original_body_com_vel_w = wp.to_torch(articulation.data.body_com_vel_w).clone() + original_body_link_pose_w = articulation.data.body_link_pose_w.torch.clone() + original_body_com_vel_w = articulation.data.body_com_vel_w.torch.clone() rand_joint_pos = pos_dist.sample() rand_joint_vel = vel_dist.sample() @@ -2219,65 +2090,65 @@ def test_write_joint_state_data_consistency(sim, num_articulations, device, grav articulation.write_joint_position_to_sim_index(position=rand_joint_pos) articulation.write_joint_velocity_to_sim_index(velocity=rand_joint_vel) # make sure valued updated - body_link_pose_w = wp.to_torch(articulation.data.body_link_pose_w) - body_com_vel_w = wp.to_torch(articulation.data.body_com_vel_w) + body_link_pose_w = articulation.data.body_link_pose_w.torch + body_com_vel_w = articulation.data.body_com_vel_w.torch original_body_states = torch.cat([original_body_link_pose_w, original_body_com_vel_w], dim=-1) body_state_w = torch.cat([body_link_pose_w, body_com_vel_w], dim=-1) assert torch.count_nonzero(original_body_states[:, 1:] != body_state_w[:, 1:]) > ( len(original_body_states[:, 1:]) / 2 ) # validate body - link consistency - body_link_vel_w = wp.to_torch(articulation.data.body_link_vel_w) - torch.testing.assert_close(body_link_pose_w, wp.to_torch(articulation.data.body_link_pose_w)) + body_link_vel_w = articulation.data.body_link_vel_w.torch + torch.testing.assert_close(body_link_pose_w, articulation.data.body_link_pose_w.torch) # skip lin_vel because it differs from link frame, this should be fine because we are only checking # if velocity update is triggered, which can be determined by comparing angular velocity torch.testing.assert_close(body_com_vel_w[..., 3:], body_link_vel_w[..., 3:]) # validate link - com conistency - body_com_pos_b = wp.to_torch(articulation.data.body_com_pos_b) - body_com_quat_b = wp.to_torch(articulation.data.body_com_quat_b) + body_com_pos_b = articulation.data.body_com_pos_b.torch + body_com_quat_b = articulation.data.body_com_quat_b.torch expected_com_pos, expected_com_quat = math_utils.combine_frame_transforms( body_link_pose_w[..., :3].view(-1, 3), body_link_pose_w[..., 3:].view(-1, 4), body_com_pos_b.view(-1, 3), body_com_quat_b.view(-1, 4), ) - body_com_pos_w = wp.to_torch(articulation.data.body_com_pos_w) - body_com_quat_w = wp.to_torch(articulation.data.body_com_quat_w) + body_com_pos_w = articulation.data.body_com_pos_w.torch + body_com_quat_w = articulation.data.body_com_quat_w.torch torch.testing.assert_close(expected_com_pos.view(len(env_idx), -1, 3), body_com_pos_w) torch.testing.assert_close(expected_com_quat.view(len(env_idx), -1, 4), body_com_quat_w) # validate body - com consistency - body_com_lin_vel_w = wp.to_torch(articulation.data.body_com_lin_vel_w) - body_com_ang_vel_w = wp.to_torch(articulation.data.body_com_ang_vel_w) + body_com_lin_vel_w = articulation.data.body_com_lin_vel_w.torch + body_com_ang_vel_w = articulation.data.body_com_ang_vel_w.torch torch.testing.assert_close(body_com_vel_w[..., :3], body_com_lin_vel_w) torch.testing.assert_close(body_com_vel_w[..., 3:], body_com_ang_vel_w) # validate pos_w, quat_w, pos_b, quat_b is consistent with pose_w and pose_b expected_com_pose_w = torch.cat((body_com_pos_w, body_com_quat_w), dim=2) expected_com_pose_b = torch.cat((body_com_pos_b, body_com_quat_b), dim=2) - body_pos_w = wp.to_torch(articulation.data.body_pos_w) - body_quat_w = wp.to_torch(articulation.data.body_quat_w) + body_pos_w = articulation.data.body_pos_w.torch + body_quat_w = articulation.data.body_quat_w.torch expected_body_pose_w = torch.cat((body_pos_w, body_quat_w), dim=2) - body_link_pos_w = wp.to_torch(articulation.data.body_link_pos_w) - body_link_quat_w = wp.to_torch(articulation.data.body_link_quat_w) + body_link_pos_w = articulation.data.body_link_pos_w.torch + body_link_quat_w = articulation.data.body_link_quat_w.torch expected_body_link_pose_w = torch.cat((body_link_pos_w, body_link_quat_w), dim=2) - body_com_pose_w = wp.to_torch(articulation.data.body_com_pose_w) - body_com_pose_b = wp.to_torch(articulation.data.body_com_pose_b) - body_pose_w = wp.to_torch(articulation.data.body_pose_w) - body_link_pose_w_fresh = wp.to_torch(articulation.data.body_link_pose_w) + body_com_pose_w = articulation.data.body_com_pose_w.torch + body_com_pose_b = articulation.data.body_com_pose_b.torch + body_pose_w = articulation.data.body_pose_w.torch + body_link_pose_w_fresh = articulation.data.body_link_pose_w.torch torch.testing.assert_close(body_com_pose_w, expected_com_pose_w) torch.testing.assert_close(body_com_pose_b, expected_com_pose_b) torch.testing.assert_close(body_pose_w, expected_body_pose_w) torch.testing.assert_close(body_link_pose_w_fresh, expected_body_link_pose_w) # validate pose_w is consistent with individual properties - body_vel_w = wp.to_torch(articulation.data.body_vel_w) - body_com_vel_w_fresh = wp.to_torch(articulation.data.body_com_vel_w) + body_vel_w = articulation.data.body_vel_w.torch + body_com_vel_w_fresh = articulation.data.body_com_vel_w.torch torch.testing.assert_close(body_pose_w, body_link_pose_w) torch.testing.assert_close(body_vel_w, body_com_vel_w) torch.testing.assert_close(body_link_pose_w_fresh, body_link_pose_w) - torch.testing.assert_close(body_com_pose_w, wp.to_torch(articulation.data.body_com_pose_w)) + torch.testing.assert_close(body_com_pose_w, articulation.data.body_com_pose_w.torch) torch.testing.assert_close(body_vel_w, body_com_vel_w_fresh) @@ -2314,11 +2185,11 @@ def test_spatial_tendons(sim, num_articulations, device, articulation_type): # Check that fixed base assert articulation.is_fixed_base # Check buffers that exists and have correct shapes - assert wp.to_torch(articulation.data.root_pos_w).shape == (num_articulations, 3) - assert wp.to_torch(articulation.data.root_quat_w).shape == (num_articulations, 4) - assert wp.to_torch(articulation.data.joint_pos).shape == (num_articulations, 3) - assert wp.to_torch(articulation.data.body_mass).shape == (num_articulations, articulation.num_bodies) - assert wp.to_torch(articulation.data.body_inertia).shape == (num_articulations, articulation.num_bodies, 9) + assert articulation.data.root_pos_w.torch.shape == (num_articulations, 3) + assert articulation.data.root_quat_w.torch.shape == (num_articulations, 4) + assert articulation.data.joint_pos.torch.shape == (num_articulations, 3) + assert articulation.data.body_mass.torch.shape == (num_articulations, articulation.num_bodies) + assert articulation.data.body_inertia.torch.shape == (num_articulations, articulation.num_bodies, 9) assert articulation.num_spatial_tendons == 1 articulation.set_spatial_tendon_stiffness_index(stiffness=10.0) @@ -2338,7 +2209,6 @@ def test_spatial_tendons(sim, num_articulations, device, articulation_type): @pytest.mark.parametrize("num_articulations", [1, 2]) @pytest.mark.parametrize("device", ["cuda:0", "cpu"]) @pytest.mark.parametrize("articulation_type", ["panda"]) -@pytest.mark.isaacsim_ci def test_write_joint_frictions_to_sim(sim, num_articulations, device, add_ground_plane, articulation_type): """Test applying of joint position target functions correctly for a robotic arm.""" articulation_cfg = generate_articulation_cfg(articulation_type=articulation_type) @@ -2406,5 +2276,201 @@ def test_write_joint_frictions_to_sim(sim, num_articulations, device, add_ground assert torch.allclose(joint_friction_coeff_sim_2, friction_2) +@pytest.mark.parametrize("num_articulations", [2]) +@pytest.mark.parametrize("device", ["cuda:0"]) +@pytest.mark.parametrize("articulation_type", ["anymal"]) +def test_body_q_consistent_after_root_write(num_articulations, device, articulation_type): + """Test that body_q is fresh when collide() runs after a root pose write. + + Regression test for a NaN bug where collide() used stale body_q after env + reset because eval_fk was not called between write_root_pose and collide. + + Uses ``use_mujoco_contacts=False`` so the Newton collision pipeline is + active, then patches ``_simulate_physics_only`` to capture body_q at + the moment collide() is called and asserts it matches joint_q. + """ + from unittest.mock import patch + + sim_cfg = SimulationCfg( + dt=1 / 200, + physics=NewtonCfg( + solver_cfg=MJWarpSolverCfg( + njmax=70, + nconmax=70, + integrator="implicitfast", + use_mujoco_contacts=False, + ), + num_substeps=1, + use_cuda_graph=False, + ), + ) + with build_simulation_context(sim_cfg=sim_cfg, device=device) as sim: + sim._app_control_on_stop_handle = None + articulation_cfg = generate_articulation_cfg(articulation_type=articulation_type) + articulation, env_pos = generate_articulation(articulation_cfg, num_articulations, device) + + sim.reset() + + model = SimulationManager.get_model() + jc_starts = model.joint_coord_world_start.numpy() + body_starts = model.body_world_start.numpy() + + for _ in range(5): + sim.step() + articulation.update(sim.cfg.dt) + + # Teleport env 0 by 10m (simulating a reset) + new_pose = articulation.data.default_root_pose.torch.clone() + new_pose[0, 0] += 10.0 + new_pose[0, 1] += 5.0 + articulation.write_root_pose_to_sim_index( + root_pose=new_pose[0:1], + env_ids=torch.tensor([0], device=device, dtype=torch.int32), + ) + + # Patch _simulate_physics_only to capture body_q before collide runs + captured = {} + original_simulate = SimulationManager._simulate_physics_only.__func__ + + @classmethod # type: ignore[misc] + def _patched_simulate(cls): + if cls._needs_collision_pipeline: + bq = wp.to_torch(cls._state_0.body_q) + jq = wp.to_torch(cls._state_0.joint_q) + b0 = int(body_starts[0]) + jc0 = int(jc_starts[0]) + captured["bq_root"] = bq[b0, :3].clone() + captured["jq_root"] = jq[jc0 : jc0 + 3].clone() + original_simulate(cls) + + with patch.object(SimulationManager, "_simulate_physics_only", _patched_simulate): + sim.step() + articulation.update(sim.cfg.dt) + + assert captured, "collision pipeline did not run — _needs_collision_pipeline is False" + + bq_root = captured["bq_root"] + jq_root = captured["jq_root"] + diff = (jq_root - bq_root).abs().max().item() + assert diff < 0.01, ( + f"body_q was stale when collide() ran: diff={diff:.4f}m, jq={jq_root.tolist()}, bq={bq_root.tolist()}" + ) + + +@pytest.mark.isaacsim_ci +@pytest.mark.parametrize("add_ground_plane", [True]) +@pytest.mark.parametrize("num_articulations", [1, 2]) +@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) +@pytest.mark.parametrize("articulation_type", ["panda"]) +def test_set_material_properties(sim, num_articulations, device, add_ground_plane, articulation_type): + """Test getting and setting material properties (friction/restitution) via view-level APIs.""" + articulation_cfg = generate_articulation_cfg(articulation_type=articulation_type) + articulation, _ = generate_articulation( + articulation_cfg=articulation_cfg, num_articulations=num_articulations, device=device + ) + + # Play the simulator + sim.reset() + + # Get friction/restitution bindings via view-level API + model = SimulationManager.get_model() + friction_binding = articulation._root_view.get_attribute("shape_material_mu", model)[:, 0] + restitution_binding = articulation._root_view.get_attribute("shape_material_restitution", model)[:, 0] + num_shapes = friction_binding.shape[1] + + # Test 1: Set all shapes via in-place writes to the warp binding + friction = torch.empty(num_articulations, num_shapes, device=device).uniform_(0.4, 0.8) + restitution = torch.empty(num_articulations, num_shapes, device=device).uniform_(0.0, 0.2) + + wp.to_torch(friction_binding)[:] = friction + wp.to_torch(restitution_binding)[:] = restitution + SimulationManager.add_model_change(SolverNotifyFlags.SHAPE_PROPERTIES) + + # Simulate physics + sim.step() + articulation.update(sim.cfg.dt) + + # Verify by reading back from the binding + mu = wp.to_torch(friction_binding) + restitution_check = wp.to_torch(restitution_binding) + torch.testing.assert_close(mu, friction) + torch.testing.assert_close(restitution_check, restitution) + + # Test 2: Set subset of shapes (only shape 0) + if num_shapes > 1: + subset_friction = torch.empty(num_articulations, device=device).uniform_(0.1, 0.2) + subset_restitution = torch.empty(num_articulations, device=device).uniform_(0.5, 0.6) + + wp.to_torch(friction_binding)[:, 0] = subset_friction + wp.to_torch(restitution_binding)[:, 0] = subset_restitution + SimulationManager.add_model_change(SolverNotifyFlags.SHAPE_PROPERTIES) + + sim.step() + articulation.update(sim.cfg.dt) + + # Check only the subset was updated + mu_updated = wp.to_torch(friction_binding) + restitution_updated = wp.to_torch(restitution_binding) + torch.testing.assert_close(mu_updated[:, 0], subset_friction) + torch.testing.assert_close(restitution_updated[:, 0], subset_restitution) + + +@pytest.mark.parametrize("num_articulations", [2]) +@pytest.mark.parametrize("device", ["cuda:0"]) +@pytest.mark.parametrize("add_ground_plane", [True]) +@pytest.mark.parametrize("articulation_type", ["anymal"]) +def test_randomize_rigid_body_com(sim, num_articulations, device, add_ground_plane, articulation_type): + """Test that randomize_rigid_body_com modifies CoM and affects simulation dynamics.""" + articulation_cfg = generate_articulation_cfg(articulation_type=articulation_type) + articulation, _ = generate_articulation(articulation_cfg, num_articulations, device=device) + + sim.reset() + assert articulation.is_initialized + + original_com = articulation.data.body_com_pos_b.torch.clone() + + com_offset = torch.zeros(num_articulations, articulation.num_bodies, 3, device=device) + com_offset[..., 0] = 0.5 + new_com = original_com + com_offset + env_ids = torch.arange(num_articulations, device=device, dtype=torch.int32) + articulation.set_coms_index(coms=new_com, env_ids=env_ids) + + updated_com = articulation.data.body_com_pos_b.torch + torch.testing.assert_close(updated_com, new_com, atol=1e-5, rtol=1e-5) + + +@pytest.mark.parametrize("num_articulations", [2]) +@pytest.mark.parametrize("device", ["cuda:0"]) +@pytest.mark.parametrize("add_ground_plane", [True]) +@pytest.mark.parametrize("articulation_type", ["anymal"]) +def test_randomize_rigid_body_collider_offsets(sim, num_articulations, device, add_ground_plane, articulation_type): + """Test that Newton collider offset randomization (shape_margin, shape_gap) takes effect.""" + articulation_cfg = generate_articulation_cfg(articulation_type=articulation_type) + articulation, _ = generate_articulation(articulation_cfg, num_articulations, device=device) + + sim.reset() + assert articulation.is_initialized + + model = SimulationManager.get_model() + original_margin = wp.to_torch(articulation.root_view.get_attribute("shape_margin", model)).clone() + original_gap = wp.to_torch(articulation.root_view.get_attribute("shape_gap", model)).clone() + + new_margin = original_margin.clone() + new_margin[:, 0] += 0.01 + articulation.root_view.set_attribute("shape_margin", model, wp.from_torch(new_margin, dtype=wp.float32)) + + new_gap = original_gap.clone() + new_gap[:, 0] += 0.005 + articulation.root_view.set_attribute("shape_gap", model, wp.from_torch(new_gap, dtype=wp.float32)) + + with wp.ScopedDevice(device): + SimulationManager._solver.notify_model_changed(SolverNotifyFlags.SHAPE_PROPERTIES) + + updated_margin = wp.to_torch(articulation.root_view.get_attribute("shape_margin", model)) + updated_gap = wp.to_torch(articulation.root_view.get_attribute("shape_gap", model)) + torch.testing.assert_close(updated_margin, new_margin) + torch.testing.assert_close(updated_gap, new_gap) + + if __name__ == "__main__": pytest.main([__file__, "-v", "--maxfail=1"]) diff --git a/source/isaaclab_newton/test/assets/test_rigid_object.py b/source/isaaclab_newton/test/assets/test_rigid_object.py index 9cc1717d8c5f..3b8e3aa9bf85 100644 --- a/source/isaaclab_newton/test/assets/test_rigid_object.py +++ b/source/isaaclab_newton/test/assets/test_rigid_object.py @@ -119,9 +119,9 @@ def generate_cubes_scene( return cube_object, origins +@pytest.mark.isaacsim_ci @pytest.mark.parametrize("num_cubes", [1, 2]) @pytest.mark.parametrize("device", ["cuda:0", "cpu"]) -@pytest.mark.isaacsim_ci def test_initialization(num_cubes, device): """Test initialization for prim with rigid body API at the provided prim path.""" with _newton_sim_context(device, auto_add_lighting=True) as sim: @@ -140,10 +140,10 @@ def test_initialization(num_cubes, device): assert len(cube_object.body_names) == 1 # Check buffers that exists and have correct shapes - assert wp.to_torch(cube_object.data.root_pos_w).shape == (num_cubes, 3) - assert wp.to_torch(cube_object.data.root_quat_w).shape == (num_cubes, 4) - assert wp.to_torch(cube_object.data.body_mass).shape == (num_cubes, 1) - assert wp.to_torch(cube_object.data.body_inertia).shape == (num_cubes, 1, 9) + assert cube_object.data.root_pos_w.torch.shape == (num_cubes, 3) + assert cube_object.data.root_quat_w.torch.shape == (num_cubes, 4) + assert cube_object.data.body_mass.torch.shape == (num_cubes, 1) + assert cube_object.data.body_inertia.torch.shape == (num_cubes, 1, 9) # Simulate physics for _ in range(2): @@ -153,10 +153,10 @@ def test_initialization(num_cubes, device): cube_object.update(sim.cfg.dt) +@pytest.mark.isaacsim_ci @pytest.mark.skip(reason="Newton does not support kinematic rigid bodies") @pytest.mark.parametrize("num_cubes", [1, 2]) @pytest.mark.parametrize("device", ["cuda:0", "cpu"]) -@pytest.mark.isaacsim_ci def test_initialization_with_kinematic_enabled(num_cubes, device): """Test that initialization for prim with kinematic flag enabled.""" with _newton_sim_context(device, auto_add_lighting=True) as sim: @@ -175,8 +175,8 @@ def test_initialization_with_kinematic_enabled(num_cubes, device): assert len(cube_object.body_names) == 1 # Check buffers that exists and have correct shapes - assert wp.to_torch(cube_object.data.root_pos_w).shape == (num_cubes, 3) - assert wp.to_torch(cube_object.data.root_quat_w).shape == (num_cubes, 4) + assert cube_object.data.root_pos_w.torch.shape == (num_cubes, 3) + assert cube_object.data.root_quat_w.torch.shape == (num_cubes, 4) # Simulate physics for _ in range(2): @@ -185,16 +185,16 @@ def test_initialization_with_kinematic_enabled(num_cubes, device): # update object cube_object.update(sim.cfg.dt) # check that the object is kinematic - default_root_pose = wp.to_torch(cube_object.data.default_root_pose).clone() - default_root_vel = wp.to_torch(cube_object.data.default_root_vel).clone() + default_root_pose = cube_object.data.default_root_pose.torch.clone() + default_root_vel = cube_object.data.default_root_vel.torch.clone() default_root_pose[:, :3] += origins - torch.testing.assert_close(wp.to_torch(cube_object.data.root_link_pose_w), default_root_pose) - torch.testing.assert_close(wp.to_torch(cube_object.data.root_com_vel_w), default_root_vel) + torch.testing.assert_close(cube_object.data.root_link_pose_w.torch, default_root_pose) + torch.testing.assert_close(cube_object.data.root_com_vel_w.torch, default_root_vel) +@pytest.mark.isaacsim_ci @pytest.mark.parametrize("num_cubes", [1, 2]) @pytest.mark.parametrize("device", ["cuda:0", "cpu"]) -@pytest.mark.isaacsim_ci def test_initialization_with_no_rigid_body(num_cubes, device): """Test that initialization fails when no rigid body is found at the provided prim path.""" with _newton_sim_context(device, auto_add_lighting=True) as sim: @@ -210,9 +210,9 @@ def test_initialization_with_no_rigid_body(num_cubes, device): sim.reset() +@pytest.mark.isaacsim_ci @pytest.mark.parametrize("num_cubes", [1, 2]) @pytest.mark.parametrize("device", ["cuda:0", "cpu"]) -@pytest.mark.isaacsim_ci def test_initialization_with_articulation_root(num_cubes, device): """Test that initialization fails when an articulation root is found at the provided prim path.""" with _newton_sim_context(device, auto_add_lighting=True) as sim: @@ -228,8 +228,8 @@ def test_initialization_with_articulation_root(num_cubes, device): sim.reset() -@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) @pytest.mark.isaacsim_ci +@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) def test_external_force_buffer(device): """Test if external force buffer correctly updates in the force value is zero case. @@ -276,8 +276,8 @@ def test_external_force_buffer(device): # check if the cube's force and torque buffers are correctly updated for i in range(cube_object.num_instances): - assert wp.to_torch(cube_object._permanent_wrench_composer.composed_force)[i, 0, 0].item() == force - assert wp.to_torch(cube_object._permanent_wrench_composer.composed_torque)[i, 0, 0].item() == force + assert cube_object._permanent_wrench_composer.composed_force.torch[i, 0, 0].item() == force + assert cube_object._permanent_wrench_composer.composed_torque.torch[i, 0, 0].item() == force # Check if the instantaneous wrench is correctly added to the permanent wrench cube_object.permanent_wrench_composer.add_forces_and_torques_index( @@ -296,9 +296,9 @@ def test_external_force_buffer(device): cube_object.update(sim.cfg.dt) +@pytest.mark.isaacsim_ci @pytest.mark.parametrize("num_cubes", [2, 4]) @pytest.mark.parametrize("device", ["cuda:0", "cpu"]) -@pytest.mark.isaacsim_ci def test_external_force_on_single_body(num_cubes, device): """Test application of external force on the base of the object. @@ -322,13 +322,13 @@ def test_external_force_on_single_body(num_cubes, device): # Sample a force equal to the weight of the object external_wrench_b = torch.zeros(cube_object.num_instances, len(body_ids), 6, device=sim.device) # Every 2nd cube should have a force applied to it - external_wrench_b[0::2, :, 2] = 9.81 * wp.to_torch(cube_object.data.body_mass)[0] + external_wrench_b[0::2, :, 2] = 9.81 * cube_object.data.body_mass.torch[0] # Now we are ready! for i in range(5): # reset root state - root_pose = wp.to_torch(cube_object.data.default_root_pose).clone() - root_vel = wp.to_torch(cube_object.data.default_root_vel).clone() + root_pose = cube_object.data.default_root_pose.torch.clone() + root_vel = cube_object.data.default_root_vel.torch.clone() # need to shift the position of the cubes otherwise they will be on top of each other root_pose[:, :3] = origins @@ -341,7 +341,7 @@ def test_external_force_on_single_body(num_cubes, device): is_global = False if i % 2 == 0: is_global = True - positions = wp.to_torch(cube_object.data.body_com_pos_w)[:, body_ids, :3] + positions = cube_object.data.body_com_pos_w.torch[:, body_ids, :3] else: positions = None @@ -366,13 +366,12 @@ def test_external_force_on_single_body(num_cubes, device): # First object should still be at the same Z position (1.0) torch.testing.assert_close( - wp.to_torch(cube_object.data.root_pos_w)[0::2, 2], torch.ones(num_cubes // 2, device=sim.device) + cube_object.data.root_pos_w.torch[0::2, 2], torch.ones(num_cubes // 2, device=sim.device) ) # Second object should have fallen, so it's Z height should be less than initial height of 1.0 - assert torch.all(wp.to_torch(cube_object.data.root_pos_w)[1::2, 2] < 1.0) + assert torch.all(cube_object.data.root_pos_w.torch[1::2, 2] < 1.0) -@pytest.mark.skip(reason="Newton wrench composer at-position force composition differs from PhysX") @pytest.mark.parametrize("num_cubes", [2, 4]) @pytest.mark.parametrize("device", ["cuda:0", "cpu"]) def test_external_force_on_single_body_at_position(num_cubes, device): @@ -399,19 +398,14 @@ def test_external_force_on_single_body_at_position(num_cubes, device): external_wrench_b = torch.zeros(cube_object.num_instances, len(body_ids), 6, device=sim.device) external_wrench_positions_b = torch.zeros(cube_object.num_instances, len(body_ids), 3, device=sim.device) # Every 2nd cube should have a force applied to it - external_wrench_b[0::2, :, 2] = 500.0 + external_wrench_b[0::2, :, 2] = 50.0 external_wrench_positions_b[0::2, :, 1] = 1.0 - # Desired force and torque - desired_force = torch.zeros(cube_object.num_instances, len(body_ids), 3, device=sim.device) - desired_force[0::2, :, 2] = 1000.0 - desired_torque = torch.zeros(cube_object.num_instances, len(body_ids), 3, device=sim.device) - desired_torque[0::2, :, 0] = 1000.0 # Now we are ready! for i in range(5): # reset root state - root_pose = wp.to_torch(cube_object.data.default_root_pose).clone() - root_vel = wp.to_torch(cube_object.data.default_root_vel).clone() + root_pose = cube_object.data.default_root_pose.torch.clone() + root_vel = cube_object.data.default_root_vel.torch.clone() # need to shift the position of the cubes otherwise they will be on top of each other root_pose[:, :3] = origins @@ -424,7 +418,7 @@ def test_external_force_on_single_body_at_position(num_cubes, device): is_global = False if i % 2 == 0: is_global = True - body_com_pos_w = wp.to_torch(cube_object.data.body_com_pos_w)[:, body_ids, :3] + body_com_pos_w = cube_object.data.body_com_pos_w.torch[:, body_ids, :3] external_wrench_positions_b[..., 0] = 0.0 external_wrench_positions_b[..., 1] = 1.0 external_wrench_positions_b[..., 2] = 0.0 @@ -449,18 +443,6 @@ def test_external_force_on_single_body_at_position(num_cubes, device): body_ids=body_ids, is_global=is_global, ) - torch.testing.assert_close( - wp.to_torch(cube_object._permanent_wrench_composer.composed_force)[:, 0, :], - desired_force[:, 0, :], - rtol=1e-6, - atol=1e-7, - ) - torch.testing.assert_close( - wp.to_torch(cube_object._permanent_wrench_composer.composed_torque)[:, 0, :], - desired_torque[:, 0, :], - rtol=1e-6, - atol=1e-7, - ) # perform simulation for _ in range(5): # apply action to the object @@ -473,14 +455,14 @@ def test_external_force_on_single_body_at_position(num_cubes, device): cube_object.update(sim.cfg.dt) # The first object should be rotating around it's X axis - assert torch.all(torch.abs(wp.to_torch(cube_object.data.root_ang_vel_b)[0::2, 0]) > 0.1) + assert torch.all(torch.abs(cube_object.data.root_ang_vel_b.torch[0::2, 0]) > 0.1) # Second object should have fallen, so it's Z height should be less than initial height of 1.0 - assert torch.all(wp.to_torch(cube_object.data.root_pos_w)[1::2, 2] < 1.0) + assert torch.all(cube_object.data.root_pos_w.torch[1::2, 2] < 1.0) +@pytest.mark.isaacsim_ci @pytest.mark.parametrize("num_cubes", [1, 2]) @pytest.mark.parametrize("device", ["cuda:0", "cpu"]) -@pytest.mark.isaacsim_ci def test_set_rigid_object_state(num_cubes, device): """Test setting the state of the rigid object. @@ -503,10 +485,10 @@ def test_set_rigid_object_state(num_cubes, device): # Set each state type individually as they are dependent on each other for state_type_to_randomize in state_types: state_dict = { - "root_pos_w": torch.zeros_like(wp.to_torch(cube_object.data.root_pos_w), device=sim.device), + "root_pos_w": torch.zeros_like(cube_object.data.root_pos_w.torch, device=sim.device), "root_quat_w": default_orientation(num=num_cubes, device=sim.device), - "root_lin_vel_w": torch.zeros_like(wp.to_torch(cube_object.data.root_lin_vel_w), device=sim.device), - "root_ang_vel_w": torch.zeros_like(wp.to_torch(cube_object.data.root_ang_vel_w), device=sim.device), + "root_lin_vel_w": torch.zeros_like(cube_object.data.root_lin_vel_w.torch, device=sim.device), + "root_ang_vel_w": torch.zeros_like(cube_object.data.root_ang_vel_w.torch, device=sim.device), } # Now we are ready! @@ -538,7 +520,7 @@ def test_set_rigid_object_state(num_cubes, device): # assert that set root quantities are equal to the ones set in the state_dict for key, expected_value in state_dict.items(): - value = wp.to_torch(getattr(cube_object.data, key)) + value = getattr(cube_object.data, key).torch # Newton reads state directly from sim (not cached), so post-step drift # from velocity integration causes larger differences than PhysX torch.testing.assert_close(value, expected_value, rtol=1e-1, atol=1e-1) @@ -546,9 +528,9 @@ def test_set_rigid_object_state(num_cubes, device): cube_object.update(sim.cfg.dt) +@pytest.mark.isaacsim_ci @pytest.mark.parametrize("num_cubes", [1, 2]) @pytest.mark.parametrize("device", ["cuda:0", "cpu"]) -@pytest.mark.isaacsim_ci def test_reset_rigid_object(num_cubes, device): """Test resetting the state of the rigid object.""" with _newton_sim_context(device, gravity_enabled=True, auto_add_lighting=True) as sim: @@ -567,13 +549,13 @@ def test_reset_rigid_object(num_cubes, device): cube_object.update(sim.cfg.dt) # Move the object to a random position - root_pose = wp.to_torch(cube_object.data.default_root_pose).clone() + root_pose = cube_object.data.default_root_pose.torch.clone() root_pose[:, :3] = torch.randn(num_cubes, 3, device=sim.device) # Random orientation root_pose[:, 3:7] = random_orientation(num=num_cubes, device=sim.device) cube_object.write_root_pose_to_sim_index(root_pose=root_pose) - root_vel = wp.to_torch(cube_object.data.default_root_vel).clone() + root_vel = cube_object.data.default_root_vel.torch.clone() cube_object.write_root_velocity_to_sim_index(root_velocity=root_vel) if i % 2 == 0: @@ -583,18 +565,17 @@ def test_reset_rigid_object(num_cubes, device): # Reset should zero external forces and torques assert not cube_object._instantaneous_wrench_composer.active assert not cube_object._permanent_wrench_composer.active - assert torch.count_nonzero(wp.to_torch(cube_object._instantaneous_wrench_composer.composed_force)) == 0 - assert torch.count_nonzero(wp.to_torch(cube_object._instantaneous_wrench_composer.composed_torque)) == 0 - assert torch.count_nonzero(wp.to_torch(cube_object._permanent_wrench_composer.composed_force)) == 0 - assert torch.count_nonzero(wp.to_torch(cube_object._permanent_wrench_composer.composed_torque)) == 0 + assert torch.count_nonzero(cube_object._instantaneous_wrench_composer.composed_force.torch) == 0 + assert torch.count_nonzero(cube_object._instantaneous_wrench_composer.composed_torque.torch) == 0 + assert torch.count_nonzero(cube_object._permanent_wrench_composer.composed_force.torch) == 0 + assert torch.count_nonzero(cube_object._permanent_wrench_composer.composed_torque.torch) == 0 -@pytest.mark.skip(reason="Newton friction/restitution/material not yet supported") +@pytest.mark.isaacsim_ci @pytest.mark.parametrize("num_cubes", [1, 2]) @pytest.mark.parametrize("device", ["cuda:0", "cpu"]) -@pytest.mark.isaacsim_ci def test_rigid_body_set_material_properties(num_cubes, device): - """Test getting and setting material properties of rigid object.""" + """Test getting and setting material properties of rigid object via view-level APIs.""" with _newton_sim_context(device, gravity_enabled=True, add_ground_plane=True, auto_add_lighting=True) as sim: sim._app_control_on_stop_handle = None # Generate cubes scene @@ -603,36 +584,51 @@ def test_rigid_body_set_material_properties(num_cubes, device): # Play sim sim.reset() - # Set material properties - static_friction = torch.FloatTensor(num_cubes, 1).uniform_(0.4, 0.8) - dynamic_friction = torch.FloatTensor(num_cubes, 1).uniform_(0.4, 0.8) - restitution = torch.FloatTensor(num_cubes, 1).uniform_(0.0, 0.2) + # Get friction/restitution bindings via view-level API + model = SimulationManager.get_model() + friction_binding = cube_object._root_view.get_attribute("shape_material_mu", model)[:, 0] + restitution_binding = cube_object._root_view.get_attribute("shape_material_restitution", model)[:, 0] + num_shapes = friction_binding.shape[1] - materials = torch.cat([static_friction, dynamic_friction, restitution], dim=-1) + # Set material properties via in-place writes to the warp binding + friction = torch.empty(num_cubes, num_shapes, device=device).uniform_(0.4, 0.8) + restitution = torch.empty(num_cubes, num_shapes, device=device).uniform_(0.0, 0.2) - indices = torch.tensor(range(num_cubes), dtype=torch.int32) - # Add friction to cube - cube_object.root_view.set_material_properties( - wp.from_torch(materials, dtype=wp.float32), wp.from_torch(indices, dtype=wp.int32) - ) + wp.to_torch(friction_binding)[:] = friction + wp.to_torch(restitution_binding)[:] = restitution + SimulationManager.add_model_change(SolverNotifyFlags.SHAPE_PROPERTIES) # Simulate physics - # perform rendering sim.step() - # update object cube_object.update(sim.cfg.dt) - # Get material properties - materials_to_check = wp.to_torch(cube_object.root_view.get_material_properties()) + # Verify by reading back from the binding + mu = wp.to_torch(friction_binding) + restitution_check = wp.to_torch(restitution_binding) + torch.testing.assert_close(mu, friction) + torch.testing.assert_close(restitution_check, restitution) + + +def _set_newton_material_properties(cube_object, friction_val, restitution_val, device): + """Helper to set material properties via Newton view-level APIs.""" + model = SimulationManager.get_model() + friction_binding = cube_object._root_view.get_attribute("shape_material_mu", model)[:, 0] + restitution_binding = cube_object._root_view.get_attribute("shape_material_restitution", model)[:, 0] + num_envs = friction_binding.shape[0] + num_shapes = friction_binding.shape[1] + + friction_tensor = torch.full((num_envs, num_shapes), friction_val, device=device) + restitution_tensor = torch.full((num_envs, num_shapes), restitution_val, device=device) - # Check if material properties are set correctly - torch.testing.assert_close(materials_to_check.reshape(num_cubes, 3), materials) + wp.to_torch(friction_binding)[:] = friction_tensor + wp.to_torch(restitution_binding)[:] = restitution_tensor + SimulationManager.add_model_change(SolverNotifyFlags.SHAPE_PROPERTIES) -@pytest.mark.skip(reason="Newton friction/restitution/material not yet supported") +@pytest.mark.isaacsim_ci +@pytest.mark.skip(reason="MuJoCo contact at height=0 does not settle the same as PhysX — cube falls on z-axis") @pytest.mark.parametrize("num_cubes", [1, 2]) @pytest.mark.parametrize("device", ["cuda:0", "cpu"]) -@pytest.mark.isaacsim_ci def test_rigid_body_no_friction(num_cubes, device): """Test that a rigid object with no friction will maintain it's velocity when sliding across a plane.""" with _newton_sim_context(device, auto_add_lighting=True) as sim: @@ -640,11 +636,12 @@ def test_rigid_body_no_friction(num_cubes, device): # Generate cubes scene cube_object, _ = generate_cubes_scene(num_cubes=num_cubes, height=0.0, device=device) - # Create ground plane with no friction + # Create ground plane with near-zero friction + # Note: MuJoCo requires friction >= MJ_MINMU (1e-5), so we use 1e-4 cfg = sim_utils.GroundPlaneCfg( physics_material=materials.RigidBodyMaterialCfg( - static_friction=0.0, - dynamic_friction=0.0, + static_friction=1e-4, + dynamic_friction=1e-4, restitution=0.0, ) ) @@ -653,17 +650,8 @@ def test_rigid_body_no_friction(num_cubes, device): # Play sim sim.reset() - # Set material friction properties to be all zero - static_friction = torch.zeros(num_cubes, 1) - dynamic_friction = torch.zeros(num_cubes, 1) - restitution = torch.FloatTensor(num_cubes, 1).uniform_(0.0, 0.2) - - cube_object_materials = torch.cat([static_friction, dynamic_friction, restitution], dim=-1) - indices = torch.tensor(range(num_cubes), dtype=torch.int32) - - cube_object.root_view.set_material_properties( - wp.from_torch(cube_object_materials, dtype=wp.float32), wp.from_torch(indices, dtype=wp.int32) - ) + # Set material friction to near-zero via view-level API + _set_newton_material_properties(cube_object, friction_val=1e-4, restitution_val=0.0, device=device) # Set initial velocity # Initial velocity in X to get the block moving @@ -686,14 +674,14 @@ def test_rigid_body_no_friction(num_cubes, device): tolerance = 1e-5 torch.testing.assert_close( - wp.to_torch(cube_object.data.root_lin_vel_w), initial_velocity[:, :3], rtol=1e-5, atol=tolerance + cube_object.data.root_lin_vel_w.torch, initial_velocity[:, :3], rtol=1e-5, atol=tolerance ) -@pytest.mark.skip(reason="Newton friction/restitution/material not yet supported") +@pytest.mark.isaacsim_ci +@pytest.mark.skip(reason="MuJoCo uses Coulomb friction (single mu), no static/dynamic distinction") @pytest.mark.parametrize("num_cubes", [1, 2]) @pytest.mark.parametrize("device", ["cuda:0", "cpu"]) -@pytest.mark.isaacsim_ci def test_rigid_body_with_static_friction(num_cubes, device): """Test that static friction applied to rigid object works as expected. @@ -711,7 +699,7 @@ def test_rigid_body_with_static_friction(num_cubes, device): cfg = sim_utils.GroundPlaneCfg( physics_material=materials.RigidBodyMaterialCfg( static_friction=static_friction_coefficient, - dynamic_friction=static_friction_coefficient, # This shouldn't be required but is due to a bug in PhysX + dynamic_friction=static_friction_coefficient, ) ) cfg.func("/World/GroundPlane", cfg) @@ -719,19 +707,12 @@ def test_rigid_body_with_static_friction(num_cubes, device): # Play sim sim.reset() - # Set static friction to be non-zero - # Dynamic friction also needs to be zero due to a bug in PhysX - static_friction = torch.Tensor([[static_friction_coefficient]] * num_cubes) - dynamic_friction = torch.Tensor([[static_friction_coefficient]] * num_cubes) - restitution = torch.zeros(num_cubes, 1) - - cube_object_materials = torch.cat([static_friction, dynamic_friction, restitution], dim=-1) - - indices = torch.tensor(range(num_cubes), dtype=torch.int32) - - # Add friction to cube - cube_object.root_view.set_material_properties( - wp.from_torch(cube_object_materials, dtype=wp.float32), wp.from_torch(indices, dtype=wp.int32) + # Set friction via view-level API + _set_newton_material_properties( + cube_object, + friction_val=static_friction_coefficient, + restitution_val=0.0, + device=device, ) # let everything settle @@ -739,7 +720,7 @@ def test_rigid_body_with_static_friction(num_cubes, device): sim.step() cube_object.update(sim.cfg.dt) cube_object.write_root_velocity_to_sim_index(root_velocity=torch.zeros((num_cubes, 6), device=sim.device)) - cube_mass = wp.to_torch(cube_object.data.body_mass) + cube_mass = cube_object.data.body_mass.torch gravity_magnitude = abs(sim.cfg.gravity[2]) # 2 cases: force applied is below and above mu # below mu: block should not move as the force applied is <= mu @@ -760,7 +741,7 @@ def test_rigid_body_with_static_friction(num_cubes, device): ) # Get root state - initial_root_pos = wp.to_torch(cube_object.data.root_pos_w).clone() + initial_root_pos = cube_object.data.root_pos_w.torch.clone() # Simulate physics for _ in range(200): # apply the wrench @@ -771,16 +752,16 @@ def test_rigid_body_with_static_friction(num_cubes, device): if force == "below_mu": # Assert that the block has not moved torch.testing.assert_close( - wp.to_torch(cube_object.data.root_pos_w), initial_root_pos, rtol=2e-3, atol=2e-3 + cube_object.data.root_pos_w.torch, initial_root_pos, rtol=2e-3, atol=2e-3 ) if force == "above_mu": - assert (wp.to_torch(cube_object.data.root_pos_w)[..., 0] - initial_root_pos[..., 0] > 0.02).all() + assert (cube_object.data.root_pos_w.torch[..., 0] - initial_root_pos[..., 0] > 0.02).all() -@pytest.mark.skip(reason="Newton friction/restitution/material not yet supported") +@pytest.mark.isaacsim_ci +@pytest.mark.skip(reason="MuJoCo restitution model differs from PhysX — inelastic collisions still bounce") @pytest.mark.parametrize("num_cubes", [1, 2]) @pytest.mark.parametrize("device", ["cuda:0", "cpu"]) -@pytest.mark.isaacsim_ci def test_rigid_body_with_restitution(num_cubes, device): """Test that restitution when applied to rigid object works as expected. @@ -800,7 +781,7 @@ def test_rigid_body_with_restitution(num_cubes, device): elif expected_collision_type == "partially_elastic": restitution_coefficient = 0.5 - # Create ground plane such that has a restitution of 1.0 (perfectly elastic collision) + # Create ground plane cfg = sim_utils.GroundPlaneCfg( physics_material=materials.RigidBodyMaterialCfg( restitution=restitution_coefficient, @@ -808,8 +789,6 @@ def test_rigid_body_with_restitution(num_cubes, device): ) cfg.func("/World/GroundPlane", cfg) - indices = torch.tensor(range(num_cubes), dtype=torch.int32) - # Play sim sim.reset() @@ -824,25 +803,22 @@ def test_rigid_body_with_restitution(num_cubes, device): cube_object.write_root_pose_to_sim_index(root_pose=root_pose) cube_object.write_root_velocity_to_sim_index(root_velocity=root_vel) - static_friction = torch.zeros(num_cubes, 1) - dynamic_friction = torch.zeros(num_cubes, 1) - restitution = torch.Tensor([[restitution_coefficient]] * num_cubes) - - cube_object_materials = torch.cat([static_friction, dynamic_friction, restitution], dim=-1) - - # Add restitution to cube - cube_object.root_view.set_material_properties( - wp.from_torch(cube_object_materials, dtype=wp.float32), wp.from_torch(indices, dtype=wp.int32) + # Set restitution via view-level API + _set_newton_material_properties( + cube_object, + friction_val=0.0, + restitution_val=restitution_coefficient, + device=device, ) - curr_z_velocity = wp.to_torch(cube_object.data.root_lin_vel_w)[:, 2].clone() + curr_z_velocity = cube_object.data.root_lin_vel_w.torch[:, 2].clone() for _ in range(100): sim.step() # update object cube_object.update(sim.cfg.dt) - curr_z_velocity = wp.to_torch(cube_object.data.root_lin_vel_w)[:, 2].clone() + curr_z_velocity = cube_object.data.root_lin_vel_w.torch[:, 2].clone() if expected_collision_type == "inelastic": # assert that the block has not bounced by checking that the z velocity is less than or equal to 0 @@ -861,9 +837,9 @@ def test_rigid_body_with_restitution(num_cubes, device): assert (curr_z_velocity > 0.0).all() +@pytest.mark.isaacsim_ci @pytest.mark.parametrize("num_cubes", [1, 2]) @pytest.mark.parametrize("device", ["cuda:0", "cpu"]) -@pytest.mark.isaacsim_ci def test_rigid_body_set_mass(num_cubes, device): """Test getting and setting mass of rigid object.""" with _newton_sim_context(device, gravity_enabled=False, add_ground_plane=True, auto_add_lighting=True) as sim: @@ -875,7 +851,7 @@ def test_rigid_body_set_mass(num_cubes, device): sim.reset() # Get masses before increasing - original_masses = wp.to_torch(cube_object.data.body_mass) + original_masses = cube_object.data.body_mass.torch assert original_masses.shape == (num_cubes, 1) @@ -885,7 +861,7 @@ def test_rigid_body_set_mass(num_cubes, device): # Set masses using Newton API cube_object.set_masses_index(masses=wp.from_torch(masses, dtype=wp.float32)) - torch.testing.assert_close(wp.to_torch(cube_object.data.body_mass), masses) + torch.testing.assert_close(cube_object.data.body_mass.torch, masses) # Simulate physics # perform rendering @@ -893,16 +869,16 @@ def test_rigid_body_set_mass(num_cubes, device): # update object cube_object.update(sim.cfg.dt) - masses_to_check = wp.to_torch(cube_object.data.body_mass) + masses_to_check = cube_object.data.body_mass.torch # Check if mass is set correctly torch.testing.assert_close(masses, masses_to_check) +@pytest.mark.isaacsim_ci @pytest.mark.parametrize("num_cubes", [1, 2]) @pytest.mark.parametrize("device", ["cuda:0", "cpu"]) @pytest.mark.parametrize("gravity_enabled", [True, False]) -@pytest.mark.isaacsim_ci def test_gravity_vec_w(num_cubes, device, gravity_enabled): """Test that gravity vector direction is set correctly for the rigid object.""" with _newton_sim_context(device, gravity_enabled=gravity_enabled) as sim: @@ -920,9 +896,9 @@ def test_gravity_vec_w(num_cubes, device, gravity_enabled): sim.reset() # Check that gravity is set correctly - assert wp.to_torch(cube_object.data.GRAVITY_VEC_W)[0, 0] == gravity_dir[0] - assert wp.to_torch(cube_object.data.GRAVITY_VEC_W)[0, 1] == gravity_dir[1] - assert wp.to_torch(cube_object.data.GRAVITY_VEC_W)[0, 2] == gravity_dir[2] + assert cube_object.data.GRAVITY_VEC_W.torch[0, 0] == gravity_dir[0] + assert cube_object.data.GRAVITY_VEC_W.torch[0, 1] == gravity_dir[1] + assert cube_object.data.GRAVITY_VEC_W.torch[0, 2] == gravity_dir[2] # Simulate physics for _ in range(2): @@ -936,13 +912,13 @@ def test_gravity_vec_w(num_cubes, device, gravity_enabled): if gravity_enabled: gravity[:, :, 2] = -9.81 # Check the body accelerations are correct - torch.testing.assert_close(wp.to_torch(cube_object.data.body_acc_w), gravity) + torch.testing.assert_close(cube_object.data.body_acc_w.torch, gravity) +@pytest.mark.isaacsim_ci @pytest.mark.parametrize("num_cubes", [1, 2]) @pytest.mark.parametrize("device", ["cuda:0", "cpu"]) @pytest.mark.parametrize("with_offset", [True, False]) -@pytest.mark.isaacsim_ci @flaky(max_runs=3, min_passes=1) def test_body_root_state_properties(num_cubes, device, with_offset): """Test the root_com_state_w, root_link_state_w, body_com_state_w, and body_link_state_w properties.""" @@ -970,11 +946,11 @@ def test_body_root_state_properties(num_cubes, device, with_offset): SimulationManager._solver.notify_model_changed(SolverNotifyFlags.BODY_INERTIAL_PROPERTIES) # check center of mass has been set - torch.testing.assert_close(wp.to_torch(cube_object.data.body_com_pos_b).squeeze(1), offset) + torch.testing.assert_close(cube_object.data.body_com_pos_b.torch.squeeze(1), offset) - # random z spin velocity + # random z spin velocity (bounded to keep numerical drift within the position tolerance below) spin_twist = torch.zeros(6, device=device) - spin_twist[5] = torch.randn(1, device=device) + spin_twist[5] = 0.5 * torch.randn(1, device=device).clamp(-1.0, 1.0) # Simulate physics for _ in range(100): @@ -986,14 +962,14 @@ def test_body_root_state_properties(num_cubes, device, with_offset): cube_object.update(sim.cfg.dt) # get state properties - root_link_pose_w = wp.to_torch(cube_object.data.root_link_pose_w) - root_link_vel_w = wp.to_torch(cube_object.data.root_link_vel_w) - root_com_pose_w = wp.to_torch(cube_object.data.root_com_pose_w) - root_com_vel_w = wp.to_torch(cube_object.data.root_com_vel_w) - body_link_pose_w = wp.to_torch(cube_object.data.body_link_pose_w) - body_link_vel_w = wp.to_torch(cube_object.data.body_link_vel_w) - body_com_pose_w = wp.to_torch(cube_object.data.body_com_pose_w) - body_com_vel_w = wp.to_torch(cube_object.data.body_com_vel_w) + root_link_pose_w = cube_object.data.root_link_pose_w.torch + root_link_vel_w = cube_object.data.root_link_vel_w.torch + root_com_pose_w = cube_object.data.root_com_pose_w.torch + root_com_vel_w = cube_object.data.root_com_vel_w.torch + body_link_pose_w = cube_object.data.body_link_pose_w.torch + body_link_vel_w = cube_object.data.body_link_vel_w.torch + body_com_pose_w = cube_object.data.body_com_pose_w.torch + body_com_vel_w = cube_object.data.body_com_vel_w.torch # if offset is [0,0,0] all root_state_%_w will match and all body_%_w will match if not with_offset: @@ -1025,7 +1001,7 @@ def test_body_root_state_properties(num_cubes, device, with_offset): torch.testing.assert_close(-offset, body_link_state_pos_rel_com.squeeze(-2), **_tol) # orientation of com will be a constant rotation from link orientation - com_quat_b = wp.to_torch(cube_object.data.body_com_quat_b) + com_quat_b = cube_object.data.body_com_quat_b.torch com_quat_w = quat_mul(body_link_pose_w[..., 3:], com_quat_b) torch.testing.assert_close(com_quat_w, body_com_pose_w[..., 3:], **_tol) torch.testing.assert_close(com_quat_w.squeeze(-2), root_com_pose_w[..., 3:], **_tol) @@ -1052,11 +1028,11 @@ def test_body_root_state_properties(num_cubes, device, with_offset): torch.testing.assert_close(body_com_vel_w[..., 3:], body_link_vel_w[..., 3:]) +@pytest.mark.isaacsim_ci @pytest.mark.parametrize("num_cubes", [1, 2]) @pytest.mark.parametrize("device", ["cuda:0", "cpu"]) @pytest.mark.parametrize("with_offset", [True, False]) @pytest.mark.parametrize("state_location", ["com", "link"]) -@pytest.mark.isaacsim_ci def test_write_root_state(num_cubes, device, with_offset, state_location): """Test the setters for root_state using both the link frame and center of mass as reference frame.""" with _newton_sim_context(device, gravity_enabled=False, auto_add_lighting=True) as sim: @@ -1084,10 +1060,10 @@ def test_write_root_state(num_cubes, device, with_offset, state_location): SimulationManager._solver.notify_model_changed(SolverNotifyFlags.BODY_INERTIAL_PROPERTIES) # check center of mass has been set - torch.testing.assert_close(wp.to_torch(cube_object.data.body_com_pos_b).squeeze(1), offset) + torch.testing.assert_close(cube_object.data.body_com_pos_b.torch.squeeze(1), offset) rand_state = torch.zeros(num_cubes, 13, device=device) - rand_state[..., :7] = wp.to_torch(cube_object.data.default_root_pose) + rand_state[..., :7] = cube_object.data.default_root_pose.torch rand_state[..., :3] += env_pos # make quaternion a unit vector rand_state[..., 3:7] = torch.nn.functional.normalize(rand_state[..., 3:7], dim=-1) @@ -1116,18 +1092,18 @@ def test_write_root_state(num_cubes, device, with_offset, state_location): ) if state_location == "com": - torch.testing.assert_close(rand_state[..., :7], wp.to_torch(cube_object.data.root_com_pose_w)) - torch.testing.assert_close(rand_state[..., 7:], wp.to_torch(cube_object.data.root_com_vel_w)) + torch.testing.assert_close(rand_state[..., :7], cube_object.data.root_com_pose_w.torch) + torch.testing.assert_close(rand_state[..., 7:], cube_object.data.root_com_vel_w.torch) elif state_location == "link": - torch.testing.assert_close(rand_state[..., :7], wp.to_torch(cube_object.data.root_link_pose_w)) - torch.testing.assert_close(rand_state[..., 7:], wp.to_torch(cube_object.data.root_link_vel_w)) + torch.testing.assert_close(rand_state[..., :7], cube_object.data.root_link_pose_w.torch) + torch.testing.assert_close(rand_state[..., 7:], cube_object.data.root_link_vel_w.torch) +@pytest.mark.isaacsim_ci @pytest.mark.parametrize("num_cubes", [1, 2]) @pytest.mark.parametrize("device", ["cuda:0", "cpu"]) @pytest.mark.parametrize("with_offset", [True]) @pytest.mark.parametrize("state_location", ["com", "link", "root"]) -@pytest.mark.isaacsim_ci def test_write_state_functions_data_consistency(num_cubes, device, with_offset, state_location): """Test the setters for root_state using both the link frame and center of mass as reference frame.""" with _newton_sim_context(device, gravity_enabled=False, auto_add_lighting=True) as sim: @@ -1154,7 +1130,7 @@ def test_write_state_functions_data_consistency(num_cubes, device, with_offset, SimulationManager._solver.notify_model_changed(SolverNotifyFlags.BODY_INERTIAL_PROPERTIES) # check center of mass has been set - torch.testing.assert_close(wp.to_torch(cube_object.data.body_com_pos_b).squeeze(1), offset) + torch.testing.assert_close(cube_object.data.body_com_pos_b.torch.squeeze(1), offset) rand_state = torch.rand(num_cubes, 13, device=device) rand_state[..., :3] += env_pos @@ -1177,9 +1153,9 @@ def test_write_state_functions_data_consistency(num_cubes, device, with_offset, cube_object.write_root_velocity_to_sim_index(root_velocity=rand_state[..., 7:]) if state_location == "com": - root_com_pose_w = wp.to_torch(cube_object.data.root_com_pose_w) - root_com_vel_w = wp.to_torch(cube_object.data.root_com_vel_w) - body_com_pose_b = wp.to_torch(cube_object.data.body_com_pose_b) + root_com_pose_w = cube_object.data.root_com_pose_w.torch + root_com_vel_w = cube_object.data.root_com_vel_w.torch + body_com_pose_b = cube_object.data.body_com_pose_b.torch expected_root_link_pos, expected_root_link_quat = combine_frame_transforms( root_com_pose_w[:, :3], root_com_pose_w[:, 3:], @@ -1187,19 +1163,19 @@ def test_write_state_functions_data_consistency(num_cubes, device, with_offset, quat_inv(body_com_pose_b[:, 0, 3:7]), ) expected_root_link_pose = torch.cat((expected_root_link_pos, expected_root_link_quat), dim=1) - root_link_pose_w = wp.to_torch(cube_object.data.root_link_pose_w) - root_link_vel_w = wp.to_torch(cube_object.data.root_link_vel_w) + root_link_pose_w = cube_object.data.root_link_pose_w.torch + root_link_vel_w = cube_object.data.root_link_vel_w.torch # test both root_pose and root_link successfully updated when root_com updates torch.testing.assert_close(expected_root_link_pose, root_link_pose_w) # skip lin_vel because it differs from link frame, this should be fine because we are only checking # if velocity update is triggered, which can be determined by comparing angular velocity torch.testing.assert_close(root_com_vel_w[:, 3:], root_link_vel_w[:, 3:]) torch.testing.assert_close(expected_root_link_pose, root_link_pose_w) - torch.testing.assert_close(root_com_vel_w[:, 3:], wp.to_torch(cube_object.data.root_com_vel_w)[:, 3:]) + torch.testing.assert_close(root_com_vel_w[:, 3:], cube_object.data.root_com_vel_w.torch[:, 3:]) elif state_location == "link": - root_link_pose_w = wp.to_torch(cube_object.data.root_link_pose_w) - root_link_vel_w = wp.to_torch(cube_object.data.root_link_vel_w) - body_com_pose_b = wp.to_torch(cube_object.data.body_com_pose_b) + root_link_pose_w = cube_object.data.root_link_pose_w.torch + root_link_vel_w = cube_object.data.root_link_vel_w.torch + body_com_pose_b = cube_object.data.body_com_pose_b.torch expected_com_pos, expected_com_quat = combine_frame_transforms( root_link_pose_w[:, :3], root_link_pose_w[:, 3:], @@ -1207,19 +1183,19 @@ def test_write_state_functions_data_consistency(num_cubes, device, with_offset, body_com_pose_b[:, 0, 3:7], ) expected_com_pose = torch.cat((expected_com_pos, expected_com_quat), dim=1) - root_com_pose_w = wp.to_torch(cube_object.data.root_com_pose_w) - root_com_vel_w = wp.to_torch(cube_object.data.root_com_vel_w) + root_com_pose_w = cube_object.data.root_com_pose_w.torch + root_com_vel_w = cube_object.data.root_com_vel_w.torch # test both root_pose and root_com successfully updated when root_link updates torch.testing.assert_close(expected_com_pose, root_com_pose_w) # skip lin_vel because it differs from link frame, this should be fine because we are only checking # if velocity update is triggered, which can be determined by comparing angular velocity torch.testing.assert_close(root_link_vel_w[:, 3:], root_com_vel_w[:, 3:]) - torch.testing.assert_close(root_link_pose_w, wp.to_torch(cube_object.data.root_link_pose_w)) - torch.testing.assert_close(root_link_vel_w[:, 3:], wp.to_torch(cube_object.data.root_com_vel_w)[:, 3:]) + torch.testing.assert_close(root_link_pose_w, cube_object.data.root_link_pose_w.torch) + torch.testing.assert_close(root_link_vel_w[:, 3:], cube_object.data.root_com_vel_w.torch[:, 3:]) elif state_location == "root": - root_link_pose_w = wp.to_torch(cube_object.data.root_link_pose_w) - root_com_vel_w = wp.to_torch(cube_object.data.root_com_vel_w) - body_com_pose_b = wp.to_torch(cube_object.data.body_com_pose_b) + root_link_pose_w = cube_object.data.root_link_pose_w.torch + root_com_vel_w = cube_object.data.root_com_vel_w.torch + body_com_pose_b = cube_object.data.body_com_pose_b.torch expected_com_pos, expected_com_quat = combine_frame_transforms( root_link_pose_w[:, :3], root_link_pose_w[:, 3:], @@ -1227,17 +1203,17 @@ def test_write_state_functions_data_consistency(num_cubes, device, with_offset, body_com_pose_b[:, 0, 3:7], ) expected_com_pose = torch.cat((expected_com_pos, expected_com_quat), dim=1) - root_com_pose_w = wp.to_torch(cube_object.data.root_com_pose_w) - root_link_vel_w = wp.to_torch(cube_object.data.root_link_vel_w) + root_com_pose_w = cube_object.data.root_com_pose_w.torch + root_link_vel_w = cube_object.data.root_link_vel_w.torch # test both root_com and root_link successfully updated when root_pose updates torch.testing.assert_close(expected_com_pose, root_com_pose_w) - torch.testing.assert_close(root_com_vel_w, wp.to_torch(cube_object.data.root_com_vel_w)) - torch.testing.assert_close(root_link_pose_w, wp.to_torch(cube_object.data.root_link_pose_w)) + torch.testing.assert_close(root_com_vel_w, cube_object.data.root_com_vel_w.torch) + torch.testing.assert_close(root_link_pose_w, cube_object.data.root_link_pose_w.torch) torch.testing.assert_close(root_com_vel_w[:, 3:], root_link_vel_w[:, 3:]) -@pytest.mark.skip(reason="PhysX-specific warmup test") @pytest.mark.isaacsim_ci +@pytest.mark.skip(reason="PhysX-specific warmup test") def test_warmup_attach_stage_not_called_for_cpu(): """Regression test: attach_stage() must not be called for CPU in _warmup_and_create_views(). diff --git a/source/isaaclab_newton/test/assets/test_rigid_object_collection.py b/source/isaaclab_newton/test/assets/test_rigid_object_collection.py index a1086d4371ec..0873da8ecf22 100644 --- a/source/isaaclab_newton/test/assets/test_rigid_object_collection.py +++ b/source/isaaclab_newton/test/assets/test_rigid_object_collection.py @@ -137,10 +137,10 @@ def test_initialization(num_envs, num_cubes, device): assert len(object_collection.body_names) == num_cubes # Check buffers that exist and have correct shapes - assert wp.to_torch(object_collection.data.body_link_pos_w).shape == (num_envs, num_cubes, 3) - assert wp.to_torch(object_collection.data.body_link_quat_w).shape == (num_envs, num_cubes, 4) - assert wp.to_torch(object_collection.data.body_mass).shape == (num_envs, num_cubes) - assert wp.to_torch(object_collection.data.body_inertia).shape == (num_envs, num_cubes, 9) + assert object_collection.data.body_link_pos_w.torch.shape == (num_envs, num_cubes, 3) + assert object_collection.data.body_link_quat_w.torch.shape == (num_envs, num_cubes, 4) + assert object_collection.data.body_mass.torch.shape == (num_envs, num_cubes) + assert object_collection.data.body_inertia.torch.shape == (num_envs, num_cubes, 9) # Simulate physics for _ in range(2): @@ -171,19 +171,19 @@ def test_initialization_with_kinematic_enabled(num_envs, num_cubes, device): assert len(object_collection.body_names) == num_cubes # Check buffers that exist and have correct shapes - assert wp.to_torch(object_collection.data.body_link_pos_w).shape == (num_envs, num_cubes, 3) - assert wp.to_torch(object_collection.data.body_link_quat_w).shape == (num_envs, num_cubes, 4) + assert object_collection.data.body_link_pos_w.torch.shape == (num_envs, num_cubes, 3) + assert object_collection.data.body_link_quat_w.torch.shape == (num_envs, num_cubes, 4) # Simulate physics for _ in range(2): sim.step() object_collection.update(sim.cfg.dt) # check that the object is kinematic - default_body_pose = wp.to_torch(object_collection.data.default_body_pose).clone() - default_body_vel = wp.to_torch(object_collection.data.default_body_vel).clone() + default_body_pose = object_collection.data.default_body_pose.torch.clone() + default_body_vel = object_collection.data.default_body_vel.torch.clone() default_body_pose[..., :3] += origins.unsqueeze(1) - torch.testing.assert_close(wp.to_torch(object_collection.data.body_link_pose_w), default_body_pose) - torch.testing.assert_close(wp.to_torch(object_collection.data.body_link_vel_w), default_body_vel) + torch.testing.assert_close(object_collection.data.body_link_pose_w.torch, default_body_pose) + torch.testing.assert_close(object_collection.data.body_link_vel_w.torch, default_body_vel) @pytest.mark.parametrize("num_cubes", [1, 2]) @@ -241,10 +241,8 @@ def test_external_force_buffer(device): # check if the object collection's force and torque buffers are correctly updated for i in range(num_envs): - assert wp.to_torch(object_collection._permanent_wrench_composer.composed_force)[i, 0, 0].item() == force - assert ( - wp.to_torch(object_collection._permanent_wrench_composer.composed_torque)[i, 0, 0].item() == force - ) + assert object_collection._permanent_wrench_composer.composed_force.torch[i, 0, 0].item() == force + assert object_collection._permanent_wrench_composer.composed_torque.torch[i, 0, 0].item() == force object_collection.instantaneous_wrench_composer.add_forces_and_torques_index( body_ids=object_ids, @@ -274,12 +272,12 @@ def test_external_force_on_single_body(num_envs, num_cubes, device): # Sample a force equal to the weight of the object external_wrench_b = torch.zeros(object_collection.num_instances, len(object_ids), 6, device=sim.device) # Every 2nd cube should have a force applied to it - external_wrench_b[:, 0::2, 2] = 9.81 * wp.to_torch(object_collection.data.body_mass)[:, 0::2] + external_wrench_b[:, 0::2, 2] = 9.81 * object_collection.data.body_mass.torch[:, 0::2] for i in range(5): # reset object state - body_pose = wp.to_torch(object_collection.data.default_body_pose).clone() - body_vel = wp.to_torch(object_collection.data.default_body_vel).clone() + body_pose = object_collection.data.default_body_pose.torch.clone() + body_vel = object_collection.data.default_body_vel.torch.clone() # need to shift the position of the cubes otherwise they will be on top of each other body_pose[..., :2] += origins.unsqueeze(1)[..., :2] object_collection.write_body_link_pose_to_sim_index(body_poses=body_pose) @@ -289,7 +287,7 @@ def test_external_force_on_single_body(num_envs, num_cubes, device): is_global = False if i % 2 == 0: - positions = wp.to_torch(object_collection.data.body_link_pos_w)[:, object_ids, :3] + positions = object_collection.data.body_link_pos_w.torch[:, object_ids, :3] is_global = True else: positions = None @@ -313,11 +311,11 @@ def test_external_force_on_single_body(num_envs, num_cubes, device): # First object should still be at the same Z position (1.0) torch.testing.assert_close( - wp.to_torch(object_collection.data.body_link_pos_w)[:, 0::2, 2], - torch.ones_like(wp.to_torch(object_collection.data.body_link_pos_w)[:, 0::2, 2]), + object_collection.data.body_link_pos_w.torch[:, 0::2, 2], + torch.ones_like(object_collection.data.body_link_pos_w.torch[:, 0::2, 2]), ) # Second object should have fallen, so it's Z height should be less than initial height of 1.0 - assert torch.all(wp.to_torch(object_collection.data.body_link_pos_w)[:, 1::2, 2] < 1.0) + assert torch.all(object_collection.data.body_link_pos_w.torch[:, 1::2, 2] < 1.0) @pytest.mark.parametrize("num_envs", [1, 2]) @@ -344,14 +342,14 @@ def test_external_force_on_single_body_at_position(num_envs, num_cubes, device): object_collection.num_instances, len(object_ids), 3, device=sim.device ) # Every 2nd cube should have a force applied to it - external_wrench_b[:, 0::2, 2] = 500.0 + external_wrench_b[:, 0::2, 2] = 50.0 external_wrench_positions_b[:, 0::2, 1] = 1.0 # Desired force and torque for i in range(5): # reset object state - body_pose = wp.to_torch(object_collection.data.default_body_pose).clone() - body_vel = wp.to_torch(object_collection.data.default_body_vel).clone() + body_pose = object_collection.data.default_body_pose.torch.clone() + body_vel = object_collection.data.default_body_vel.torch.clone() # need to shift the position of the cubes otherwise they will be on top of each other body_pose[..., :2] += origins.unsqueeze(1)[..., :2] object_collection.write_body_link_pose_to_sim_index(body_poses=body_pose) @@ -361,7 +359,7 @@ def test_external_force_on_single_body_at_position(num_envs, num_cubes, device): is_global = False if i % 2 == 0: - body_com_pos_w = wp.to_torch(object_collection.data.body_link_pos_w)[:, object_ids, :3] + body_com_pos_w = object_collection.data.body_link_pos_w.torch[:, object_ids, :3] external_wrench_positions_b[..., 0] = 0.0 external_wrench_positions_b[..., 1] = 1.0 external_wrench_positions_b[..., 2] = 0.0 @@ -398,9 +396,9 @@ def test_external_force_on_single_body_at_position(num_envs, num_cubes, device): object_collection.update(sim.cfg.dt) # First object should be rotating around it's X axis - assert torch.all(wp.to_torch(object_collection.data.body_com_ang_vel_b)[:, 0::2, 0] > 0.1) + assert torch.all(object_collection.data.body_com_ang_vel_b.torch[:, 0::2, 0] > 0.1) # Second object should have fallen, so it's Z height should be less than initial height of 1.0 - assert torch.all(wp.to_torch(object_collection.data.body_link_pos_w)[:, 1::2, 2] < 1.0) + assert torch.all(object_collection.data.body_link_pos_w.torch[:, 1::2, 2] < 1.0) @pytest.mark.parametrize("num_envs", [1, 3]) @@ -423,17 +421,15 @@ def test_set_object_state(num_envs, num_cubes, device): # Set each state type individually as they are dependent on each other for state_type_to_randomize in state_types: state_dict = { - "body_link_pos_w": torch.zeros_like( - wp.to_torch(object_collection.data.body_link_pos_w), device=sim.device - ), + "body_link_pos_w": torch.zeros_like(object_collection.data.body_link_pos_w.torch, device=sim.device), "body_link_quat_w": default_orientation(num=num_cubes * num_envs, device=sim.device).view( num_envs, num_cubes, 4 ), "body_com_lin_vel_w": torch.zeros_like( - wp.to_torch(object_collection.data.body_com_lin_vel_w), device=sim.device + object_collection.data.body_com_lin_vel_w.torch, device=sim.device ), "body_com_ang_vel_w": torch.zeros_like( - wp.to_torch(object_collection.data.body_com_ang_vel_w), device=sim.device + object_collection.data.body_com_ang_vel_w.torch, device=sim.device ), } @@ -469,7 +465,7 @@ def test_set_object_state(num_envs, num_cubes, device): # assert that set object quantities are equal to the ones set in the state_dict for key, expected_value in state_dict.items(): - value = wp.to_torch(getattr(object_collection.data, key)) + value = getattr(object_collection.data, key).torch # Newton reads state directly from sim (not cached), so post-step drift # from velocity integration causes larger differences than PhysX torch.testing.assert_close(value, expected_value, rtol=1e-1, atol=1e-1) @@ -492,12 +488,12 @@ def test_reset_object_collection(num_envs, num_cubes, device): object_collection.update(sim.cfg.dt) # Move the object to a random position - body_pose = wp.to_torch(object_collection.data.default_body_pose).clone() + body_pose = object_collection.data.default_body_pose.torch.clone() body_pose[..., :3] = torch.randn(num_envs, num_cubes, 3, device=sim.device) # Random orientation body_pose[..., 3:7] = random_orientation(num=num_cubes, device=sim.device) object_collection.write_body_link_pose_to_sim_index(body_poses=body_pose) - body_vel = wp.to_torch(object_collection.data.default_body_vel).clone() + body_vel = object_collection.data.default_body_vel.torch.clone() object_collection.write_body_com_velocity_to_sim_index(body_velocities=body_vel) if i % 2 == 0: @@ -506,58 +502,49 @@ def test_reset_object_collection(num_envs, num_cubes, device): # Reset should zero external forces and torques assert not object_collection._instantaneous_wrench_composer.active assert not object_collection._permanent_wrench_composer.active - assert ( - torch.count_nonzero(wp.to_torch(object_collection._instantaneous_wrench_composer.composed_force)) - == 0 - ) - assert ( - torch.count_nonzero(wp.to_torch(object_collection._instantaneous_wrench_composer.composed_torque)) - == 0 - ) - assert ( - torch.count_nonzero(wp.to_torch(object_collection._permanent_wrench_composer.composed_force)) == 0 - ) - assert ( - torch.count_nonzero(wp.to_torch(object_collection._permanent_wrench_composer.composed_torque)) == 0 - ) + assert torch.count_nonzero(object_collection._instantaneous_wrench_composer.composed_force.torch) == 0 + assert torch.count_nonzero(object_collection._instantaneous_wrench_composer.composed_torque.torch) == 0 + assert torch.count_nonzero(object_collection._permanent_wrench_composer.composed_force.torch) == 0 + assert torch.count_nonzero(object_collection._permanent_wrench_composer.composed_torque.torch) == 0 -@pytest.mark.skip(reason="Newton doesn't support friction/restitution/material properties yet") @pytest.mark.parametrize("num_envs", [1, 3]) @pytest.mark.parametrize("num_cubes", [1, 2]) @pytest.mark.parametrize("device", ["cuda:0", "cpu"]) def test_set_material_properties(num_envs, num_cubes, device): - """Test getting and setting material properties of rigid object.""" + """Test getting and setting material properties of rigid object collection via view-level APIs.""" with _newton_sim_context(device, auto_add_lighting=True) as sim: sim._app_control_on_stop_handle = None object_collection, _ = generate_cubes_scene(num_envs=num_envs, num_cubes=num_cubes, device=device) sim.reset() - # Set material properties - static_friction = torch.FloatTensor(num_envs, num_cubes, 1).uniform_(0.4, 0.8) - dynamic_friction = torch.FloatTensor(num_envs, num_cubes, 1).uniform_(0.4, 0.8) - restitution = torch.FloatTensor(num_envs, num_cubes, 1).uniform_(0.0, 0.2) + # Get friction/restitution bindings via view-level API + # The collection's _root_view stores data in flat view order: (num_envs * num_cubes, ...) + model = SimulationManager.get_model() + friction_raw = object_collection._root_view.get_attribute("shape_material_mu", model) + restitution_raw = object_collection._root_view.get_attribute("shape_material_restitution", model) - materials = torch.cat([static_friction, dynamic_friction, restitution], dim=-1) + # Shape is (num_envs * num_cubes, num_shapes_per_body, 1) — slice off trailing dim + friction_binding = friction_raw[:, :, 0] + restitution_binding = restitution_raw[:, :, 0] - # Add friction to cube - indices = torch.tensor(range(num_cubes * num_envs), dtype=torch.int) - object_collection.root_view.set_material_properties( - object_collection.reshape_data_to_view_3d(wp.from_torch(materials, dtype=wp.float32), 3, device="cpu"), - wp.from_torch(indices, dtype=wp.int32), - ) + # Generate random values matching the flat view shape + friction = torch.empty_like(wp.to_torch(friction_binding)).uniform_(0.4, 0.8) + restitution = torch.empty_like(wp.to_torch(restitution_binding)).uniform_(0.0, 0.2) + + wp.to_torch(friction_binding)[:] = friction + wp.to_torch(restitution_binding)[:] = restitution + SimulationManager.add_model_change(SolverNotifyFlags.SHAPE_PROPERTIES) # Perform simulation sim.step() object_collection.update(sim.cfg.dt) - # Get material properties - materials_to_check = object_collection.root_view.get_material_properties() - - # Check if material properties are set correctly - torch.testing.assert_close( - wp.to_torch(object_collection.reshape_view_to_data_3d(materials_to_check, 3, device="cpu")), materials - ) + # Verify by reading back from the binding + mu = wp.to_torch(friction_binding) + restitution_check = wp.to_torch(restitution_binding) + torch.testing.assert_close(mu, friction) + torch.testing.assert_close(restitution_check, restitution) @pytest.mark.parametrize("num_envs", [1, 3]) @@ -576,7 +563,7 @@ def test_gravity_vec_w(num_envs, num_cubes, device, gravity_enabled): sim.reset() # Check if gravity vector is set correctly - gravity_vec = wp.to_torch(object_collection.data.GRAVITY_VEC_W) + gravity_vec = object_collection.data.GRAVITY_VEC_W.torch assert gravity_vec[0, 0, 0] == gravity_dir[0] assert gravity_vec[0, 0, 1] == gravity_dir[1] assert gravity_vec[0, 0, 2] == gravity_dir[2] @@ -592,7 +579,7 @@ def test_gravity_vec_w(num_envs, num_cubes, device, gravity_enabled): gravity[..., 2] = -9.81 # Check the body accelerations are correct - torch.testing.assert_close(wp.to_torch(object_collection.data.body_com_acc_w), gravity) + torch.testing.assert_close(object_collection.data.body_com_acc_w.torch, gravity) @pytest.mark.parametrize("num_envs", [1, 4]) @@ -624,14 +611,14 @@ def test_object_state_properties(num_envs, num_cubes, device, with_offset): SimulationManager._solver.notify_model_changed(SolverNotifyFlags.BODY_INERTIAL_PROPERTIES) # check center of mass has been set - torch.testing.assert_close(wp.to_torch(cube_object.data.body_com_pos_b), offset) + torch.testing.assert_close(cube_object.data.body_com_pos_b.torch, offset) # random z spin velocity spin_twist = torch.zeros(6, device=device) spin_twist[5] = torch.randn(1, device=device) # initial spawn point - init_com = wp.to_torch(cube_object.data.body_com_pose_w)[..., :3] + init_com = cube_object.data.body_com_pose_w.torch[..., :3] for i in range(10): # spin the object around Z axis (com) @@ -640,10 +627,10 @@ def test_object_state_properties(num_envs, num_cubes, device, with_offset): cube_object.update(sim.cfg.dt) # get state properties - object_link_pose_w = wp.to_torch(cube_object.data.body_link_pose_w) - object_link_vel_w = wp.to_torch(cube_object.data.body_link_vel_w) - object_com_pose_w = wp.to_torch(cube_object.data.body_com_pose_w) - object_com_vel_w = wp.to_torch(cube_object.data.body_com_vel_w) + object_link_pose_w = cube_object.data.body_link_pose_w.torch + object_link_vel_w = cube_object.data.body_link_vel_w.torch + object_com_pose_w = cube_object.data.body_com_pose_w.torch + object_com_vel_w = cube_object.data.body_com_vel_w.torch # if offset is [0,0,0] all object_state_%_w will match and all body_%_w will match if not with_offset: @@ -665,7 +652,7 @@ def test_object_state_properties(num_envs, num_cubes, device, with_offset): torch.testing.assert_close(-offset, object_link_state_pos_rel_com, **_tol) # orientation of com will be a constant rotation from link orientation - com_quat_b = wp.to_torch(cube_object.data.body_com_quat_b) + com_quat_b = cube_object.data.body_com_quat_b.torch com_quat_w = quat_mul(object_link_pose_w[..., 3:], com_quat_b) torch.testing.assert_close(com_quat_w, object_com_pose_w[..., 3:], **_tol) @@ -723,11 +710,11 @@ def test_write_object_state(num_envs, num_cubes, device, with_offset, state_loca SimulationManager._solver.notify_model_changed(SolverNotifyFlags.BODY_INERTIAL_PROPERTIES) # check center of mass has been set - torch.testing.assert_close(wp.to_torch(cube_object.data.body_com_pos_b), offset) + torch.testing.assert_close(cube_object.data.body_com_pos_b.torch, offset) rand_state = torch.zeros(num_envs, num_cubes, 13, device=device) - rand_state[..., :7] = wp.to_torch(cube_object.data.default_body_pose) - rand_state[..., :3] += wp.to_torch(cube_object.data.body_link_pos_w) + rand_state[..., :7] = cube_object.data.default_body_pose.torch + rand_state[..., :3] += cube_object.data.body_link_pos_w.torch # make quaternion a unit vector rand_state[..., 3:7] = torch.nn.functional.normalize(rand_state[..., 3:7], dim=-1) @@ -761,11 +748,11 @@ def test_write_object_state(num_envs, num_cubes, device, with_offset, state_loca ) if state_location == "com": - torch.testing.assert_close(rand_state[..., :7], wp.to_torch(cube_object.data.body_com_pose_w)) - torch.testing.assert_close(rand_state[..., 7:], wp.to_torch(cube_object.data.body_com_vel_w)) + torch.testing.assert_close(rand_state[..., :7], cube_object.data.body_com_pose_w.torch) + torch.testing.assert_close(rand_state[..., 7:], cube_object.data.body_com_vel_w.torch) elif state_location == "link": - torch.testing.assert_close(rand_state[..., :7], wp.to_torch(cube_object.data.body_link_pose_w)) - torch.testing.assert_close(rand_state[..., 7:], wp.to_torch(cube_object.data.body_link_vel_w)) + torch.testing.assert_close(rand_state[..., :7], cube_object.data.body_link_pose_w.torch) + torch.testing.assert_close(rand_state[..., 7:], cube_object.data.body_link_vel_w.torch) @pytest.mark.parametrize("num_envs", [1, 3]) @@ -801,10 +788,10 @@ def test_write_object_state_functions_data_consistency(num_envs, num_cubes, devi SimulationManager._solver.notify_model_changed(SolverNotifyFlags.BODY_INERTIAL_PROPERTIES) # check center of mass has been set - torch.testing.assert_close(wp.to_torch(cube_object.data.body_com_pos_b), offset) + torch.testing.assert_close(cube_object.data.body_com_pos_b.torch, offset) rand_state = torch.rand(num_envs, num_cubes, 13, device=device) - rand_state[..., :3] += wp.to_torch(cube_object.data.body_link_pos_w) + rand_state[..., :3] += cube_object.data.body_link_pos_w.torch # make quaternion a unit vector rand_state[..., 3:7] = torch.nn.functional.normalize(rand_state[..., 3:7], dim=-1) @@ -813,8 +800,8 @@ def test_write_object_state_functions_data_consistency(num_envs, num_cubes, devi sim.step() cube_object.update(sim.cfg.dt) - body_link_pose_w = wp.to_torch(cube_object.data.body_link_pose_w) - body_com_pose_w = wp.to_torch(cube_object.data.body_com_pose_w) + body_link_pose_w = cube_object.data.body_link_pose_w.torch + body_com_pose_w = cube_object.data.body_com_pose_w.torch object_link_to_com_pos, object_link_to_com_quat = subtract_frame_transforms( body_link_pose_w[..., :3].view(-1, 3), body_link_pose_w[..., 3:7].view(-1, 4), @@ -845,8 +832,8 @@ def test_write_object_state_functions_data_consistency(num_envs, num_cubes, devi ) if state_location == "com": - com_pose_w = wp.to_torch(cube_object.data.body_com_pose_w) - com_vel_w = wp.to_torch(cube_object.data.body_com_vel_w) + com_pose_w = cube_object.data.body_com_pose_w.torch + com_vel_w = cube_object.data.body_com_vel_w.torch expected_root_link_pos, expected_root_link_quat = combine_frame_transforms( com_pose_w[..., :3].view(-1, 3), com_pose_w[..., 3:].view(-1, 4), @@ -856,18 +843,18 @@ def test_write_object_state_functions_data_consistency(num_envs, num_cubes, devi expected_object_link_pose = torch.cat((expected_root_link_pos, expected_root_link_quat), dim=1).view( num_envs, -1, 7 ) - link_pose_w = wp.to_torch(cube_object.data.body_link_pose_w) - link_vel_w = wp.to_torch(cube_object.data.body_link_vel_w) + link_pose_w = cube_object.data.body_link_pose_w.torch + link_vel_w = cube_object.data.body_link_vel_w.torch # test both root_pose and root_link successfully updated when root_com updates torch.testing.assert_close(expected_object_link_pose, link_pose_w) # skip lin_vel because it differs from link frame, this should be fine because we are only checking # if velocity update is triggered, which can be determined by comparing angular velocity torch.testing.assert_close(com_vel_w[..., 3:], link_vel_w[..., 3:]) torch.testing.assert_close(expected_object_link_pose, link_pose_w) - torch.testing.assert_close(com_vel_w[..., 3:], wp.to_torch(cube_object.data.body_com_vel_w)[..., 3:]) + torch.testing.assert_close(com_vel_w[..., 3:], cube_object.data.body_com_vel_w.torch[..., 3:]) elif state_location == "link": - link_pose_w = wp.to_torch(cube_object.data.body_link_pose_w) - link_vel_w = wp.to_torch(cube_object.data.body_link_vel_w) + link_pose_w = cube_object.data.body_link_pose_w.torch + link_vel_w = cube_object.data.body_link_vel_w.torch expected_com_pos, expected_com_quat = combine_frame_transforms( link_pose_w[..., :3].view(-1, 3), link_pose_w[..., 3:].view(-1, 4), @@ -875,18 +862,18 @@ def test_write_object_state_functions_data_consistency(num_envs, num_cubes, devi object_link_to_com_quat, ) expected_object_com_pose = torch.cat((expected_com_pos, expected_com_quat), dim=1).view(num_envs, -1, 7) - com_pose_w = wp.to_torch(cube_object.data.body_com_pose_w) - com_vel_w = wp.to_torch(cube_object.data.body_com_vel_w) + com_pose_w = cube_object.data.body_com_pose_w.torch + com_vel_w = cube_object.data.body_com_vel_w.torch # test both root_pose and root_com successfully updated when root_link updates torch.testing.assert_close(expected_object_com_pose, com_pose_w) # skip lin_vel because it differs from link frame, this should be fine because we are only checking # if velocity update is triggered, which can be determined by comparing angular velocity torch.testing.assert_close(link_vel_w[..., 3:], com_vel_w[..., 3:]) - torch.testing.assert_close(link_pose_w, wp.to_torch(cube_object.data.body_link_pose_w)) - torch.testing.assert_close(link_vel_w[..., 3:], wp.to_torch(cube_object.data.body_com_vel_w)[..., 3:]) + torch.testing.assert_close(link_pose_w, cube_object.data.body_link_pose_w.torch) + torch.testing.assert_close(link_vel_w[..., 3:], cube_object.data.body_com_vel_w.torch[..., 3:]) elif state_location == "root": - body_link_pose_w = wp.to_torch(cube_object.data.body_link_pose_w) - body_com_vel_w = wp.to_torch(cube_object.data.body_com_vel_w) + body_link_pose_w = cube_object.data.body_link_pose_w.torch + body_com_vel_w = cube_object.data.body_com_vel_w.torch expected_object_com_pos, expected_object_com_quat = combine_frame_transforms( body_link_pose_w[..., :3].view(-1, 3), body_link_pose_w[..., 3:].view(-1, 4), @@ -896,10 +883,10 @@ def test_write_object_state_functions_data_consistency(num_envs, num_cubes, devi expected_object_com_pose = torch.cat((expected_object_com_pos, expected_object_com_quat), dim=1).view( num_envs, -1, 7 ) - com_pose_w = wp.to_torch(cube_object.data.body_com_pose_w) - com_vel_w = wp.to_torch(cube_object.data.body_com_vel_w) - link_pose_w = wp.to_torch(cube_object.data.body_link_pose_w) - link_vel_w = wp.to_torch(cube_object.data.body_link_vel_w) + com_pose_w = cube_object.data.body_com_pose_w.torch + com_vel_w = cube_object.data.body_com_vel_w.torch + link_pose_w = cube_object.data.body_link_pose_w.torch + link_vel_w = cube_object.data.body_link_vel_w.torch # test both root_com and root_link successfully updated when root_pose updates torch.testing.assert_close(expected_object_com_pose, com_pose_w) torch.testing.assert_close(body_com_vel_w, com_vel_w) diff --git a/source/isaaclab_newton/test/physics/test_newton_manager_abstraction.py b/source/isaaclab_newton/test/physics/test_newton_manager_abstraction.py new file mode 100644 index 000000000000..f8ac77586cc0 --- /dev/null +++ b/source/isaaclab_newton/test/physics/test_newton_manager_abstraction.py @@ -0,0 +1,274 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Tests for the per-solver :class:`NewtonManager` abstraction. + +Covers: + +* :attr:`NewtonSolverCfg.class_type` resolves to the matching manager subclass. +* :meth:`NewtonCfg.__post_init__` propagates ``solver_cfg.class_type`` onto + :attr:`NewtonCfg.class_type` so that ``SimulationContext`` picks the right + manager. +* Each leaf manager subclasses :class:`NewtonManager` and implements + :meth:`_build_solver` (with the abstract base raising ``NotImplementedError``). +* The cross-config validation in :meth:`NewtonMJWarpManager._build_solver` + rejects the ``MJWarp + use_mujoco_contacts=True + collision_cfg`` combination. +* Manager name dispatch (used by :class:`InteractiveScene` and the various + factory dispatchers) still starts with ``"newton"``. +* End-to-end: spinning up a simulation with each solver builds the correct + solver, sets the right ``_use_single_state`` / ``_needs_collision_pipeline`` + flags, and lands canonical state on :class:`NewtonManager` so that external + ``NewtonManager._foo`` reads keep working. +""" + +from __future__ import annotations + +import pytest +from isaaclab_newton.physics import ( + FeatherstoneSolverCfg, + KaminoSolverCfg, + MJWarpSolverCfg, + NewtonCfg, + NewtonCollisionPipelineCfg, + NewtonFeatherstoneManager, + NewtonKaminoManager, + NewtonManager, + NewtonMJWarpManager, + NewtonSolverCfg, + NewtonXPBDManager, + XPBDSolverCfg, +) +from newton.solvers import SolverFeatherstone, SolverKamino, SolverMuJoCo, SolverXPBD + +from isaaclab.sim import SimulationCfg, build_simulation_context + +# --------------------------------------------------------------------------- +# Lightweight (no sim) parametrisation +# --------------------------------------------------------------------------- + +# (solver_cfg_factory, expected_manager, expected_solver_cls, +# expected_use_single_state, expected_needs_collision_pipeline) +SOLVER_MATRIX = [ + pytest.param( + lambda: MJWarpSolverCfg(use_mujoco_contacts=True), + NewtonMJWarpManager, + SolverMuJoCo, + True, + False, + id="mjwarp_internal_contacts", + ), + pytest.param( + lambda: MJWarpSolverCfg(use_mujoco_contacts=False), + NewtonMJWarpManager, + SolverMuJoCo, + True, + True, + id="mjwarp_newton_pipeline", + ), + pytest.param( + lambda: XPBDSolverCfg(), + NewtonXPBDManager, + SolverXPBD, + False, + True, + id="xpbd", + ), + pytest.param( + lambda: FeatherstoneSolverCfg(), + NewtonFeatherstoneManager, + SolverFeatherstone, + False, + True, + id="featherstone", + ), + pytest.param( + lambda: KaminoSolverCfg(use_collision_detector=True), + NewtonKaminoManager, + SolverKamino, + False, + False, + id="kamino_internal_contacts", + ), + pytest.param( + lambda: KaminoSolverCfg(use_collision_detector=False), + NewtonKaminoManager, + SolverKamino, + False, + True, + id="kamino_newton_pipeline", + ), +] + + +# --------------------------------------------------------------------------- +# class_type wiring (no SimulationContext required) +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + "solver_cfg_factory, expected_manager, _solver_cls, _single_state, _pipeline", + SOLVER_MATRIX, +) +def test_solver_cfg_class_type_resolves_to_subclass( + solver_cfg_factory, expected_manager, _solver_cls, _single_state, _pipeline +): + """Each ``*SolverCfg.class_type`` resolves to its matching manager subclass.""" + solver_cfg = solver_cfg_factory() + # ``class_type`` is a lazy ``"module:Class"`` reference; calling its + # ``_resolve()`` returns the actual class. ``__name__`` works without + # forcing import (LazyType caches metadata) and is sufficient identity. + assert solver_cfg.class_type.__name__ == expected_manager.__name__ + + +@pytest.mark.parametrize( + "solver_cfg_factory, expected_manager, _solver_cls, _single_state, _pipeline", + SOLVER_MATRIX, +) +def test_newton_cfg_post_init_propagates_class_type( + solver_cfg_factory, expected_manager, _solver_cls, _single_state, _pipeline +): + """``NewtonCfg.__post_init__`` lifts ``solver_cfg.class_type`` onto ``NewtonCfg.class_type``.""" + cfg = NewtonCfg(solver_cfg=solver_cfg_factory()) + assert cfg.class_type.__name__ == expected_manager.__name__ + + +# --------------------------------------------------------------------------- +# Manager class hierarchy and factory contracts +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + "manager", [NewtonMJWarpManager, NewtonXPBDManager, NewtonFeatherstoneManager, NewtonKaminoManager] +) +def test_subclass_of_newton_manager(manager): + """All concrete managers inherit from :class:`NewtonManager`.""" + assert issubclass(manager, NewtonManager) + # Subclasses must override the abstract factory. + assert manager._build_solver is not NewtonManager._build_solver + + +def test_abstract_build_solver_raises(): + """Calling :meth:`_build_solver` on the abstract base raises.""" + with pytest.raises(NotImplementedError): + NewtonManager._build_solver(model=None, solver_cfg=NewtonSolverCfg()) + + +@pytest.mark.parametrize( + "manager", [NewtonMJWarpManager, NewtonXPBDManager, NewtonFeatherstoneManager, NewtonKaminoManager] +) +def test_manager_name_starts_with_newton(manager): + """The ``"newton"`` prefix is required by :class:`InteractiveScene` and the + various backend factories that dispatch on ``physics_manager.__name__.lower()``. + """ + assert manager.__name__.lower().startswith("newton") + + +# --------------------------------------------------------------------------- +# End-to-end: build each solver via SimulationContext +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + "solver_cfg_factory, expected_manager, expected_solver_cls," + " expected_use_single_state, expected_needs_collision_pipeline", + SOLVER_MATRIX, +) +def test_initialize_solver_populates_canonical_state( + solver_cfg_factory, + expected_manager, + expected_solver_cls, + expected_use_single_state, + expected_needs_collision_pipeline, +): + """End-to-end: ``SimulationContext`` resolves the right manager subclass and + ``initialize_solver`` lands the right solver + flags on :class:`NewtonManager`. + + External code reads :class:`NewtonManager` attributes directly (``_solver``, + ``_use_single_state``, ``_needs_collision_pipeline``). Even though dispatch + runs through a leaf subclass (e.g. :class:`NewtonMJWarpManager`), shared + state is assigned through the explicit base class so that those reads keep + working regardless of which leaf is active. This test is the regression + guard for that contract. + + The builder is pre-populated with a minimal one-body / one-joint scene + (instead of relying on a USD stage) for two reasons: + + 1. :class:`SolverMuJoCo` requires at least one joint to convert the model + to MJCF; a ground-plane-only scene fails MJCF conversion. + 2. Pre-populating ``NewtonManager._builder`` causes + :meth:`NewtonManager.start_simulation` to skip + :meth:`instantiate_builder_from_stage`, so the test does not depend on + USD asset packages. + """ + sim_cfg = SimulationCfg( + dt=1.0 / 120.0, + device="cuda:0", + gravity=(0.0, 0.0, -9.81), + physics=NewtonCfg(solver_cfg=solver_cfg_factory(), use_cuda_graph=False), + ) + + with build_simulation_context(sim_cfg=sim_cfg) as sim: + # Resolved manager class matches the expected leaf. + resolved_manager = sim.physics_manager + # ``physics_manager`` is a LazyType proxy — compare by ``__name__`` to + # avoid forcing identity-by-id checks against the unresolved proxy. + assert resolved_manager.__name__ == expected_manager.__name__ + assert resolved_manager.__name__.lower().startswith("newton") + + # Pre-populate the builder with a minimal scene so MJCF conversion has + # something to work with. + builder = NewtonManager.create_builder() + body = builder.add_body(mass=1.0) + builder.add_joint_revolute(parent=-1, child=body, axis=(0, 0, 1)) + NewtonManager.set_builder(builder) + + # Force resolution and bring up the solver. + sim.reset() + + # Canonical state lives on the base class. + assert NewtonManager._solver is not None + assert isinstance(NewtonManager._solver, expected_solver_cls) + assert NewtonManager._use_single_state is expected_use_single_state + assert NewtonManager._needs_collision_pipeline is expected_needs_collision_pipeline + + # ``_contacts`` is allocated whichever way contacts are handled + # (MuJoCo internal buffer or Newton pipeline output). + # Kamino with internal contacts does not currently set NewtonManager._contacts. + if expected_solver_cls is not SolverKamino: + assert NewtonManager._contacts is not None + + # One step should not raise — proves the dispatch wiring lines up + # end-to-end. (We do not assert physics; that's covered by the + # asset/sensor test suites.) + sim.step(render=False) + + +def test_mjwarp_internal_contacts_with_collision_cfg_raises(): + """Combining ``use_mujoco_contacts=True`` with a ``collision_cfg`` is rejected. + + The check lives in :meth:`NewtonMJWarpManager._build_solver` because it + needs both the solver cfg subtype and the parent :class:`NewtonCfg`, so it + fires during :meth:`NewtonManager.initialize_solver` (i.e. on + ``sim.reset()``) rather than at cfg construction time. + """ + sim_cfg = SimulationCfg( + dt=1.0 / 120.0, + device="cuda:0", + gravity=(0.0, 0.0, -9.81), + physics=NewtonCfg( + solver_cfg=MJWarpSolverCfg(use_mujoco_contacts=True), + collision_cfg=NewtonCollisionPipelineCfg(), + use_cuda_graph=False, + ), + ) + + with build_simulation_context(sim_cfg=sim_cfg) as sim: + builder = NewtonManager.create_builder() + body = builder.add_body(mass=1.0) + builder.add_joint_revolute(parent=-1, child=body, axis=(0, 0, 1)) + NewtonManager.set_builder(builder) + + with pytest.raises(ValueError, match="collision_cfg cannot be set"): + sim.reset() diff --git a/source/isaaclab_newton/test/sensors/__init__.py b/source/isaaclab_newton/test/sensors/__init__.py index 460a30569089..acd8a74be49f 100644 --- a/source/isaaclab_newton/test/sensors/__init__.py +++ b/source/isaaclab_newton/test/sensors/__init__.py @@ -2,3 +2,4 @@ # All rights reserved. # # SPDX-License-Identifier: BSD-3-Clause +"""Tests for Newton sensors.""" diff --git a/source/isaaclab_newton/test/sensors/test_contact_sensor.py b/source/isaaclab_newton/test/sensors/test_contact_sensor.py index c3da11a99696..066803ee884b 100644 --- a/source/isaaclab_newton/test/sensors/test_contact_sensor.py +++ b/source/isaaclab_newton/test/sensors/test_contact_sensor.py @@ -26,7 +26,6 @@ import pytest import torch -import warp as wp from physics.physics_test_utils import ( COLLISION_PIPELINES, STABLE_SHAPES, @@ -124,7 +123,7 @@ def test_contact_lifecycle(device: str, use_mujoco_contacts: bool, shape_type: S contact_sensor: ContactSensor = scene["contact_sensor_a"] obj: RigidObject = scene["object_a"] - root_pose = wp.to_torch(obj.data.root_link_pose_w).clone() + root_pose = obj.data.root_link_pose_w.torch.clone() for group_idx, base_height in enumerate(base_heights): for i in range(envs_per_group): env_idx = group_idx * envs_per_group + i @@ -139,13 +138,13 @@ def test_contact_lifecycle(device: str, use_mujoco_contacts: bool, shape_type: S for _ in range(5): perform_sim_step(sim, scene, SIM_DT) - forces = torch.norm(wp.to_torch(contact_sensor.data.net_forces_w), dim=-1) + forces = torch.norm(contact_sensor.data.net_forces_w.torch, dim=-1) for env_idx in range(num_envs): assert forces[env_idx].max().item() < 0.01, f"Env {env_idx}: No contact should be detected while in air." for tick in range(5, total_fall_steps): perform_sim_step(sim, scene, SIM_DT) - forces = torch.norm(wp.to_torch(contact_sensor.data.net_forces_w), dim=-1) + forces = torch.norm(contact_sensor.data.net_forces_w.torch, dim=-1) for env_idx in range(num_envs): if forces[env_idx].max().item() > 0.1 and not contact_detected[env_idx]: contact_detected[env_idx] = True @@ -184,7 +183,7 @@ def test_contact_lifecycle(device: str, use_mujoco_contacts: bool, shape_type: S for step in range(lift_steps): perform_sim_step(sim, scene, SIM_DT) if step > 10: - forces = torch.norm(wp.to_torch(contact_sensor.data.net_forces_w), dim=-1) + forces = torch.norm(contact_sensor.data.net_forces_w.torch, dim=-1) for env_idx in range(num_envs): if forces[env_idx].max().item() < 0.01: no_contact_detected[env_idx] = True @@ -257,8 +256,8 @@ def test_horizontal_collision_detects_contact(device: str, use_mujoco_contacts: sensor_a: ContactSensor = scene["contact_sensor_a"] sensor_b: ContactSensor = scene["contact_sensor_b"] - pose_a = wp.to_torch(object_a.data.root_link_pose_w).clone() - pose_b = wp.to_torch(object_b.data.root_link_pose_w).clone() + pose_a = object_a.data.root_link_pose_w.torch.clone() + pose_b = object_b.data.root_link_pose_w.torch.clone() for group_idx, (_, separation) in enumerate(group_configs): for i in range(envs_per_group): env_idx = group_idx * envs_per_group + i @@ -278,8 +277,8 @@ def test_horizontal_collision_detects_contact(device: str, use_mujoco_contacts: for tick in range(collision_steps): perform_sim_step(sim, scene, SIM_DT) - forces_a = torch.norm(wp.to_torch(sensor_a.data.net_forces_w), dim=-1) - forces_b = torch.norm(wp.to_torch(sensor_b.data.net_forces_w), dim=-1) + forces_a = torch.norm(sensor_a.data.net_forces_w.torch, dim=-1) + forces_b = torch.norm(sensor_b.data.net_forces_w.torch, dim=-1) for env_idx in range(num_envs): if forces_a[env_idx].max().item() > 0.1: contact_detected_a[env_idx] = True @@ -310,7 +309,7 @@ def test_resting_object_contact_force(device: str, use_mujoco_contacts: bool): - Force direction is upward (positive Z) - Heavier object has proportionally larger force """ - settle_steps = 120 + settle_steps = 90 num_envs = 4 mass_a, mass_b = 2.0, 4.0 gravity_magnitude = 9.81 @@ -336,7 +335,7 @@ def test_resting_object_contact_force(device: str, use_mujoco_contacts: bool): mass_props=sim_utils.MassPropertiesCfg(mass=mass_a), activate_contact_sensors=True, ), - init_state=RigidObjectCfg.InitialStateCfg(pos=(-0.5, 0.0, 0.5)), + init_state=RigidObjectCfg.InitialStateCfg(pos=(-0.5, 0.0, 0.2)), ) scene_cfg.object_b = RigidObjectCfg( prim_path="{ENV_REGEX_NS}/BoxB", @@ -347,7 +346,7 @@ def test_resting_object_contact_force(device: str, use_mujoco_contacts: bool): mass_props=sim_utils.MassPropertiesCfg(mass=mass_b), activate_contact_sensors=True, ), - init_state=RigidObjectCfg.InitialStateCfg(pos=(0.5, 0.0, 0.5)), + init_state=RigidObjectCfg.InitialStateCfg(pos=(0.5, 0.0, 0.2)), ) scene_cfg.contact_sensor_a = ContactSensorCfg( prim_path="{ENV_REGEX_NS}/BoxA", update_period=0.0, history_length=1 @@ -363,28 +362,42 @@ def test_resting_object_contact_force(device: str, use_mujoco_contacts: bool): sensor_a: ContactSensor = scene["contact_sensor_a"] sensor_b: ContactSensor = scene["contact_sensor_b"] - for _ in range(settle_steps): + # Average contact force over the last `avg_window` ticks of the settle period to reject + # per-step solver oscillation around the resting force. + avg_window = 20 + force_a_samples: list[torch.Tensor] = [] + force_b_samples: list[torch.Tensor] = [] + for step in range(settle_steps): perform_sim_step(sim, scene, SIM_DT) + if step >= settle_steps - avg_window: + force_a_samples.append(sensor_a.data.net_forces_w.torch.clone()) + force_b_samples.append(sensor_b.data.net_forces_w.torch.clone()) - forces_a = wp.to_torch(sensor_a.data.net_forces_w) - forces_b = wp.to_torch(sensor_b.data.net_forces_w) + forces_a = torch.stack(force_a_samples).mean(dim=0) + forces_b = torch.stack(force_b_samples).mean(dim=0) force_mags_a = torch.norm(forces_a, dim=-1) force_mags_b = torch.norm(forces_b, dim=-1) + errs: list[str] = [] for env_idx in range(num_envs): fa = force_mags_a[env_idx].max().item() fb = force_mags_b[env_idx].max().item() - assert abs(fa - expected_force_a) < 0.2 * expected_force_a, ( - f"Env {env_idx}: BoxA ({mass_a}kg) force should be ~{expected_force_a:.2f} N. Got {fa:.2f} N" - ) - assert abs(fb - expected_force_b) < 0.2 * expected_force_b, ( - f"Env {env_idx}: BoxB ({mass_b}kg) force should be ~{expected_force_b:.2f} N. Got {fb:.2f} N" - ) - assert fb > fa, f"Env {env_idx}: Heavier BoxB should have larger force. A: {fa:.2f}, B: {fb:.2f}" - - assert forces_a[env_idx, 0, 2].item() > 0.1, f"Env {env_idx}: BoxA Z force should be positive" - assert forces_b[env_idx, 0, 2].item() > 0.1, f"Env {env_idx}: BoxB Z force should be positive" + if abs(fa - expected_force_a) >= 0.02 * expected_force_a: + errs.append( + f"Env {env_idx}: BoxA ({mass_a}kg) force should be ~{expected_force_a:.2f} N. Got {fa:.2f} N" + ) + if abs(fb - expected_force_b) >= 0.02 * expected_force_b: + errs.append( + f"Env {env_idx}: BoxB ({mass_b}kg) force should be ~{expected_force_b:.2f} N. Got {fb:.2f} N" + ) + if fb <= fa: + errs.append(f"Env {env_idx}: Heavier BoxB should have larger force. A: {fa:.2f}, B: {fb:.2f}") + if forces_a[env_idx, 0, 2].item() <= 0.1: + errs.append(f"Env {env_idx}: BoxA Z force should be positive") + if forces_b[env_idx, 0, 2].item() <= 0.1: + errs.append(f"Env {env_idx}: BoxB Z force should be positive") + assert not errs, "\n".join(errs) @pytest.mark.parametrize("device", ["cuda:0", "cpu"]) @@ -430,7 +443,7 @@ def test_higher_drop_produces_larger_impact_force(device: str, use_mujoco_contac obj: RigidObject = scene["object_a"] contact_sensor: ContactSensor = scene["contact_sensor_a"] - root_pose = wp.to_torch(obj.data.root_link_pose_w).clone() + root_pose = obj.data.root_link_pose_w.torch.clone() for env_idx in range(num_envs): root_pose[env_idx, 2] = drop_heights[env_idx] + object_radius obj.write_root_pose_to_sim_index(root_pose=root_pose) @@ -441,7 +454,7 @@ def test_higher_drop_produces_larger_impact_force(device: str, use_mujoco_contac for _ in range(total_steps): perform_sim_step(sim, scene, SIM_DT) - force_magnitudes = torch.norm(wp.to_torch(contact_sensor.data.net_forces_w), dim=-1) + force_magnitudes = torch.norm(contact_sensor.data.net_forces_w.torch, dim=-1) for env_idx in range(num_envs): f = force_magnitudes[env_idx].max().item() if f > 0.1: @@ -477,7 +490,8 @@ def test_higher_drop_produces_larger_impact_force(device: str, use_mujoco_contac False, id="newton_contacts", marks=pytest.mark.xfail( - reason="Newton contact forces are flaky in CI runs, but passes very consistently locally", strict=False + reason="Newton force_matrix_w is non-deterministic across hardware (reports 0 or inflated values)", + strict=False, ), ), pytest.param(True, id="mujoco_contacts"), @@ -494,7 +508,7 @@ def test_filter_enables_force_matrix(device: str, use_mujoco_contacts: bool): - net_forces_w reports total contact (ground + B) - force_matrix < net_forces (ground contact excluded from matrix) """ - settle_steps = 180 + settle_steps = 240 num_envs = 4 mass_b = 2.0 gravity = 9.81 @@ -530,7 +544,7 @@ def test_filter_enables_force_matrix(device: str, use_mujoco_contacts: bool): mass_props=sim_utils.MassPropertiesCfg(mass=mass_b), activate_contact_sensors=True, ), - init_state=RigidObjectCfg.InitialStateCfg(pos=(0.0, 0.0, 0.8)), + init_state=RigidObjectCfg.InitialStateCfg(pos=(0.0, 0.0, 0.55)), ) scene_cfg.contact_sensor_a = ContactSensorCfg( @@ -546,29 +560,42 @@ def test_filter_enables_force_matrix(device: str, use_mujoco_contacts: bool): contact_sensor: ContactSensor = scene["contact_sensor_a"] - for _ in range(settle_steps): + # Average over the last `avg_window` ticks to reject per-step solver oscillation. + avg_window = 20 + matrix_samples: list[torch.Tensor] = [] + net_samples: list[torch.Tensor] = [] + for step in range(settle_steps): perform_sim_step(sim, scene, SIM_DT) - - force_matrix_raw = contact_sensor.data.force_matrix_w - net_forces_raw = contact_sensor.data.net_forces_w - - assert force_matrix_raw is not None, "force_matrix_w should not be None when filter is set" - - force_matrix = wp.to_torch(force_matrix_raw) - net_forces = wp.to_torch(net_forces_raw) - + if step >= settle_steps - avg_window: + matrix_raw = contact_sensor.data.force_matrix_w + net_raw = contact_sensor.data.net_forces_w + if not matrix_samples: + assert matrix_raw is not None, "force_matrix_w should not be None when filter is set" + matrix_samples.append(matrix_raw.torch.clone()) + net_samples.append(net_raw.torch.clone()) + + force_matrix = torch.stack(matrix_samples).mean(dim=0) + net_forces = torch.stack(net_samples).mean(dim=0) + + expected_b_on_a = torch.tensor([0.0, 0.0, -expected_force_from_b], device=device) + tolerance = 0.05 * expected_force_from_b + errs: list[str] = [] for env_idx in range(num_envs): - matrix_force = torch.norm(force_matrix[env_idx]).item() - net_force = torch.norm(net_forces[env_idx]).item() - - tolerance = 0.3 * expected_force_from_b - assert abs(matrix_force - expected_force_from_b) < tolerance, ( - f"Env {env_idx}: force_matrix should be ~{expected_force_from_b:.2f} N. Got: {matrix_force:.2f} N" - ) - assert matrix_force < net_force, ( - f"Env {env_idx}: force_matrix (B only) should be < net_forces (all). " - f"Matrix: {matrix_force:.2f} N, Net: {net_force:.2f} N" - ) + b_on_a = force_matrix[env_idx, 0, 0] + net_contact = net_forces[env_idx, 0] + + error = torch.norm(b_on_a - expected_b_on_a).item() + if error >= tolerance: + errs.append( + f"Env {env_idx}: B-on-A should be ~{expected_b_on_a.tolist()} N. " + f"Got {b_on_a.tolist()}, error {error:.2f} N" + ) + if torch.norm(b_on_a).item() >= torch.norm(net_contact).item(): + errs.append( + f"Env {env_idx}: |B-on-A| should be < |net contact|. " + f"B-on-A: {b_on_a.tolist()}, Net: {net_contact.tolist()}" + ) + assert not errs, "\n".join(errs) # =================================================================== @@ -695,14 +722,14 @@ def test_finger_contact_sensor_isolation(device: str, use_mujoco_contacts: bool, # Newton's articulation.reset() doesn't write default_joint_pos to sim (unlike # ManagerBasedEnv's reset_scene_to_default event). Without this, joints start at 0.0 # which is below thumb_joint_0's lower limit (0.279 rad), causing violent oscillation. - default_jpos = wp.to_torch(hand.data.default_joint_pos).clone() - default_jvel = wp.to_torch(hand.data.default_joint_vel).clone() + default_jpos = hand.data.default_joint_pos.torch.clone() + default_jvel = hand.data.default_joint_vel.torch.clone() hand.write_joint_position_to_sim_index(position=default_jpos) hand.write_joint_velocity_to_sim_index(velocity=default_jvel) hand.set_joint_position_target_index(target=default_jpos) - hand_world_pos = wp.to_torch(hand.data.root_link_pose_w)[:, :3] - drop_pose = wp.to_torch(drop_object.data.root_link_pose_w).clone() + hand_world_pos = hand.data.root_link_pose_w.torch[:, :3] + drop_pose = drop_object.data.root_link_pose_w.torch.clone() for env_idx, finger in enumerate(finger_names): offset = ALLEGRO_FINGERTIP_OFFSETS[finger] drop_pose[env_idx, 0] = hand_world_pos[env_idx, 0] + offset[0] @@ -713,9 +740,9 @@ def test_finger_contact_sensor_isolation(device: str, use_mujoco_contacts: bool, for _ in range(30): perform_sim_step(sim, scene, SIM_DT) - hand_world_pos = wp.to_torch(hand.data.root_link_pose_w)[:, :3] + hand_world_pos = hand.data.root_link_pose_w.torch[:, :3] drop_object.reset() - drop_pose = wp.to_torch(drop_object.data.root_link_pose_w).clone() + drop_pose = drop_object.data.root_link_pose_w.torch.clone() for env_idx, finger in enumerate(finger_names): offset = ALLEGRO_FINGERTIP_OFFSETS[finger] drop_pose[env_idx, 0] = hand_world_pos[env_idx, 0] + offset[0] @@ -733,7 +760,7 @@ def test_finger_contact_sensor_isolation(device: str, use_mujoco_contacts: bool, perform_sim_step(sim, scene, SIM_DT) for finger_name, sensor in finger_sensors.items(): if sensor.data.net_forces_w is not None: - forces = wp.to_torch(sensor.data.net_forces_w) + forces = sensor.data.net_forces_w.torch for env_idx in range(num_envs): f = torch.norm(forces[env_idx]).item() peak_forces[finger_name][env_idx] = max(peak_forces[finger_name][env_idx], f) diff --git a/source/isaaclab_newton/test/sensors/test_frame_transformer.py b/source/isaaclab_newton/test/sensors/test_frame_transformer.py new file mode 100644 index 000000000000..513ba9dda918 --- /dev/null +++ b/source/isaaclab_newton/test/sensors/test_frame_transformer.py @@ -0,0 +1,812 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Tests to verify frame transformer sensor functionality using Newton physics.""" + +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +import math + +import pytest +import scipy.spatial.transform as tf +import torch +from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg + +import isaaclab.sim as sim_utils +import isaaclab.utils.math as math_utils +from isaaclab.assets import RigidObjectCfg +from isaaclab.scene import InteractiveScene, InteractiveSceneCfg +from isaaclab.sensors import FrameTransformerCfg, OffsetCfg +from isaaclab.sim import SimulationCfg +from isaaclab.terrains import TerrainImporterCfg +from isaaclab.utils import configclass + +## +# Pre-defined configs +## +from isaaclab_assets.robots.anymal import ANYMAL_C_CFG # isort:skip + + +def quat_from_euler_rpy(roll, pitch, yaw, degrees=False): + """Converts Euler XYZ to Quaternion (x, y, z, w).""" + quat = tf.Rotation.from_euler("xyz", (roll, pitch, yaw), degrees=degrees).as_quat() + return tuple(quat.tolist()) # scipy already returns xyzw + + +def euler_rpy_apply(rpy, xyz, degrees=False): + """Applies rotation from Euler XYZ on position vector.""" + rot = tf.Rotation.from_euler("xyz", rpy, degrees=degrees) + return tuple(rot.apply(xyz).tolist()) + + +@configclass +class MySceneCfg(InteractiveSceneCfg): + """Example scene configuration.""" + + # terrain - flat terrain plane + terrain = TerrainImporterCfg(prim_path="/World/ground", terrain_type="plane") + + # articulation - robot + robot = ANYMAL_C_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") + + # sensors - frame transformer (filled inside unit test) + frame_transformer: FrameTransformerCfg = None + + # block + cube: RigidObjectCfg = RigidObjectCfg( + prim_path="{ENV_REGEX_NS}/cube", + spawn=sim_utils.CuboidCfg( + size=(0.2, 0.2, 0.2), + rigid_props=sim_utils.RigidBodyPropertiesCfg(max_depenetration_velocity=1.0), + mass_props=sim_utils.MassPropertiesCfg(mass=1.0), + physics_material=sim_utils.RigidBodyMaterialCfg(), + visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(0.5, 0.0, 0.0)), + ), + init_state=RigidObjectCfg.InitialStateCfg(pos=(2.0, 0.0, 5)), + ) + + +@pytest.fixture +def sim(): + """Create a simulation context with Newton physics.""" + sim_cfg = SimulationCfg( + dt=1 / 120, + physics=NewtonCfg( + solver_cfg=MJWarpSolverCfg( + njmax=70, + nconmax=70, + ls_iterations=40, + cone="elliptic", + impratio=100, + ls_parallel=False, + integrator="implicitfast", + ), + num_substeps=2, + debug_mode=True, + ), + ) + with sim_utils.build_simulation_context(sim_cfg=sim_cfg) as sim: + sim._app_control_on_stop_handle = None + # Set main camera + sim.set_camera_view(eye=(5.0, 5.0, 5.0), target=(0.0, 0.0, 0.0)) + yield sim + # Cleanup is handled by build_simulation_context + + +def test_frame_transformer_feet_wrt_base(sim): + """Test feet transformations w.r.t. base source frame. + + In this test, the source frame is the robot base. + """ + # Spawn things into stage + scene_cfg = MySceneCfg(num_envs=2, env_spacing=5.0, lazy_sensor_update=False) + scene_cfg.frame_transformer = FrameTransformerCfg( + prim_path="{ENV_REGEX_NS}/Robot/base", + target_frames=[ + FrameTransformerCfg.FrameCfg( + name="LF_FOOT_USER", + prim_path="{ENV_REGEX_NS}/Robot/LF_SHANK", + offset=OffsetCfg( + pos=euler_rpy_apply(rpy=(0, 0, -math.pi / 2), xyz=(0.08795, 0.01305, -0.33797)), + rot=quat_from_euler_rpy(0, 0, -math.pi / 2), + ), + ), + FrameTransformerCfg.FrameCfg( + name="RF_FOOT_USER", + prim_path="{ENV_REGEX_NS}/Robot/RF_SHANK", + offset=OffsetCfg( + pos=euler_rpy_apply(rpy=(0, 0, math.pi / 2), xyz=(0.08795, -0.01305, -0.33797)), + rot=quat_from_euler_rpy(0, 0, math.pi / 2), + ), + ), + FrameTransformerCfg.FrameCfg( + name="LH_FOOT_USER", + prim_path="{ENV_REGEX_NS}/Robot/LH_SHANK", + offset=OffsetCfg( + pos=euler_rpy_apply(rpy=(0, 0, -math.pi / 2), xyz=(-0.08795, 0.01305, -0.33797)), + rot=quat_from_euler_rpy(0, 0, -math.pi / 2), + ), + ), + FrameTransformerCfg.FrameCfg( + name="RH_FOOT_USER", + prim_path="{ENV_REGEX_NS}/Robot/RH_SHANK", + offset=OffsetCfg( + pos=euler_rpy_apply(rpy=(0, 0, math.pi / 2), xyz=(-0.08795, -0.01305, -0.33797)), + rot=quat_from_euler_rpy(0, 0, math.pi / 2), + ), + ), + ], + ) + scene = InteractiveScene(scene_cfg) + + # Play the simulator + sim.reset() + + # Acquire the index of ground truth bodies + feet_indices, feet_names = scene.articulations["robot"].find_bodies(["LF_FOOT", "RF_FOOT", "LH_FOOT", "RH_FOOT"]) + + target_frame_names = scene.sensors["frame_transformer"].data.target_frame_names + + # Reorder the feet indices to match the order of the target frames with _USER suffix removed + target_frame_names = [name.split("_USER")[0] for name in target_frame_names] + + # Find the indices of the feet in the order of the target frames + reordering_indices = [feet_names.index(name) for name in target_frame_names] + feet_indices = [feet_indices[i] for i in reordering_indices] + + # default joint targets + default_actions = scene.articulations["robot"].data.default_joint_pos.torch.clone() + # Define simulation stepping + sim_dt = sim.get_physics_dt() + # Simulate physics + for count in range(100): + # # reset + if count % 25 == 0: + # reset root state + root_state = scene.articulations["robot"].data.default_root_state.torch.clone() + root_state[:, :3] += scene.env_origins + joint_pos = scene.articulations["robot"].data.default_joint_pos.torch + joint_vel = scene.articulations["robot"].data.default_joint_vel.torch + # -- set root state + # -- robot + scene.articulations["robot"].write_root_pose_to_sim(root_state[:, :7]) + scene.articulations["robot"].write_root_velocity_to_sim(root_state[:, 7:]) + scene.articulations["robot"].write_joint_state_to_sim(joint_pos, joint_vel) + # reset buffers + scene.reset() + + # set joint targets + robot_actions = default_actions + 0.5 * torch.randn_like(default_actions) + scene.articulations["robot"].set_joint_position_target(robot_actions) + # write data to sim + scene.write_data_to_sim() + # perform step + sim.step() + # read data from sim + scene.update(sim_dt) + + # check absolute frame transforms in world frame + # -- ground-truth + root_pose_w = scene.articulations["robot"].data.root_pose_w.torch + feet_pos_w_gt = scene.articulations["robot"].data.body_pos_w.torch[:, feet_indices] + feet_quat_w_gt = scene.articulations["robot"].data.body_quat_w.torch[:, feet_indices] + # -- frame transformer + source_pos_w_tf = scene.sensors["frame_transformer"].data.source_pos_w.torch + source_quat_w_tf = scene.sensors["frame_transformer"].data.source_quat_w.torch + feet_pos_w_tf = scene.sensors["frame_transformer"].data.target_pos_w.torch + feet_quat_w_tf = scene.sensors["frame_transformer"].data.target_quat_w.torch + + # check if they are same + torch.testing.assert_close(root_pose_w[:, :3], source_pos_w_tf) + torch.testing.assert_close(root_pose_w[:, 3:], source_quat_w_tf) + torch.testing.assert_close(feet_pos_w_gt, feet_pos_w_tf) + torch.testing.assert_close(feet_quat_w_gt, feet_quat_w_tf) + + # check if relative transforms are same + feet_pos_source_tf = scene.sensors["frame_transformer"].data.target_pos_source.torch + feet_quat_source_tf = scene.sensors["frame_transformer"].data.target_quat_source.torch + for index in range(len(feet_indices)): + # ground-truth + foot_pos_b, foot_quat_b = math_utils.subtract_frame_transforms( + root_pose_w[:, :3], root_pose_w[:, 3:], feet_pos_w_tf[:, index], feet_quat_w_tf[:, index] + ) + # check if they are same + torch.testing.assert_close(feet_pos_source_tf[:, index], foot_pos_b) + torch.testing.assert_close(feet_quat_source_tf[:, index], foot_quat_b) + + +def test_frame_transformer_feet_wrt_thigh(sim): + """Test feet transformation w.r.t. thigh source frame.""" + # Spawn things into stage + scene_cfg = MySceneCfg(num_envs=2, env_spacing=5.0, lazy_sensor_update=False) + scene_cfg.frame_transformer = FrameTransformerCfg( + prim_path="{ENV_REGEX_NS}/Robot/LF_THIGH", + target_frames=[ + FrameTransformerCfg.FrameCfg( + name="LF_FOOT_USER", + prim_path="{ENV_REGEX_NS}/Robot/LF_SHANK", + offset=OffsetCfg( + pos=euler_rpy_apply(rpy=(0, 0, -math.pi / 2), xyz=(0.08795, 0.01305, -0.33797)), + rot=quat_from_euler_rpy(0, 0, -math.pi / 2), + ), + ), + FrameTransformerCfg.FrameCfg( + name="RF_FOOT_USER", + prim_path="{ENV_REGEX_NS}/Robot/RF_SHANK", + offset=OffsetCfg( + pos=euler_rpy_apply(rpy=(0, 0, math.pi / 2), xyz=(0.08795, -0.01305, -0.33797)), + rot=quat_from_euler_rpy(0, 0, math.pi / 2), + ), + ), + ], + ) + scene = InteractiveScene(scene_cfg) + + # Play the simulator + sim.reset() + + # Acquire the index of ground truth bodies + source_frame_index = scene.articulations["robot"].find_bodies("LF_THIGH")[0][0] + feet_indices, feet_names = scene.articulations["robot"].find_bodies(["LF_FOOT", "RF_FOOT"]) + # Check names are parsed the same order + user_feet_names = [f"{name}_USER" for name in feet_names] + assert scene.sensors["frame_transformer"].data.target_frame_names == user_feet_names + + # default joint targets + default_actions = scene.articulations["robot"].data.default_joint_pos.torch.clone() + # Define simulation stepping + sim_dt = sim.get_physics_dt() + # Simulate physics + for count in range(100): + # # reset + if count % 25 == 0: + # reset root state + root_state = scene.articulations["robot"].data.default_root_state.torch.clone() + root_state[:, :3] += scene.env_origins + joint_pos = scene.articulations["robot"].data.default_joint_pos.torch + joint_vel = scene.articulations["robot"].data.default_joint_vel.torch + # -- set root state + # -- robot + scene.articulations["robot"].write_root_pose_to_sim(root_state[:, :7]) + scene.articulations["robot"].write_root_velocity_to_sim(root_state[:, 7:]) + scene.articulations["robot"].write_joint_state_to_sim(joint_pos, joint_vel) + # reset buffers + scene.reset() + + # set joint targets + robot_actions = default_actions + 0.5 * torch.randn_like(default_actions) + scene.articulations["robot"].set_joint_position_target(robot_actions) + # write data to sim + scene.write_data_to_sim() + # perform step + sim.step() + # read data from sim + scene.update(sim_dt) + + # check absolute frame transforms in world frame + # -- ground-truth + source_pose_w_gt = scene.articulations["robot"].data.body_state_w.torch[:, source_frame_index, :7] + feet_pos_w_gt = scene.articulations["robot"].data.body_pos_w.torch[:, feet_indices] + feet_quat_w_gt = scene.articulations["robot"].data.body_quat_w.torch[:, feet_indices] + # -- frame transformer + source_pos_w_tf = scene.sensors["frame_transformer"].data.source_pos_w.torch + source_quat_w_tf = scene.sensors["frame_transformer"].data.source_quat_w.torch + feet_pos_w_tf = scene.sensors["frame_transformer"].data.target_pos_w.torch + feet_quat_w_tf = scene.sensors["frame_transformer"].data.target_quat_w.torch + # check if they are same + torch.testing.assert_close(source_pose_w_gt[:, :3], source_pos_w_tf) + torch.testing.assert_close(source_pose_w_gt[:, 3:], source_quat_w_tf) + torch.testing.assert_close(feet_pos_w_gt, feet_pos_w_tf) + torch.testing.assert_close(feet_quat_w_gt, feet_quat_w_tf) + + # check if relative transforms are same + feet_pos_source_tf = scene.sensors["frame_transformer"].data.target_pos_source.torch + feet_quat_source_tf = scene.sensors["frame_transformer"].data.target_quat_source.torch + for index in range(len(feet_indices)): + # ground-truth + foot_pos_b, foot_quat_b = math_utils.subtract_frame_transforms( + source_pose_w_gt[:, :3], source_pose_w_gt[:, 3:], feet_pos_w_tf[:, index], feet_quat_w_tf[:, index] + ) + # check if they are same + torch.testing.assert_close(feet_pos_source_tf[:, index], foot_pos_b) + torch.testing.assert_close(feet_quat_source_tf[:, index], foot_quat_b) + + +def test_frame_transformer_robot_body_to_external_cube(sim): + """Test transformation from robot body to a cube in the scene.""" + # Spawn things into stage + scene_cfg = MySceneCfg(num_envs=2, env_spacing=5.0, lazy_sensor_update=False) + scene_cfg.frame_transformer = FrameTransformerCfg( + prim_path="{ENV_REGEX_NS}/Robot/base", + target_frames=[ + FrameTransformerCfg.FrameCfg( + name="CUBE_USER", + prim_path="{ENV_REGEX_NS}/cube", + ), + ], + ) + scene = InteractiveScene(scene_cfg) + + # Play the simulator + sim.reset() + + # default joint targets + default_actions = scene.articulations["robot"].data.default_joint_pos.torch.clone() + # Define simulation stepping + sim_dt = sim.get_physics_dt() + # Simulate physics + for count in range(100): + # # reset + if count % 25 == 0: + # reset root state + root_state = scene.articulations["robot"].data.default_root_state.torch.clone() + root_state[:, :3] += scene.env_origins + joint_pos = scene.articulations["robot"].data.default_joint_pos.torch + joint_vel = scene.articulations["robot"].data.default_joint_vel.torch + # -- set root state + # -- robot + scene.articulations["robot"].write_root_pose_to_sim(root_state[:, :7]) + scene.articulations["robot"].write_root_velocity_to_sim(root_state[:, 7:]) + scene.articulations["robot"].write_joint_state_to_sim(joint_pos, joint_vel) + # reset buffers + scene.reset() + + # set joint targets + robot_actions = default_actions + 0.5 * torch.randn_like(default_actions) + scene.articulations["robot"].set_joint_position_target(robot_actions) + # write data to sim + scene.write_data_to_sim() + # perform step + sim.step() + # read data from sim + scene.update(sim_dt) + + # check absolute frame transforms in world frame + # -- ground-truth + root_pose_w = scene.articulations["robot"].data.root_pose_w.torch + cube_pos_w_gt = scene.rigid_objects["cube"].data.root_pos_w.torch + cube_quat_w_gt = scene.rigid_objects["cube"].data.root_quat_w.torch + # -- frame transformer + source_pos_w_tf = scene.sensors["frame_transformer"].data.source_pos_w.torch + source_quat_w_tf = scene.sensors["frame_transformer"].data.source_quat_w.torch + cube_pos_w_tf = scene.sensors["frame_transformer"].data.target_pos_w.torch.squeeze() + cube_quat_w_tf = scene.sensors["frame_transformer"].data.target_quat_w.torch.squeeze() + + # check if they are same + torch.testing.assert_close(root_pose_w[:, :3], source_pos_w_tf) + torch.testing.assert_close(root_pose_w[:, 3:], source_quat_w_tf) + torch.testing.assert_close(cube_pos_w_gt, cube_pos_w_tf) + torch.testing.assert_close(cube_quat_w_gt, cube_quat_w_tf) + + # check if relative transforms are same + cube_pos_source_tf = scene.sensors["frame_transformer"].data.target_pos_source.torch + cube_quat_source_tf = scene.sensors["frame_transformer"].data.target_quat_source.torch + # ground-truth + cube_pos_b, cube_quat_b = math_utils.subtract_frame_transforms( + root_pose_w[:, :3], root_pose_w[:, 3:], cube_pos_w_tf, cube_quat_w_tf + ) + # check if they are same + torch.testing.assert_close(cube_pos_source_tf[:, 0], cube_pos_b) + torch.testing.assert_close(cube_quat_source_tf[:, 0], cube_quat_b) + + +@pytest.mark.isaacsim_ci +def test_frame_transformer_offset_frames(sim): + """Test body transformation w.r.t. base source frame. + + In this test, the source frame is the cube frame. + """ + # Spawn things into stage + scene_cfg = MySceneCfg(num_envs=2, env_spacing=5.0, lazy_sensor_update=False) + scene_cfg.frame_transformer = FrameTransformerCfg( + prim_path="{ENV_REGEX_NS}/cube", + target_frames=[ + FrameTransformerCfg.FrameCfg( + name="CUBE_CENTER", + prim_path="{ENV_REGEX_NS}/cube", + ), + FrameTransformerCfg.FrameCfg( + name="CUBE_TOP", + prim_path="{ENV_REGEX_NS}/cube", + offset=OffsetCfg( + pos=(0.0, 0.0, 0.1), + rot=(0.0, 0.0, 0.0, 1.0), + ), + ), + FrameTransformerCfg.FrameCfg( + name="CUBE_BOTTOM", + prim_path="{ENV_REGEX_NS}/cube", + offset=OffsetCfg( + pos=(0.0, 0.0, -0.1), + rot=(0.0, 0.0, 0.0, 1.0), + ), + ), + ], + ) + scene = InteractiveScene(scene_cfg) + + # Play the simulator + sim.reset() + + # Define simulation stepping + sim_dt = sim.get_physics_dt() + # Simulate physics + for count in range(100): + # # reset + if count % 25 == 0: + # reset root state + root_state = scene["cube"].data.default_root_state.torch.clone() + root_state[:, :3] += scene.env_origins + # -- set root state + # -- cube + scene["cube"].write_root_pose_to_sim(root_state[:, :7]) + scene["cube"].write_root_velocity_to_sim(root_state[:, 7:]) + # reset buffers + scene.reset() + + # write data to sim + scene.write_data_to_sim() + # perform step + sim.step() + # read data from sim + scene.update(sim_dt) + + # check absolute frame transforms in world frame + # -- ground-truth + cube_pos_w_gt = scene["cube"].data.root_pos_w.torch + cube_quat_w_gt = scene["cube"].data.root_quat_w.torch + # -- frame transformer + source_pos_w_tf = scene.sensors["frame_transformer"].data.source_pos_w.torch + source_quat_w_tf = scene.sensors["frame_transformer"].data.source_quat_w.torch + target_pos_w_tf = scene.sensors["frame_transformer"].data.target_pos_w.torch.squeeze() + target_quat_w_tf = scene.sensors["frame_transformer"].data.target_quat_w.torch.squeeze() + target_frame_names = scene.sensors["frame_transformer"].data.target_frame_names + + cube_center_idx = target_frame_names.index("CUBE_CENTER") + cube_bottom_idx = target_frame_names.index("CUBE_BOTTOM") + cube_top_idx = target_frame_names.index("CUBE_TOP") + + # check if they are same + torch.testing.assert_close(cube_pos_w_gt, source_pos_w_tf) + torch.testing.assert_close(cube_quat_w_gt, source_quat_w_tf) + torch.testing.assert_close(cube_pos_w_gt, target_pos_w_tf[:, cube_center_idx]) + torch.testing.assert_close(cube_quat_w_gt, target_quat_w_tf[:, cube_center_idx]) + + # test offsets are applied correctly + # -- cube top + cube_pos_top = target_pos_w_tf[:, cube_top_idx] + cube_quat_top = target_quat_w_tf[:, cube_top_idx] + torch.testing.assert_close( + cube_pos_top, cube_pos_w_gt + torch.tensor([0.0, 0.0, 0.1], device=cube_pos_w_gt.device) + ) + torch.testing.assert_close(cube_quat_top, cube_quat_w_gt) + + # -- cube bottom + cube_pos_bottom = target_pos_w_tf[:, cube_bottom_idx] + cube_quat_bottom = target_quat_w_tf[:, cube_bottom_idx] + torch.testing.assert_close( + cube_pos_bottom, cube_pos_w_gt + torch.tensor([0.0, 0.0, -0.1], device=cube_pos_w_gt.device) + ) + torch.testing.assert_close(cube_quat_bottom, cube_quat_w_gt) + + +@pytest.mark.isaacsim_ci +def test_frame_transformer_all_bodies(sim): + """Test transformation of all bodies w.r.t. base source frame. + + In this test, the source frame is the robot base. + + The target_frames are all bodies in the robot, implemented using .* pattern. + """ + # Spawn things into stage + scene_cfg = MySceneCfg(num_envs=2, env_spacing=5.0, lazy_sensor_update=False) + scene_cfg.frame_transformer = FrameTransformerCfg( + prim_path="{ENV_REGEX_NS}/Robot/base", + target_frames=[ + FrameTransformerCfg.FrameCfg( + prim_path="{ENV_REGEX_NS}/Robot/.*", + ), + ], + ) + scene = InteractiveScene(scene_cfg) + + # Play the simulator + sim.reset() + + target_frame_names = scene.sensors["frame_transformer"].data.target_frame_names + articulation_body_names = scene.articulations["robot"].data.body_names + + reordering_indices = [target_frame_names.index(name) for name in articulation_body_names] + + # default joint targets + default_actions = scene.articulations["robot"].data.default_joint_pos.torch.clone() + # Define simulation stepping + sim_dt = sim.get_physics_dt() + # Simulate physics + for count in range(100): + # # reset + if count % 25 == 0: + # reset root state + root_state = scene.articulations["robot"].data.default_root_state.torch.clone() + root_state[:, :3] += scene.env_origins + joint_pos = scene.articulations["robot"].data.default_joint_pos.torch + joint_vel = scene.articulations["robot"].data.default_joint_vel.torch + # -- set root state + # -- robot + scene.articulations["robot"].write_root_pose_to_sim(root_state[:, :7]) + scene.articulations["robot"].write_root_velocity_to_sim(root_state[:, 7:]) + scene.articulations["robot"].write_joint_state_to_sim(joint_pos, joint_vel) + # reset buffers + scene.reset() + + # set joint targets + robot_actions = default_actions + 0.5 * torch.randn_like(default_actions) + scene.articulations["robot"].set_joint_position_target(robot_actions) + # write data to sim + scene.write_data_to_sim() + # perform step + sim.step() + # read data from sim + scene.update(sim_dt) + + # check absolute frame transforms in world frame + # -- ground-truth + root_pose_w = scene.articulations["robot"].data.root_pose_w.torch + bodies_pos_w_gt = scene.articulations["robot"].data.body_pos_w.torch + bodies_quat_w_gt = scene.articulations["robot"].data.body_quat_w.torch + + # -- frame transformer + source_pos_w_tf = scene.sensors["frame_transformer"].data.source_pos_w.torch + source_quat_w_tf = scene.sensors["frame_transformer"].data.source_quat_w.torch + bodies_pos_w_tf = scene.sensors["frame_transformer"].data.target_pos_w.torch + bodies_quat_w_tf = scene.sensors["frame_transformer"].data.target_quat_w.torch + + # check if they are same + torch.testing.assert_close(root_pose_w[:, :3], source_pos_w_tf) + torch.testing.assert_close(root_pose_w[:, 3:], source_quat_w_tf) + torch.testing.assert_close(bodies_pos_w_gt, bodies_pos_w_tf[:, reordering_indices]) + torch.testing.assert_close(bodies_quat_w_gt, bodies_quat_w_tf[:, reordering_indices]) + + bodies_pos_source_tf = scene.sensors["frame_transformer"].data.target_pos_source.torch + bodies_quat_source_tf = scene.sensors["frame_transformer"].data.target_quat_source.torch + + # Go through each body and check if relative transforms are same + for index in range(len(articulation_body_names)): + body_pos_b, body_quat_b = math_utils.subtract_frame_transforms( + root_pose_w[:, :3], root_pose_w[:, 3:], bodies_pos_w_tf[:, index], bodies_quat_w_tf[:, index] + ) + + torch.testing.assert_close(bodies_pos_source_tf[:, index], body_pos_b) + torch.testing.assert_close(bodies_quat_source_tf[:, index], body_quat_b) + + +@pytest.mark.isaacsim_ci +def test_sensor_print(sim): + """Test sensor print is working correctly.""" + # Spawn things into stage + scene_cfg = MySceneCfg(num_envs=2, env_spacing=5.0, lazy_sensor_update=False) + scene_cfg.frame_transformer = FrameTransformerCfg( + prim_path="{ENV_REGEX_NS}/Robot/base", + target_frames=[ + FrameTransformerCfg.FrameCfg( + prim_path="{ENV_REGEX_NS}/Robot/.*", + ), + ], + ) + scene = InteractiveScene(scene_cfg) + + # Play the simulator + sim.reset() + # print info + print(scene.sensors["frame_transformer"]) + + +@pytest.mark.isaacsim_ci +@pytest.mark.parametrize("source_robot", ["Robot", "Robot_1"]) +@pytest.mark.parametrize("path_prefix", ["{ENV_REGEX_NS}", "/World"]) +def test_frame_transformer_duplicate_body_names(sim, source_robot, path_prefix): + """Test tracking bodies with same leaf name at different hierarchy levels. + + This test verifies that bodies with the same leaf name but different paths + (e.g., Robot/LF_SHANK vs Robot_1/LF_SHANK, or arm/link vs leg/link) are tracked + separately using their full relative paths internally. + + The test uses 4 target frames to cover both scenarios: + + Explicit frame names (recommended when bodies share the same leaf name): + User provides unique names like "Robot_LF_SHANK" and "Robot_1_LF_SHANK" to + distinguish between bodies at different hierarchy levels. This makes it + easy to identify which transform belongs to which body. + + Implicit frame names (backward compatibility): + When no name is provided, it defaults to the leaf body name (e.g., "RF_SHANK"). + This preserves backward compatibility for users who may have existing code like + `idx = target_frame_names.index("RF_SHANK")`. However, when multiple bodies share + the same leaf name, this results in duplicate frame names. The transforms are + still distinct because internal body tracking uses full relative paths. + + Args: + source_robot: The robot to use as the source frame ("Robot" or "Robot_1"). + This tests that both source frames work correctly when there are + duplicate body names. + path_prefix: The path prefix to use ("{ENV_REGEX_NS}" for env patterns or "/World" for direct paths). + """ + + # Create a custom scene config with two robots + @configclass + class MultiRobotSceneCfg(InteractiveSceneCfg): + """Scene with two robots having bodies with same names.""" + + terrain = TerrainImporterCfg(prim_path="/World/ground", terrain_type="plane") + + # Frame transformer will be set after config creation (needs source_robot parameter) + frame_transformer: FrameTransformerCfg = None # type: ignore + + # Use multiple envs for env patterns, single env for direct paths + num_envs = 2 if path_prefix == "{ENV_REGEX_NS}" else 1 + env_spacing = 10.0 if path_prefix == "{ENV_REGEX_NS}" else 0.0 + + # Create scene config with appropriate prim paths + scene_cfg = MultiRobotSceneCfg(num_envs=num_envs, env_spacing=env_spacing, lazy_sensor_update=False) + scene_cfg.robot = ANYMAL_C_CFG.replace(prim_path=f"{path_prefix}/Robot") + scene_cfg.robot_1 = ANYMAL_C_CFG.replace( + prim_path=f"{path_prefix}/Robot_1", + init_state=ANYMAL_C_CFG.init_state.replace(pos=(2.0, 0.0, 0.6)), + ) + + # Frame transformer tracking same-named bodies from both robots + # Source frame is parametrized to test both Robot/base and Robot_1/base + scene_cfg.frame_transformer = FrameTransformerCfg( + prim_path=f"{path_prefix}/{source_robot}/base", + target_frames=[ + # Explicit frame names (recommended when bodies share the same leaf name) + FrameTransformerCfg.FrameCfg( + name="Robot_LF_SHANK", + prim_path=f"{path_prefix}/Robot/LF_SHANK", + ), + FrameTransformerCfg.FrameCfg( + name="Robot_1_LF_SHANK", + prim_path=f"{path_prefix}/Robot_1/LF_SHANK", + ), + # Implicit frame names (backward compatibility) + FrameTransformerCfg.FrameCfg( + prim_path=f"{path_prefix}/Robot/RF_SHANK", + ), + FrameTransformerCfg.FrameCfg( + prim_path=f"{path_prefix}/Robot_1/RF_SHANK", + ), + ], + ) + scene = InteractiveScene(scene_cfg) + + # Play the simulator + sim.reset() + + # Get target frame names + target_frame_names = scene.sensors["frame_transformer"].data.target_frame_names + + # Verify explicit frame names are present + assert "Robot_LF_SHANK" in target_frame_names, f"Expected 'Robot_LF_SHANK', got {target_frame_names}" + assert "Robot_1_LF_SHANK" in target_frame_names, f"Expected 'Robot_1_LF_SHANK', got {target_frame_names}" + + # Without explicit names, both RF_SHANK frames default to same name "RF_SHANK" + # This results in duplicate frame names (expected behavior for backwards compatibility) + rf_shank_count = target_frame_names.count("RF_SHANK") + assert rf_shank_count == 2, f"Expected 2 'RF_SHANK' entries (name collision), got {rf_shank_count}" + + # Get indices for explicit named frames + robot_lf_idx = target_frame_names.index("Robot_LF_SHANK") + robot_1_lf_idx = target_frame_names.index("Robot_1_LF_SHANK") + + # Get indices for implicit named frames (both named "RF_SHANK") + rf_shank_indices = [i for i, name in enumerate(target_frame_names) if name == "RF_SHANK"] + assert len(rf_shank_indices) == 2, f"Expected 2 RF_SHANK indices, got {rf_shank_indices}" + + # Acquire ground truth body indices + robot_base_body_idx = scene.articulations["robot"].find_bodies("base")[0][0] + robot_1_base_body_idx = scene.articulations["robot_1"].find_bodies("base")[0][0] + robot_lf_shank_body_idx = scene.articulations["robot"].find_bodies("LF_SHANK")[0][0] + robot_1_lf_shank_body_idx = scene.articulations["robot_1"].find_bodies("LF_SHANK")[0][0] + robot_rf_shank_body_idx = scene.articulations["robot"].find_bodies("RF_SHANK")[0][0] + robot_1_rf_shank_body_idx = scene.articulations["robot_1"].find_bodies("RF_SHANK")[0][0] + + # Determine expected source frame based on parameter + expected_source_robot = "robot" if source_robot == "Robot" else "robot_1" + expected_source_base_body_idx = robot_base_body_idx if source_robot == "Robot" else robot_1_base_body_idx + + # Define simulation stepping + sim_dt = sim.get_physics_dt() + + # Simulate physics + for count in range(20): + # Reset periodically + if count % 10 == 0: + # Reset robot + root_state = scene.articulations["robot"].data.default_root_state.torch.clone() + root_state[:, :3] += scene.env_origins + scene.articulations["robot"].write_root_pose_to_sim(root_state[:, :7]) + scene.articulations["robot"].write_root_velocity_to_sim(root_state[:, 7:]) + scene.articulations["robot"].write_joint_state_to_sim( + scene.articulations["robot"].data.default_joint_pos.torch, + scene.articulations["robot"].data.default_joint_vel.torch, + ) + # Reset robot_1 + root_state_1 = scene.articulations["robot_1"].data.default_root_state.torch.clone() + root_state_1[:, :3] += scene.env_origins + scene.articulations["robot_1"].write_root_pose_to_sim(root_state_1[:, :7]) + scene.articulations["robot_1"].write_root_velocity_to_sim(root_state_1[:, 7:]) + scene.articulations["robot_1"].write_joint_state_to_sim( + scene.articulations["robot_1"].data.default_joint_pos.torch, + scene.articulations["robot_1"].data.default_joint_vel.torch, + ) + scene.reset() + + # Write data to sim + scene.write_data_to_sim() + # Perform step + sim.step() + # Read data from sim + scene.update(sim_dt) + + # Get frame transformer data + frame_transformer_data = scene.sensors["frame_transformer"].data + source_pos_w = frame_transformer_data.source_pos_w.torch + source_quat_w = frame_transformer_data.source_quat_w.torch + target_pos_w = frame_transformer_data.target_pos_w.torch + + # Get ground truth positions and orientations (after scene.update() so they're current) + robot_lf_pos_w = scene.articulations["robot"].data.body_pos_w.torch[:, robot_lf_shank_body_idx] + robot_1_lf_pos_w = scene.articulations["robot_1"].data.body_pos_w.torch[:, robot_1_lf_shank_body_idx] + robot_rf_pos_w = scene.articulations["robot"].data.body_pos_w.torch[:, robot_rf_shank_body_idx] + robot_1_rf_pos_w = scene.articulations["robot_1"].data.body_pos_w.torch[:, robot_1_rf_shank_body_idx] + + # Get expected source frame positions and orientations (after scene.update() so they're current) + expected_source_base_pos_w = scene.articulations[expected_source_robot].data.body_pos_w.torch[ + :, expected_source_base_body_idx + ] + expected_source_base_quat_w = scene.articulations[expected_source_robot].data.body_quat_w.torch[ + :, expected_source_base_body_idx + ] + + # TEST 1: Verify source frame is correctly resolved + # The source_pos_w should match the expected source robot's base world position + torch.testing.assert_close(source_pos_w, expected_source_base_pos_w, rtol=1e-5, atol=1e-5) + torch.testing.assert_close(source_quat_w, expected_source_base_quat_w, rtol=1e-5, atol=1e-5) + + # TEST 2: Explicit named frames (LF_SHANK) should have DIFFERENT world positions + lf_pos_difference = torch.linalg.norm(target_pos_w[:, robot_lf_idx] - target_pos_w[:, robot_1_lf_idx], dim=-1) + assert torch.all(lf_pos_difference > 1.0), ( + f"Robot_LF_SHANK and Robot_1_LF_SHANK should have different positions (got diff={lf_pos_difference}). " + "This indicates body name collision bug." + ) + + # Verify explicit named frames match correct robot bodies + torch.testing.assert_close(target_pos_w[:, robot_lf_idx], robot_lf_pos_w) + torch.testing.assert_close(target_pos_w[:, robot_1_lf_idx], robot_1_lf_pos_w) + + # TEST 3: Implicit named frames (RF_SHANK) should also have DIFFERENT world positions + # Even though they have the same frame name, internal body tracking uses full paths + rf_pos_difference = torch.linalg.norm( + target_pos_w[:, rf_shank_indices[0]] - target_pos_w[:, rf_shank_indices[1]], dim=-1 + ) + assert torch.all(rf_pos_difference > 1.0), ( + f"The two RF_SHANK frames should have different positions (got diff={rf_pos_difference}). " + "This indicates body name collision bug in internal body tracking." + ) + + # Verify implicit named frames match correct robot bodies + # Note: Order depends on internal processing, so we check both match one of the robots + rf_positions = [target_pos_w[:, rf_shank_indices[0]], target_pos_w[:, rf_shank_indices[1]]] + + # Each tracked position should match one of the ground truth positions + for rf_pos in rf_positions: + matches_robot = torch.allclose(rf_pos, robot_rf_pos_w, atol=1e-5) + matches_robot_1 = torch.allclose(rf_pos, robot_1_rf_pos_w, atol=1e-5) + assert matches_robot or matches_robot_1, ( + f"RF_SHANK position {rf_pos} doesn't match either robot's RF_SHANK position" + ) diff --git a/source/isaaclab_newton/test/sensors/test_imu.py b/source/isaaclab_newton/test/sensors/test_imu.py new file mode 100644 index 000000000000..3edb4c908398 --- /dev/null +++ b/source/isaaclab_newton/test/sensors/test_imu.py @@ -0,0 +1,233 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Tests to verify IMU sensor functionality using Newton physics.""" + +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +import pytest +import torch +import warp as wp +from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg + +import isaaclab.sim as sim_utils +from isaaclab.assets import RigidObjectCfg +from isaaclab.scene import InteractiveScene, InteractiveSceneCfg +from isaaclab.sensors.imu import Imu, ImuCfg +from isaaclab.sim import SimulationCfg +from isaaclab.terrains import TerrainImporterCfg +from isaaclab.utils import configclass + + +@configclass +class ImuTestSceneCfg(InteractiveSceneCfg): + """Scene with a rigid cube and an IMU sensor.""" + + env_spacing = 2.0 + terrain = TerrainImporterCfg(prim_path="/World/ground", terrain_type="plane") + + cube = RigidObjectCfg( + prim_path="{ENV_REGEX_NS}/Cube", + spawn=sim_utils.CuboidCfg( + size=(0.2, 0.2, 0.2), + rigid_props=sim_utils.RigidBodyPropertiesCfg(), + mass_props=sim_utils.MassPropertiesCfg(mass=1.0), + collision_props=sim_utils.CollisionPropertiesCfg(), + physics_material=sim_utils.RigidBodyMaterialCfg(), + visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(0.5, 0.0, 0.0)), + ), + init_state=RigidObjectCfg.InitialStateCfg(pos=(0.0, 0.0, 1.0)), + ) + + imu = ImuCfg( + prim_path="{ENV_REGEX_NS}/Cube", + ) + + +@pytest.fixture +def sim(): + """Create a simulation context with Newton physics.""" + sim_cfg = SimulationCfg( + dt=1.0 / 200.0, + physics=NewtonCfg( + solver_cfg=MJWarpSolverCfg(), + num_substeps=1, + ), + ) + with sim_utils.build_simulation_context(sim_cfg=sim_cfg) as sim: + sim._app_control_on_stop_handle = None + sim.set_camera_view(eye=(5.0, 5.0, 5.0), target=(0.0, 0.0, 0.0)) + yield sim + + +def test_sensor_initialization(sim): + """Test that the Newton IMU sensor initializes correctly.""" + scene_cfg = ImuTestSceneCfg(num_envs=2) + scene = InteractiveScene(scene_cfg) + sim.reset() + + imu: Imu = scene["imu"] + assert imu.num_instances == 2 + assert imu.data.ang_vel_b is not None + assert imu.data.lin_acc_b is not None + + +def test_data_shapes(sim): + """Test that IMU output tensors have correct shapes.""" + scene_cfg = ImuTestSceneCfg(num_envs=2) + scene = InteractiveScene(scene_cfg) + sim.reset() + + sim.step() + scene.update(sim.get_physics_dt()) + + imu: Imu = scene["imu"] + ang_vel = imu.data.ang_vel_b.torch + lin_acc = imu.data.lin_acc_b.torch + + assert ang_vel.shape == (2, 3) + assert lin_acc.shape == (2, 3) + + +def test_gravity_at_rest(sim): + """Test that a resting IMU measures gravity (~9.81 m/s^2 upward).""" + scene_cfg = ImuTestSceneCfg(num_envs=2) + scene = InteractiveScene(scene_cfg) + sim.reset() + + # Step enough for the cube to settle on the ground + for _ in range(500): + sim.step() + scene.update(sim.get_physics_dt()) + + imu: Imu = scene["imu"] + lin_acc = imu.data.lin_acc_b.torch + + # At rest, accelerometer should read ~9.81 in the up direction (Z body frame) + torch.testing.assert_close( + lin_acc[:, 2], + torch.full((lin_acc.shape[0],), 9.81, dtype=lin_acc.dtype, device=lin_acc.device), + atol=0.5, + rtol=0.0, + ) + # X and Y components should be near zero + torch.testing.assert_close( + lin_acc[:, :2], + torch.zeros(lin_acc.shape[0], 2, dtype=lin_acc.dtype, device=lin_acc.device), + atol=0.5, + rtol=0.0, + ) + + +def test_angular_velocity_at_rest(sim): + """Test that a resting IMU reports near-zero angular velocity.""" + scene_cfg = ImuTestSceneCfg(num_envs=2) + scene = InteractiveScene(scene_cfg) + sim.reset() + + for _ in range(500): + sim.step() + scene.update(sim.get_physics_dt()) + + imu: Imu = scene["imu"] + ang_vel = imu.data.ang_vel_b.torch + + torch.testing.assert_close( + ang_vel, + torch.zeros_like(ang_vel), + atol=0.1, + rtol=0.0, + ) + + +def test_reset(sim): + """Test that reset zeroes out IMU data.""" + scene_cfg = ImuTestSceneCfg(num_envs=2) + scene = InteractiveScene(scene_cfg) + sim.reset() + + # Step enough for the cube to settle on the ground so the accelerometer reads gravity. + # The cube falls from z=1.0 (bottom at z=0.9) and reaches the ground in ~86 steps + # at 200 Hz; 200 steps gives time to settle after impact. + for _ in range(200): + sim.step() + scene.update(sim.get_physics_dt()) + + imu: Imu = scene["imu"] + + lin_acc = imu.data.lin_acc_b.torch + assert torch.any(lin_acc != 0), "Expected non-zero data before reset" + + imu.reset() + + # Access internal buffers directly: accessing imu.data triggers lazy re-evaluation + # which re-fills from the Newton sensor, so we check the raw buffers instead. + ang_vel_after = wp.to_torch(imu._data._ang_vel_b) + lin_acc_after = wp.to_torch(imu._data._lin_acc_b) + + torch.testing.assert_close(ang_vel_after, torch.zeros_like(ang_vel_after)) + torch.testing.assert_close(lin_acc_after, torch.zeros_like(lin_acc_after)) + + +@configclass +class FreefallSceneCfg(InteractiveSceneCfg): + """Scene with a rigid cube and IMU but no ground plane (freefall).""" + + env_spacing = 2.0 + cube = RigidObjectCfg( + prim_path="{ENV_REGEX_NS}/Cube", + spawn=sim_utils.CuboidCfg( + size=(0.2, 0.2, 0.2), + rigid_props=sim_utils.RigidBodyPropertiesCfg(), + mass_props=sim_utils.MassPropertiesCfg(mass=1.0), + collision_props=sim_utils.CollisionPropertiesCfg(), + physics_material=sim_utils.RigidBodyMaterialCfg(), + visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(0.5, 0.0, 0.0)), + ), + init_state=RigidObjectCfg.InitialStateCfg(pos=(0.0, 0.0, 5.0)), + ) + + imu = ImuCfg( + prim_path="{ENV_REGEX_NS}/Cube", + ) + + +def test_freefall_acceleration(sim): + """Test that a freefalling IMU measures near-zero acceleration.""" + scene_cfg = FreefallSceneCfg(num_envs=2) + scene = InteractiveScene(scene_cfg) + sim.reset() + + # Step a few times while the cube is in freefall (no ground contact) + for _ in range(10): + sim.step() + scene.update(sim.get_physics_dt()) + + imu: Imu = scene["imu"] + lin_acc = imu.data.lin_acc_b.torch + + # In freefall, accelerometer should read near zero (gravity and inertial acceleration cancel) + acc_magnitude = torch.norm(lin_acc, dim=-1) + torch.testing.assert_close( + acc_magnitude, + torch.zeros_like(acc_magnitude), + atol=0.5, + rtol=0.0, + ) + + +def test_sensor_print(sim): + """Test that the sensor string representation works.""" + scene_cfg = ImuTestSceneCfg(num_envs=2) + scene = InteractiveScene(scene_cfg) + sim.reset() + + imu: Imu = scene["imu"] + sensor_str = str(imu) + assert "newton" in sensor_str + assert "IMU sensor" in sensor_str diff --git a/source/isaaclab_newton/test/sensors/test_joint_wrench_sensor.py b/source/isaaclab_newton/test/sensors/test_joint_wrench_sensor.py new file mode 100644 index 000000000000..fedf7c359081 --- /dev/null +++ b/source/isaaclab_newton/test/sensors/test_joint_wrench_sensor.py @@ -0,0 +1,488 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Tests for the Newton JointWrenchSensor.""" + +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +import pytest +import torch +import warp as wp +from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg + +import isaaclab.sim as sim_utils +from isaaclab.actuators import ImplicitActuatorCfg +from isaaclab.assets import Articulation, ArticulationCfg +from isaaclab.scene import InteractiveScene, InteractiveSceneCfg +from isaaclab.sensors.joint_wrench import JointWrenchSensor, JointWrenchSensorCfg +from isaaclab.sim import SimulationCfg +from isaaclab.terrains import TerrainImporterCfg +from isaaclab.utils import configclass +from isaaclab.utils import math as math_utils +from isaaclab.utils.assets import ISAAC_NUCLEUS_DIR, ISAACLAB_NUCLEUS_DIR + +from isaaclab_assets.robots.ant import ANT_CFG + + +def _make_single_joint_articulation_cfg() -> ArticulationCfg: + """Single-joint revolute test articulation (root ``CenterPivot`` + arm ``Arm``).""" + return ArticulationCfg( + prim_path="{ENV_REGEX_NS}/Robot", + spawn=sim_utils.UsdFileCfg( + usd_path=f"{ISAAC_NUCLEUS_DIR}/Robots/IsaacSim/SimpleArticulation/revolute_articulation.usd", + joint_drive_props=sim_utils.JointDrivePropertiesCfg(max_effort=80.0, max_velocity=5.0), + ), + actuators={ + "joint": ImplicitActuatorCfg( + joint_names_expr=[".*"], + stiffness=2000.0, + damping=100.0, + ), + }, + init_state=ArticulationCfg.InitialStateCfg(pos=(0.0, 0.0, 1.0)), + ) + + +def _make_cartpole_articulation_cfg(pole_damping: float = 0.0) -> ArticulationCfg: + """Two-joint cartpole articulation (cart + pole). + + Args: + pole_damping: Damping for the cart-to-pole revolute joint. + """ + return ArticulationCfg( + prim_path="{ENV_REGEX_NS}/Robot", + spawn=sim_utils.UsdFileCfg( + usd_path=f"{ISAACLAB_NUCLEUS_DIR}/Robots/Classic/Cartpole/cartpole.usd", + ), + init_state=ArticulationCfg.InitialStateCfg( + pos=(0.0, 0.0, 2.0), + joint_pos={"slider_to_cart": 0.0, "cart_to_pole": 0.0}, + ), + actuators={ + "cart_actuator": ImplicitActuatorCfg( + joint_names_expr=["slider_to_cart"], effort_limit_sim=400.0, stiffness=0.0, damping=10.0 + ), + "pole_actuator": ImplicitActuatorCfg( + joint_names_expr=["cart_to_pole"], effort_limit_sim=400.0, stiffness=0.0, damping=pole_damping + ), + }, + ) + + +@configclass +class _SingleJointSceneCfg(InteractiveSceneCfg): + """Scene with a single-joint articulation and the joint-wrench sensor.""" + + env_spacing = 2.0 + terrain = TerrainImporterCfg(prim_path="/World/ground", terrain_type="plane") + robot = _make_single_joint_articulation_cfg() + wrench = JointWrenchSensorCfg(prim_path="{ENV_REGEX_NS}/Robot") + + +@configclass +class _CartpoleSceneCfg(InteractiveSceneCfg): + """Scene with a cartpole (2-joint) articulation and the joint-wrench sensor.""" + + env_spacing = 4.0 + terrain = TerrainImporterCfg(prim_path="/World/ground", terrain_type="plane") + robot = _make_cartpole_articulation_cfg() + wrench = JointWrenchSensorCfg(prim_path="{ENV_REGEX_NS}/Robot") + + +@configclass +class _CartpoleDampedSceneCfg(InteractiveSceneCfg): + """Cartpole with pole damping for steady-state physics validation tests.""" + + env_spacing = 4.0 + terrain = TerrainImporterCfg(prim_path="/World/ground", terrain_type="plane") + robot = _make_cartpole_articulation_cfg(pole_damping=10.0) + wrench = JointWrenchSensorCfg(prim_path="{ENV_REGEX_NS}/Robot") + + +@configclass +class _NestedRootAntSceneCfg(InteractiveSceneCfg): + """Ant USD asset whose articulation root is nested under the configured asset prim.""" + + env_spacing = 4.0 + terrain = TerrainImporterCfg(prim_path="/World/ground", terrain_type="plane") + robot = ANT_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") + wrench = JointWrenchSensorCfg(prim_path="{ENV_REGEX_NS}/Robot") + + +@pytest.fixture +def sim(): + """Simulation context using the Newton backend.""" + sim_cfg = SimulationCfg( + dt=1.0 / 200.0, + physics=NewtonCfg( + solver_cfg=MJWarpSolverCfg(), + num_substeps=1, + ), + ) + with sim_utils.build_simulation_context(sim_cfg=sim_cfg) as sim_ctx: + sim_ctx._app_control_on_stop_handle = None + yield sim_ctx + + +# --------------------------------------------------------------------------- +# Sensor data — pre-init contract +# --------------------------------------------------------------------------- + + +def test_data_before_init_is_none(): + """``force``/``torque`` return ``None`` before :meth:`create_buffers` runs.""" + from isaaclab_newton.sensors.joint_wrench import JointWrenchSensorData + + data = JointWrenchSensorData() + assert data.force is None + assert data.torque is None + + +# --------------------------------------------------------------------------- +# Initialization and shapes +# --------------------------------------------------------------------------- + + +def test_initialization_and_shapes(sim): + """Sensor initializes on sim reset and exposes correctly-shaped buffers.""" + scene = InteractiveScene(_SingleJointSceneCfg(num_envs=2)) + sim.reset() + + sensor: JointWrenchSensor = scene["wrench"] + sim.step() + scene.update(sim.get_physics_dt()) + + # revolute_articulation has one joint whose child is "Arm". + num_envs = 2 + num_joints = 1 + assert sensor.data.force.torch.shape == (num_envs, num_joints, 3) + assert sensor.data.torque.torch.shape == (num_envs, num_joints, 3) + assert sensor.body_names == ["Arm"] + + +def test_multi_body_articulation(sim): + """Cartpole (2 joints) exposes a wrench for each joint labelled by its child body.""" + scene = InteractiveScene(_CartpoleSceneCfg(num_envs=2)) + sim.reset() + + sensor: JointWrenchSensor = scene["wrench"] + sim.step() + scene.update(sim.get_physics_dt()) + + num_envs = 2 + num_joints = 2 + assert sensor.data.force.torch.shape == (num_envs, num_joints, 3) + assert sensor.data.torque.torch.shape == (num_envs, num_joints, 3) + assert len(sensor.body_names) == 2 + assert "rail" not in [n.lower() for n in sensor.body_names] + + +def test_nested_articulation_root_resolution(sim): + """Sensor accepts an asset prim path whose articulation root is nested in the USD asset.""" + scene = InteractiveScene(_NestedRootAntSceneCfg(num_envs=1)) + sim.reset() + + robot: Articulation = scene["robot"] + sensor: JointWrenchSensor = scene["wrench"] + sim.step() + scene.update(sim.get_physics_dt()) + + assert len(sensor.body_names) == robot.num_joints + assert set(sensor.body_names).issubset(set(robot.body_names)) + assert sensor.data.force.torch.shape == (1, robot.num_joints, 3) + assert sensor.data.torque.torch.shape == (1, robot.num_joints, 3) + + +# --------------------------------------------------------------------------- +# Physical correctness +# --------------------------------------------------------------------------- + + +def _compute_expected_wrench_in_joint_frame( + sensor, + robot, + env: int, + joint: int, + gravity: torch.Tensor, + ext_force_b: torch.Tensor | None = None, + ext_torque_b: torch.Tensor | None = None, + descendant_body_names: list[str] | None = None, +): + """Compute the analytical joint-frame wrench for a single joint. + + Uses the same geometric data (body_com, joint_X_c, body_q) and frame + transformations as the kernel, but computes the wrench analytically from + known loads rather than reading body_parent_f. Computes the moment of + forces about the joint anchor and rotates the result into the child-side + joint frame. + + For terminal links, the wrench is due to the child body alone. For + interior joints, pass all bodies in the subtree below the joint via + ``descendant_body_names`` so the helper sums their gravitational + contributions. + + Args: + sensor: The JointWrenchSensor instance (used to read Newton model bindings). + robot: The Articulation asset (used for body mass lookup). + env: Environment index. + joint: Joint index within the sensor. + gravity: Gravity vector in world frame, shape (3,). + ext_force_b: External force on the child body in body frame [N], shape (3,). + ext_torque_b: External torque on the child body in body frame [N·m], shape (3,). + descendant_body_names: Bodies whose gravitational load acts through this + joint. Defaults to the child body only (correct for terminal links). + For an interior joint, pass all bodies in the subtree below the joint. + + Returns: + A tuple of (force, torque) tensors, each shape (3,), in the child-side + joint frame. + """ + body_idx = wp.to_torch(sensor._joint_child)[joint].item() + + # Link transform in world (of the child body — defines the joint frame). + link_xform = wp.to_torch(sensor._sim_bind_body_q)[env, body_idx] # (7,) = pos(3) + quat(4) + link_pos = link_xform[:3] + link_quat = link_xform[3:] # wp.quatf = (x, y, z, w) + + # Joint anchor and orientation in world = link_xform * joint_X_c. + joint_X_c = wp.to_torch(sensor._sim_bind_joint_X_c)[env, joint] # (7,) + jxc_pos = joint_X_c[:3] + jxc_quat = joint_X_c[3:] + anchor_world = link_pos + math_utils.quat_apply(link_quat.unsqueeze(0), jxc_pos.unsqueeze(0)).squeeze(0) + joint_quat_world = math_utils.quat_mul(link_quat.unsqueeze(0), jxc_quat.unsqueeze(0)).squeeze(0) + + # Bodies whose weight contributes to the wrench at this joint. + if descendant_body_names is None: + descendant_body_names = [sensor.body_names[joint]] + + link_names = list(sensor._root_view.link_names) + + total_force_w = torch.zeros(3, device=gravity.device) + total_torque_w = torch.zeros(3, device=gravity.device) + + for body_name in descendant_body_names: + b_idx = link_names.index(body_name) + b_xform = wp.to_torch(sensor._sim_bind_body_q)[env, b_idx] + b_pos = b_xform[:3] + b_quat = b_xform[3:] + b_com_local = wp.to_torch(sensor._sim_bind_body_com)[env, b_idx] + b_com_world = b_pos + math_utils.quat_apply(b_quat.unsqueeze(0), b_com_local.unsqueeze(0)).squeeze(0) + + art_b_idx = robot.body_names.index(body_name) + mass = robot.data.body_mass.torch[env, art_b_idx].item() + weight_w = mass * gravity + + total_force_w = total_force_w + weight_w + r = b_com_world - anchor_world + total_torque_w = total_torque_w + torch.cross(r, weight_w, dim=-1) + + # External force/torque on the child body only (if provided). Actuator + # torque is intentionally omitted; see tolerance comment in calling tests. + if ext_force_b is not None: + ext_force_w = math_utils.quat_apply(link_quat.unsqueeze(0), ext_force_b.unsqueeze(0)).squeeze(0) + total_force_w = total_force_w + ext_force_w + # Moment of the external force about the joint anchor (applied at child COM). + child_com_local = wp.to_torch(sensor._sim_bind_body_com)[env, body_idx] + child_com_world = link_pos + math_utils.quat_apply( + link_quat.unsqueeze(0), child_com_local.unsqueeze(0) + ).squeeze(0) + total_torque_w = total_torque_w + torch.cross(child_com_world - anchor_world, ext_force_w, dim=-1) + if ext_torque_b is not None: + total_torque_w = total_torque_w + math_utils.quat_apply( + link_quat.unsqueeze(0), ext_torque_b.unsqueeze(0) + ).squeeze(0) + + # Reaction wrench = negation of total wrench (joint supports against all loads). + reaction_force_w = -total_force_w + reaction_torque_w = -total_torque_w + + # Rotate into joint frame. + expected_force = math_utils.quat_apply_inverse( + joint_quat_world.unsqueeze(0), reaction_force_w.unsqueeze(0) + ).squeeze(0) + expected_torque = math_utils.quat_apply_inverse( + joint_quat_world.unsqueeze(0), reaction_torque_w.unsqueeze(0) + ).squeeze(0) + + return expected_force, expected_torque + + +def test_force_and_torque_components_at_rest(sim): + """Component-level validation of force and torque against analytical expectations (gravity only).""" + scene = InteractiveScene(_SingleJointSceneCfg(num_envs=1)) + sim.reset() + + sensor: JointWrenchSensor = scene["wrench"] + robot: Articulation = scene["robot"] + for _ in range(400): + sim.step() + scene.update(sim.get_physics_dt()) + + gravity = torch.tensor(sim.cfg.gravity, device=sim.device) + expected_force, expected_torque = _compute_expected_wrench_in_joint_frame( + sensor, + robot, + env=0, + joint=0, + gravity=gravity, + ) + + force = sensor.data.force.torch[0, 0] + torque = sensor.data.torque.torch[0, 0] + + torch.testing.assert_close(force, expected_force, atol=1e-2, rtol=1e-3) + torch.testing.assert_close(torque, expected_torque, atol=1e-2, rtol=1e-3) + + +def test_wrench_with_external_force_and_torque(sim): + """Full analytical wrench validation with external force and torque applied. + + Mirrors the PhysX ``test_body_incoming_joint_wrench_b_single_joint`` pattern: + apply a known wrench, settle, compute the expected reaction wrench analytically, + and compare component-by-component. + """ + scene = InteractiveScene(_SingleJointSceneCfg(num_envs=1)) + sim.reset() + + sensor: JointWrenchSensor = scene["wrench"] + robot: Articulation = scene["robot"] + arm_idx = robot.body_names.index("Arm") + + # Apply 10 N in body-Y and 10 N·m in body-Z on the arm (matches PhysX test). + ext_force_b = torch.zeros((1, robot.num_bodies, 3), device=sim.device) + ext_force_b[:, arm_idx, 1] = 10.0 + ext_torque_b = torch.zeros((1, robot.num_bodies, 3), device=sim.device) + ext_torque_b[:, arm_idx, 2] = 10.0 + + for _ in range(800): + robot.permanent_wrench_composer.set_forces_and_torques_index(forces=ext_force_b, torques=ext_torque_b) + robot.write_data_to_sim() + sim.step() + scene.update(sim.get_physics_dt()) + + gravity = torch.tensor(sim.cfg.gravity, device=sim.device) + expected_force, expected_torque = _compute_expected_wrench_in_joint_frame( + sensor, + robot, + env=0, + joint=0, + gravity=gravity, + ext_force_b=ext_force_b[0, arm_idx], + ext_torque_b=ext_torque_b[0, arm_idx], + ) + + force = sensor.data.force.torch[0, 0] + torque = sensor.data.torque.torch[0, 0] + + # The PD actuator contributes a small torque (~0.1 N·m) to body_parent_f that is + # not modelled in the analytical helper. Force is unaffected (actuator is pure torque). + torch.testing.assert_close(force, expected_force, atol=1e-2, rtol=1e-3) + torch.testing.assert_close(torque, expected_torque, atol=0.15, rtol=1e-2) + + +def test_interior_joint_wrench_at_rest(sim): + """Interior joint wrench accounts for the weight of all descendant bodies. + + The cartpole has two joints: ``slider_to_cart`` (interior, supports cart + and pole) and ``cart_to_pole`` (terminal, supports pole only). At steady + state with gravity as the only load, the reaction wrench at the interior + joint must equal the combined weight of cart and pole, with torque + computed from each body's moment about the joint anchor. + """ + scene = InteractiveScene(_CartpoleDampedSceneCfg(num_envs=1)) + sim.reset() + + sensor: JointWrenchSensor = scene["wrench"] + robot: Articulation = scene["robot"] + + for _ in range(800): + sim.step() + scene.update(sim.get_physics_dt()) + + gravity = torch.tensor(sim.cfg.gravity, device=sim.device) + + # Interior joint (index 0, slider_to_cart): reaction wrench supports + # all bodies in the subtree — both cart and pole. + expected_force, expected_torque = _compute_expected_wrench_in_joint_frame( + sensor, + robot, + env=0, + joint=0, + gravity=gravity, + descendant_body_names=list(sensor.body_names), + ) + + force = sensor.data.force.torch[0, 0] + torque = sensor.data.torque.torch[0, 0] + + torch.testing.assert_close(force, expected_force, atol=1e-2, rtol=1e-3) + torch.testing.assert_close(torque, expected_torque, atol=1e-2, rtol=1e-3) + + +# --------------------------------------------------------------------------- +# String representation +# --------------------------------------------------------------------------- + + +def test_sensor_print(sim): + """Test that the sensor string representation works.""" + scene = InteractiveScene(_SingleJointSceneCfg(num_envs=2)) + sim.reset() + + sensor: JointWrenchSensor = scene["wrench"] + sensor_str = str(sensor) + assert "newton" in sensor_str + assert "Joint wrench sensor" in sensor_str + + +# --------------------------------------------------------------------------- +# Reset behavior +# --------------------------------------------------------------------------- + + +def test_reset_zeros_buffers(sim): + """Resetting the sensor clears the force / torque buffers.""" + scene = InteractiveScene(_SingleJointSceneCfg(num_envs=2)) + sim.reset() + + sensor: JointWrenchSensor = scene["wrench"] + for _ in range(100): + sim.step() + scene.update(sim.get_physics_dt()) + + assert torch.any(sensor.data.force.torch != 0), "Expected non-zero data before reset" + + sensor.reset() + + # Access raw buffers to skip lazy re-population from the Newton view on the next data read. + force_after = wp.to_torch(sensor._data._force) + torque_after = wp.to_torch(sensor._data._torque) + torch.testing.assert_close(force_after, torch.zeros_like(force_after)) + torch.testing.assert_close(torque_after, torch.zeros_like(torque_after)) + + +def test_reset_with_env_ids_only_zeros_selected_envs(sim): + """Partial reset via env_ids should zero the selected envs and preserve the others.""" + scene = InteractiveScene(_SingleJointSceneCfg(num_envs=4)) + sim.reset() + + sensor: JointWrenchSensor = scene["wrench"] + for _ in range(100): + sim.step() + scene.update(sim.get_physics_dt()) + + force_before = sensor.data.force.torch.clone() + assert torch.any(force_before != 0), "Expected non-zero data before reset" + + sensor.reset(env_ids=[0, 2]) + + force_after = wp.to_torch(sensor._data._force) + torch.testing.assert_close(force_after[0], torch.zeros_like(force_after[0])) + torch.testing.assert_close(force_after[2], torch.zeros_like(force_after[2])) + torch.testing.assert_close(force_after[1], force_before[1]) + torch.testing.assert_close(force_after[3], force_before[3]) diff --git a/source/isaaclab_newton/test/sensors/test_pva.py b/source/isaaclab_newton/test/sensors/test_pva.py new file mode 100644 index 000000000000..8d14b9cb77ef --- /dev/null +++ b/source/isaaclab_newton/test/sensors/test_pva.py @@ -0,0 +1,332 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Tests to verify PVA sensor functionality using Newton physics.""" + +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +import pytest +import torch +import warp as wp +from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg + +import isaaclab.sim as sim_utils +from isaaclab.assets import RigidObjectCfg +from isaaclab.scene import InteractiveScene, InteractiveSceneCfg +from isaaclab.sensors.pva import Pva, PvaCfg +from isaaclab.sim import SimulationCfg +from isaaclab.terrains import TerrainImporterCfg +from isaaclab.utils import configclass + + +@configclass +class PvaTestSceneCfg(InteractiveSceneCfg): + """Scene with a rigid cube and a PVA sensor.""" + + env_spacing = 2.0 + terrain = TerrainImporterCfg(prim_path="/World/ground", terrain_type="plane") + + cube = RigidObjectCfg( + prim_path="{ENV_REGEX_NS}/Cube", + spawn=sim_utils.CuboidCfg( + size=(0.2, 0.2, 0.2), + rigid_props=sim_utils.RigidBodyPropertiesCfg(), + mass_props=sim_utils.MassPropertiesCfg(mass=1.0), + collision_props=sim_utils.CollisionPropertiesCfg(), + physics_material=sim_utils.RigidBodyMaterialCfg(), + visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(0.5, 0.0, 0.0)), + ), + init_state=RigidObjectCfg.InitialStateCfg(pos=(0.0, 0.0, 1.0)), + ) + + pva = PvaCfg( + prim_path="{ENV_REGEX_NS}/Cube", + ) + + +@pytest.fixture +def sim(): + """Create a simulation context with Newton physics.""" + sim_cfg = SimulationCfg( + dt=1.0 / 200.0, + physics=NewtonCfg( + solver_cfg=MJWarpSolverCfg(), + num_substeps=1, + ), + ) + with sim_utils.build_simulation_context(sim_cfg=sim_cfg) as sim: + sim._app_control_on_stop_handle = None + sim.set_camera_view(eye=(5.0, 5.0, 5.0), target=(0.0, 0.0, 0.0)) + yield sim + + +def test_sensor_initialization(sim): + """Test that the Newton PVA sensor initializes correctly.""" + scene_cfg = PvaTestSceneCfg(num_envs=2) + scene = InteractiveScene(scene_cfg) + sim.reset() + + pva: Pva = scene["pva"] + assert pva.num_instances == 2 + assert pva.data.pos_w is not None + assert pva.data.quat_w is not None + assert pva.data.lin_vel_b is not None + assert pva.data.ang_vel_b is not None + assert pva.data.lin_acc_b is not None + assert pva.data.ang_acc_b is not None + assert pva.data.projected_gravity_b is not None + assert pva.data.pose_w is not None + + +def test_data_shapes(sim): + """Test that PVA output tensors have correct shapes.""" + scene_cfg = PvaTestSceneCfg(num_envs=2) + scene = InteractiveScene(scene_cfg) + sim.reset() + + sim.step() + scene.update(sim.get_physics_dt()) + + pva: Pva = scene["pva"] + assert pva.data.pos_w.torch.shape == (2, 3) + assert pva.data.quat_w.torch.shape == (2, 4) + assert pva.data.pose_w.torch.shape == (2, 7) + assert pva.data.lin_vel_b.torch.shape == (2, 3) + assert pva.data.ang_vel_b.torch.shape == (2, 3) + assert pva.data.lin_acc_b.torch.shape == (2, 3) + assert pva.data.ang_acc_b.torch.shape == (2, 3) + assert pva.data.projected_gravity_b.torch.shape == (2, 3) + + +def test_gravity_at_rest(sim): + """Test that a resting PVA sensor reports correct projected gravity.""" + scene_cfg = PvaTestSceneCfg(num_envs=2) + scene = InteractiveScene(scene_cfg) + sim.reset() + + # Cube falls from z=1.0 (bottom at z=0.9), reaches ground in ~86 steps at 200 Hz. + for _ in range(200): + sim.step() + scene.update(sim.get_physics_dt()) + + pva: Pva = scene["pva"] + proj_grav = pva.data.projected_gravity_b.torch + + expected = torch.tensor([[0.0, 0.0, -1.0]], dtype=proj_grav.dtype, device=proj_grav.device).repeat(2, 1) + torch.testing.assert_close(proj_grav, expected, atol=0.05, rtol=0.0) + + +def test_velocity_at_rest(sim): + """Test that a resting PVA sensor reports near-zero velocity.""" + scene_cfg = PvaTestSceneCfg(num_envs=2) + scene = InteractiveScene(scene_cfg) + sim.reset() + + for _ in range(200): + sim.step() + scene.update(sim.get_physics_dt()) + + pva: Pva = scene["pva"] + lin_vel = pva.data.lin_vel_b.torch + ang_vel = pva.data.ang_vel_b.torch + + torch.testing.assert_close(lin_vel, torch.zeros_like(lin_vel), atol=0.05, rtol=0.0) + torch.testing.assert_close(ang_vel, torch.zeros_like(ang_vel), atol=0.05, rtol=0.0) + + +def test_position_nonzero(sim): + """Test that the PVA sensor reports a non-zero world-frame position.""" + scene_cfg = PvaTestSceneCfg(num_envs=2) + scene = InteractiveScene(scene_cfg) + sim.reset() + + sim.step() + scene.update(sim.get_physics_dt()) + + pva: Pva = scene["pva"] + pos = pva.data.pos_w.torch + + assert torch.all(pos[:, 2] > 0.0), f"Expected positive z position, got {pos[:, 2]}" + + +def test_reset(sim): + """Test that reset zeroes out PVA data.""" + scene_cfg = PvaTestSceneCfg(num_envs=2) + scene = InteractiveScene(scene_cfg) + sim.reset() + + for _ in range(10): + sim.step() + scene.update(sim.get_physics_dt()) + + pva: Pva = scene["pva"] + + pos = pva.data.pos_w.torch + assert torch.any(pos != 0), "Expected non-zero data before reset" + + pva.reset() + + # Access internal buffers directly to avoid lazy re-evaluation via pva.data + # (the data property triggers _update_buffers_impl which would overwrite reset values). + pos = wp.to_torch(pva._data._pos_w) + lin_vel = wp.to_torch(pva._data._lin_vel_b) + ang_vel = wp.to_torch(pva._data._ang_vel_b) + lin_acc = wp.to_torch(pva._data._lin_acc_b) + ang_acc = wp.to_torch(pva._data._ang_acc_b) + quat = wp.to_torch(pva._data._quat_w) + + torch.testing.assert_close(pos, torch.zeros_like(pos)) + torch.testing.assert_close(lin_vel, torch.zeros_like(lin_vel)) + torch.testing.assert_close(ang_vel, torch.zeros_like(ang_vel)) + torch.testing.assert_close(lin_acc, torch.zeros_like(lin_acc)) + torch.testing.assert_close(ang_acc, torch.zeros_like(ang_acc)) + expected_quat = torch.tensor([[0.0, 0.0, 0.0, 1.0]], dtype=quat.dtype, device=quat.device).repeat(2, 1) + torch.testing.assert_close(quat, expected_quat) + + +@configclass +class FreefallSceneCfg(InteractiveSceneCfg): + """Scene with a rigid cube and PVA but no ground plane (freefall).""" + + env_spacing = 2.0 + cube = RigidObjectCfg( + prim_path="{ENV_REGEX_NS}/Cube", + spawn=sim_utils.CuboidCfg( + size=(0.2, 0.2, 0.2), + rigid_props=sim_utils.RigidBodyPropertiesCfg(), + mass_props=sim_utils.MassPropertiesCfg(mass=1.0), + collision_props=sim_utils.CollisionPropertiesCfg(), + physics_material=sim_utils.RigidBodyMaterialCfg(), + visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(0.5, 0.0, 0.0)), + ), + init_state=RigidObjectCfg.InitialStateCfg(pos=(0.0, 0.0, 5.0)), + ) + + pva = PvaCfg( + prim_path="{ENV_REGEX_NS}/Cube", + ) + + +def test_freefall_velocity_increases(sim): + """Test that a freefalling body's downward velocity increases over time.""" + scene_cfg = FreefallSceneCfg(num_envs=2) + scene = InteractiveScene(scene_cfg) + sim.reset() + + for _ in range(50): + sim.step() + scene.update(sim.get_physics_dt()) + + pva: Pva = scene["pva"] + lin_vel = pva.data.lin_vel_b.torch + + speed = torch.norm(lin_vel, dim=-1) + assert torch.all(speed > 0.1), f"Expected non-zero velocity in freefall, got {speed}" + + +def test_freefall_acceleration(sim): + """Test that a freefalling body reports coordinate acceleration equal to gravity. + + PVA reports coordinate acceleration (from body_qdd), not proper acceleration. + In freefall, coordinate acceleration equals gravitational acceleration (~9.81 m/s^2 + downward). For an upright body, this is (0, 0, -9.81) in the body frame. + """ + scene_cfg = FreefallSceneCfg(num_envs=2) + scene = InteractiveScene(scene_cfg) + sim.reset() + + for _ in range(10): + sim.step() + scene.update(sim.get_physics_dt()) + + pva: Pva = scene["pva"] + lin_acc = pva.data.lin_acc_b.torch + ang_acc = pva.data.ang_acc_b.torch + + # Coordinate acceleration in freefall should be ~(0, 0, -9.81) in body frame. + expected_acc = torch.tensor([[0.0, 0.0, -9.81]], dtype=lin_acc.dtype, device=lin_acc.device).repeat(2, 1) + torch.testing.assert_close(lin_acc, expected_acc, atol=0.5, rtol=0.0) + + # Angular acceleration should be near zero (no torques in freefall). + torch.testing.assert_close(ang_acc, torch.zeros_like(ang_acc), atol=0.05, rtol=0.0) + + +def test_sensor_print(sim): + """Test that the sensor string representation works.""" + scene_cfg = PvaTestSceneCfg(num_envs=2) + scene = InteractiveScene(scene_cfg) + sim.reset() + + pva: Pva = scene["pva"] + sensor_str = str(pva) + assert "newton" in sensor_str + assert "Pva sensor" in sensor_str + + +@configclass +class OffsetRotatedSceneCfg(InteractiveSceneCfg): + """Scene with a tilted cube and offset PVA sensor in freefall. + + The cube is rotated 90 degrees about the X axis and the sensor has a + +Z offset of 0.5 m in the body frame. This exercises the lever-arm + velocity/acceleration corrections and body-frame gravity projection. + """ + + env_spacing = 2.0 + cube = RigidObjectCfg( + prim_path="{ENV_REGEX_NS}/Cube", + spawn=sim_utils.CuboidCfg( + size=(0.2, 0.2, 0.2), + rigid_props=sim_utils.RigidBodyPropertiesCfg(), + mass_props=sim_utils.MassPropertiesCfg(mass=1.0), + collision_props=sim_utils.CollisionPropertiesCfg(), + physics_material=sim_utils.RigidBodyMaterialCfg(), + visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(0.5, 0.0, 0.0)), + ), + init_state=RigidObjectCfg.InitialStateCfg( + pos=(0.0, 0.0, 5.0), + rot=(0.7071068, 0.0, 0.0, 0.7071068), # 90 deg about X (x, y, z, w) + ), + ) + + pva = PvaCfg( + prim_path="{ENV_REGEX_NS}/Cube", + offset=PvaCfg.OffsetCfg(pos=(0.0, 0.0, 0.5)), + ) + + +def test_offset_and_rotated_body(sim): + """Test position offset and body-frame gravity for a 90-degree-tilted body. + + With a 90-deg rotation about X, the body-frame +Z offset of 0.5 m maps + to world-frame (0, -0.5, 0). Projected gravity in the tilted sensor + frame should be approximately (0, -1, 0) instead of (0, 0, -1). + """ + scene_cfg = OffsetRotatedSceneCfg(num_envs=2) + scene = InteractiveScene(scene_cfg) + sim.reset() + + sim.step() + scene.update(sim.get_physics_dt()) + + pva: Pva = scene["pva"] + pos = pva.data.pos_w.torch + proj_grav = pva.data.projected_gravity_b.torch + + # pos_w is in absolute world frame; subtract env origins to get env-relative position. + # Expected env-relative: body at (0,0,5) + R_x(90) * (0,0,0.5) = (0, -0.5, 5) + env_pos = pos - scene.env_origins.to(pos.device) + torch.testing.assert_close(env_pos[:, 0], torch.zeros(2, dtype=pos.dtype, device=pos.device), atol=0.01, rtol=0.0) + torch.testing.assert_close( + env_pos[:, 1], torch.full((2,), -0.5, dtype=pos.dtype, device=pos.device), atol=0.01, rtol=0.0 + ) + assert torch.all(env_pos[:, 2] > 4.5), f"Expected z near 5.0, got {env_pos[:, 2]}" + + # Projected gravity: R_x(-90) * (0, 0, -1) = (0, -1, 0) + expected_grav = torch.tensor([[0.0, -1.0, 0.0]], dtype=proj_grav.dtype, device=proj_grav.device).repeat(2, 1) + torch.testing.assert_close(proj_grav, expected_grav, atol=0.05, rtol=0.0) diff --git a/source/isaaclab_newton/test/sensors/test_site_injection.py b/source/isaaclab_newton/test/sensors/test_site_injection.py new file mode 100644 index 000000000000..6bf40635a6c0 --- /dev/null +++ b/source/isaaclab_newton/test/sensors/test_site_injection.py @@ -0,0 +1,320 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Unit tests for site injection, validation, and sensor index building.""" + +import pytest +import warp as wp +from isaaclab_newton.physics.newton_manager import NewtonManager +from isaaclab_newton.sensors.frame_transformer.frame_transformer import FrameTransformer + +from isaaclab.utils.warp.math_ops import transform_to_vec_quat + +# --------------------------------------------------------------------------- +# transform_to_vec_quat +# --------------------------------------------------------------------------- + + +class TestTransformToVecQuat: + """Tests for the zero-copy view split utility.""" + + def test_1d_pos_quat_split(self): + """1D array: position is first 3 floats, quaternion is last 4.""" + t = wp.zeros(3, dtype=wp.transformf, device="cpu") + pos, quat = transform_to_vec_quat(t) + assert pos.shape == (3,) + assert quat.shape == (3,) + assert pos.dtype == wp.vec3f + assert quat.dtype == wp.quatf + + def test_2d_pos_quat_split(self): + """2D array: shapes are (N, M) with vec3f and quatf dtypes.""" + t = wp.zeros((2, 4), dtype=wp.transformf, device="cpu") + pos, quat = transform_to_vec_quat(t) + assert pos.shape == (2, 4) + assert quat.shape == (2, 4) + assert pos.dtype == wp.vec3f + assert quat.dtype == wp.quatf + + def test_zero_copy_1d(self): + """Writes through pos/quat views are reflected in the original transform array.""" + t = wp.zeros(1, dtype=wp.transformf, device="cpu") + pos, quat = transform_to_vec_quat(t) + # Write known values through the views + pos.numpy()[0] = (1.0, 2.0, 3.0) + quat.numpy()[0] = (0.0, 0.0, 0.0, 1.0) + floats = t.view(wp.float32).numpy() + assert list(floats[0]) == pytest.approx([1.0, 2.0, 3.0, 0.0, 0.0, 0.0, 1.0]) + + def test_invalid_ndim_raises(self): + """Passing a 0D or 4D array raises an error.""" + with pytest.raises((ValueError, IndexError)): + transform_to_vec_quat(wp.zeros((), dtype=wp.transformf, device="cpu")) + + def test_wrong_dtype_raises(self): + """Passing wrong dtype raises TypeError.""" + with pytest.raises(TypeError): + transform_to_vec_quat(wp.zeros(3, dtype=wp.vec3f, device="cpu")) + + +# --------------------------------------------------------------------------- +# NewtonManager._cl_inject_sites_fallback +# --------------------------------------------------------------------------- + + +class MockBuilder: + """Minimal stand-in for ModelBuilder.""" + + def __init__(self, body_labels: list[str]): + self.body_label = body_labels + self._next_idx = 0 + + def add_site(self, body: int, xform: wp.transform, label: str) -> int: + idx = self._next_idx + self._next_idx += 1 + return idx + + +class TestFallbackGlobalSite: + """Global site (body_pattern=None) must produce a (int, None) entry.""" + + def setup_method(self): + NewtonManager.clear() + NewtonManager._builder = MockBuilder(["body0", "body1"]) + + def test_global_site_entry_is_int_none_tuple(self): + xform = wp.transform() + NewtonManager._cl_pending_sites = {(None, tuple(xform)): ("ft_0", xform)} + NewtonManager._cl_inject_sites_fallback() + + entry = NewtonManager._cl_site_index_map["ft_0"] + global_idx, per_world = entry + assert isinstance(global_idx, int) + assert per_world is None + + def test_global_site_pending_cleared(self): + xform = wp.transform() + NewtonManager._cl_pending_sites = {(None, tuple(xform)): ("ft_0", xform)} + NewtonManager._cl_inject_sites_fallback() + + assert len(NewtonManager._cl_pending_sites) == 0 + + +class TestFallbackLocalSingleBody: + """Single-body local site must produce a (None, [[idx]]) entry — one world.""" + + def setup_method(self): + NewtonManager.clear() + NewtonManager._builder = MockBuilder(["Robot/base", "Robot/hand"]) + + def test_single_body_entry_shape(self): + xform = wp.transform() + NewtonManager._cl_pending_sites = {("Robot/base", tuple(xform)): ("ft_0", xform)} + NewtonManager._cl_inject_sites_fallback() + + entry = NewtonManager._cl_site_index_map["ft_0"] + global_idx, per_world = entry + assert global_idx is None + assert isinstance(per_world, list) + assert len(per_world) == 1 # one world + assert len(per_world[0]) == 1 # one match + assert isinstance(per_world[0][0], int) + + +class TestFallbackLocalWildcard: + """Wildcard local site matching N bodies must produce (None, [[idx0..idxN-1]]) — one world.""" + + def setup_method(self): + NewtonManager.clear() + NewtonManager._builder = MockBuilder(["Robot/FL_foot", "Robot/FR_foot", "Robot/RL_foot", "Robot/RR_foot"]) + + def test_wildcard_entry_shape(self): + xform = wp.transform() + NewtonManager._cl_pending_sites = {("Robot/.*_foot", tuple(xform)): ("ft_0", xform)} + NewtonManager._cl_inject_sites_fallback() + + entry = NewtonManager._cl_site_index_map["ft_0"] + global_idx, per_world = entry + assert global_idx is None + assert len(per_world) == 1 # one world + assert len(per_world[0]) == 4 # four bodies matched + + def test_no_match_raises(self): + xform = wp.transform() + NewtonManager._cl_pending_sites = {("Robot/nonexistent", tuple(xform)): ("ft_0", xform)} + with pytest.raises(ValueError): + NewtonManager._cl_inject_sites_fallback() + + +# --------------------------------------------------------------------------- +# FrameTransformer._validate_site_map +# --------------------------------------------------------------------------- + + +def _make_site_map( + source_per_world: list[list[int]], + target_per_worlds: list[list[list[int]]], + world_origin_idx: int = 0, +) -> dict: + m = { + "world_origin": (world_origin_idx, None), + "source": (None, source_per_world), + } + for i, pw in enumerate(target_per_worlds): + m[f"target_{i}"] = (None, pw) + return m + + +class TestSourceValidation: + def test_valid_source_one_per_env(self): + site_map = _make_site_map([[10], [20]], []) + indices, _ = FrameTransformer._validate_site_map("source", "/Robot/base", [], [], site_map, num_envs=2) + assert indices == [10, 20] + + def test_source_wrong_env_count_raises(self): + # site map has 1 world entry but num_envs=2 + site_map = _make_site_map([[10]], []) + with pytest.raises(ValueError, match="1 world entries.*expected 2"): + FrameTransformer._validate_site_map("source", "/Robot/base", [], [], site_map, num_envs=2) + + def test_source_zero_in_env_raises(self): + site_map = _make_site_map([[], [20]], []) + with pytest.raises(ValueError, match="matched 0 bodies in env 0"): + FrameTransformer._validate_site_map("source", "/Robot/base", [], [], site_map, num_envs=2) + + def test_source_two_in_env_raises(self): + site_map = _make_site_map([[10, 11], [20]], []) + with pytest.raises(ValueError, match="matched 2 bodies in env 0"): + FrameTransformer._validate_site_map("source", "/Robot/base", [], [], site_map, num_envs=2) + + +class TestTargetValidation: + def test_valid_single_target_per_env(self): + site_map = _make_site_map([[10], [20]], [[[30], [40]]]) + _, tgt = FrameTransformer._validate_site_map( + "source", "/Robot/base", ["target_0"], ["/Robot/hand"], site_map, num_envs=2 + ) + assert tgt[0] == [[30], [40]] + + def test_valid_wildcard_two_bodies_per_env(self): + site_map = _make_site_map([[10], [20]], [[[30, 31], [40, 41]]]) + _, tgt = FrameTransformer._validate_site_map( + "source", "/Robot/base", ["target_0"], ["/Robot/foot.*"], site_map, num_envs=2 + ) + assert tgt[0] == [[30, 31], [40, 41]] + + def test_target_zero_bodies_raises(self): + site_map = _make_site_map([[10], [20]], [[[], []]]) + with pytest.raises(ValueError, match="matched no bodies"): + FrameTransformer._validate_site_map( + "source", "/Robot/base", ["target_0"], ["/Robot/foot.*"], site_map, num_envs=2 + ) + + def test_target_non_uniform_raises(self): + site_map = _make_site_map([[10], [20]], [[[30, 31], [40]]]) + with pytest.raises(ValueError, match="different numbers of bodies"): + FrameTransformer._validate_site_map( + "source", "/Robot/base", ["target_0"], ["/Robot/foot.*"], site_map, num_envs=2 + ) + + +# --------------------------------------------------------------------------- +# FrameTransformer._build_sensor_index_lists +# --------------------------------------------------------------------------- + + +def _call(source_indices, target_per_world, target_frame_body_names, shape_labels, world_origin_idx, num_envs): + return FrameTransformer._build_sensor_index_lists( + source_indices, target_per_world, target_frame_body_names, shape_labels, world_origin_idx, num_envs + ) + + +class TestZeroTargets: + def test_zero_targets_shapes_refs(self): + """0 targets: shapes/refs contain only source entries.""" + names, tgt_per_tgt, shapes, refs = _call( + source_indices=[10, 11], + target_per_world=[], + target_frame_body_names=[], + shape_labels={}, + world_origin_idx=0, + num_envs=2, + ) + assert shapes == [10, 11] + assert refs == [0, 0] + assert names == [] + assert tgt_per_tgt == [] + + +class TestSingleTarget: + def test_one_env_one_target(self): + """1 env, 1 target: [src, tgt] shapes, [world_orig, src] refs.""" + names, tgt_per_tgt, shapes, refs = _call( + source_indices=[10], + target_per_world=[[[20]]], + target_frame_body_names=["hand"], + shape_labels={}, + world_origin_idx=0, + num_envs=1, + ) + assert shapes == [10, 20] + assert refs == [0, 10] + assert names == ["hand"] + + def test_two_envs_two_targets(self): + """2 envs, 2 targets: stride-2 interleaved layout.""" + names, tgt_per_tgt, shapes, refs = _call( + source_indices=[10, 11], + target_per_world=[[[20], [21]], [[30], [31]]], + target_frame_body_names=["arm", "hand"], + shape_labels={}, + world_origin_idx=0, + num_envs=2, + ) + assert shapes == [10, 20, 30, 11, 21, 31] + assert refs == [0, 10, 10, 0, 11, 11] + assert names == ["arm", "hand"] + + +class TestWildcardExpansion: + def test_wildcard_two_bodies_per_env_indices(self): + """Wildcard: 2 bodies per env → 2 expanded target entries, correct indices.""" + shape_labels = {20: "FL_foot/label_0", 21: "FL_foot/label_0", 22: "FR_foot/label_0", 23: "FR_foot/label_0"} + names, tgt_per_tgt, shapes, refs = _call( + source_indices=[10, 11], + target_per_world=[[[20, 22], [21, 23]]], + target_frame_body_names=["foot"], + shape_labels=shape_labels, + world_origin_idx=0, + num_envs=2, + ) + assert shapes == [10, 20, 22, 11, 21, 23] + assert refs == [0, 10, 10, 0, 11, 11] + assert tgt_per_tgt == [[20, 21], [22, 23]] + + def test_wildcard_uses_body_names_from_shape_labels(self): + """Wildcard: body names derived from shape_labels when n_bodies > 1.""" + shape_labels = {20: "FL_foot/label_0", 21: "FL_foot/label_0", 22: "FR_foot/label_0", 23: "FR_foot/label_0"} + names, tgt_per_tgt, shapes, refs = _call( + source_indices=[10, 11], + target_per_world=[[[20, 22], [21, 23]]], + target_frame_body_names=["foot"], + shape_labels=shape_labels, + world_origin_idx=0, + num_envs=2, + ) + assert names == ["FL_foot", "FR_foot"] + + def test_wildcard_single_body_uses_config_name(self): + """Single body match: config name is used regardless of shape_labels.""" + names, tgt_per_tgt, shapes, refs = _call( + source_indices=[10, 11], + target_per_world=[[[20], [21]]], + target_frame_body_names=["foot"], + shape_labels={}, + world_origin_idx=0, + num_envs=2, + ) + assert names == ["foot"] diff --git a/source/isaaclab_newton/test/sim/__init__.py b/source/isaaclab_newton/test/sim/__init__.py new file mode 100644 index 000000000000..460a30569089 --- /dev/null +++ b/source/isaaclab_newton/test/sim/__init__.py @@ -0,0 +1,4 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause diff --git a/source/isaaclab_newton/test/sim/test_views_xform_prim_newton.py b/source/isaaclab_newton/test/sim/test_views_xform_prim_newton.py new file mode 100644 index 000000000000..e8b28aad2d95 --- /dev/null +++ b/source/isaaclab_newton/test/sim/test_views_xform_prim_newton.py @@ -0,0 +1,198 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Newton backend tests for FrameView. + +Imports the shared contract tests and provides the Newton-specific +``view_factory`` fixture. Also includes Newton-only guard tests and +the world-attached prim edge case. +""" + +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +sys.path.insert(0, str(Path(__file__).resolve().parents[3] / "isaaclab" / "test" / "sim")) + +import pytest +import torch +import warp as wp +from frame_view_contract_utils import * # noqa: F401, F403 — import all contract tests +from frame_view_contract_utils import CHILD_OFFSET, ViewBundle, _wp_vec3f, _wp_vec4f +from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg +from isaaclab_newton.physics.newton_manager import NewtonManager +from isaaclab_newton.sim.views import NewtonSiteFrameView as FrameView + +from pxr import Gf + +import isaaclab.sim as sim_utils +from isaaclab.assets import RigidObjectCfg +from isaaclab.scene import InteractiveScene, InteractiveSceneCfg +from isaaclab.sim import SimulationCfg, build_simulation_context +from isaaclab.utils import configclass + +NEWTON_SIM_CFG = SimulationCfg(physics=NewtonCfg(solver_cfg=MJWarpSolverCfg())) +WORLD_MARKER_POS = (5.0, 3.0, 1.0) + + +@configclass +class _SceneCfg(InteractiveSceneCfg): + cube: RigidObjectCfg = RigidObjectCfg( + prim_path="{ENV_REGEX_NS}/Cube", + spawn=sim_utils.CuboidCfg( + size=(0.2, 0.2, 0.2), + rigid_props=sim_utils.RigidBodyPropertiesCfg(), + mass_props=sim_utils.MassPropertiesCfg(mass=1.0), + collision_props=sim_utils.CollisionPropertiesCfg(), + ), + init_state=RigidObjectCfg.InitialStateCfg(pos=(0.0, 0.0, 1.0)), + ) + + +def _sim_context(device, num_envs=4): + NEWTON_SIM_CFG.device = device + return build_simulation_context(device=device, sim_cfg=NEWTON_SIM_CFG, add_ground_plane=True) + + +def _get_body_positions(num_envs, device="cpu"): + model = NewtonManager.get_model() + body_labels = list(model.body_label) + body_q_t = wp.to_torch(NewtonManager.get_state_0().body_q) + return torch.stack([body_q_t[body_labels.index(f"/World/envs/env_{i}/Cube"), :3] for i in range(num_envs)]) + + +def _set_body_positions(positions, num_envs): + model = NewtonManager.get_model() + body_labels = list(model.body_label) + body_q_t = wp.to_torch(NewtonManager.get_state_0().body_q) + for i in range(num_envs): + body_q_t[body_labels.index(f"/World/envs/env_{i}/Cube"), :3] = positions[i] + + +# ------------------------------------------------------------------ +# Contract fixture +# ------------------------------------------------------------------ + + +@pytest.fixture +def view_factory(): + """Newton factory: CameraMount child Xform at CHILD_OFFSET under each Cube body.""" + + def factory(num_envs: int, device: str) -> ViewBundle: + ctx = _sim_context(device, num_envs=num_envs) + sim = ctx.__enter__() + sim._app_control_on_stop_handle = None + InteractiveScene(_SceneCfg(num_envs=num_envs, env_spacing=2.0)) + + stage = sim_utils.get_current_stage() + for i in range(num_envs): + prim = stage.DefinePrim(f"/World/envs/env_{i}/Cube/CameraMount", "Xform") + sim_utils.standardize_xform_ops(prim) + prim.GetAttribute("xformOp:translate").Set(Gf.Vec3d(*CHILD_OFFSET)) + prim.GetAttribute("xformOp:orient").Set(Gf.Quatd(1.0, 0.0, 0.0, 0.0)) + + sim.reset() + view = FrameView("/World/envs/env_.*/Cube/CameraMount", device=device) + + return ViewBundle( + view=view, + get_parent_pos=_get_body_positions, + set_parent_pos=_set_body_positions, + teardown=lambda: ctx.__exit__(None, None, None), + ) + + return factory + + +# ================================================================== +# Newton-only: guard tests +# ================================================================== + + +@pytest.mark.parametrize("device", ["cpu", "cuda:0"]) +def test_reject_body_path(device): + """FrameView rejects prim paths that resolve to a Newton physics body.""" + ctx = _sim_context(device, num_envs=2) + sim = ctx.__enter__() + sim._app_control_on_stop_handle = None + InteractiveScene(_SceneCfg(num_envs=2, env_spacing=2.0)) + sim.reset() + + with pytest.raises(ValueError, match="physics body"): + FrameView("/World/envs/env_.*/Cube", device=device) + ctx.__exit__(None, None, None) + + +@pytest.mark.parametrize("device", ["cpu", "cuda:0"]) +def test_reject_shape_path(device): + """FrameView rejects prim paths that resolve to a Newton collision shape.""" + ctx = _sim_context(device, num_envs=2) + sim = ctx.__enter__() + sim._app_control_on_stop_handle = None + InteractiveScene(_SceneCfg(num_envs=2, env_spacing=2.0)) + sim.reset() + + shape_labels = list(NewtonManager.get_model().shape_label) + if not shape_labels: + pytest.skip("No shapes in model") + + with pytest.raises(ValueError, match="collision shape"): + FrameView(shape_labels[0], device=device) + ctx.__exit__(None, None, None) + + +# ================================================================== +# Newton edge case: world-attached prim (body=-1) +# ================================================================== + + +@pytest.mark.parametrize("device", ["cpu", "cuda:0"]) +def test_world_attached_returns_initial_pose(device): + """A world-rooted Xform returns its USD-authored position.""" + ctx = _sim_context(device, num_envs=2) + sim = ctx.__enter__() + sim._app_control_on_stop_handle = None + InteractiveScene(_SceneCfg(num_envs=2, env_spacing=2.0)) + + stage = sim_utils.get_current_stage() + prim = stage.DefinePrim("/World/StaticMarker", "Xform") + sim_utils.standardize_xform_ops(prim) + prim.GetAttribute("xformOp:translate").Set(Gf.Vec3d(*WORLD_MARKER_POS)) + prim.GetAttribute("xformOp:orient").Set(Gf.Quatd(1.0, 0.0, 0.0, 0.0)) + + sim.reset() + view = FrameView("/World/StaticMarker", device=device) + + pos = view.get_world_poses()[0].torch + expected = torch.tensor([list(WORLD_MARKER_POS)], device=device) + torch.testing.assert_close(pos, expected, atol=1e-5, rtol=0) + ctx.__exit__(None, None, None) + + +@pytest.mark.parametrize("device", ["cpu", "cuda:0"]) +def test_world_attached_set_world_roundtrip(device): + """A world-attached prim can be repositioned via set_world_poses.""" + ctx = _sim_context(device, num_envs=2) + sim = ctx.__enter__() + sim._app_control_on_stop_handle = None + InteractiveScene(_SceneCfg(num_envs=2, env_spacing=2.0)) + + stage = sim_utils.get_current_stage() + prim = stage.DefinePrim("/World/StaticMarker", "Xform") + sim_utils.standardize_xform_ops(prim) + prim.GetAttribute("xformOp:translate").Set(Gf.Vec3d(*WORLD_MARKER_POS)) + prim.GetAttribute("xformOp:orient").Set(Gf.Quatd(1.0, 0.0, 0.0, 0.0)) + + sim.reset() + view = FrameView("/World/StaticMarker", device=device) + + new_pos = _wp_vec3f([[10.0, 20.0, 30.0]], device=device) + new_quat = _wp_vec4f([[0.0, 0.0, 0.0, 1.0]], device=device) + view.set_world_poses(new_pos, new_quat) + + ret_pos, ret_quat = view.get_world_poses() + torch.testing.assert_close(ret_pos.torch, wp.to_torch(new_pos), atol=1e-5, rtol=0) + torch.testing.assert_close(ret_quat.torch, wp.to_torch(new_quat), atol=1e-5, rtol=0) + ctx.__exit__(None, None, None) diff --git a/source/isaaclab_ov/changelog.d/.gitkeep b/source/isaaclab_ov/changelog.d/.gitkeep new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/source/isaaclab_ov/changelog.d/pbarejko-open-usd.rst b/source/isaaclab_ov/changelog.d/pbarejko-open-usd.rst new file mode 100644 index 000000000000..455768ad5a5c --- /dev/null +++ b/source/isaaclab_ov/changelog.d/pbarejko-open-usd.rst @@ -0,0 +1,7 @@ +Fixed +^^^^^ + +* Fixed ``AttributeError: 'Renderer' object has no attribute 'add_usd'`` in + :class:`~isaaclab_ov.renderers.OVRTXRenderer` when using ``ovrtx`` 0.3.0 or + newer. The renderer now calls :meth:`ovrtx.Renderer.open_usd` on 0.3.0+ and + falls back to ``Renderer.add_usd`` on older versions. diff --git a/source/isaaclab_ov/changelog.d/rschmitt_decouple_renderer_camera.rst b/source/isaaclab_ov/changelog.d/rschmitt_decouple_renderer_camera.rst new file mode 100644 index 000000000000..1de2259dc2c3 --- /dev/null +++ b/source/isaaclab_ov/changelog.d/rschmitt_decouple_renderer_camera.rst @@ -0,0 +1,4 @@ +Changed +^^^^^^^^ + +* Modified the OVRTX renderer to use the new patterns from renderer/camera decoupling. diff --git a/source/isaaclab_ov/config/extension.toml b/source/isaaclab_ov/config/extension.toml index 67f5582202d9..ba8f5046c4eb 100644 --- a/source/isaaclab_ov/config/extension.toml +++ b/source/isaaclab_ov/config/extension.toml @@ -1,5 +1,5 @@ [package] -version = "0.1.2" +version = "0.1.3" title = "Omniverse renderers for IsaacLab" description = "Extension providing Omniverse renderers (OVRTX, ovphysx, etc.) for tiled camera rendering." readme = "docs/README.md" diff --git a/source/isaaclab_ov/docs/CHANGELOG.rst b/source/isaaclab_ov/docs/CHANGELOG.rst index 2babcbdabd9a..e8afeda30bda 100644 --- a/source/isaaclab_ov/docs/CHANGELOG.rst +++ b/source/isaaclab_ov/docs/CHANGELOG.rst @@ -1,6 +1,29 @@ Changelog --------- +0.1.3 (2026-04-30) +~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Simple-shading outputs, with RTX Minimal mode resolved from the requested camera data types and written on + the injected render product in USD. +* Expanded unit tests for OVRTX Warp kernels in ``test_ovrtx_renderer_kernels.py``. + +Changed +^^^^^^^ + +* OVRTX integration now branches ``read_gpu_transforms``, depth tile extraction, and semantic ID coloring kernels on + ovrtx **0.3.0** vs older versions so tiled buffers and transforms stay correct across ovrtx versions. +* RGB tiling reads ``LdrColor`` and supports both 3- and 4-channel buffers. + +Removed +^^^^^^^ + +* Removed ``OVRTXRendererCfg.simple_shading_mode``. Request simple shading via the simple-shading data types on the + camera instead; the renderer derives RTX minimal mode from the data types. + 0.1.2 (2026-03-23) ~~~~~~~~~~~~~~~~~~ diff --git a/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer.py b/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer.py index a4e3551f9be2..5d1782373d87 100644 --- a/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer.py +++ b/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer.py @@ -22,7 +22,6 @@ import logging import math import os -import weakref from typing import TYPE_CHECKING, Any logger = logging.getLogger(__name__) @@ -37,18 +36,22 @@ # By setting OVRTX_SKIP_USD_CHECK, we prevent the C library from loading the pxr Python package. os.environ["OVRTX_SKIP_USD_CHECK"] = "1" +import ovrtx from ovrtx import Device, PrimMode, Renderer, RendererConfig, Semantic +from packaging.version import Version -from isaaclab.renderers.base_renderer import BaseRenderer +from isaaclab.renderers import BaseRenderer, RenderBufferKind, RenderBufferSpec from isaaclab.utils.math import convert_camera_frame_orientation_convention from .ovrtx_renderer_cfg import OVRTXRendererCfg from .ovrtx_renderer_kernels import ( DEVICE, create_camera_transforms_kernel, - extract_depth_tile_from_tiled_buffer_kernel, - extract_tile_from_tiled_buffer_kernel, + extract_all_depth_tiles_kernel, + extract_all_depth_tiles_kernel_legacy, + extract_all_rgba_tiles_kernel, generate_random_colors_from_ids_kernel, + generate_random_colors_from_ids_kernel_legacy, sync_newton_transforms_kernel, ) from .ovrtx_usd import ( @@ -58,48 +61,63 @@ ) if TYPE_CHECKING: - from isaaclab.sensors import SensorBase + from isaaclab.sensors.camera.camera_data import CameraData +from isaaclab.renderers.camera_render_spec import CameraRenderSpec -class OVRTXRenderData: - """OVRTX-specific RenderData. Holds warp output buffers and weak ref to sensor. +# Shared integration floor for this module; reuse for ovrtx features that share one support floor. +_OVRTX_VERSION = Version(ovrtx.__version__) +_IS_OVRTX_0_3_0_OR_NEWER = Version("0.3.0") <= _OVRTX_VERSION + +# The resolved integer value is assigned to the ``omni:rtx:minimal:mode`` attribute of the render product. +_RTX_MINIMAL_MODES = { + RenderBufferKind.SIMPLE_SHADING_CONSTANT_DIFFUSE.value: 1, + RenderBufferKind.SIMPLE_SHADING_DIFFUSE_MDL.value: 2, + RenderBufferKind.SIMPLE_SHADING_FULL_MDL.value: 3, +} + + +def _resolve_rtx_minimal_mode(data_types: list[str]) -> int | None: + """Resolve the RTX minimal mode from data types. + + RTX minimal mode is used to control the rendering quality. The higher the mode, the higher the quality. - Follows Newton Warp pattern: weak ref to sensor avoids circular reference while - allowing access to sensor config when needed. + If multiple simple shading data types are requested, the first one in the list is used and a warning is logged. + + If no simple shading data types are requested, None is returned. + + Args: + data_types: List of data types. + + Returns: + The resolved RTX minimal mode if simple shading data types are requested, otherwise None. """ + filtered_data_types = [data_type for data_type in data_types if data_type in _RTX_MINIMAL_MODES] + if not filtered_data_types: + return None + + if len(filtered_data_types) > 1: + logger.warning( + "Multiple simple shading data types requested (%s). Using the first in the list (%s).", + filtered_data_types, + filtered_data_types[0], + ) + + return _RTX_MINIMAL_MODES[filtered_data_types[0]] - @staticmethod - def _create_warp_buffers( - width: int, - height: int, - num_envs: int, - data_types: list[str], - device, - ) -> dict: - """Create warp output buffers for OVRTX renderer.""" - buffers = {} - if any(dt in ("rgba", "rgb") for dt in data_types): - buffers["rgba"] = wp.zeros((num_envs, height, width, 4), dtype=wp.uint8, device=device) - buffers["rgb"] = buffers["rgba"][:, :, :, :3] - if "albedo" in data_types: - buffers["albedo"] = wp.zeros((num_envs, height, width, 4), dtype=wp.uint8, device=device) - if "semantic_segmentation" in data_types: - buffers["semantic_segmentation"] = wp.zeros((num_envs, height, width, 4), dtype=wp.uint8, device=device) - for depth_key in ("depth", "distance_to_image_plane", "distance_to_camera"): - if depth_key in data_types: - buffers[depth_key] = wp.zeros((num_envs, height, width, 1), dtype=wp.float32, device=device) - return buffers - - def __init__(self, sensor: SensorBase, device): - """Create render data from sensor. Holds weak ref to avoid circular reference.""" - self.sensor: weakref.ref[object] | None = weakref.ref(sensor) - self.width = sensor.cfg.width - self.height = sensor.cfg.height - self.num_envs = sensor.num_instances - self.data_types = sensor.cfg.data_types if sensor.cfg.data_types else ["rgb"] + +class OVRTXRenderData: + """OVRTX-specific RenderData. Holds warp output buffers sized from :class:`CameraRenderSpec`.""" + + def __init__(self, spec: CameraRenderSpec, device): + """Create render data from a camera render specification.""" + self.width = spec.cfg.width + self.height = spec.cfg.height + self.num_envs = spec.num_instances + self.data_types = spec.cfg.data_types if spec.cfg.data_types else ["rgb"] self.num_cols = math.ceil(math.sqrt(self.num_envs)) self.num_rows = math.ceil(self.num_envs / self.num_cols) - self.warp_buffers = self._create_warp_buffers(self.width, self.height, self.num_envs, self.data_types, device) + self.warp_buffers: dict[str, wp.array] = {} class OVRTXRenderer(BaseRenderer): @@ -111,6 +129,22 @@ class OVRTXRenderer(BaseRenderer): cfg: OVRTXRendererCfg + def supported_output_types(self) -> dict[RenderBufferKind, RenderBufferSpec]: + """Publish the per-output layout this OVRTX backend writes. + See :meth:`~isaaclab.renderers.base_renderer.BaseRenderer.supported_output_types`.""" + return { + RenderBufferKind.RGBA: RenderBufferSpec(4, torch.uint8), + RenderBufferKind.RGB: RenderBufferSpec(3, torch.uint8), + RenderBufferKind.ALBEDO: RenderBufferSpec(4, torch.uint8), + RenderBufferKind.SIMPLE_SHADING_CONSTANT_DIFFUSE: RenderBufferSpec(3, torch.uint8), + RenderBufferKind.SIMPLE_SHADING_DIFFUSE_MDL: RenderBufferSpec(3, torch.uint8), + RenderBufferKind.SIMPLE_SHADING_FULL_MDL: RenderBufferSpec(3, torch.uint8), + RenderBufferKind.SEMANTIC_SEGMENTATION: RenderBufferSpec(4, torch.uint8), + RenderBufferKind.DEPTH: RenderBufferSpec(1, torch.float32), + RenderBufferKind.DISTANCE_TO_IMAGE_PLANE: RenderBufferSpec(1, torch.float32), + RenderBufferKind.DISTANCE_TO_CAMERA: RenderBufferSpec(1, torch.float32), + } + def __init__(self, cfg: OVRTXRendererCfg): self.cfg = cfg self._usd_handles = [] @@ -119,7 +153,6 @@ def __init__(self, cfg: OVRTXRendererCfg): self._object_binding = None self._object_newton_indices: wp.array | None = None self._initialized_scene = False - self._sensor_ref: weakref.ref[object] | None = None self._exported_usd_path: str | None = None self._camera_rel_path: str | None = None self._output_semantic_color_buffer: wp.array | None = None @@ -143,25 +176,22 @@ def prepare_stage(self, stage: Any, num_envs: int) -> None: self._exported_usd_path = export_path logger.info("Exported to %s", export_path) - def initialize(self, sensor: SensorBase): + def initialize(self, spec: CameraRenderSpec): """Initialize the OVRTX renderer with internal environment cloning. - Args: - sensor: The TiledCamera sensor. width, height, num_envs, data_types are - obtained from sensor when needed. Weak ref stored to avoid circular ref. + spec: Tiled camera description (resolution, paths, data types). """ - self._sensor_ref = weakref.ref(sensor) - width = sensor.cfg.width - height = sensor.cfg.height - num_envs = sensor.num_instances - data_types = sensor.cfg.data_types if sensor.cfg.data_types else ["rgb"] + width = spec.cfg.width + height = spec.cfg.height + num_envs = spec.num_instances + data_types = spec.cfg.data_types if spec.cfg.data_types else ["rgb"] env_0_prefix = "/World/envs/env_0/" - first_cam_path = sensor._view.prims[0].GetPath().pathString + first_cam_path = spec.camera_prim_paths[0] if not first_cam_path.startswith(env_0_prefix): raise RuntimeError(f"Expected camera prim under '{env_0_prefix}', got '{first_cam_path}'") - self._camera_rel_path = first_cam_path.removeprefix(env_0_prefix) + self._camera_rel_path = spec.camera_path_relative_to_env_0 usd_scene_path = self._exported_usd_path use_cloning = self.cfg.use_cloning @@ -170,7 +200,7 @@ def initialize(self, sensor: SensorBase): OVRTX_CONFIG = RendererConfig( log_file_path=self.cfg.log_file_path, log_level=self.cfg.log_level, - read_gpu_transforms=False, + read_gpu_transforms=_IS_OVRTX_0_3_0_OR_NEWER, ) self._renderer = Renderer(OVRTX_CONFIG) assert self._renderer, "Renderer should be valid after creation" @@ -178,6 +208,7 @@ def initialize(self, sensor: SensorBase): if usd_scene_path is not None: logger.info("Injecting camera definitions...") + combined_usd_path, render_product_path = inject_cameras_into_usd( usd_scene_path, self.cfg, @@ -185,15 +216,20 @@ def initialize(self, sensor: SensorBase): height=height, num_envs=num_envs, data_types=data_types, + minimal_mode=_resolve_rtx_minimal_mode(data_types), camera_rel_path=self._camera_rel_path, ) self._render_product_paths.append(render_product_path) logger.info("Loading USD into OvRTX...") try: - handle = self._renderer.add_usd(combined_usd_path, path_prefix=None) - self._usd_handles.append(handle) - logger.info("USD loaded (path: %s, handle: %s)", combined_usd_path, handle) + if _IS_OVRTX_0_3_0_OR_NEWER: + self._renderer.open_usd(combined_usd_path) + logger.info("USD loaded as root layer (path: %s)", combined_usd_path) + else: + handle = self._renderer.add_usd(combined_usd_path, path_prefix=None) + self._usd_handles.append(handle) + logger.info("USD loaded (path: %s, handle: %s)", combined_usd_path, handle) except Exception as e: logger.exception("Error loading USD: %s", e) raise @@ -321,20 +357,54 @@ def _setup_object_bindings(self): except Exception as e: logger.warning("Error setting up object bindings: %s", e) - def create_render_data(self, sensor: SensorBase) -> OVRTXRenderData: + def create_render_data(self, spec: CameraRenderSpec) -> OVRTXRenderData: """Create OVRTX-specific RenderData with GPU buffers. Performs OVRTX initialization (stage export, USD load, bindings) on first call, matching the interface of Isaac RTX and Newton Warp which need no separate initialize(). - RenderData holds weak ref to sensor (Newton pattern) to avoid circular reference. """ if not self._initialized_scene: - self.initialize(sensor) - return OVRTXRenderData(sensor, DEVICE) + self.initialize(spec) + return OVRTXRenderData(spec, DEVICE) - def set_outputs(self, render_data: OVRTXRenderData, output_data: dict) -> None: - """No-op; OVRTX uses internal warp buffers.""" - pass + # Map torch dtypes to their warp counterparts for zero-copy wrapping. + _TORCH_TO_WP_DTYPE: dict[torch.dtype, Any] = { + torch.uint8: wp.uint8, + torch.float32: wp.float32, + torch.int32: wp.int32, + } + + def set_outputs(self, render_data: OVRTXRenderData, output_data: dict[str, torch.Tensor]) -> None: + """Wrap caller-owned torch output tensors as zero-copy warp arrays. + + Aliased views over a contiguous sibling (e.g. ``rgb`` over ``rgba``) are + skipped; any other non-contiguous tensor raises ``ValueError``. + + See :meth:`~isaaclab.renderers.base_renderer.BaseRenderer.set_outputs`. + """ + render_data.warp_buffers = {} + for name, tensor in output_data.items(): + if not tensor.is_contiguous(): + if tensor.data_ptr() in {t.data_ptr() for t in output_data.values() if t.is_contiguous()}: + continue + raise ValueError( + f"OVRTXRenderer.set_outputs: output '{name}' is non-contiguous and is not an" + " alias of a contiguous output tensor; cannot wrap as a zero-copy warp array." + ) + wp_dtype = self._TORCH_TO_WP_DTYPE.get(tensor.dtype) + if wp_dtype is None: + raise ValueError( + f"OVRTXRenderer.set_outputs: unsupported torch dtype {tensor.dtype} for output" + f" '{name}'. Add it to OVRTXRenderer._TORCH_TO_WP_DTYPE." + ) + torch_array = wp.from_torch(tensor) + render_data.warp_buffers[name] = wp.array( + ptr=torch_array.ptr, + dtype=wp_dtype, + shape=tuple(tensor.shape), + device=torch_array.device, + copy=False, + ) def update_transforms(self) -> None: """Sync physics objects to OVRTX.""" @@ -387,18 +457,20 @@ def update_camera( wp_transforms_view = wp.from_dlpack(attr_mapping.tensor, dtype=wp.mat44d) wp.copy(wp_transforms_view, camera_transforms) - def write_output( + def read_output( self, render_data: OVRTXRenderData, - output_name: str, - output_data: torch.Tensor, + camera_data: CameraData, ) -> None: - """Copy from render_data warp buffer to output tensor.""" - if output_name not in render_data.warp_buffers: - return - src = render_data.warp_buffers[output_name] - if src.ptr != output_data.data_ptr(): - wp.copy(dest=wp.from_torch(output_data), src=src) + """No-op: outputs already live in the caller's torch storage. + + :meth:`set_outputs` wraps each ``camera_data.output`` tensor as a + zero-copy warp array stored in ``render_data.warp_buffers``, and + :meth:`render` writes the rendered tiles directly into those warp + arrays. There is therefore nothing to copy here. + + See :meth:`~isaaclab.renderers.base_renderer.BaseRenderer.read_output`. + """ def _generate_random_colors_from_ids(self, input_ids: wp.array) -> wp.array: """Generate pseudo-random colors from semantic IDs.""" @@ -408,7 +480,11 @@ def _generate_random_colors_from_ids(self, input_ids: wp.array) -> wp.array: output_colors = self._output_semantic_color_buffer wp.launch( - kernel=generate_random_colors_from_ids_kernel, + kernel=( + generate_random_colors_from_ids_kernel + if _IS_OVRTX_0_3_0_OR_NEWER + else generate_random_colors_from_ids_kernel_legacy + ), dim=input_ids.shape, inputs=[input_ids, output_colors], device=DEVICE, @@ -424,60 +500,66 @@ def _extract_rgba_tiles( buffer_key: str, suffix: str = "", ) -> None: - """Extract per-env RGBA tiles from tiled buffer into output_buffers.""" - for env_idx in range(render_data.num_envs): - tile_x = env_idx % render_data.num_cols - tile_y = env_idx // render_data.num_cols - wp.launch( - kernel=extract_tile_from_tiled_buffer_kernel, - dim=(render_data.height, render_data.width), - inputs=[ - tiled_data, - output_buffers[buffer_key][env_idx], - tile_x, - tile_y, - render_data.width, - render_data.height, - ], - device=DEVICE, - ) + """Extract per-env RGBA tiles from tiled buffer into output_buffers (single kernel launch).""" + output_buffer = output_buffers[buffer_key] + num_channels = output_buffer.shape[-1] + if num_channels not in (3, 4): + raise ValueError(f"Expected RGB (3 channels) or RGBA (4 channels), got {num_channels}") + + wp.launch( + kernel=extract_all_rgba_tiles_kernel, + dim=(render_data.num_envs, render_data.height, render_data.width), + inputs=[ + tiled_data, + output_buffer, + render_data.num_cols, + render_data.width, + render_data.height, + num_channels, + ], + device=DEVICE, + ) def _extract_depth_tiles( self, render_data: OVRTXRenderData, tiled_depth_data: wp.array, output_buffers: dict ) -> None: - """Extract per-env depth tiles into output_buffers.""" - for env_idx in range(render_data.num_envs): - tile_x = env_idx % render_data.num_cols - tile_y = env_idx // render_data.num_cols - for depth_type in ["depth", "distance_to_image_plane", "distance_to_camera"]: - if depth_type in output_buffers: - wp.launch( - kernel=extract_depth_tile_from_tiled_buffer_kernel, - dim=(render_data.height, render_data.width), - inputs=[ - tiled_depth_data, - output_buffers[depth_type][env_idx], - tile_x, - tile_y, - render_data.width, - render_data.height, - ], - device=DEVICE, - ) + """Extract per-env depth tiles into output_buffers (single kernel launch).""" + kernel = extract_all_depth_tiles_kernel if _IS_OVRTX_0_3_0_OR_NEWER else extract_all_depth_tiles_kernel_legacy + + for depth_type in ["depth", "distance_to_image_plane", "distance_to_camera"]: + if depth_type in output_buffers: + wp.launch( + kernel=kernel, + dim=(render_data.num_envs, render_data.height, render_data.width), + inputs=[ + tiled_depth_data, + output_buffers[depth_type], + render_data.num_cols, + render_data.width, + render_data.height, + ], + device=DEVICE, + ) def _process_render_frame(self, render_data: OVRTXRenderData, frame, output_buffers: dict) -> None: """Extract RGB, depth, albedo, and semantic from a single render frame into output_buffers.""" - rgb_render_var = ( - "SimpleShadingSD" - if "SimpleShadingSD" in frame.render_vars - else "LdrColor" - if "LdrColor" in frame.render_vars - else None - ) - if rgb_render_var and "rgba" in output_buffers: - with frame.render_vars[rgb_render_var].map(device=Device.CUDA) as mapping: - tiled_data = wp.from_dlpack(mapping.tensor) - self._extract_rgba_tiles(render_data, tiled_data, output_buffers, "rgba", suffix="rgb") + if "LdrColor" in frame.render_vars: + buffer_key = None + + if "rgba" in output_buffers: + buffer_key = "rgba" + else: + # The output buffers must contain only one simple shading data type at most after resolution of the data + # types during creation of the output buffers (OVRTXRenderData._create_warp_buffers). + for dt in _RTX_MINIMAL_MODES: + if dt in output_buffers: + buffer_key = dt + break + + if buffer_key is not None: + with frame.render_vars["LdrColor"].map(device=Device.CUDA) as mapping: + tiled_data = wp.from_dlpack(mapping.tensor) + self._extract_rgba_tiles(render_data, tiled_data, output_buffers, buffer_key) for depth_var in ["DistanceToImagePlaneSD", "DepthSD"]: if depth_var not in frame.render_vars: @@ -543,9 +625,6 @@ def render(self, render_data: OVRTXRenderData) -> None: def cleanup(self, render_data: OVRTXRenderData | None) -> None: """Release renderer resources. See :meth:`~isaaclab.renderers.base_renderer.BaseRenderer.cleanup`.""" - if render_data is not None: - render_data.sensor = None # Break weak ref (Newton pattern) - self._sensor_ref = None # Unbind before tearing down renderer def _safe_unbind(binding, name: str) -> None: diff --git a/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer_cfg.py b/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer_cfg.py index 1a53a07687a9..9c26d3c79bf1 100644 --- a/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer_cfg.py +++ b/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer_cfg.py @@ -17,21 +17,15 @@ class OVRTXRendererCfg(RendererCfg): """Configuration for OVRTX Renderer. The OVRTX renderer uses the ovrtx library for high-fidelity RTX-based rendering. - width, height, num_envs, and data_types are obtained from the sensor when - create_render_data() is called (same pattern as Isaac RTX). + width, height, num_envs, and data_types are obtained from the + :class:`~isaaclab.renderers.camera_render_spec.CameraRenderSpec` when + :meth:`~isaaclab.renderers.base_renderer.BaseRenderer.create_render_data` is called + (same pattern as Isaac RTX). """ renderer_type: str = "ovrtx" """Type identifier for OVRTX renderer.""" - simple_shading_mode: bool = True - """Whether to use simple shading mode (default: True). - - When enabled, uses SimpleShadingSD RenderVar instead of LdrColor for RGB rendering. - Provides faster, simpler rendering suitable for many vision-based tasks. - Set to False to use full RTX path-traced rendering with LdrColor. - """ - temp_usd_dir: str = str(Path(tempfile.gettempdir()) / "ovrtx") """Directory for temporary combined USD files (scene + injected cameras). Used by the OVRTX renderer when building the render scope; must be writable. diff --git a/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer_kernels.py b/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer_kernels.py index 7bf587ee4aaa..c287f1257632 100644 --- a/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer_kernels.py +++ b/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer_kernels.py @@ -73,6 +73,94 @@ def extract_tile_from_tiled_buffer_kernel( tile_buffer[y, x, 3] = tiled_buffer[src_y, src_x, 3] +@wp.kernel +def extract_all_rgba_tiles_kernel( + tiled_buffer: wp.array(dtype=wp.uint8, ndim=3), # type: ignore + output_buffer: wp.array(dtype=wp.uint8, ndim=4), # type: ignore + num_cols: int, + tile_width: int, + tile_height: int, + num_channels: int, +): + """Extract ALL RGBA or RGB tiles from a tiled buffer in a single kernel launch. + + Args: + tiled_buffer: 3D uint8 array of shape (H, W, 4) for RGBA or (H, W, 3) for RGB. + output_buffer: 4D uint8 array of shape (num_envs, H, W, 4) for RGBA or (num_envs, H, W, 3) for RGB. + num_cols: number of columns in the tiled buffer. + tile_width: width of each tile. + tile_height: height of each tile. + num_channels: number of channels in the output buffer. Use 3 for RGB or 4 for RGBA. + If a value other than 3 or 4 is given, it will be treated as 3 (RGB). + """ + env_idx, y, x = wp.tid() + tile_x = env_idx % num_cols + tile_y = env_idx // num_cols + src_x = tile_x * tile_width + x + src_y = tile_y * tile_height + y + + # RGB + output_buffer[env_idx, y, x, 0] = tiled_buffer[src_y, src_x, 0] + output_buffer[env_idx, y, x, 1] = tiled_buffer[src_y, src_x, 1] + output_buffer[env_idx, y, x, 2] = tiled_buffer[src_y, src_x, 2] + + # Alpha (if it is RGBA) + if num_channels == 4: + output_buffer[env_idx, y, x, 3] = tiled_buffer[src_y, src_x, 3] + + +@wp.kernel +def extract_all_depth_tiles_kernel_legacy( + tiled_buffer: wp.array(dtype=wp.float32, ndim=2), # type: ignore + output_buffer: wp.array(dtype=wp.float32, ndim=4), # type: ignore + num_cols: int, + tile_width: int, + tile_height: int, +): + """Extract all depth tiles from a tiled buffer in a single kernel launch. + + Used with ovrtx older than 0.3.0. + + Args: + tiled_buffer: 2D float32 array of shape (H, W) for depth. + output_buffer: 4D float32 array of shape (num_envs, H, W, 1) for depth. + num_cols: number of columns in the tiled buffer. + tile_width: width of each tile. + tile_height: height of each tile. + """ + env_idx, y, x = wp.tid() + tile_x = env_idx % num_cols + tile_y = env_idx // num_cols + src_x = tile_x * tile_width + x + src_y = tile_y * tile_height + y + output_buffer[env_idx, y, x, 0] = tiled_buffer[src_y, src_x] + + +@wp.kernel +def extract_all_depth_tiles_kernel( + tiled_buffer: wp.array(dtype=wp.float32, ndim=3), # type: ignore + output_buffer: wp.array(dtype=wp.float32, ndim=4), # type: ignore + num_cols: int, + tile_width: int, + tile_height: int, +): + """Extract all depth tiles from a tiled buffer in a single kernel launch. + + Args: + tiled_buffer: 3D float32 array of shape (H, W, 1) for depth. + output_buffer: 4D float32 array of shape (num_envs, H, W, 1) for depth. + num_cols: number of columns in the tiled buffer. + tile_width: width of each tile. + tile_height: height of each tile. + """ + env_idx, y, x = wp.tid() + tile_x = env_idx % num_cols + tile_y = env_idx // num_cols + src_x = tile_x * tile_width + x + src_y = tile_y * tile_height + y + output_buffer[env_idx, y, x, 0] = tiled_buffer[src_y, src_x, 0] + + @wp.kernel def extract_depth_tile_from_tiled_buffer_kernel( tiled_buffer: wp.array(dtype=wp.float32, ndim=2), # type: ignore @@ -114,6 +202,13 @@ def random_color_from_id(input_id: wp.uint32) -> wp.uint32: Returns: uint32 color: ``r | (g<<8) | (b<<16) | (a<<24)`` """ + if input_id == wp.uint32(0): + # BACKGROUND special case + return wp.uint32(0) + if input_id == wp.uint32(1): + # UNLABELLED special case + return wp.uint32(0xFF000000) + hash_val = color_hash(input_id) # Golden ratio inverse = 1.0 / 1.618033988749895 (Replicator constant) @@ -191,30 +286,35 @@ def random_color_from_id(input_id: wp.uint32) -> wp.uint32: @wp.kernel -def generate_random_colors_from_ids_kernel( +def generate_random_colors_from_ids_kernel_legacy( input_ids: wp.array(dtype=wp.uint32, ndim=2), # type: ignore output_colors: wp.array(dtype=wp.uint32, ndim=2), # type: ignore ): """Generate random colors given IDs (e.g. semantic IDs). + Used with ovrtx older than 0.3.0. + Args: - input_ids: 2D uint32 array of semantic IDs per pixel + input_ids: 2D uint32 array of shape (H, W) for semantic IDs per pixel. output_data: 2D uint32 array; each word is `r | (g<<8) | (b<<16) | (a<<24)` """ i, j = wp.tid() + output_colors[i, j] = random_color_from_id(input_ids[i, j]) - input_id = input_ids[i, j] - if input_id == wp.uint32(0): - # BACKGROUND special case - output_color = wp.uint32(0) - elif input_id == wp.uint32(1): - # UNLABELLED special case - output_color = wp.uint32(0xFF000000) - else: - output_color = random_color_from_id(input_id) +@wp.kernel +def generate_random_colors_from_ids_kernel( + input_ids: wp.array(dtype=wp.uint32, ndim=3), # type: ignore + output_colors: wp.array(dtype=wp.uint32, ndim=3), # type: ignore +): + """Generate random colors given IDs (e.g. semantic IDs). - output_colors[i, j] = output_color + Args: + input_ids: 3D uint32 array for semantic IDs per pixel. + output_colors: 3D uint32 array for colors per pixel; each word is ``r | (g<<8) | (b<<16) | (a<<24)``. + """ + i, j, k = wp.tid() + output_colors[i, j, k] = random_color_from_id(input_ids[i, j, k]) @wp.kernel diff --git a/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_usd.py b/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_usd.py index 48ed2f8a968f..a222981ea2ed 100644 --- a/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_usd.py +++ b/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_usd.py @@ -19,8 +19,8 @@ logger = logging.getLogger(__name__) -def get_render_var_config(data_types: list[str], simple_shading_mode: bool) -> tuple[str, str, str]: - """Return (render_var_path, render_var_name, source_name) from data_types and shading mode.""" +def get_render_var_config(data_types: list[str]) -> tuple[str, str, str]: + """Return (render_var_path, render_var_name, source_name) from data_types.""" use_depth = any(dt in ["depth", "distance_to_image_plane", "distance_to_camera"] for dt in data_types) use_albedo = "albedo" in data_types use_semantic = "semantic_segmentation" in data_types @@ -32,8 +32,6 @@ def get_render_var_config(data_types: list[str], simple_shading_mode: bool) -> t return "/Render/Vars/albedo", "albedo", "DiffuseAlbedoSD" if use_semantic and not (use_rgb or use_albedo): return "/Render/Vars/semantic", "semantic", "SemanticSegmentation" - if simple_shading_mode: - return "/Render/Vars/SimpleShading", "SimpleShading", "SimpleShadingSD" return "/Render/Vars/LdrColor", "LdrColor", "LdrColor" @@ -45,16 +43,35 @@ def build_render_scope_usd( source_name: str, tiled_width: int, tiled_height: int, - simple_shading_mode: bool = False, + minimal_mode: int | None = None, ) -> str: - """Build the Render scope USD string (def Scope Render, RenderProduct, Vars).""" - render_mode = "Minimal" if simple_shading_mode else "RealTimePathTracing" - logger.info("Rendering mode: %s (omni:rtx:rendermode=%s)", render_var_name, render_mode) - if simple_shading_mode: - logger.info("Simple shading mode: ENABLED") - else: - logger.info("Simple shading mode: DISABLED (using full RTX path tracing)") + """Build the Render scope USD string (def Scope Render, RenderProduct, Vars). + + Args: + camera_paths: List of camera prim paths. + render_product_name: Name of the render product. + render_var_path: Path of the render variable. + render_var_name: Name of the render variable. + source_name: Name of the source. + tiled_width: Width of the tiled image. + tiled_height: Height of the tiled image. + minimal_mode: RTX minimal mode. None if not requested. Valid values are 1, 2, 3. + + Returns: + The USD string for the render scope. + """ camera_rel_list = ", ".join([f"<{p}>" for p in camera_paths]) + + if minimal_mode is None: + render_mode_lines = ['token omni:rtx:rendermode = "RealTimePathTracing"'] + else: + render_mode_lines = [ + 'token omni:rtx:rendermode = "Minimal"', + f"int omni:rtx:minimal:mode = {minimal_mode}", + ] + + render_mode_block = "\n ".join(render_mode_lines) + return f''' def Scope "Render" {{ @@ -63,7 +80,8 @@ def RenderProduct "{render_product_name}" ( ) {{ rel camera = [{camera_rel_list}] token omni:rtx:background:source:type = "domeLight" - token omni:rtx:rendermode = "{render_mode}" + float omni:rtx:rt:ambientLight:intensity = 1.0 + {render_mode_block} token[] omni:rtx:waitForEvents = ["AllLoadingFinished", "OnlyOnFirstRequest"] rel orderedVars = <{render_var_path}> uniform int2 resolution = ({tiled_width}, {tiled_height}) @@ -81,7 +99,7 @@ def RenderVar "{render_var_name}" def _tiled_resolution(num_envs: int, width: int, height: int) -> tuple[int, int]: - """Compute tiled width and height from env count and per-env resolution (same as TiledCamera).""" + """Compute tiled width and height from env count and per-env resolution (same as Camera).""" num_cols = math.ceil(math.sqrt(num_envs)) num_rows = math.ceil(num_envs / num_cols) return num_cols * width, num_rows * height @@ -94,6 +112,7 @@ def inject_cameras_into_usd( height: int, num_envs: int, data_types: list[str], + minimal_mode: int | None = None, camera_rel_path: str = "Camera", ) -> tuple[str, str]: """Inject camera and render product definitions into an existing USD file. @@ -108,8 +127,8 @@ def inject_cameras_into_usd( height: Tile height from sensor config. num_envs: Number of environments from scene. data_types: Data types from sensor config. - camera_rel_path: Camera prim path relative to the env root (e.g. ``"Camera"`` - or ``"Robot/head_cam"``). + minimal_mode: RTX minimal mode. None if not requested. Valid values are 1, 2, 3. + camera_rel_path: Camera prim path relative to the env root (e.g. ``"Camera"`` or ``"Robot/head_cam"``). """ with open(usd_scene_path) as f: original_usd = f.read() @@ -121,7 +140,7 @@ def inject_cameras_into_usd( render_product_name = "RenderProduct" render_product_path = f"/Render/{render_product_name}" - render_var_path, render_var_name, source_name = get_render_var_config(data_types, cfg.simple_shading_mode) + render_var_path, render_var_name, source_name = get_render_var_config(data_types) camera_content = build_render_scope_usd( camera_paths, @@ -131,7 +150,7 @@ def inject_cameras_into_usd( source_name, tiled_width, tiled_height, - simple_shading_mode=cfg.simple_shading_mode, + minimal_mode, ) combined_usd = original_usd.rstrip() + "\n\n" + camera_content diff --git a/source/isaaclab_ov/setup.py b/source/isaaclab_ov/setup.py index 5382be2573f8..c955c54bfa15 100644 --- a/source/isaaclab_ov/setup.py +++ b/source/isaaclab_ov/setup.py @@ -26,13 +26,12 @@ keywords=["robotics", "simulation", "rendering", "ovrtx", "omniverse"], license="BSD-3-Clause", include_package_data=True, - python_requires=">=3.11", + python_requires=">=3.12", install_requires=[], extras_require=EXTRAS_REQUIRE, packages=["isaaclab_ov"], classifiers=[ "Natural Language :: English", - "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", ], zip_safe=False, diff --git a/source/isaaclab_ov/test/test_ovrtx_renderer_contract.py b/source/isaaclab_ov/test/test_ovrtx_renderer_contract.py new file mode 100644 index 000000000000..b6c590a54a54 --- /dev/null +++ b/source/isaaclab_ov/test/test_ovrtx_renderer_contract.py @@ -0,0 +1,105 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Tests for the OVRTX renderer output contract.""" + +import pytest +import torch + +pytest.importorskip("isaaclab_ov") +pytest.importorskip("ovrtx") + +from isaaclab_ov.renderers import OVRTXRendererCfg +from isaaclab_ov.renderers.ovrtx_renderer import OVRTXRenderData, OVRTXRenderer + +from isaaclab.sensors.camera import CameraCfg +from isaaclab.sensors.camera.camera_data import CameraData, RenderBufferKind, RenderBufferSpec +from isaaclab.sim import PinholeCameraCfg + +pytestmark = pytest.mark.isaacsim_ci + +_SPAWN = PinholeCameraCfg( + focal_length=24.0, + focus_distance=400.0, + horizontal_aperture=20.955, + clipping_range=(0.1, 1.0e5), +) + + +def _make_camera_cfg(data_types: list[str]) -> CameraCfg: + return CameraCfg( + height=8, + width=16, + prim_path="/World/Camera", + spawn=_SPAWN, + data_types=data_types, + ) + + +def _make_ovrtx_render_data() -> OVRTXRenderData: + rd = OVRTXRenderData.__new__(OVRTXRenderData) + rd.warp_buffers = {} + return rd + + +def test_ovrtx_supported_output_types_key_set(): + """OVRTX publishes the documented key set and per-output spec.""" + renderer = OVRTXRenderer(OVRTXRendererCfg()) + specs = renderer.supported_output_types() + + assert set(specs.keys()) == { + RenderBufferKind.RGB, + RenderBufferKind.RGBA, + RenderBufferKind.ALBEDO, + RenderBufferKind.SEMANTIC_SEGMENTATION, + RenderBufferKind.DEPTH, + RenderBufferKind.DISTANCE_TO_IMAGE_PLANE, + RenderBufferKind.DISTANCE_TO_CAMERA, + } + assert specs[RenderBufferKind.RGBA] == RenderBufferSpec(4, torch.uint8) + assert specs[RenderBufferKind.DEPTH] == RenderBufferSpec(1, torch.float32) + + +def test_ovrtx_set_outputs_wraps_caller_torch_zero_copy(): + """OVRTXRenderer.set_outputs publishes warp views over the caller's torch storage.""" + import warp as wp + + renderer = OVRTXRenderer(OVRTXRendererCfg()) + + if not torch.cuda.is_available(): + pytest.skip("OVRTX zero-copy wrapping requires a CUDA device") + device = "cuda" + + cfg = _make_camera_cfg(["rgb", "rgba", "depth"]) + data = CameraData.allocate( + data_types=cfg.data_types, + height=8, + width=16, + num_views=2, + device=device, + supported_specs=renderer.supported_output_types(), + ) + render_data = _make_ovrtx_render_data() + renderer.set_outputs(render_data, data.output) + + assert set(render_data.warp_buffers.keys()) >= {"rgba", "depth"} + assert render_data.warp_buffers["rgba"].ptr == wp.from_torch(data.output["rgba"]).ptr + assert render_data.warp_buffers["depth"].ptr == wp.from_torch(data.output["depth"]).ptr + assert "rgb" not in render_data.warp_buffers + + +def test_ovrtx_read_output_is_a_no_op_after_consolidation(): + """OVRTXRenderer.read_output is a no-op once set_outputs wires up zero-copy.""" + renderer = OVRTXRenderer(OVRTXRendererCfg()) + render_data = _make_ovrtx_render_data() + camera_data = CameraData() + camera_data.info = {} + camera_data.output = {} + + result = renderer.read_output(render_data, camera_data) + assert result is None + assert render_data.warp_buffers == {} + assert camera_data.info == {} + assert camera_data.output == {} diff --git a/source/isaaclab_ov/test/test_ovrtx_renderer_kernels.py b/source/isaaclab_ov/test/test_ovrtx_renderer_kernels.py index 5bbbb6139e2b..ed416d05a7e6 100644 --- a/source/isaaclab_ov/test/test_ovrtx_renderer_kernels.py +++ b/source/isaaclab_ov/test/test_ovrtx_renderer_kernels.py @@ -12,7 +12,11 @@ import warp as wp from isaaclab_ov.renderers.ovrtx_renderer_kernels import ( DEVICE, + extract_all_depth_tiles_kernel, + extract_all_depth_tiles_kernel_legacy, + extract_all_rgba_tiles_kernel, generate_random_colors_from_ids_kernel, + generate_random_colors_from_ids_kernel_legacy, ) @@ -68,44 +72,383 @@ def _reference_color(input_id: int) -> int: return r | (g << 8) | (b << 16) | (a << 24) -@pytest.mark.skip(reason="OVRTX is optional and experimental feature and temporarily is excluded from testing.") +def _reference_extract_all_depth_tiles_legacy( + tiled_2d: np.ndarray, + num_envs: int, + num_cols: int, + tile_width: int, + tile_height: int, +) -> np.ndarray: + """NumPy reference for ``extract_all_depth_tiles_kernel_legacy`` (2D tiled buffer).""" + out = np.zeros((num_envs, tile_height, tile_width, 1), dtype=np.float32) + for env_idx in range(num_envs): + tile_x = env_idx % num_cols + tile_y = env_idx // num_cols + for y in range(tile_height): + for x in range(tile_width): + src_y = tile_y * tile_height + y + src_x = tile_x * tile_width + x + out[env_idx, y, x, 0] = tiled_2d[src_y, src_x] + return out + + +def _reference_extract_all_depth_tiles( + tiled_np: np.ndarray, + num_envs: int, + num_cols: int, + tile_width: int, + tile_height: int, +) -> np.ndarray: + """NumPy reference for ``extract_all_depth_tiles_kernel``.""" + return _reference_extract_all_depth_tiles_legacy(tiled_np[..., 0], num_envs, num_cols, tile_width, tile_height) + + +def _reference_extract_all_rgba_tiles( + tiled_np: np.ndarray, + num_envs: int, + num_cols: int, + tile_width: int, + tile_height: int, + num_channels: int, +) -> np.ndarray: + """NumPy reference for ``extract_all_rgba_tiles_kernel``.""" + out_c = 4 if num_channels == 4 else 3 + out = np.zeros((num_envs, tile_height, tile_width, out_c), dtype=np.uint8) + for env_idx in range(num_envs): + tile_x = env_idx % num_cols + tile_y = env_idx // num_cols + for y in range(tile_height): + for x in range(tile_width): + src_y = tile_y * tile_height + y + src_x = tile_x * tile_width + x + out[env_idx, y, x, 0] = tiled_np[src_y, src_x, 0] + out[env_idx, y, x, 1] = tiled_np[src_y, src_x, 1] + out[env_idx, y, x, 2] = tiled_np[src_y, src_x, 2] + if num_channels == 4: + out[env_idx, y, x, 3] = tiled_np[src_y, src_x, 3] + return out + + +class TestExtractAllDepthTilesKernel: + """Tests for ``extract_all_depth_tiles_kernel``.""" + + def test_two_by_two_tile_grid(self): + num_cols = 2 + num_envs = 4 + tile_width = 2 + tile_height = 3 + tiled_h = (num_envs // num_cols) * tile_height + tiled_w = num_cols * tile_width + tiled_np = np.zeros((tiled_h, tiled_w, 1), dtype=np.float32) + for h in range(tiled_h): + for w in range(tiled_w): + tiled_np[h, w, 0] = float(h * 1000 + w) + + tiled_wp = wp.array(tiled_np, dtype=wp.float32, ndim=3, device=DEVICE) + output_wp = wp.zeros(shape=(num_envs, tile_height, tile_width, 1), dtype=wp.float32, device=DEVICE) + + wp.launch( + kernel=extract_all_depth_tiles_kernel, + dim=(num_envs, tile_height, tile_width), + inputs=[tiled_wp, output_wp, num_cols, tile_width, tile_height], + device=DEVICE, + ) + wp.synchronize() + + expected = _reference_extract_all_depth_tiles(tiled_np, num_envs, num_cols, tile_width, tile_height) + np.testing.assert_allclose(output_wp.numpy(), expected, rtol=0, atol=0) + + def test_single_tile(self): + num_cols = 1 + num_envs = 1 + tile_width = 4 + tile_height = 4 + tiled_np = np.arange(tile_height * tile_width, dtype=np.float32).reshape(tile_height, tile_width, 1) + + tiled_wp = wp.array(tiled_np, dtype=wp.float32, ndim=3, device=DEVICE) + output_wp = wp.zeros(shape=(num_envs, tile_height, tile_width, 1), dtype=wp.float32, device=DEVICE) + + wp.launch( + kernel=extract_all_depth_tiles_kernel, + dim=(num_envs, tile_height, tile_width), + inputs=[tiled_wp, output_wp, num_cols, tile_width, tile_height], + device=DEVICE, + ) + wp.synchronize() + + expected = _reference_extract_all_depth_tiles(tiled_np, num_envs, num_cols, tile_width, tile_height) + np.testing.assert_array_equal(output_wp.numpy(), expected) + + @pytest.mark.parametrize( + ("num_cols", "num_envs", "tile_width", "tile_height"), + [ + (3, 6, 2, 2), + (1, 3, 5, 1), + (4, 8, 1, 1), + ], + ) + def test_various_layouts(self, num_cols, num_envs, tile_width, tile_height): + num_rows = (num_envs + num_cols - 1) // num_cols + tiled_h = num_rows * tile_height + tiled_w = num_cols * tile_width + rng = np.random.default_rng(12345) + tiled_np = rng.random((tiled_h, tiled_w, 1), dtype=np.float32).astype(np.float32) + + tiled_wp = wp.array(tiled_np, dtype=wp.float32, ndim=3, device=DEVICE) + output_wp = wp.zeros(shape=(num_envs, tile_height, tile_width, 1), dtype=wp.float32, device=DEVICE) + + wp.launch( + kernel=extract_all_depth_tiles_kernel, + dim=(num_envs, tile_height, tile_width), + inputs=[tiled_wp, output_wp, num_cols, tile_width, tile_height], + device=DEVICE, + ) + wp.synchronize() + + expected = _reference_extract_all_depth_tiles(tiled_np, num_envs, num_cols, tile_width, tile_height) + np.testing.assert_allclose(output_wp.numpy(), expected, rtol=1e-6, atol=1e-6) + + +class TestExtractAllDepthTilesKernelLegacy: + """Tests for ``extract_all_depth_tiles_kernel_legacy`` (ovrtx < 0.3.0, 2D tiled buffer).""" + + def test_two_by_two_tile_grid(self): + num_cols = 2 + num_envs = 4 + tile_width = 2 + tile_height = 3 + tiled_h = (num_envs // num_cols) * tile_height + tiled_w = num_cols * tile_width + tiled_np = np.zeros((tiled_h, tiled_w), dtype=np.float32) + for h in range(tiled_h): + for w in range(tiled_w): + tiled_np[h, w] = float(h * 1000 + w) + + tiled_wp = wp.array(tiled_np, dtype=wp.float32, ndim=2, device=DEVICE) + output_wp = wp.zeros(shape=(num_envs, tile_height, tile_width, 1), dtype=wp.float32, device=DEVICE) + + wp.launch( + kernel=extract_all_depth_tiles_kernel_legacy, + dim=(num_envs, tile_height, tile_width), + inputs=[tiled_wp, output_wp, num_cols, tile_width, tile_height], + device=DEVICE, + ) + wp.synchronize() + + expected = _reference_extract_all_depth_tiles_legacy(tiled_np, num_envs, num_cols, tile_width, tile_height) + np.testing.assert_allclose(output_wp.numpy(), expected, rtol=0, atol=0) + + def test_single_tile(self): + num_cols = 1 + num_envs = 1 + tile_width = 4 + tile_height = 4 + tiled_np = np.arange(tile_height * tile_width, dtype=np.float32).reshape(tile_height, tile_width) + + tiled_wp = wp.array(tiled_np, dtype=wp.float32, ndim=2, device=DEVICE) + output_wp = wp.zeros(shape=(num_envs, tile_height, tile_width, 1), dtype=wp.float32, device=DEVICE) + + wp.launch( + kernel=extract_all_depth_tiles_kernel_legacy, + dim=(num_envs, tile_height, tile_width), + inputs=[tiled_wp, output_wp, num_cols, tile_width, tile_height], + device=DEVICE, + ) + wp.synchronize() + + expected = _reference_extract_all_depth_tiles_legacy(tiled_np, num_envs, num_cols, tile_width, tile_height) + np.testing.assert_array_equal(output_wp.numpy(), expected) + + @pytest.mark.parametrize( + ("num_cols", "num_envs", "tile_width", "tile_height"), + [ + (3, 6, 2, 2), + (1, 3, 5, 1), + (4, 8, 1, 1), + ], + ) + def test_various_layouts(self, num_cols, num_envs, tile_width, tile_height): + num_rows = (num_envs + num_cols - 1) // num_cols + tiled_h = num_rows * tile_height + tiled_w = num_cols * tile_width + rng = np.random.default_rng(12345) + tiled_np = rng.random((tiled_h, tiled_w), dtype=np.float32).astype(np.float32) + + tiled_wp = wp.array(tiled_np, dtype=wp.float32, ndim=2, device=DEVICE) + output_wp = wp.zeros(shape=(num_envs, tile_height, tile_width, 1), dtype=wp.float32, device=DEVICE) + + wp.launch( + kernel=extract_all_depth_tiles_kernel_legacy, + dim=(num_envs, tile_height, tile_width), + inputs=[tiled_wp, output_wp, num_cols, tile_width, tile_height], + device=DEVICE, + ) + wp.synchronize() + + expected = _reference_extract_all_depth_tiles_legacy(tiled_np, num_envs, num_cols, tile_width, tile_height) + np.testing.assert_allclose(output_wp.numpy(), expected, rtol=1e-6, atol=1e-6) + + +class TestExtractAllRgbaTilesKernel: + """Tests for ``extract_all_rgba_tiles_kernel``.""" + + def test_two_by_two_tile_grid_rgba(self): + num_cols = 2 + num_envs = 4 + tile_width = 2 + tile_height = 3 + num_channels = 4 + tiled_h = (num_envs // num_cols) * tile_height + tiled_w = num_cols * tile_width + tiled_np = np.zeros((tiled_h, tiled_w, 4), dtype=np.uint8) + for h in range(tiled_h): + for w in range(tiled_w): + tiled_np[h, w, 0] = (h * 17 + w) % 256 + tiled_np[h, w, 1] = (h * 31 + w * 3) % 256 + tiled_np[h, w, 2] = (h + w * 11) % 256 + tiled_np[h, w, 3] = (h * 7 + w * 13) % 256 + + tiled_wp = wp.array(tiled_np, dtype=wp.uint8, ndim=3, device=DEVICE) + output_wp = wp.zeros(shape=(num_envs, tile_height, tile_width, num_channels), dtype=wp.uint8, device=DEVICE) + + wp.launch( + kernel=extract_all_rgba_tiles_kernel, + dim=(num_envs, tile_height, tile_width), + inputs=[tiled_wp, output_wp, num_cols, tile_width, tile_height, num_channels], + device=DEVICE, + ) + wp.synchronize() + + expected = _reference_extract_all_rgba_tiles( + tiled_np, num_envs, num_cols, tile_width, tile_height, num_channels + ) + np.testing.assert_array_equal(output_wp.numpy(), expected) + + def test_single_tile_rgb(self): + num_cols = 1 + num_envs = 1 + tile_width = 4 + tile_height = 4 + num_channels = 3 + tiled_np = np.arange(tile_height * tile_width * 3, dtype=np.uint8).reshape(tile_height, tile_width, 3) + + tiled_wp = wp.array(tiled_np, dtype=wp.uint8, ndim=3, device=DEVICE) + output_wp = wp.zeros(shape=(num_envs, tile_height, tile_width, num_channels), dtype=wp.uint8, device=DEVICE) + + wp.launch( + kernel=extract_all_rgba_tiles_kernel, + dim=(num_envs, tile_height, tile_width), + inputs=[tiled_wp, output_wp, num_cols, tile_width, tile_height, num_channels], + device=DEVICE, + ) + wp.synchronize() + + expected = _reference_extract_all_rgba_tiles( + tiled_np, num_envs, num_cols, tile_width, tile_height, num_channels + ) + np.testing.assert_array_equal(output_wp.numpy(), expected) + + def test_num_channels_not_four_skips_alpha(self): + """Values other than 4 use the RGB-only path (same as RGB tiled input).""" + num_cols = 1 + num_envs = 1 + tile_width = 2 + tile_height = 2 + tiled_np = np.array( + [ + [[1, 2, 3, 99], [4, 5, 6, 88]], + [[7, 8, 9, 77], [10, 11, 12, 66]], + ], + dtype=np.uint8, + ) + + tiled_wp = wp.array(tiled_np, dtype=wp.uint8, ndim=3, device=DEVICE) + output_wp = wp.zeros(shape=(1, 2, 2, 3), dtype=wp.uint8, device=DEVICE) + + wp.launch( + kernel=extract_all_rgba_tiles_kernel, + dim=(1, tile_height, tile_width), + inputs=[tiled_wp, output_wp, num_cols, tile_width, tile_height, 2], + device=DEVICE, + ) + wp.synchronize() + + expected = _reference_extract_all_rgba_tiles(tiled_np, num_envs, num_cols, tile_width, tile_height, 2) + np.testing.assert_array_equal(output_wp.numpy(), expected) + + @pytest.mark.parametrize( + ("num_cols", "num_envs", "tile_width", "tile_height", "num_channels"), + [ + (3, 6, 2, 2, 3), + (3, 6, 2, 2, 4), + (1, 3, 5, 1, 3), + (4, 8, 1, 1, 4), + ], + ) + def test_various_layouts(self, num_cols, num_envs, tile_width, tile_height, num_channels): + num_rows = (num_envs + num_cols - 1) // num_cols + tiled_h = num_rows * tile_height + tiled_w = num_cols * tile_width + c_in = 4 if num_channels == 4 else 3 + rng = np.random.default_rng(24680) + tiled_np = rng.integers(0, 256, size=(tiled_h, tiled_w, c_in), dtype=np.uint8) + + tiled_wp = wp.array(tiled_np, dtype=wp.uint8, ndim=3, device=DEVICE) + output_wp = wp.zeros( + shape=(num_envs, tile_height, tile_width, num_channels), + dtype=wp.uint8, + device=DEVICE, + ) + + wp.launch( + kernel=extract_all_rgba_tiles_kernel, + dim=(num_envs, tile_height, tile_width), + inputs=[tiled_wp, output_wp, num_cols, tile_width, tile_height, num_channels], + device=DEVICE, + ) + wp.synchronize() + + expected = _reference_extract_all_rgba_tiles( + tiled_np, num_envs, num_cols, tile_width, tile_height, num_channels + ) + np.testing.assert_array_equal(output_wp.numpy(), expected) + + class TestRandomColorsFromIdsKernel: """Tests for generate_random_colors_from_ids_kernel.""" def test_random_colors(self): - inputs_np = np.array([[0, 1], [2, 3]], dtype=np.uint32) - input_ids = wp.array(inputs_np, dtype=wp.uint32, ndim=2, device=DEVICE) - h, w = inputs_np.shape - output_colors = wp.zeros(shape=(h, w), dtype=wp.uint32, device=DEVICE) + inputs_np = np.array([[[0], [1]], [[2], [3]]], dtype=np.uint32) + input_ids = wp.array(inputs_np, dtype=wp.uint32, ndim=3, device=DEVICE) + output_colors = wp.zeros(shape=inputs_np.shape, dtype=wp.uint32, device=DEVICE) wp.launch( kernel=generate_random_colors_from_ids_kernel, - dim=(h, w), + dim=inputs_np.shape, inputs=[input_ids, output_colors], device=DEVICE, ) wp.synchronize() out_np = output_colors.numpy() - for i in range(h): - for j in range(w): - input_id = int(inputs_np[i, j]) - ref_color = _reference_color(input_id) - out_color = int(out_np[i, j]) - assert out_color == ref_color, ( - f"At ({i},{j}) id={input_id}: expected 0x{ref_color:08x}, got 0x{out_color:08x}" - ) + for (i, j, k), input_id in np.ndenumerate(inputs_np): + input_id = int(np.uint32(input_id)) + ref_color = _reference_color(input_id) + out_color = int(out_np[i, j, k]) + assert out_color == ref_color, ( + f"At ({i},{j},{k}) id={input_id}: expected 0x{ref_color:08x}, got 0x{out_color:08x}" + ) def test_deterministic_across_launches(self): - h, w = 4, 4 + shape = (4, 4, 1) rng = np.random.default_rng(42) - inputs_np = rng.integers(0, 2**31, size=(h, w), dtype=np.uint32) - input_ids = wp.array(inputs_np, dtype=wp.uint32, ndim=2, device=DEVICE) - output_colors = wp.zeros(shape=(h, w), dtype=wp.uint32, device=DEVICE) + inputs_np = rng.integers(0, 2**31, size=shape, dtype=np.uint32) + input_ids = wp.array(inputs_np, dtype=wp.uint32, ndim=3, device=DEVICE) + output_colors = wp.zeros(shape=shape, dtype=wp.uint32, device=DEVICE) wp.launch( kernel=generate_random_colors_from_ids_kernel, - dim=(h, w), + dim=shape, inputs=[input_ids, output_colors], device=DEVICE, ) @@ -114,7 +457,89 @@ def test_deterministic_across_launches(self): wp.launch( kernel=generate_random_colors_from_ids_kernel, - dim=(h, w), + dim=shape, + inputs=[input_ids, output_colors], + device=DEVICE, + ) + wp.synchronize() + second_run = output_colors.numpy() + + np.testing.assert_array_equal(first_run, second_run) + + @pytest.mark.parametrize( + "input_value", + [ + 0, + 1, + 2, + 3, + 100, + ], + ) + def test_single_value(self, input_value): + inputs_np = np.array([[[input_value]]], dtype=np.uint32) + input_ids = wp.array(inputs_np, dtype=wp.uint32, ndim=3, device=DEVICE) + output_colors = wp.zeros(shape=(1, 1, 1), dtype=wp.uint32, device=DEVICE) + + wp.launch( + kernel=generate_random_colors_from_ids_kernel, + dim=(1, 1, 1), + inputs=[input_ids, output_colors], + device=DEVICE, + ) + wp.synchronize() + + ref_color = _reference_color(int(np.uint32(input_value))) + out_color = int(output_colors.numpy()[0, 0, 0]) + assert out_color == ref_color, ( + f"id=0x{int(np.uint32(input_value)):08x}: expected 0x{ref_color:08x}, got 0x{out_color:08x}" + ) + + +class TestRandomColorsFromIdsKernelLegacy: + """Tests for ``generate_random_colors_from_ids_kernel_legacy`` (ovrtx < 0.3.0, 2D buffers).""" + + def test_random_colors(self): + inputs_np = np.array([[0, 1], [2, 3]], dtype=np.uint32) + input_ids = wp.array(inputs_np, dtype=wp.uint32, ndim=2, device=DEVICE) + output_colors = wp.zeros(shape=inputs_np.shape, dtype=wp.uint32, device=DEVICE) + + wp.launch( + kernel=generate_random_colors_from_ids_kernel_legacy, + dim=inputs_np.shape, + inputs=[input_ids, output_colors], + device=DEVICE, + ) + wp.synchronize() + + out_np = output_colors.numpy() + for (i, j), input_id in np.ndenumerate(inputs_np): + input_id = int(np.uint32(input_id)) + ref_color = _reference_color(input_id) + out_color = int(out_np[i, j]) + assert out_color == ref_color, ( + f"At ({i},{j}) id={input_id}: expected 0x{ref_color:08x}, got 0x{out_color:08x}" + ) + + def test_deterministic_across_launches(self): + shape = (4, 4) + rng = np.random.default_rng(42) + inputs_np = rng.integers(0, 2**31, size=shape, dtype=np.uint32) + input_ids = wp.array(inputs_np, dtype=wp.uint32, ndim=2, device=DEVICE) + output_colors = wp.zeros(shape=shape, dtype=wp.uint32, device=DEVICE) + + wp.launch( + kernel=generate_random_colors_from_ids_kernel_legacy, + dim=shape, + inputs=[input_ids, output_colors], + device=DEVICE, + ) + wp.synchronize() + first_run = output_colors.numpy().copy() + + wp.launch( + kernel=generate_random_colors_from_ids_kernel_legacy, + dim=shape, inputs=[input_ids, output_colors], device=DEVICE, ) @@ -139,7 +564,7 @@ def test_single_value(self, input_value): output_colors = wp.zeros(shape=(1, 1), dtype=wp.uint32, device=DEVICE) wp.launch( - kernel=generate_random_colors_from_ids_kernel, + kernel=generate_random_colors_from_ids_kernel_legacy, dim=(1, 1), inputs=[input_ids, output_colors], device=DEVICE, diff --git a/source/isaaclab_ovphysx/changelog.d/pr-5458-merge-develop.rst b/source/isaaclab_ovphysx/changelog.d/pr-5458-merge-develop.rst new file mode 100644 index 000000000000..546cb8acc1c7 --- /dev/null +++ b/source/isaaclab_ovphysx/changelog.d/pr-5458-merge-develop.rst @@ -0,0 +1,7 @@ +Removed +^^^^^^^ + +* Removed ``ArticulationData.body_incoming_joint_wrench_b`` to match the + shared articulation data API. Code that needs incoming joint reaction + wrenches should use a backend joint-wrench sensor instead of the articulation + data object. diff --git a/source/isaaclab_ovphysx/config/extension.toml b/source/isaaclab_ovphysx/config/extension.toml new file mode 100644 index 000000000000..8648b7fa9587 --- /dev/null +++ b/source/isaaclab_ovphysx/config/extension.toml @@ -0,0 +1,21 @@ +[package] + +# Note: Semantic Versioning is used: https://semver.org/ +version = "0.1.2" + +# Description +title = "OvPhysX simulation interfaces for IsaacLab core package" +description = "Extension providing IsaacLab with ovphysx/TensorBindingsAPI specific abstractions." +readme = "docs/README.md" +repository = "https://github.com/isaac-sim/IsaacLab" +category = "robotics" +keywords = ["robotics", "simulation", "ovphysx", "tensorbindingsapi"] + +[dependencies] +"isaaclab" = {} + +[core] +reloadable = false + +[[python.module]] +name = "isaaclab_ovphysx" diff --git a/source/isaaclab_ovphysx/docs/CHANGELOG.rst b/source/isaaclab_ovphysx/docs/CHANGELOG.rst new file mode 100644 index 000000000000..b2eb969d7845 --- /dev/null +++ b/source/isaaclab_ovphysx/docs/CHANGELOG.rst @@ -0,0 +1,43 @@ +Changelog +--------- + +0.1.2 (2026-04-23) +~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Wrapped :attr:`~isaaclab_ovphysx.assets.ArticulationData.GRAVITY_VEC_W` and + :attr:`~isaaclab_ovphysx.assets.ArticulationData.FORWARD_VEC_B` in + :class:`~isaaclab.utils.warp.ProxyArray` to match the PhysX and Newton + backends. Public observations such as + :func:`~isaaclab.envs.mdp.observations.projected_gravity` access + ``asset.data.GRAVITY_VEC_W.torch``; the previous raw ``wp.array`` lacked + ``.torch`` and raised ``AttributeError`` on the ovphysx backend. + + +0.1.1 (2026-04-21) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Replaced private ``_find_names`` (fnmatch + regex) with the standard + :func:`~isaaclab.utils.string.resolve_matching_names` for all finder + methods, unifying name-resolution behavior across backends. Fnmatch-style + glob patterns (e.g. ``joint_*``) are no longer supported; use regex + equivalents (e.g. ``joint_.*``). ``find_fixed_tendons`` and + ``find_spatial_tendons`` now raise ``ValueError`` on empty tendon lists, + matching the PhysX backend. +* Changed ``find_joints`` ``joint_subset`` parameter from ``list[int]`` + (indices) to ``list[str]`` (names) to match the ``BaseArticulation`` + interface. Callers passing indices should convert to names first. + + +0.1.0 (2026-04-20) +~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Initial release of the ``isaaclab_ovphysx`` extension. diff --git a/source/isaaclab_ovphysx/isaaclab_ovphysx/__init__.py b/source/isaaclab_ovphysx/isaaclab_ovphysx/__init__.py new file mode 100644 index 000000000000..69b5f5512333 --- /dev/null +++ b/source/isaaclab_ovphysx/isaaclab_ovphysx/__init__.py @@ -0,0 +1,25 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Package containing the ovphysx/TensorBindingsAPI simulation interfaces for IsaacLab.""" + +import os + +import toml + +ISAACLAB_OVPHYSX_EXT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), "../")) +"""Path to the extension source directory.""" + +# Find config/extension.toml: bundled inside the package (wheel install) or in the +# parent directory (editable install). +_pkg_dir = os.path.dirname(os.path.abspath(__file__)) +_toml_path = os.path.join(_pkg_dir, "config", "extension.toml") +if not os.path.isfile(_toml_path): + _toml_path = os.path.join(ISAACLAB_OVPHYSX_EXT_DIR, "config", "extension.toml") + +ISAACLAB_OVPHYSX_METADATA = toml.load(_toml_path) +"""Extension metadata dictionary parsed from the extension.toml file.""" + +__version__ = ISAACLAB_OVPHYSX_METADATA["package"]["version"] diff --git a/source/isaaclab_ovphysx/isaaclab_ovphysx/assets/__init__.py b/source/isaaclab_ovphysx/isaaclab_ovphysx/assets/__init__.py new file mode 100644 index 000000000000..c644c05de13c --- /dev/null +++ b/source/isaaclab_ovphysx/isaaclab_ovphysx/assets/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Sub-package for ovphysx-backed assets.""" + +from isaaclab.utils.module import lazy_export + +lazy_export() diff --git a/source/isaaclab_ovphysx/isaaclab_ovphysx/assets/__init__.pyi b/source/isaaclab_ovphysx/isaaclab_ovphysx/assets/__init__.pyi new file mode 100644 index 000000000000..516e15c5ef6a --- /dev/null +++ b/source/isaaclab_ovphysx/isaaclab_ovphysx/assets/__init__.pyi @@ -0,0 +1,11 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +__all__ = [ + "Articulation", + "ArticulationData", +] + +from .articulation import Articulation, ArticulationData diff --git a/source/isaaclab_ovphysx/isaaclab_ovphysx/assets/articulation/__init__.py b/source/isaaclab_ovphysx/isaaclab_ovphysx/assets/articulation/__init__.py new file mode 100644 index 000000000000..d3798bf9652b --- /dev/null +++ b/source/isaaclab_ovphysx/isaaclab_ovphysx/assets/articulation/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Sub-module for ovphysx-backed articulated assets.""" + +from isaaclab.utils.module import lazy_export + +lazy_export() diff --git a/source/isaaclab_ovphysx/isaaclab_ovphysx/assets/articulation/__init__.pyi b/source/isaaclab_ovphysx/isaaclab_ovphysx/assets/articulation/__init__.pyi new file mode 100644 index 000000000000..9e482491fe54 --- /dev/null +++ b/source/isaaclab_ovphysx/isaaclab_ovphysx/assets/articulation/__init__.pyi @@ -0,0 +1,12 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +__all__ = [ + "Articulation", + "ArticulationData", +] + +from .articulation import Articulation +from .articulation_data import ArticulationData diff --git a/source/isaaclab_ovphysx/isaaclab_ovphysx/assets/articulation/articulation.py b/source/isaaclab_ovphysx/isaaclab_ovphysx/assets/articulation/articulation.py new file mode 100644 index 000000000000..f3919d56da73 --- /dev/null +++ b/source/isaaclab_ovphysx/isaaclab_ovphysx/assets/articulation/articulation.py @@ -0,0 +1,2675 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Articulation implementation backed by ovphysx TensorBindingsAPI.""" + +from __future__ import annotations + +import logging +import re +from collections.abc import Sequence +from typing import TYPE_CHECKING, Any + +import numpy as np +import torch +import warp as wp + +from isaaclab.assets.articulation.base_articulation import BaseArticulation +from isaaclab.physics import PhysicsManager +from isaaclab.utils.string import resolve_matching_names +from isaaclab.utils.wrench_composer import WrenchComposer + +from isaaclab_ovphysx import tensor_types as TT +from isaaclab_ovphysx.physics import OvPhysxManager + +from .articulation_data import ArticulationData +from .kernels import _body_wrench_to_world, _scatter_rows_partial, update_soft_joint_pos_limits + +if TYPE_CHECKING: + from isaaclab.actuators import ActuatorBase + from isaaclab.assets.articulation.articulation_cfg import ArticulationCfg + +logger = logging.getLogger(__name__) + + +class Articulation(BaseArticulation): + """Articulation backed by the ovphysx TensorBindingsAPI. + + Reads and writes simulation state through ovphysx.TensorBinding objects created + from the OvPhysxManager's PhysX instance. + """ + + __backend_name__ = "ovphysx" + + cfg: ArticulationCfg + + def __init__(self, cfg: ArticulationCfg): + super().__init__(cfg) + + """ + Properties + """ + + @property + def data(self) -> ArticulationData: + """Data container with simulation state for this articulation.""" + return self._data + + @property + def num_instances(self) -> int: + """Number of articulation instances (environments).""" + return self._num_instances + + @property + def is_fixed_base(self) -> bool: + """Whether the articulation is a fixed-base or floating-base system.""" + return self._is_fixed_base + + @property + def num_joints(self) -> int: + """Number of joints in the articulation.""" + return self._num_joints + + @property + def num_fixed_tendons(self) -> int: + """Number of fixed tendons in the articulation.""" + return getattr(self, "_num_fixed_tendons", 0) + + @property + def num_spatial_tendons(self) -> int: + """Number of spatial tendons in the articulation.""" + return getattr(self, "_num_spatial_tendons", 0) + + @property + def num_bodies(self) -> int: + """Number of bodies (links) in the articulation.""" + return self._num_bodies + + @property + def joint_names(self) -> list[str]: + """Ordered names of joints in the articulation.""" + return self._joint_names + + @property + def fixed_tendon_names(self) -> list[str]: + """Ordered names of fixed tendons in the articulation.""" + return getattr(self, "_fixed_tendon_names", []) + + @property + def spatial_tendon_names(self) -> list[str]: + """Ordered names of spatial tendons in the articulation.""" + return getattr(self, "_spatial_tendon_names", []) + + @property + def body_names(self) -> list[str]: + """Ordered names of bodies (links) in the articulation.""" + return self._body_names + + @property + def root_view(self) -> Any: + """Root articulation view (not available for ovphysx backend).""" + return None + + @property + def instantaneous_wrench_composer(self) -> WrenchComposer | None: + """Wrench composer for forces applied only during the current step.""" + return self._instantaneous_wrench_composer + + @property + def permanent_wrench_composer(self) -> WrenchComposer | None: + """Wrench composer for forces applied persistently every step.""" + return self._permanent_wrench_composer + + """ + Operations. + """ + + def reset(self, env_ids: Sequence[int] | None = None, env_mask: wp.array | None = None) -> None: + """Reset the articulation. + + .. caution:: + If both `env_ids` and `env_mask` are provided, then `env_mask` takes precedence over `env_ids`. + + Args: + env_ids: Environment indices. If None, then all indices are used. + env_mask: Environment mask. If None, then all the instances are updated. Shape is (num_instances,). + """ + # use ellipses object to skip initial indices. + if (env_ids is None) or (env_ids == slice(None)): + env_ids = slice(None) + # reset actuators + for actuator in self.actuators.values(): + actuator.reset(env_ids) + # reset external wrenches. + self._instantaneous_wrench_composer.reset(env_ids, env_mask) + self._permanent_wrench_composer.reset(env_ids, env_mask) + + def write_data_to_sim(self) -> None: + """Apply external wrenches, actuator model, and write commands into the simulation.""" + # Apply external wrenches (before actuators, same as PhysX backend). + self._apply_external_wrenches() + + self._apply_actuator_model() + # Write effort tensor to simulation. + if self._effort_binding is not None: + self._effort_binding.write(self._effort_write_view) + # Write position and velocity targets in one shot (not per-actuator). + if self._has_implicit_actuators: + if self._pos_target_binding is not None: + self._pos_target_binding.write(self._pos_target_write_view) + if self._vel_target_binding is not None: + self._vel_target_binding.write(self._vel_target_write_view) + + def update(self, dt: float) -> None: + """Update internal data buffers after a simulation step. + + Args: + dt: The simulation time step [s] used for finite-difference quantities. + """ + self._data.update(dt) + + """ + Operations - Finders. + """ + + def find_bodies(self, name_keys: str | Sequence[str], preserve_order: bool = False) -> tuple[list[int], list[str]]: + """Find bodies in the articulation based on the name keys. + + Please check the :func:`isaaclab.utils.string.resolve_matching_names` function for more + information on the name matching. + + Args: + name_keys: A regular expression or a list of regular expressions to match the body names. + preserve_order: Whether to preserve the order of the name keys in the output. Defaults to False. + + Returns: + A tuple of lists containing the body indices and names. + """ + return resolve_matching_names(name_keys, self._body_names, preserve_order) + + def find_joints( + self, + name_keys: str | Sequence[str], + joint_subset: list[str] | None = None, + preserve_order: bool = False, + ) -> tuple[list[int], list[str]]: + """Find joints in the articulation based on the name keys. + + Please check the :func:`isaaclab.utils.string.resolve_matching_names` function for more + information on the name matching. + + Args: + name_keys: A regular expression or a list of regular expressions to match the joint names. + joint_subset: A subset of joints to search for. Defaults to None, which means all joints + in the articulation are searched. + preserve_order: Whether to preserve the order of the name keys in the output. Defaults to False. + + Returns: + A tuple of lists containing the joint indices and names. + """ + if joint_subset is None: + joint_subset = self._joint_names + return resolve_matching_names(name_keys, joint_subset, preserve_order) + + def find_fixed_tendons( + self, + name_keys: str | Sequence[str], + tendon_subsets: list[str] | None = None, + preserve_order: bool = False, + ) -> tuple[list[int], list[str]]: + """Find fixed tendons in the articulation based on the name keys. + + Args: + name_keys: A regular expression or a list of regular expressions + to match the joint names with fixed tendons. + tendon_subsets: A subset of joints with fixed tendons to search + for. Defaults to None, which means all joints in the + articulation are searched. + preserve_order: Whether to preserve the order of the name keys in + the output. Defaults to False. + + Returns: + A tuple of lists containing the tendon indices and names. + """ + if tendon_subsets is None: + tendon_subsets = self.fixed_tendon_names + return resolve_matching_names(name_keys, tendon_subsets, preserve_order) + + def find_spatial_tendons( + self, + name_keys: str | Sequence[str], + tendon_subsets: list[str] | None = None, + preserve_order: bool = False, + ) -> tuple[list[int], list[str]]: + """Find spatial tendons in the articulation based on the name keys. + + Args: + name_keys: A regular expression or a list of regular expressions + to match the tendon names. + tendon_subsets: A subset of tendons to search for. Defaults to + None, which means all tendons in the articulation are searched. + preserve_order: Whether to preserve the order of the name keys in + the output. Defaults to False. + + Returns: + A tuple of lists containing the tendon indices and names. + """ + if tendon_subsets is None: + tendon_subsets = self.spatial_tendon_names + return resolve_matching_names(name_keys, tendon_subsets, preserve_order) + + """ + Operations - State Writers. + """ + + def write_root_pose_to_sim_index( + self, + *, + root_pose: torch.Tensor | wp.array, + env_ids: Sequence[int] | wp.array | None = None, + ) -> None: + """Set the root pose over selected environment indices into the simulation. + + The root pose comprises of the cartesian position and quaternion orientation in (x, y, z, w). + + Args: + root_pose: Root poses in simulation frame. Shape is (len(env_ids),) with dtype wp.transformf. + env_ids: Environment indices. If None, then all indices are used. + """ + n = self._n_envs_index(env_ids) + self.assert_shape_and_dtype(root_pose, (n,), wp.transformf, "root_pose") + self._write_root_state(TT.ROOT_POSE, root_pose, env_ids) + + def write_root_pose_to_sim_mask( + self, + *, + root_pose: torch.Tensor | wp.array, + env_mask: wp.array | None = None, + ) -> None: + """Set the root pose over masked environments into the simulation. + + The root pose comprises of the cartesian position and quaternion orientation in (x, y, z, w). + + Args: + root_pose: Root poses in simulation frame. Shape is (num_instances,) with dtype wp.transformf. + env_mask: Environment mask. If None, then all instances are updated. + """ + self.assert_shape_and_dtype(root_pose, (self._num_instances,), wp.transformf, "root_pose") + self._write_root_state(TT.ROOT_POSE, root_pose, mask=env_mask) + + def write_root_link_pose_to_sim_index( + self, + *, + root_pose: torch.Tensor | wp.array, + env_ids: Sequence[int] | wp.array | None = None, + ) -> None: + """Set the root link pose over selected environment indices into the simulation. + + The root pose comprises of the cartesian position and quaternion orientation in (x, y, z, w). + + Args: + root_pose: Root link poses in simulation frame. Shape is (len(env_ids),) with dtype wp.transformf. + env_ids: Environment indices. If None, then all indices are used. + """ + n = self._n_envs_index(env_ids) + self.assert_shape_and_dtype(root_pose, (n,), wp.transformf, "root_pose") + self._write_root_state(TT.ROOT_POSE, root_pose, env_ids) + + def write_root_link_pose_to_sim_mask( + self, + *, + root_pose: torch.Tensor | wp.array, + env_mask: wp.array | None = None, + ) -> None: + """Set the root link pose over masked environments into the simulation. + + The root pose comprises of the cartesian position and quaternion orientation in (x, y, z, w). + + Args: + root_pose: Root link poses in simulation frame. Shape is (num_instances,) with dtype wp.transformf. + env_mask: Environment mask. If None, then all instances are updated. + """ + self.assert_shape_and_dtype(root_pose, (self._num_instances,), wp.transformf, "root_pose") + self._write_root_state(TT.ROOT_POSE, root_pose, mask=env_mask) + + def write_root_com_pose_to_sim_index( + self, + *, + root_pose: torch.Tensor | wp.array, + env_ids: Sequence[int] | wp.array | None = None, + ) -> None: + """Set the root center of mass pose over selected environment indices into the simulation. + + The root pose comprises of the cartesian position and quaternion orientation in (x, y, z, w). + The orientation is the orientation of the principal axes of inertia. + + Args: + root_pose: Root center of mass poses in simulation frame. Shape is (len(env_ids),) + with dtype wp.transformf. + env_ids: Environment indices. If None, then all indices are used. + """ + n = self._n_envs_index(env_ids) + self.assert_shape_and_dtype(root_pose, (n,), wp.transformf, "root_pose") + self._write_root_state(TT.ROOT_POSE, root_pose, env_ids) + + def write_root_com_pose_to_sim_mask( + self, + *, + root_pose: torch.Tensor | wp.array, + env_mask: wp.array | None = None, + ) -> None: + """Set the root center of mass pose over masked environments into the simulation. + + The root pose comprises of the cartesian position and quaternion orientation in (x, y, z, w). + The orientation is the orientation of the principal axes of inertia. + + Args: + root_pose: Root center of mass poses in simulation frame. Shape is (num_instances,) + with dtype wp.transformf. + env_mask: Environment mask. If None, then all instances are updated. + """ + self.assert_shape_and_dtype(root_pose, (self._num_instances,), wp.transformf, "root_pose") + self._write_root_state(TT.ROOT_POSE, root_pose, mask=env_mask) + + def write_root_velocity_to_sim_index( + self, + *, + root_velocity: torch.Tensor | wp.array, + env_ids: Sequence[int] | wp.array | None = None, + ) -> None: + """Set the root velocity over selected environment indices into the simulation. + + The velocity comprises linear velocity (x, y, z) and angular velocity (x, y, z) in that order. + + Args: + root_velocity: Root velocities in simulation world frame. Shape is (len(env_ids),) + with dtype wp.spatial_vectorf. + env_ids: Environment indices. If None, then all indices are used. + """ + n = self._n_envs_index(env_ids) + self.assert_shape_and_dtype(root_velocity, (n,), wp.spatial_vectorf, "root_velocity") + self._write_root_state(TT.ROOT_VELOCITY, root_velocity, env_ids) + + def write_root_velocity_to_sim_mask( + self, + *, + root_velocity: torch.Tensor | wp.array, + env_mask: wp.array | None = None, + ) -> None: + """Set the root velocity over masked environments into the simulation. + + The velocity comprises linear velocity (x, y, z) and angular velocity (x, y, z) in that order. + + Args: + root_velocity: Root velocities in simulation world frame. Shape is (num_instances,) + with dtype wp.spatial_vectorf. + env_mask: Environment mask. If None, then all instances are updated. + """ + self.assert_shape_and_dtype(root_velocity, (self._num_instances,), wp.spatial_vectorf, "root_velocity") + self._write_root_state(TT.ROOT_VELOCITY, root_velocity, mask=env_mask) + + def write_root_com_velocity_to_sim_index( + self, + *, + root_velocity: torch.Tensor | wp.array, + env_ids: Sequence[int] | wp.array | None = None, + ) -> None: + """Set the root center of mass velocity over selected environment indices into the simulation. + + The velocity comprises linear velocity (x, y, z) and angular velocity (x, y, z) in that order. + + Args: + root_velocity: Root center of mass velocities in simulation world frame. + Shape is (len(env_ids),) with dtype wp.spatial_vectorf. + env_ids: Environment indices. If None, then all indices are used. + """ + n = self._n_envs_index(env_ids) + self.assert_shape_and_dtype(root_velocity, (n,), wp.spatial_vectorf, "root_velocity") + self._write_root_state(TT.ROOT_VELOCITY, root_velocity, env_ids) + + def write_root_com_velocity_to_sim_mask( + self, + *, + root_velocity: torch.Tensor | wp.array, + env_mask: wp.array | None = None, + ) -> None: + """Set the root center of mass velocity over masked environments into the simulation. + + The velocity comprises linear velocity (x, y, z) and angular velocity (x, y, z) in that order. + + Args: + root_velocity: Root center of mass velocities in simulation world frame. + Shape is (num_instances,) with dtype wp.spatial_vectorf. + env_mask: Environment mask. If None, then all instances are updated. + """ + self.assert_shape_and_dtype(root_velocity, (self._num_instances,), wp.spatial_vectorf, "root_velocity") + self._write_root_state(TT.ROOT_VELOCITY, root_velocity, mask=env_mask) + + def write_root_link_velocity_to_sim_index( + self, + *, + root_velocity: torch.Tensor | wp.array, + env_ids: Sequence[int] | wp.array | None = None, + ) -> None: + """Set the root link velocity over selected environment indices into the simulation. + + The velocity comprises linear velocity (x, y, z) and angular velocity (x, y, z) in that order. + + .. note:: + This sets the velocity of the root's frame rather than the root's center of mass. + + Args: + root_velocity: Root frame velocities in simulation world frame. + Shape is (len(env_ids),) with dtype wp.spatial_vectorf. + env_ids: Environment indices. If None, then all indices are used. + """ + n = self._n_envs_index(env_ids) + self.assert_shape_and_dtype(root_velocity, (n,), wp.spatial_vectorf, "root_velocity") + self._write_root_state(TT.ROOT_VELOCITY, root_velocity, env_ids) + + def write_root_link_velocity_to_sim_mask( + self, + *, + root_velocity: torch.Tensor | wp.array, + env_mask: wp.array | None = None, + ) -> None: + """Set the root link velocity over masked environments into the simulation. + + The velocity comprises linear velocity (x, y, z) and angular velocity (x, y, z) in that order. + + .. note:: + This sets the velocity of the root's frame rather than the root's center of mass. + + Args: + root_velocity: Root frame velocities in simulation world frame. + Shape is (num_instances,) with dtype wp.spatial_vectorf. + env_mask: Environment mask. If None, then all instances are updated. + """ + self.assert_shape_and_dtype(root_velocity, (self._num_instances,), wp.spatial_vectorf, "root_velocity") + self._write_root_state(TT.ROOT_VELOCITY, root_velocity, mask=env_mask) + + """ + Operations - Joint State Writers. + """ + + def write_joint_state_to_sim_mask( + self, + joint_pos: torch.Tensor | wp.array, + joint_vel: torch.Tensor | wp.array, + env_mask: wp.array | None = None, + joint_mask: wp.array | None = None, + ) -> None: + """Write joint positions and velocities over masked environments into the simulation. + + Args: + joint_pos: Joint positions. Shape is (num_instances, num_joints). + joint_vel: Joint velocities. Shape is (num_instances, num_joints). + env_mask: Environment mask. If None, then all instances are updated. + joint_mask: Joint mask. If None, then all joints are updated. + """ + self.write_joint_position_to_sim_mask(position=joint_pos, env_mask=env_mask, joint_mask=joint_mask) + self.write_joint_velocity_to_sim_mask(velocity=joint_vel, env_mask=env_mask, joint_mask=joint_mask) + + def write_joint_position_to_sim_index( + self, + *, + position: torch.Tensor | wp.array, + joint_ids: Sequence[int] | None = None, + env_ids: Sequence[int] | wp.array | None = None, + ) -> None: + """Write joint positions over selected environment and joint indices into the simulation. + + Args: + position: Joint positions. Shape is (len(env_ids), len(joint_ids)). + joint_ids: Joint indices. If None, then all joints are used. + env_ids: Environment indices. If None, then all indices are used. + """ + n = self._n_envs_index(env_ids) + d = len(joint_ids) if joint_ids is not None else self._num_joints + self.assert_shape_and_dtype(position, (n, d), wp.float32, "position") + self._write_flat_tensor(TT.DOF_POSITION, position, env_ids, joint_ids) + self.data._joint_pos_buf.timestamp = -1.0 + + def write_joint_position_to_sim_mask( + self, + *, + position: torch.Tensor | wp.array, + joint_mask: wp.array | None = None, + env_mask: wp.array | None = None, + ) -> None: + """Write joint positions over masked environments into the simulation. + + Args: + position: Joint positions. Shape is (num_instances, num_joints). + joint_mask: Joint mask. If None, then all joints are updated. + env_mask: Environment mask. If None, then all instances are updated. + """ + self.assert_shape_and_dtype(position, (self._num_instances, self._num_joints), wp.float32, "position") + self._write_flat_tensor_mask(TT.DOF_POSITION, position, env_mask, joint_mask) + self.data._joint_pos_buf.timestamp = -1.0 + + def write_joint_velocity_to_sim_index( + self, + *, + velocity: torch.Tensor | wp.array, + joint_ids: Sequence[int] | None = None, + env_ids: Sequence[int] | wp.array | None = None, + ) -> None: + """Write joint velocities over selected environment and joint indices into the simulation. + + Args: + velocity: Joint velocities. Shape is (len(env_ids), len(joint_ids)). + joint_ids: Joint indices. If None, then all joints are used. + env_ids: Environment indices. If None, then all indices are used. + """ + n = self._n_envs_index(env_ids) + d = len(joint_ids) if joint_ids is not None else self._num_joints + self.assert_shape_and_dtype(velocity, (n, d), wp.float32, "velocity") + self._write_flat_tensor(TT.DOF_VELOCITY, velocity, env_ids, joint_ids) + self.data._joint_vel_buf.timestamp = -1.0 + + def write_joint_velocity_to_sim_mask( + self, + *, + velocity: torch.Tensor | wp.array, + joint_mask: wp.array | None = None, + env_mask: wp.array | None = None, + ) -> None: + """Write joint velocities over masked environments into the simulation. + + Args: + velocity: Joint velocities. Shape is (num_instances, num_joints). + joint_mask: Joint mask. If None, then all joints are updated. + env_mask: Environment mask. If None, then all instances are updated. + """ + self.assert_shape_and_dtype(velocity, (self._num_instances, self._num_joints), wp.float32, "velocity") + self._write_flat_tensor_mask(TT.DOF_VELOCITY, velocity, env_mask, joint_mask) + self.data._joint_vel_buf.timestamp = -1.0 + + """ + Operations - Simulation Parameters Writers. + """ + + def write_joint_stiffness_to_sim_index( + self, + *, + stiffness: torch.Tensor | wp.array, + joint_ids: Sequence[int] | None = None, + env_ids: Sequence[int] | wp.array | None = None, + ) -> None: + """Write joint stiffness over selected indices into the simulation. + + Args: + stiffness: Joint stiffness. Shape is (len(env_ids), len(joint_ids)). + joint_ids: Joint indices. If None, then all joints are used. + env_ids: Environment indices. If None, then all indices are used. + """ + n = self._n_envs_index(env_ids) + d = len(joint_ids) if joint_ids is not None else self._num_joints + self.assert_shape_and_dtype(stiffness, (n, d), wp.float32, "stiffness") + self._write_flat_tensor(TT.DOF_STIFFNESS, stiffness, env_ids, joint_ids) + + def write_joint_stiffness_to_sim_mask( + self, + *, + stiffness: torch.Tensor | wp.array, + joint_mask: wp.array | None = None, + env_mask: wp.array | None = None, + ) -> None: + """Write joint stiffness over masked environments into the simulation. + + Args: + stiffness: Joint stiffness. Shape is (num_instances, num_joints). + joint_mask: Joint mask. If None, then all joints are updated. + env_mask: Environment mask. If None, then all instances are updated. + """ + self.assert_shape_and_dtype(stiffness, (self._num_instances, self._num_joints), wp.float32, "stiffness") + self._write_flat_tensor_mask(TT.DOF_STIFFNESS, stiffness, env_mask, joint_mask) + + def write_joint_damping_to_sim_index( + self, + *, + damping: torch.Tensor | wp.array, + joint_ids: Sequence[int] | None = None, + env_ids: Sequence[int] | wp.array | None = None, + ) -> None: + """Write joint damping over selected indices into the simulation. + + Args: + damping: Joint damping. Shape is (len(env_ids), len(joint_ids)). + joint_ids: Joint indices. If None, then all joints are used. + env_ids: Environment indices. If None, then all indices are used. + """ + n = self._n_envs_index(env_ids) + d = len(joint_ids) if joint_ids is not None else self._num_joints + self.assert_shape_and_dtype(damping, (n, d), wp.float32, "damping") + self._write_flat_tensor(TT.DOF_DAMPING, damping, env_ids, joint_ids) + + def write_joint_damping_to_sim_mask( + self, + *, + damping: torch.Tensor | wp.array, + joint_mask: wp.array | None = None, + env_mask: wp.array | None = None, + ) -> None: + """Write joint damping over masked environments into the simulation. + + Args: + damping: Joint damping. Shape is (num_instances, num_joints). + joint_mask: Joint mask. If None, then all joints are updated. + env_mask: Environment mask. If None, then all instances are updated. + """ + self.assert_shape_and_dtype(damping, (self._num_instances, self._num_joints), wp.float32, "damping") + self._write_flat_tensor_mask(TT.DOF_DAMPING, damping, env_mask, joint_mask) + + def write_joint_position_limit_to_sim_index( + self, + *, + limits: torch.Tensor | wp.array, + joint_ids: Sequence[int] | None = None, + env_ids: Sequence[int] | wp.array | None = None, + warn_limit_violation: bool = True, + ) -> None: + """Write joint position limits over selected environment indices into the simulation. + + Args: + limits: Joint position limits [rad or m]. Shape is (len(env_ids), len(joint_ids)) + with dtype wp.vec2f. + joint_ids: Joint indices. If None, then all joints are used. + env_ids: Environment indices. If None, then all indices are used. + warn_limit_violation: Whether to use warning or info level logging when default joint + positions exceed the new limits. Defaults to True. + """ + if isinstance(limits, (int, float)): + raise ValueError("Float scalars are not supported for position limits (vec2f dtype)") + n = self._n_envs_index(env_ids) + d = len(joint_ids) if joint_ids is not None else self._num_joints + self.assert_shape_and_dtype(limits, (n, d), wp.vec2f, "limits") + self._write_flat_tensor(TT.DOF_LIMIT, limits, env_ids, joint_ids) + + def write_joint_position_limit_to_sim_mask( + self, + *, + limits: torch.Tensor | wp.array, + joint_mask: wp.array | None = None, + env_mask: wp.array | None = None, + warn_limit_violation: bool = True, + ) -> None: + """Write joint position limits over masked environments into the simulation. + + Args: + limits: Joint position limits [rad or m]. Shape is (num_instances, num_joints) + with dtype wp.vec2f. + joint_mask: Joint mask. If None, then all joints are updated. + env_mask: Environment mask. If None, then all instances are updated. + warn_limit_violation: Whether to use warning or info level logging when default joint + positions exceed the new limits. Defaults to True. + """ + if isinstance(limits, (int, float)): + raise ValueError("Float scalars are not supported for position limits (vec2f dtype)") + self.assert_shape_and_dtype(limits, (self._num_instances, self._num_joints), wp.vec2f, "limits") + self._write_flat_tensor_mask(TT.DOF_LIMIT, limits, env_mask, joint_mask) + + def write_joint_velocity_limit_to_sim_index( + self, + *, + limits: torch.Tensor | wp.array, + joint_ids: Sequence[int] | None = None, + env_ids: Sequence[int] | wp.array | None = None, + ) -> None: + """Write joint max velocity over selected environment indices into the simulation. + + The velocity limit is used to constrain the joint velocities in the physics engine. + + Args: + limits: Joint max velocity [rad/s or m/s]. Shape is (len(env_ids), len(joint_ids)). + joint_ids: Joint indices. If None, then all joints are used. + env_ids: Environment indices. If None, then all indices are used. + """ + n = self._n_envs_index(env_ids) + d = len(joint_ids) if joint_ids is not None else self._num_joints + self.assert_shape_and_dtype(limits, (n, d), wp.float32, "limits") + self._write_flat_tensor(TT.DOF_MAX_VELOCITY, limits, env_ids, joint_ids) + + def write_joint_velocity_limit_to_sim_mask( + self, + *, + limits: torch.Tensor | wp.array, + joint_mask: wp.array | None = None, + env_mask: wp.array | None = None, + ) -> None: + """Write joint max velocity over masked environments into the simulation. + + The velocity limit is used to constrain the joint velocities in the physics engine. + + Args: + limits: Joint max velocity [rad/s or m/s]. Shape is (num_instances, num_joints). + joint_mask: Joint mask. If None, then all joints are updated. + env_mask: Environment mask. If None, then all instances are updated. + """ + self.assert_shape_and_dtype(limits, (self._num_instances, self._num_joints), wp.float32, "limits") + self._write_flat_tensor_mask(TT.DOF_MAX_VELOCITY, limits, env_mask, joint_mask) + + def write_joint_effort_limit_to_sim_index( + self, + *, + limits: torch.Tensor | wp.array, + joint_ids: Sequence[int] | None = None, + env_ids: Sequence[int] | wp.array | None = None, + ) -> None: + """Write joint effort limits over selected environment indices into the simulation. + + The effort limit is used to constrain the computed joint efforts in the physics engine. + + Args: + limits: Joint effort limits [N or N*m]. Shape is (len(env_ids), len(joint_ids)). + joint_ids: Joint indices. If None, then all joints are used. + env_ids: Environment indices. If None, then all indices are used. + """ + n = self._n_envs_index(env_ids) + d = len(joint_ids) if joint_ids is not None else self._num_joints + self.assert_shape_and_dtype(limits, (n, d), wp.float32, "limits") + self._write_flat_tensor(TT.DOF_MAX_FORCE, limits, env_ids, joint_ids) + + def write_joint_effort_limit_to_sim_mask( + self, + *, + limits: torch.Tensor | wp.array, + joint_mask: wp.array | None = None, + env_mask: wp.array | None = None, + ) -> None: + """Write joint effort limits over masked environments into the simulation. + + The effort limit is used to constrain the computed joint efforts in the physics engine. + + Args: + limits: Joint effort limits [N or N*m]. Shape is (num_instances, num_joints). + joint_mask: Joint mask. If None, then all joints are updated. + env_mask: Environment mask. If None, then all instances are updated. + """ + self.assert_shape_and_dtype(limits, (self._num_instances, self._num_joints), wp.float32, "limits") + self._write_flat_tensor_mask(TT.DOF_MAX_FORCE, limits, env_mask, joint_mask) + + def write_joint_armature_to_sim_index( + self, + *, + armature: torch.Tensor | wp.array, + joint_ids: Sequence[int] | None = None, + env_ids: Sequence[int] | wp.array | None = None, + ) -> None: + """Write joint armature over selected environment indices into the simulation. + + The armature is directly added to the corresponding joint-space inertia. It helps improve the + simulation stability by reducing the joint velocities. + + Args: + armature: Joint armature [kg*m^2 or kg]. Shape is (len(env_ids), len(joint_ids)). + joint_ids: Joint indices. If None, then all joints are used. + env_ids: Environment indices. If None, then all indices are used. + """ + n = self._n_envs_index(env_ids) + d = len(joint_ids) if joint_ids is not None else self._num_joints + self.assert_shape_and_dtype(armature, (n, d), wp.float32, "armature") + self._write_flat_tensor(TT.DOF_ARMATURE, armature, env_ids, joint_ids) + + def write_joint_armature_to_sim_mask( + self, + *, + armature: torch.Tensor | wp.array, + joint_mask: wp.array | None = None, + env_mask: wp.array | None = None, + ) -> None: + """Write joint armature over masked environments into the simulation. + + The armature is directly added to the corresponding joint-space inertia. It helps improve the + simulation stability by reducing the joint velocities. + + Args: + armature: Joint armature [kg*m^2 or kg]. Shape is (num_instances, num_joints). + joint_mask: Joint mask. If None, then all joints are updated. + env_mask: Environment mask. If None, then all instances are updated. + """ + self.assert_shape_and_dtype(armature, (self._num_instances, self._num_joints), wp.float32, "armature") + self._write_flat_tensor_mask(TT.DOF_ARMATURE, armature, env_mask, joint_mask) + + def write_joint_friction_coefficient_to_sim_index( + self, + *, + joint_friction_coeff: torch.Tensor | wp.array, + joint_ids: Sequence[int] | None = None, + env_ids: Sequence[int] | wp.array | None = None, + ) -> None: + """Write joint friction coefficients over selected indices into the simulation. + + Args: + joint_friction_coeff: Joint friction coefficients. Shape is (len(env_ids), len(joint_ids)). + joint_ids: Joint indices. If None, then all joints are used. + env_ids: Environment indices. If None, then all indices are used. + """ + n = self._n_envs_index(env_ids) + d = len(joint_ids) if joint_ids is not None else self._num_joints + self.assert_shape_and_dtype(joint_friction_coeff, (n, d), wp.float32, "joint_friction_coeff") + self._write_friction_column(joint_friction_coeff, env_ids, joint_ids) + + def write_joint_friction_coefficient_to_sim_mask( + self, + *, + joint_friction_coeff: torch.Tensor | wp.array, + joint_mask: wp.array | None = None, + env_mask: wp.array | None = None, + ) -> None: + """Write joint friction coefficients over masked environments into the simulation. + + Args: + joint_friction_coeff: Joint friction coefficients. Shape is (num_instances, num_joints). + joint_mask: Joint mask. If None, then all joints are updated. + env_mask: Environment mask. If None, then all instances are updated. + """ + self.assert_shape_and_dtype( + joint_friction_coeff, (self._num_instances, self._num_joints), wp.float32, "joint_friction_coeff" + ) + self._write_friction_column_mask(joint_friction_coeff, env_mask, joint_mask) + + """ + Operations - Setters. + """ + + def set_masses_index( + self, + *, + masses: torch.Tensor | wp.array, + body_ids: Sequence[int] | None = None, + env_ids: Sequence[int] | wp.array | None = None, + ) -> None: + """Set masses of all bodies using indices. + + Args: + masses: Masses of all bodies [kg]. Shape is (len(env_ids), len(body_ids)). + body_ids: The body indices to set the masses for. Defaults to None (all bodies). + env_ids: The environment indices to set the masses for. Defaults to None (all environments). + """ + n = self._n_envs_index(env_ids) + b = len(body_ids) if body_ids is not None else self._num_bodies + self.assert_shape_and_dtype(masses, (n, b), wp.float32, "masses") + self._write_flat_tensor(TT.BODY_MASS, masses, env_ids, body_ids) + + def set_masses_mask( + self, + *, + masses: torch.Tensor | wp.array, + body_mask: wp.array | None = None, + env_mask: wp.array | None = None, + ) -> None: + """Set masses of all bodies using masks. + + Args: + masses: Masses of all bodies [kg]. Shape is (num_instances, num_bodies). + body_mask: Body mask. If None, then all bodies are used. + env_mask: Environment mask. If None, then all the instances are updated. Shape is (num_instances,). + """ + self.assert_shape_and_dtype(masses, (self._num_instances, self._num_bodies), wp.float32, "masses") + self._write_flat_tensor_mask(TT.BODY_MASS, masses, env_mask, body_mask) + + def set_coms_index( + self, + *, + coms: torch.Tensor | wp.array, + body_ids: Sequence[int] | None = None, + env_ids: Sequence[int] | wp.array | None = None, + ) -> None: + """Set center of mass pose of all bodies using indices. + + Args: + coms: Center of mass pose of all bodies. Shape is (len(env_ids), len(body_ids)) + with dtype wp.transformf. + body_ids: The body indices to set the center of mass pose for. Defaults to None (all bodies). + env_ids: The environment indices to set the center of mass pose for. + Defaults to None (all environments). + """ + n = self._n_envs_index(env_ids) + b = len(body_ids) if body_ids is not None else self._num_bodies + self.assert_shape_and_dtype(coms, (n, b), wp.transformf, "coms") + self._write_flat_tensor(TT.BODY_COM_POSE, coms, env_ids, body_ids) + + def set_coms_mask( + self, + *, + coms: torch.Tensor | wp.array, + body_mask: wp.array | None = None, + env_mask: wp.array | None = None, + ) -> None: + """Set center of mass pose of all bodies using masks. + + Args: + coms: Center of mass pose of all bodies. Shape is (num_instances, num_bodies) + with dtype wp.transformf. + body_mask: Body mask. If None, then all bodies are used. + env_mask: Environment mask. If None, then all the instances are updated. Shape is (num_instances,). + """ + self.assert_shape_and_dtype(coms, (self._num_instances, self._num_bodies), wp.transformf, "coms") + self._write_flat_tensor_mask(TT.BODY_COM_POSE, coms, env_mask, body_mask) + + def set_inertias_index( + self, + *, + inertias: torch.Tensor | wp.array, + body_ids: Sequence[int] | None = None, + env_ids: Sequence[int] | wp.array | None = None, + ) -> None: + """Set inertias of all bodies using indices. + + Args: + inertias: Inertias of all bodies [kg*m^2]. Shape is (len(env_ids), len(body_ids), 9). + body_ids: The body indices to set the inertias for. Defaults to None (all bodies). + env_ids: The environment indices to set the inertias for. Defaults to None (all environments). + """ + n = self._n_envs_index(env_ids) + b = len(body_ids) if body_ids is not None else self._num_bodies + self.assert_shape_and_dtype(inertias, (n, b, 9), wp.float32, "inertias") + self._write_flat_tensor(TT.BODY_INERTIA, inertias, env_ids, body_ids) + + def set_inertias_mask( + self, + *, + inertias: torch.Tensor | wp.array, + body_mask: wp.array | None = None, + env_mask: wp.array | None = None, + ) -> None: + """Set inertias of all bodies using masks. + + Args: + inertias: Inertias of all bodies [kg*m^2]. Shape is (num_instances, num_bodies, 9). + body_mask: Body mask. If None, then all bodies are used. + env_mask: Environment mask. If None, then all the instances are updated. Shape is (num_instances,). + """ + self.assert_shape_and_dtype(inertias, (self._num_instances, self._num_bodies, 9), wp.float32, "inertias") + self._write_flat_tensor_mask(TT.BODY_INERTIA, inertias, env_mask, body_mask) + + """ + Operations - Target Setters. + """ + + def set_joint_position_target_index( + self, + *, + target: torch.Tensor | wp.array, + joint_ids: Sequence[int] | None = None, + env_ids: Sequence[int] | wp.array | None = None, + ) -> None: + """Set joint position targets into internal buffers using indices. + + This function does not apply the joint targets to the simulation. It only fills the buffers with + the desired values. To apply the joint targets, call the :meth:`write_data_to_sim` function. + + Args: + target: Joint position targets [rad or m]. Shape is (len(env_ids), len(joint_ids)). + joint_ids: Joint indices. If None, then all joints are used. + env_ids: Environment indices. If None, then all indices are used. + """ + self._set_target_into_buffer(self._data._joint_pos_target, target, env_ids, joint_ids) + + def set_joint_position_target_mask( + self, + *, + target: torch.Tensor | wp.array, + joint_mask: wp.array | None = None, + env_mask: wp.array | None = None, + ) -> None: + """Set joint position targets into internal buffers using masks. + + Args: + target: Joint position targets [rad or m]. Shape is (num_instances, num_joints). + joint_mask: Joint mask. If None, then all joints are updated. + env_mask: Environment mask. If None, then all instances are updated. + """ + self._set_target_into_buffer_mask(self._data._joint_pos_target, target, env_mask, joint_mask) + + def set_joint_velocity_target_index( + self, + *, + target: torch.Tensor | wp.array, + joint_ids: Sequence[int] | None = None, + env_ids: Sequence[int] | wp.array | None = None, + ) -> None: + """Set joint velocity targets into internal buffers using indices. + + This function does not apply the joint targets to the simulation. It only fills the buffers with + the desired values. To apply the joint targets, call the :meth:`write_data_to_sim` function. + + Args: + target: Joint velocity targets [rad/s or m/s]. Shape is (len(env_ids), len(joint_ids)). + joint_ids: Joint indices. If None, then all joints are used. + env_ids: Environment indices. If None, then all indices are used. + """ + self._set_target_into_buffer(self._data._joint_vel_target, target, env_ids, joint_ids) + + def set_joint_velocity_target_mask( + self, + *, + target: torch.Tensor | wp.array, + joint_mask: wp.array | None = None, + env_mask: wp.array | None = None, + ) -> None: + """Set joint velocity targets into internal buffers using masks. + + Args: + target: Joint velocity targets [rad/s or m/s]. Shape is (num_instances, num_joints). + joint_mask: Joint mask. If None, then all joints are updated. + env_mask: Environment mask. If None, then all instances are updated. + """ + self._set_target_into_buffer_mask(self._data._joint_vel_target, target, env_mask, joint_mask) + + def set_joint_effort_target_index( + self, + *, + target: torch.Tensor | wp.array, + joint_ids: Sequence[int] | None = None, + env_ids: Sequence[int] | wp.array | None = None, + ) -> None: + """Set joint efforts into internal buffers using indices. + + This function does not apply the joint targets to the simulation. It only fills the buffers with + the desired values. To apply the joint targets, call the :meth:`write_data_to_sim` function. + + Args: + target: Joint effort targets [N or N*m]. Shape is (len(env_ids), len(joint_ids)). + joint_ids: Joint indices. If None, then all joints are used. + env_ids: Environment indices. If None, then all indices are used. + """ + self._set_target_into_buffer(self._data._joint_effort_target, target, env_ids, joint_ids) + + def set_joint_effort_target_mask( + self, + *, + target: torch.Tensor | wp.array, + joint_mask: wp.array | None = None, + env_mask: wp.array | None = None, + ) -> None: + """Set joint efforts into internal buffers using masks. + + Args: + target: Joint effort targets [N or N*m]. Shape is (num_instances, num_joints). + joint_mask: Joint mask. If None, then all joints are updated. + env_mask: Environment mask. If None, then all instances are updated. + """ + self._set_target_into_buffer_mask(self._data._joint_effort_target, target, env_mask, joint_mask) + + """ + Operations - Tendons. + """ + + def set_fixed_tendon_stiffness_index( + self, + *, + stiffness: float | torch.Tensor | wp.array, + fixed_tendon_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Set fixed tendon stiffness into internal buffers using indices. + + This function does not apply the tendon stiffness to the simulation. It only fills the buffers with + the desired values. To apply the tendon stiffness, call the + :meth:`write_fixed_tendon_properties_to_sim_index` method. + + Args: + stiffness: Fixed tendon stiffness. Shape is (len(env_ids), len(fixed_tendon_ids)). + fixed_tendon_ids: The tendon indices to set the stiffness for. Defaults to None (all fixed tendons). + env_ids: Environment indices. If None, then all indices are used. + """ + n = self._n_envs_index(env_ids) + t = len(fixed_tendon_ids) if fixed_tendon_ids else self._nft() + self.assert_shape_and_dtype(stiffness, (n, t), wp.float32, "stiffness") + if self._data._fixed_tendon_stiffness is not None: + self._set_target_into_buffer(self._data._fixed_tendon_stiffness, stiffness, env_ids, fixed_tendon_ids) + + def set_fixed_tendon_stiffness_mask( + self, + *, + stiffness: float | torch.Tensor | wp.array, + fixed_tendon_mask: wp.array | None = None, + env_mask: wp.array | None = None, + ) -> None: + """Set fixed tendon stiffness into internal buffers using masks. + + Args: + stiffness: Fixed tendon stiffness. Shape is (num_instances, num_fixed_tendons). + fixed_tendon_mask: Tendon mask. If None, then all fixed tendons are used. + env_mask: Environment mask. If None, then all the instances are updated. + """ + self.assert_shape_and_dtype(stiffness, (self._num_instances, self._nft()), wp.float32, "stiffness") + if self._data._fixed_tendon_stiffness is not None: + self._set_target_into_buffer_mask( + self._data._fixed_tendon_stiffness, stiffness, env_mask, fixed_tendon_mask + ) + + def set_fixed_tendon_damping_index( + self, + *, + damping: float | torch.Tensor | wp.array, + fixed_tendon_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Set fixed tendon damping into internal buffers using indices. + + Args: + damping: Fixed tendon damping. Shape is (len(env_ids), len(fixed_tendon_ids)). + fixed_tendon_ids: The tendon indices to set the damping for. Defaults to None (all fixed tendons). + env_ids: Environment indices. If None, then all indices are used. + """ + n = self._n_envs_index(env_ids) + t = len(fixed_tendon_ids) if fixed_tendon_ids else self._nft() + self.assert_shape_and_dtype(damping, (n, t), wp.float32, "damping") + if self._data._fixed_tendon_damping is not None: + self._set_target_into_buffer(self._data._fixed_tendon_damping, damping, env_ids, fixed_tendon_ids) + + def set_fixed_tendon_damping_mask( + self, + *, + damping: float | torch.Tensor | wp.array, + fixed_tendon_mask: wp.array | None = None, + env_mask: wp.array | None = None, + ) -> None: + """Set fixed tendon damping into internal buffers using masks. + + Args: + damping: Fixed tendon damping. Shape is (num_instances, num_fixed_tendons). + fixed_tendon_mask: Tendon mask. If None, then all fixed tendons are used. + env_mask: Environment mask. If None, then all the instances are updated. + """ + self.assert_shape_and_dtype(damping, (self._num_instances, self._nft()), wp.float32, "damping") + if self._data._fixed_tendon_damping is not None: + self._set_target_into_buffer_mask(self._data._fixed_tendon_damping, damping, env_mask, fixed_tendon_mask) + + def set_fixed_tendon_limit_stiffness_index( + self, + *, + limit_stiffness: float | torch.Tensor | wp.array, + fixed_tendon_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Set fixed tendon limit stiffness into internal buffers using indices. + + Args: + limit_stiffness: Fixed tendon limit stiffness. Shape is (len(env_ids), len(fixed_tendon_ids)). + fixed_tendon_ids: The tendon indices. Defaults to None (all fixed tendons). + env_ids: Environment indices. If None, then all indices are used. + """ + n = self._n_envs_index(env_ids) + t = len(fixed_tendon_ids) if fixed_tendon_ids else self._nft() + self.assert_shape_and_dtype(limit_stiffness, (n, t), wp.float32, "limit_stiffness") + if self._data._fixed_tendon_limit_stiffness is not None: + self._set_target_into_buffer( + self._data._fixed_tendon_limit_stiffness, limit_stiffness, env_ids, fixed_tendon_ids + ) + + def set_fixed_tendon_limit_stiffness_mask( + self, + *, + limit_stiffness: float | torch.Tensor | wp.array, + fixed_tendon_mask: wp.array | None = None, + env_mask: wp.array | None = None, + ) -> None: + """Set fixed tendon limit stiffness into internal buffers using masks. + + Args: + limit_stiffness: Fixed tendon limit stiffness. Shape is (num_instances, num_fixed_tendons). + fixed_tendon_mask: Tendon mask. If None, then all fixed tendons are used. + env_mask: Environment mask. If None, then all the instances are updated. + """ + self.assert_shape_and_dtype(limit_stiffness, (self._num_instances, self._nft()), wp.float32, "limit_stiffness") + if self._data._fixed_tendon_limit_stiffness is not None: + self._set_target_into_buffer_mask( + self._data._fixed_tendon_limit_stiffness, limit_stiffness, env_mask, fixed_tendon_mask + ) + + def set_fixed_tendon_position_limit_index( + self, + *, + limit: torch.Tensor | wp.array, + fixed_tendon_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Set fixed tendon position limits into internal buffers using indices. + + Args: + limit: Fixed tendon position limits. Shape is (len(env_ids), len(fixed_tendon_ids)) + with dtype wp.vec2f. + fixed_tendon_ids: The tendon indices. Defaults to None (all fixed tendons). + env_ids: Environment indices. If None, then all indices are used. + """ + n = self._n_envs_index(env_ids) + t = len(fixed_tendon_ids) if fixed_tendon_ids else self._nft() + self.assert_shape_and_dtype(limit, (n, t), wp.vec2f, "limit") + if self._data._fixed_tendon_pos_limits is not None: + self._set_target_into_buffer(self._data._fixed_tendon_pos_limits, limit, env_ids, fixed_tendon_ids) + + def set_fixed_tendon_position_limit_mask( + self, + *, + limit: torch.Tensor | wp.array, + fixed_tendon_mask: wp.array | None = None, + env_mask: wp.array | None = None, + ) -> None: + """Set fixed tendon position limits into internal buffers using masks. + + Args: + limit: Fixed tendon position limits. Shape is (num_instances, num_fixed_tendons) + with dtype wp.vec2f. + fixed_tendon_mask: Tendon mask. If None, then all fixed tendons are used. + env_mask: Environment mask. If None, then all the instances are updated. + """ + self.assert_shape_and_dtype(limit, (self._num_instances, self._nft()), wp.vec2f, "limit") + if self._data._fixed_tendon_pos_limits is not None: + self._set_target_into_buffer_mask(self._data._fixed_tendon_pos_limits, limit, env_mask, fixed_tendon_mask) + + def set_fixed_tendon_rest_length_index( + self, + *, + rest_length: float | torch.Tensor | wp.array, + fixed_tendon_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Set fixed tendon rest length into internal buffers using indices. + + Args: + rest_length: Fixed tendon rest length. Shape is (len(env_ids), len(fixed_tendon_ids)). + fixed_tendon_ids: The tendon indices. Defaults to None (all fixed tendons). + env_ids: Environment indices. If None, then all indices are used. + """ + n = self._n_envs_index(env_ids) + t = len(fixed_tendon_ids) if fixed_tendon_ids else self._nft() + self.assert_shape_and_dtype(rest_length, (n, t), wp.float32, "rest_length") + if self._data._fixed_tendon_rest_length is not None: + self._set_target_into_buffer(self._data._fixed_tendon_rest_length, rest_length, env_ids, fixed_tendon_ids) + + def set_fixed_tendon_rest_length_mask( + self, + *, + rest_length: float | torch.Tensor | wp.array, + fixed_tendon_mask: wp.array | None = None, + env_mask: wp.array | None = None, + ) -> None: + """Set fixed tendon rest length into internal buffers using masks. + + Args: + rest_length: Fixed tendon rest length. Shape is (num_instances, num_fixed_tendons). + fixed_tendon_mask: Tendon mask. If None, then all fixed tendons are used. + env_mask: Environment mask. If None, then all the instances are updated. + """ + self.assert_shape_and_dtype(rest_length, (self._num_instances, self._nft()), wp.float32, "rest_length") + if self._data._fixed_tendon_rest_length is not None: + self._set_target_into_buffer_mask( + self._data._fixed_tendon_rest_length, rest_length, env_mask, fixed_tendon_mask + ) + + def set_fixed_tendon_offset_index( + self, + *, + offset: float | torch.Tensor | wp.array, + fixed_tendon_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Set fixed tendon offset into internal buffers using indices. + + Args: + offset: Fixed tendon offset. Shape is (len(env_ids), len(fixed_tendon_ids)). + fixed_tendon_ids: The tendon indices. Defaults to None (all fixed tendons). + env_ids: Environment indices. If None, then all indices are used. + """ + n = self._n_envs_index(env_ids) + t = len(fixed_tendon_ids) if fixed_tendon_ids else self._nft() + self.assert_shape_and_dtype(offset, (n, t), wp.float32, "offset") + if self._data._fixed_tendon_offset is not None: + self._set_target_into_buffer(self._data._fixed_tendon_offset, offset, env_ids, fixed_tendon_ids) + + def set_fixed_tendon_offset_mask( + self, + *, + offset: float | torch.Tensor | wp.array, + fixed_tendon_mask: wp.array | None = None, + env_mask: wp.array | None = None, + ) -> None: + """Set fixed tendon offset into internal buffers using masks. + + Args: + offset: Fixed tendon offset. Shape is (num_instances, num_fixed_tendons). + fixed_tendon_mask: Tendon mask. If None, then all fixed tendons are used. + env_mask: Environment mask. If None, then all the instances are updated. + """ + self.assert_shape_and_dtype(offset, (self._num_instances, self._nft()), wp.float32, "offset") + if self._data._fixed_tendon_offset is not None: + self._set_target_into_buffer_mask(self._data._fixed_tendon_offset, offset, env_mask, fixed_tendon_mask) + + def write_fixed_tendon_properties_to_sim_index( + self, + *, + fixed_tendon_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Write fixed tendon properties into the simulation using indices. + + Args: + fixed_tendon_ids: The fixed tendon indices to write the properties for. Defaults to None + (all fixed tendons). + env_ids: Environment indices. If None, then all indices are used. + """ + if self._nft() == 0: + return + for tt, buf in [ + (TT.FIXED_TENDON_STIFFNESS, self._data._fixed_tendon_stiffness), + (TT.FIXED_TENDON_DAMPING, self._data._fixed_tendon_damping), + (TT.FIXED_TENDON_LIMIT_STIFFNESS, self._data._fixed_tendon_limit_stiffness), + (TT.FIXED_TENDON_LIMIT, self._data._fixed_tendon_pos_limits), + (TT.FIXED_TENDON_REST_LENGTH, self._data._fixed_tendon_rest_length), + (TT.FIXED_TENDON_OFFSET, self._data._fixed_tendon_offset), + ]: + if buf is not None: + self._write_flat_tensor(tt, buf, env_ids, fixed_tendon_ids) + + def write_fixed_tendon_properties_to_sim_mask( + self, + *, + fixed_tendon_mask: wp.array | None = None, + env_mask: wp.array | None = None, + ) -> None: + """Write fixed tendon properties into the simulation using masks. + + Args: + fixed_tendon_mask: Fixed tendon mask. If None, then all fixed tendons are used. + env_mask: Environment mask. If None, then all the instances are updated. + """ + if self._nft() == 0: + return + for tt, buf in [ + (TT.FIXED_TENDON_STIFFNESS, self._data._fixed_tendon_stiffness), + (TT.FIXED_TENDON_DAMPING, self._data._fixed_tendon_damping), + (TT.FIXED_TENDON_LIMIT_STIFFNESS, self._data._fixed_tendon_limit_stiffness), + (TT.FIXED_TENDON_LIMIT, self._data._fixed_tendon_pos_limits), + (TT.FIXED_TENDON_REST_LENGTH, self._data._fixed_tendon_rest_length), + (TT.FIXED_TENDON_OFFSET, self._data._fixed_tendon_offset), + ]: + if buf is not None: + self._write_flat_tensor_mask(tt, buf, env_mask, fixed_tendon_mask) + + def set_spatial_tendon_stiffness_index( + self, + *, + stiffness: float | torch.Tensor | wp.array, + spatial_tendon_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Set spatial tendon stiffness into internal buffers using indices. + + Args: + stiffness: Spatial tendon stiffness. Shape is (len(env_ids), len(spatial_tendon_ids)). + spatial_tendon_ids: The tendon indices. Defaults to None (all spatial tendons). + env_ids: Environment indices. If None, then all indices are used. + """ + n = self._n_envs_index(env_ids) + t = len(spatial_tendon_ids) if spatial_tendon_ids else self._nst() + self.assert_shape_and_dtype(stiffness, (n, t), wp.float32, "stiffness") + if self._data._spatial_tendon_stiffness is not None: + self._set_target_into_buffer(self._data._spatial_tendon_stiffness, stiffness, env_ids, spatial_tendon_ids) + + def set_spatial_tendon_stiffness_mask( + self, + *, + stiffness: float | torch.Tensor | wp.array, + spatial_tendon_mask: wp.array | None = None, + env_mask: wp.array | None = None, + ) -> None: + """Set spatial tendon stiffness into internal buffers using masks. + + Args: + stiffness: Spatial tendon stiffness. Shape is (num_instances, num_spatial_tendons). + spatial_tendon_mask: Tendon mask. If None, then all spatial tendons are used. + env_mask: Environment mask. If None, then all the instances are updated. + """ + self.assert_shape_and_dtype(stiffness, (self._num_instances, self._nst()), wp.float32, "stiffness") + if self._data._spatial_tendon_stiffness is not None: + self._set_target_into_buffer_mask( + self._data._spatial_tendon_stiffness, stiffness, env_mask, spatial_tendon_mask + ) + + def set_spatial_tendon_damping_index( + self, + *, + damping: float | torch.Tensor | wp.array, + spatial_tendon_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Set spatial tendon damping into internal buffers using indices. + + Args: + damping: Spatial tendon damping. Shape is (len(env_ids), len(spatial_tendon_ids)). + spatial_tendon_ids: The tendon indices. Defaults to None (all spatial tendons). + env_ids: Environment indices. If None, then all indices are used. + """ + n = self._n_envs_index(env_ids) + t = len(spatial_tendon_ids) if spatial_tendon_ids else self._nst() + self.assert_shape_and_dtype(damping, (n, t), wp.float32, "damping") + if self._data._spatial_tendon_damping is not None: + self._set_target_into_buffer(self._data._spatial_tendon_damping, damping, env_ids, spatial_tendon_ids) + + def set_spatial_tendon_damping_mask( + self, + *, + damping: float | torch.Tensor | wp.array, + spatial_tendon_mask: wp.array | None = None, + env_mask: wp.array | None = None, + ) -> None: + """Set spatial tendon damping into internal buffers using masks. + + Args: + damping: Spatial tendon damping. Shape is (num_instances, num_spatial_tendons). + spatial_tendon_mask: Tendon mask. If None, then all spatial tendons are used. + env_mask: Environment mask. If None, then all the instances are updated. + """ + self.assert_shape_and_dtype(damping, (self._num_instances, self._nst()), wp.float32, "damping") + if self._data._spatial_tendon_damping is not None: + self._set_target_into_buffer_mask( + self._data._spatial_tendon_damping, damping, env_mask, spatial_tendon_mask + ) + + def set_spatial_tendon_limit_stiffness_index( + self, + *, + limit_stiffness: float | torch.Tensor | wp.array, + spatial_tendon_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Set spatial tendon limit stiffness into internal buffers using indices. + + Args: + limit_stiffness: Spatial tendon limit stiffness. Shape is (len(env_ids), len(spatial_tendon_ids)). + spatial_tendon_ids: The tendon indices. Defaults to None (all spatial tendons). + env_ids: Environment indices. If None, then all indices are used. + """ + n = self._n_envs_index(env_ids) + t = len(spatial_tendon_ids) if spatial_tendon_ids else self._nst() + self.assert_shape_and_dtype(limit_stiffness, (n, t), wp.float32, "limit_stiffness") + if self._data._spatial_tendon_limit_stiffness is not None: + self._set_target_into_buffer( + self._data._spatial_tendon_limit_stiffness, limit_stiffness, env_ids, spatial_tendon_ids + ) + + def set_spatial_tendon_limit_stiffness_mask( + self, + *, + limit_stiffness: float | torch.Tensor | wp.array, + spatial_tendon_mask: wp.array | None = None, + env_mask: wp.array | None = None, + ) -> None: + """Set spatial tendon limit stiffness into internal buffers using masks. + + Args: + limit_stiffness: Spatial tendon limit stiffness. Shape is (num_instances, num_spatial_tendons). + spatial_tendon_mask: Tendon mask. If None, then all spatial tendons are used. + env_mask: Environment mask. If None, then all the instances are updated. + """ + self.assert_shape_and_dtype(limit_stiffness, (self._num_instances, self._nst()), wp.float32, "limit_stiffness") + if self._data._spatial_tendon_limit_stiffness is not None: + self._set_target_into_buffer_mask( + self._data._spatial_tendon_limit_stiffness, limit_stiffness, env_mask, spatial_tendon_mask + ) + + def set_spatial_tendon_offset_index( + self, + *, + offset: float | torch.Tensor | wp.array, + spatial_tendon_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Set spatial tendon offset into internal buffers using indices. + + Args: + offset: Spatial tendon offset. Shape is (len(env_ids), len(spatial_tendon_ids)). + spatial_tendon_ids: The tendon indices. Defaults to None (all spatial tendons). + env_ids: Environment indices. If None, then all indices are used. + """ + n = self._n_envs_index(env_ids) + t = len(spatial_tendon_ids) if spatial_tendon_ids else self._nst() + self.assert_shape_and_dtype(offset, (n, t), wp.float32, "offset") + if self._data._spatial_tendon_offset is not None: + self._set_target_into_buffer(self._data._spatial_tendon_offset, offset, env_ids, spatial_tendon_ids) + + def set_spatial_tendon_offset_mask( + self, + *, + offset: float | torch.Tensor | wp.array, + spatial_tendon_mask: wp.array | None = None, + env_mask: wp.array | None = None, + ) -> None: + """Set spatial tendon offset into internal buffers using masks. + + Args: + offset: Spatial tendon offset. Shape is (num_instances, num_spatial_tendons). + spatial_tendon_mask: Tendon mask. If None, then all spatial tendons are used. + env_mask: Environment mask. If None, then all the instances are updated. + """ + self.assert_shape_and_dtype(offset, (self._num_instances, self._nst()), wp.float32, "offset") + if self._data._spatial_tendon_offset is not None: + self._set_target_into_buffer_mask(self._data._spatial_tendon_offset, offset, env_mask, spatial_tendon_mask) + + def write_spatial_tendon_properties_to_sim_index( + self, + *, + spatial_tendon_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + ) -> None: + """Write spatial tendon properties into the simulation using indices. + + Args: + spatial_tendon_ids: The spatial tendon indices to write the properties for. Defaults to None + (all spatial tendons). + env_ids: Environment indices. If None, then all indices are used. + """ + if self._nst() == 0: + return + for tt, buf in [ + (TT.SPATIAL_TENDON_STIFFNESS, self._data._spatial_tendon_stiffness), + (TT.SPATIAL_TENDON_DAMPING, self._data._spatial_tendon_damping), + (TT.SPATIAL_TENDON_LIMIT_STIFFNESS, self._data._spatial_tendon_limit_stiffness), + (TT.SPATIAL_TENDON_OFFSET, self._data._spatial_tendon_offset), + ]: + if buf is not None: + self._write_flat_tensor(tt, buf, env_ids, spatial_tendon_ids) + + def write_spatial_tendon_properties_to_sim_mask( + self, + *, + spatial_tendon_mask: wp.array | None = None, + env_mask: wp.array | None = None, + ) -> None: + """Write spatial tendon properties into the simulation using masks. + + Args: + spatial_tendon_mask: Spatial tendon mask. If None, then all spatial tendons are used. + env_mask: Environment mask. If None, then all the instances are updated. + """ + if self._nst() == 0: + return + for tt, buf in [ + (TT.SPATIAL_TENDON_STIFFNESS, self._data._spatial_tendon_stiffness), + (TT.SPATIAL_TENDON_DAMPING, self._data._spatial_tendon_damping), + (TT.SPATIAL_TENDON_LIMIT_STIFFNESS, self._data._spatial_tendon_limit_stiffness), + (TT.SPATIAL_TENDON_OFFSET, self._data._spatial_tendon_offset), + ]: + if buf is not None: + self._write_flat_tensor_mask(tt, buf, env_mask, spatial_tendon_mask) + + """ + Deprecated methods. + """ + + def write_root_state_to_sim( + self, + root_state: torch.Tensor | wp.array, + env_ids: Sequence[int] | wp.array | None = None, + ) -> None: + """Deprecated in base class. Use :meth:`write_root_pose_to_sim_index` and + :meth:`write_root_velocity_to_sim_index` instead.""" + self._write_root_state(TT.ROOT_POSE, root_state[:, :7], env_ids) + self._write_root_state(TT.ROOT_VELOCITY, root_state[:, 7:], env_ids) + + def write_root_com_state_to_sim( + self, + root_state: torch.Tensor | wp.array, + env_ids: Sequence[int] | wp.array | None = None, + ) -> None: + """Deprecated in base class. Use :meth:`write_root_com_pose_to_sim_index` and + :meth:`write_root_com_velocity_to_sim_index` instead.""" + self._write_root_state(TT.ROOT_POSE, root_state[:, :7], env_ids) + self._write_root_state(TT.ROOT_VELOCITY, root_state[:, 7:], env_ids) + + def write_root_link_state_to_sim( + self, + root_state: torch.Tensor | wp.array, + env_ids: Sequence[int] | wp.array | None = None, + ) -> None: + """Deprecated in base class. Use :meth:`write_root_link_pose_to_sim_index` and + :meth:`write_root_link_velocity_to_sim_index` instead.""" + self._write_root_state(TT.ROOT_POSE, root_state[:, :7], env_ids) + self._write_root_state(TT.ROOT_VELOCITY, root_state[:, 7:], env_ids) + + def write_joint_state_to_sim( + self, + position: torch.Tensor | wp.array, + velocity: torch.Tensor | wp.array, + joint_ids: Sequence[int] | None = None, + env_ids: Sequence[int] | wp.array | None = None, + ) -> None: + """Deprecated in base class. Use :meth:`write_joint_position_to_sim_index` and + :meth:`write_joint_velocity_to_sim_index` instead.""" + self.write_joint_position_to_sim_index(position=position, joint_ids=joint_ids, env_ids=env_ids) + self.write_joint_velocity_to_sim_index(velocity=velocity, joint_ids=joint_ids, env_ids=env_ids) + + """ + Internal helper. + """ + + def _initialize_impl(self) -> None: + physx_instance = OvPhysxManager.get_physx_instance() + if physx_instance is None: + raise RuntimeError("OvPhysxManager has not been initialized yet.") + + prim_path = self.cfg.prim_path + # Convert IsaacLab prim-path notation to the glob patterns ovphysx expects. + # IsaacLab uses two conventions: + # /World/envs/env_.*/Robot -- regex dot-star for "any env index" + # /World/envs/{ENV_REGEX_NS}/Robot -- explicit placeholder + # ovphysx create_tensor_binding() uses fnmatch-style globs, so both map to '*'. + pattern = re.sub(r"\{ENV_REGEX_NS\}", "*", prim_path) + pattern = re.sub(r"\.\*", "*", pattern) # env_.* -> env_* + + # The pattern above points to the ArticulationCfg prim (e.g. /World/envs/env_*/Robot). + # However, PhysicsArticulationRootAPI may be on a CHILD prim (e.g. /Robot/torso) + # rather than on the prim itself. create_tensor_binding() only matches prims that + # *have* PhysicsArticulationRootAPI, so we need to extend the pattern to the actual + # articulation root. Mirror the PhysX backend's discovery logic: find the first + # matching prim in the USD stage, walk its subtree for the articulation root, and + # append the relative suffix to the glob pattern. + from pxr import UsdPhysics + + from isaaclab.sim.utils.queries import find_first_matching_prim, get_all_matching_child_prims + + stage = PhysicsManager._sim.stage + first_prim = find_first_matching_prim(prim_path, stage=stage) + if first_prim is None: + raise RuntimeError(f"OvPhysxManager: no prim found for path '{prim_path}'.") + first_prim_path = first_prim.GetPath().pathString + + root_prims = get_all_matching_child_prims( + first_prim_path, + predicate=lambda p: p.HasAPI(UsdPhysics.ArticulationRootAPI), + traverse_instance_prims=False, + ) + if len(root_prims) == 0: + raise RuntimeError( + f"No prim with PhysicsArticulationRootAPI found under '{first_prim_path}'." + " Check that the articulation has 'PhysicsArticulationRootAPI' applied." + ) + if len(root_prims) > 1: + raise RuntimeError( + f"Multiple articulation roots found under '{first_prim_path}': {root_prims}." + " There must be exactly one articulation root per prim path." + ) + self._articulation_root_path = root_prims[0].GetPath().pathString + root_relative = self._articulation_root_path[len(first_prim_path) :] + if root_relative: + # e.g. first_prim_path=/World/envs/env_0/Robot, root_relative=/torso + # pattern becomes /World/envs/env_*/Robot/torso + pattern = pattern + root_relative + logger.info("OvPhysxManager: articulation root at '%s' (pattern extended to '%s')", root_relative, pattern) + + # Bindings are created lazily (on first access) to avoid allocating + # handles for tensor types the user never queries. Only the root-pose + # binding is created eagerly because we need it to read articulation + # metadata (joint count, body count, names, fixed-base flag). + self._bindings: dict[int, Any] = {} + self._physx_instance = physx_instance + self._binding_pattern = pattern + + eager_types = [ + TT.ROOT_POSE, + TT.DOF_POSITION, + TT.DOF_STIFFNESS, + TT.DOF_DAMPING, + TT.DOF_LIMIT, + TT.DOF_MAX_VELOCITY, + TT.DOF_MAX_FORCE, + TT.DOF_ARMATURE, + TT.DOF_FRICTION_PROPERTIES, + TT.BODY_MASS, + TT.BODY_COM_POSE, + TT.BODY_INERTIA, + ] + for tt in eager_types: + try: + self._bindings[tt] = physx_instance.create_tensor_binding(pattern=pattern, tensor_type=tt) + except Exception: + logger.debug("Could not create tensor binding for type %s on pattern %s", tt, pattern) + + sample = next(iter(self._bindings.values())) + self._num_instances = sample.count + self._num_joints = sample.dof_count + self._num_bodies = sample.body_count + self._is_fixed_base = sample.is_fixed_base + self._joint_names = list(sample.dof_names) + self._body_names = list(sample.body_names) + + # Create data container. + self._data = ArticulationData(self._bindings, self._device, binding_getter=self._get_binding) + + # Discover tendon counts/names before buffer allocation so that + # _create_buffers can size the tendon property arrays. + self._process_tendons() + + self._create_buffers() + + self._process_cfg() + self._process_actuators_cfg() + self._validate_cfg() + self._log_articulation_info() + + # Cache the effort binding and a stable float32 view of the applied_torque + # buffer for write_data_to_sim(). The binding's internal write cache + # (keyed on object identity) handles the fast path automatically. + self._effort_binding = self._get_binding(TT.DOF_ACTUATION_FORCE) + if self._effort_binding is not None: + torque = self._data.applied_torque + shape = self._effort_binding.shape + self._effort_write_view = wp.array( + ptr=torque.ptr, + shape=shape, + dtype=wp.float32, + device=str(torque.device), + copy=False, + ) + else: + self._effort_write_view = None + + # Cache position/velocity target bindings + views for one-shot writes. + def _make_write_view(tt, buf): + b = self._get_binding(tt) + if b is None or buf is None: + return None, None + v = wp.array(ptr=buf.ptr, shape=b.shape, dtype=wp.float32, device=str(buf.device), copy=False) + return b, v + + self._pos_target_binding, self._pos_target_write_view = _make_write_view( + TT.DOF_POSITION_TARGET, self._data.joint_pos_target + ) + self._vel_target_binding, self._vel_target_write_view = _make_write_view( + TT.DOF_VELOCITY_TARGET, self._data.joint_vel_target + ) + + # Let the articulation data know that it is fully instantiated and ready to use. + self.data.is_primed = True + + def _create_buffers(self) -> None: + self._data._create_buffers() + + self._ALL_INDICES = wp.array(np.arange(self._num_instances, dtype=np.int32), device=self._device) + + self._instantaneous_wrench_composer = WrenchComposer(self) + self._permanent_wrench_composer = WrenchComposer(self) + self._wrench_buf = wp.zeros((self._num_instances, self._num_bodies, 9), dtype=wp.float32, device=self._device) + + # Joint-index arrays for each actuator (filled by _process_actuators_cfg). + self._joint_ids_per_actuator: dict[str, list[int]] = {} + self._write_scratch: dict[int, wp.array] = {} + + def _process_cfg(self) -> None: + """Process the articulation configuration (initial state, soft limits, etc.).""" + cfg = self.cfg + N = self._num_instances + D = self._num_joints + dev = self._device + + # Default root state from config (matching PhysX pattern). + default_root_pose = tuple(cfg.init_state.pos) + tuple(cfg.init_state.rot) + default_root_vel = tuple(cfg.init_state.lin_vel) + tuple(cfg.init_state.ang_vel) + np_pose = np.tile(np.array(default_root_pose, dtype=np.float32), (N, 1)) + np_vel = np.tile(np.array(default_root_vel, dtype=np.float32), (N, 1)) + wp.copy( + self._data._default_root_pose, + wp.from_numpy(np_pose, dtype=wp.transformf, device=dev), + ) + wp.copy( + self._data._default_root_vel, + wp.from_numpy(np_vel, dtype=wp.spatial_vectorf, device=dev), + ) + + # Default joint positions / velocities from config patterns. + self._resolve_joint_values(cfg.init_state.joint_pos, self._data._default_joint_pos) + self._resolve_joint_values(cfg.init_state.joint_vel, self._data._default_joint_vel) + + # Keep soft-limit computation on-device, matching the PhysX/Newton path. + wp.launch( + update_soft_joint_pos_limits, + dim=(N, D), + inputs=[self._data.joint_pos_limits, cfg.soft_joint_pos_limit_factor], + outputs=[self._data._soft_joint_pos_limits], + device=dev, + ) + + def _invalidate_initialize_callback(self, event) -> None: + self._is_initialized = False + + def _process_actuators_cfg(self) -> None: + """Build actuator instances from the config and write drive properties to PhysX. + + Mirrors what the legacy PhysX backend does in its own _process_actuators_cfg: + - For ImplicitActuator: write the configured stiffness / damping to the PhysX + drive so the solver uses exactly the values from the actuator config. + - For all explicit actuators: zero out PhysX stiffness / damping so the + USD-authored drive gains cannot interfere with the explicit torque path. + - For all actuators: write effort_limit_sim and velocity_limit_sim. + + These writes happen via TensorBinding (GPU-resident) after warmup has + allocated the GPU buffers (MODEL_INIT fires post-warmup). + """ + from isaaclab.actuators import ImplicitActuator + + self.actuators: dict[str, ActuatorBase] = {} + self._has_implicit_actuators = False + for name, act_cfg in self.cfg.actuators.items(): + joint_ids, joint_names = self.find_joints(act_cfg.joint_names_expr) + if not joint_ids: + logger.warning("Actuator '%s': no joints matched '%s'", name, act_cfg.joint_names_expr) + continue + act_cfg_copy = act_cfg.copy() + act = act_cfg_copy.class_type( + act_cfg_copy, + joint_names=joint_names, + joint_ids=joint_ids, + num_envs=self._num_instances, + device=self._device, + ) + self.actuators[name] = act + self._joint_ids_per_actuator[name] = joint_ids + + # Write drive gains and limits to PhysX to match the actuator config. + # Without this, PhysX retains whatever stiffness/damping was authored in the + # USD file, which can produce large restoring forces if the USD gains differ + # from the actuator config (e.g. a position-controlled robot exported with + # non-zero drive stiffness but configured with ImplicitActuator(stiffness=0)). + jids = list(joint_ids) + if isinstance(act, ImplicitActuator): + self._has_implicit_actuators = True + stiffness = act.stiffness # torch (N, J) + damping = act.damping # torch (N, J) + else: + stiffness = wp.zeros((self._num_instances, len(jids)), dtype=wp.float32, device=self._device) + damping = wp.zeros((self._num_instances, len(jids)), dtype=wp.float32, device=self._device) + self.write_joint_stiffness_to_sim_index(stiffness=stiffness, joint_ids=jids) + self.write_joint_damping_to_sim_index(damping=damping, joint_ids=jids) + self.write_joint_effort_limit_to_sim_index(limits=act.effort_limit_sim, joint_ids=jids) + self.write_joint_velocity_limit_to_sim_index(limits=act.velocity_limit_sim, joint_ids=jids) + + def _process_tendons(self) -> None: + """Discover tendon counts from binding metadata and names from USD. + + Tendon counts come from the ovphysx binding metadata. Tendon names are + recovered from the exported USD articulation subtree because ovphysx + exposes joint names/counts, but not the per-joint USD paths that the + PhysX backend can query directly. + """ + self._fixed_tendon_names = [] + self._spatial_tendon_names = [] + + sample = next(iter(self._bindings.values())) + self._num_fixed_tendons = getattr(sample, "fixed_tendon_count", 0) + self._num_spatial_tendons = getattr(sample, "spatial_tendon_count", 0) + + if self._num_fixed_tendons > 0 or self._num_spatial_tendons > 0: + stage_path = OvPhysxManager._stage_path + if stage_path is not None: + try: + from pxr import Usd, UsdPhysics + + from isaaclab.sim.utils.queries import get_all_matching_child_prims + + stage = Usd.Stage.Open(stage_path) + articulation_root_path = getattr(self, "_articulation_root_path", None) + if articulation_root_path is None: + joint_prims = stage.Traverse() + else: + joint_prims = get_all_matching_child_prims( + articulation_root_path, + predicate=lambda p: p.IsA(UsdPhysics.Joint), + stage=stage, + traverse_instance_prims=False, + ) + for prim in joint_prims: + if not prim.IsA(UsdPhysics.Joint): + continue + schema_names = list(prim.GetAppliedSchemas()) + metadata = prim.GetMetadata("apiSchemas") + if metadata is not None: + for field in ("prependedItems", "appendedItems", "explicitItems"): + items = getattr(metadata, field, None) + if items: + schema_names.extend(str(item) for item in items) + schemas_str = " ".join(schema_names) + name = prim.GetPath().name + if "PhysxTendonAxisRootAPI" in schemas_str: + self._fixed_tendon_names.append(name) + elif ( + "PhysxTendonAttachmentRootAPI" in schemas_str + or "PhysxTendonAttachmentLeafAPI" in schemas_str + ): + self._spatial_tendon_names.append(name) + except Exception: + logger.debug("Could not parse USD stage for tendon names at %s", stage_path) + + self._data._num_fixed_tendons = self._num_fixed_tendons + self._data._num_spatial_tendons = self._num_spatial_tendons + self._data.fixed_tendon_names = self._fixed_tendon_names + self._data.spatial_tendon_names = self._spatial_tendon_names + + def _apply_external_wrenches(self) -> None: + """Compose and write external wrenches to the LINK_WRENCH binding. + + WrenchComposer accumulates forces/torques in body (link) frame. + The LINK_WRENCH binding expects world-frame [fx,fy,fz,tx,ty,tz,px,py,pz]. + We rotate the body-frame vectors to world frame using the link quaternion + and pack them into the [N, L, 9] tensor with application position = origin. + """ + inst = self._instantaneous_wrench_composer + perm = self._permanent_wrench_composer + if not inst.active and not perm.active: + return + if inst.active: + if perm.active: + inst.add_forces_and_torques_index( + forces=perm.composed_force, + torques=perm.composed_torque, + body_ids=list(range(self._num_bodies)), + env_ids=list(range(self._num_instances)), + ) + force_b = inst.composed_force + torque_b = inst.composed_torque + else: + force_b = perm.composed_force + torque_b = perm.composed_torque + + poses = self._data.body_link_pose_w + wp.launch( + _body_wrench_to_world, + dim=(self._num_instances, self._num_bodies), + inputs=[force_b, torque_b, poses], + outputs=[self._wrench_buf], + device=self._device, + ) + wrench_binding = self._get_binding(TT.LINK_WRENCH) + if wrench_binding is not None: + wrench_binding.write(self._wrench_buf) + inst.reset() + + def _apply_actuator_model(self) -> None: + """Run the actuator model to compute torques from user targets. + + IsaacLab actuators are torch-based. We convert warp -> torch via + DLPack (zero-copy on GPU), run the actuator, then write results back. + """ + from isaaclab.utils.types import ArticulationActions + + for name, act in self.actuators.items(): + jids = act.joint_indices + if jids is None: + continue + jids_t = jids if isinstance(jids, list) else list(jids) + all_joints = len(jids_t) == self._num_joints + + # warp -> torch (zero-copy on same device via DLPack) + jp_target_full = self._data.joint_pos_target.torch + jv_target_full = self._data.joint_vel_target.torch + je_target_full = self._data.joint_effort_target.torch + jp_target = jp_target_full if all_joints else jp_target_full[:, jids_t] + jv_target = jv_target_full if all_joints else jv_target_full[:, jids_t] + je_target = je_target_full if all_joints else je_target_full[:, jids_t] + + control_action = ArticulationActions( + joint_positions=jp_target, + joint_velocities=jv_target, + joint_efforts=je_target, + ) + + jp_cur_full = self._data.joint_pos.torch + jv_cur_full = self._data.joint_vel.torch + jp_cur = jp_cur_full if all_joints else jp_cur_full[:, jids_t] + jv_cur = jv_cur_full if all_joints else jv_cur_full[:, jids_t] + + control_action = act.compute(control_action, jp_cur, jv_cur) + + if act.computed_effort is not None: + ct = wp.to_torch(self._data._computed_torque) + at = wp.to_torch(self._data._applied_torque) + if all_joints: + ct[:] = act.computed_effort + at[:] = act.applied_effort + else: + ct[:, jids_t] = act.computed_effort + at[:, jids_t] = act.applied_effort + + def _validate_cfg(self) -> None: + pass + + def _log_articulation_info(self) -> None: + """Log information about the articulation. + + .. note:: We purposefully read the values from the simulator to ensure that the values are configured as + expected. + """ + from prettytable import PrettyTable + + def format_large_number(_, v: float) -> str: + if abs(v) >= 1e3: + return f"{v:.1e}" + return f"{v:.3f}" + + def format_limits(_, v: tuple[float, float]) -> str: + if abs(v[0]) >= 1e3 or abs(v[1]) >= 1e3: + return f"[{v[0]:.1e}, {v[1]:.1e}]" + return f"[{v[0]:.3f}, {v[1]:.3f}]" + + stiffnesses = self.data.joint_stiffness.warp.numpy()[0].tolist() + dampings = self.data.joint_damping.warp.numpy()[0].tolist() + armatures = self.data.joint_armature.warp.numpy()[0].tolist() + frictions = self.data.joint_friction_coeff.warp.numpy()[0].tolist() + pos_limits_np = self.data.joint_pos_limits.warp.numpy().reshape(self._num_instances, self._num_joints, 2) + position_limits = [tuple(pos_limits_np[0, j].tolist()) for j in range(self._num_joints)] + velocity_limits = self.data.joint_vel_limits.warp.numpy()[0].tolist() + effort_limits = self.data.joint_effort_limits.warp.numpy()[0].tolist() + + joint_table = PrettyTable() + joint_table.title = f"Simulation Joint Information (Prim path: {self.cfg.prim_path})" + joint_table.field_names = [ + "Index", + "Name", + "Stiffness", + "Damping", + "Armature", + "Friction", + "Position Limits", + "Velocity Limits", + "Effort Limits", + ] + joint_table.custom_format["Stiffness"] = format_large_number + joint_table.custom_format["Damping"] = format_large_number + joint_table.custom_format["Armature"] = format_large_number + joint_table.custom_format["Friction"] = format_large_number + joint_table.custom_format["Position Limits"] = format_limits + joint_table.custom_format["Velocity Limits"] = format_large_number + joint_table.custom_format["Effort Limits"] = format_large_number + joint_table.align["Name"] = "l" + + for index, name in enumerate(self.joint_names): + joint_table.add_row( + [ + index, + name, + stiffnesses[index], + dampings[index], + armatures[index], + frictions[index], + position_limits[index], + velocity_limits[index], + effort_limits[index], + ] + ) + logger.info(f"Simulation parameters for joints in {self.cfg.prim_path}:\n" + joint_table.get_string()) + + if self.num_fixed_tendons > 0: + ft_stiffnesses = self.data.fixed_tendon_stiffness.warp.numpy()[0].tolist() + ft_dampings = self.data.fixed_tendon_damping.warp.numpy()[0].tolist() + ft_limit_stiffnesses = self.data.fixed_tendon_limit_stiffness.warp.numpy()[0].tolist() + ft_limits_np = self.data.fixed_tendon_pos_limits.warp.numpy().reshape( + self._num_instances, self.num_fixed_tendons, 2 + ) + ft_limits = [tuple(ft_limits_np[0, t].tolist()) for t in range(self.num_fixed_tendons)] + ft_rest_lengths = self.data.fixed_tendon_rest_length.warp.numpy()[0].tolist() + ft_offsets = self.data.fixed_tendon_offset.warp.numpy()[0].tolist() + + tendon_table = PrettyTable() + tendon_table.title = f"Simulation Fixed Tendon Information (Prim path: {self.cfg.prim_path})" + tendon_table.field_names = [ + "Index", + "Stiffness", + "Damping", + "Limit Stiffness", + "Limits", + "Rest Length", + "Offset", + ] + tendon_table.custom_format["Stiffness"] = format_large_number + tendon_table.custom_format["Damping"] = format_large_number + tendon_table.custom_format["Limit Stiffness"] = format_large_number + tendon_table.custom_format["Limits"] = format_limits + tendon_table.custom_format["Rest Length"] = format_large_number + tendon_table.custom_format["Offset"] = format_large_number + for index in range(self.num_fixed_tendons): + tendon_table.add_row( + [ + index, + ft_stiffnesses[index], + ft_dampings[index], + ft_limit_stiffnesses[index], + ft_limits[index], + ft_rest_lengths[index], + ft_offsets[index], + ] + ) + logger.info( + f"Simulation parameters for fixed tendons in {self.cfg.prim_path}:\n" + tendon_table.get_string() + ) + + if self.num_spatial_tendons > 0: + st_stiffnesses = self.data.spatial_tendon_stiffness.warp.numpy()[0].tolist() + st_dampings = self.data.spatial_tendon_damping.warp.numpy()[0].tolist() + st_limit_stiffnesses = self.data.spatial_tendon_limit_stiffness.warp.numpy()[0].tolist() + st_offsets = self.data.spatial_tendon_offset.warp.numpy()[0].tolist() + + tendon_table = PrettyTable() + tendon_table.title = f"Simulation Spatial Tendon Information (Prim path: {self.cfg.prim_path})" + tendon_table.field_names = [ + "Index", + "Stiffness", + "Damping", + "Limit Stiffness", + "Offset", + ] + tendon_table.float_format = ".3" + for index in range(self.num_spatial_tendons): + tendon_table.add_row( + [ + index, + st_stiffnesses[index], + st_dampings[index], + st_limit_stiffnesses[index], + st_offsets[index], + ] + ) + logger.info( + f"Simulation parameters for spatial tendons in {self.cfg.prim_path}:\n" + tendon_table.get_string() + ) + + """ + Internal helpers -- Bindings. + """ + + def _get_binding(self, tensor_type: int): + """Return a cached TensorBinding, creating it on first access. + + Bindings are lightweight handles (a pointer + shape metadata into + PhysX's shared GPU buffer). Creating one does NOT allocate new GPU + memory -- the underlying simulation buffers are allocated once by PhysX + regardless of how many bindings point into them. Still, we defer + creation so that tensor types the user never queries are never looked up. + """ + binding = self._bindings.get(tensor_type) + if binding is not None: + return binding + try: + binding = self._physx_instance.create_tensor_binding(pattern=self._binding_pattern, tensor_type=tensor_type) + self._bindings[tensor_type] = binding + return binding + except Exception: + logger.debug("Could not create tensor binding for type %s", tensor_type) + return None + + """ + Internal helpers -- Write. + """ + + def _to_flat_f32(self, data, target_shape: tuple[int, ...] | None = None) -> wp.array | np.ndarray: + """Ensure data is a contiguous float32 tensor suitable for binding I/O. + + State tensor bindings (positions, velocities, poses) live on the + simulation device (GPU in GPU mode). We always return data on + self._device so the binding device check passes. + + For structured warp dtypes (transformf, spatial_vectorf, etc.) a + zero-copy flat float32 view is created instead of roundtripping + through CPU numpy. + """ + dev = self._device + if isinstance(data, wp.array): + if str(data.device) != dev: + data = wp.clone(data, device=dev) + if data.dtype == wp.float32: + return data + # Structured dtype: zero-copy flat float32 view. + # transformf -> [N, 7], spatial_vectorf -> [N, 6], etc. + floats_per_elem = data.strides[0] // 4 + return wp.array( + ptr=data.ptr, + shape=(data.shape[0], floats_per_elem), + dtype=wp.float32, + device=dev, + copy=False, + ) + elif isinstance(data, torch.Tensor): + if data.is_cuda and dev.startswith("cuda"): + return wp.from_torch(data.detach().contiguous().float()) + np_data = data.detach().cpu().numpy().astype(np.float32) + return wp.from_numpy(np_data, dtype=wp.float32, device=dev) + elif isinstance(data, np.ndarray): + return wp.from_numpy(data.astype(np.float32), dtype=wp.float32, device=dev) + elif isinstance(data, (int, float)): + return wp.from_numpy(np.array(data, dtype=np.float32), dtype=wp.float32, device=dev) + return wp.from_numpy(np.asarray(data, dtype=np.float32), dtype=wp.float32, device=dev) + + def _as_gpu_f32_2d(self, data, cols: int) -> wp.array: + """View/convert data as 2D [rows, cols] float32 on self._device. + + For warp arrays with structured dtypes (transformf, spatial_vectorf), + creates a zero-copy flat float32 view. For torch/numpy, converts to + warp on the simulation device. + """ + dev = self._device + if isinstance(data, wp.array): + if str(data.device) != dev: + data = wp.clone(data, device=dev) + if data.dtype == wp.float32 and data.ndim == 2: + return data + n = data.shape[0] + return wp.array( + ptr=data.ptr, + shape=(n, cols), + dtype=wp.float32, + device=dev, + copy=False, + ) + if isinstance(data, torch.Tensor) and data.is_cuda and dev.startswith("cuda"): + return wp.from_torch(data.detach().contiguous().float().reshape(-1, cols)) + np_data = self._to_cpu_numpy(data).reshape(-1, cols) + return wp.from_numpy(np_data, dtype=wp.float32, device=dev) + + def _get_write_scratch(self, tensor_type: int, binding) -> wp.array: + """Return a cached GPU scratch buffer for read-modify-write.""" + if not hasattr(self, "_write_scratch"): + self._write_scratch = {} + buf = self._write_scratch.get(tensor_type) + if buf is None: + buf = wp.zeros(binding.shape, dtype=wp.float32, device=self._device) + self._write_scratch[tensor_type] = buf + return buf + + def _write_root_state(self, tensor_type: int, data, env_ids=None, mask=None, _ids_gpu=None) -> None: + """GPU-native write for root pose [N,7] or velocity [N,6]. + + Three paths, fastest first: + - Full write (no env_ids, no mask): zero-copy DLPack. + - Indexed write with full-size data: zero-copy view + indices. + The binding API only copies the indexed rows from the full buffer, + so no read-modify-write is needed when data is already [N,...]. + - Indexed write with partial data [K,...]: scatter kernel into a GPU + scratch buffer, then write with indices. + - Masked write: data is always full [N,...], pass directly with mask. + + Args: + _ids_gpu: Pre-converted GPU warp int32 array of env indices. + When provided, skips the per-call GPU->CPU->GPU conversion + of env_ids. + """ + binding = self._get_binding(tensor_type) + if binding is None: + return + N, C = binding.shape + + if env_ids is None and _ids_gpu is None and mask is None: + binding.write(self._to_flat_f32(data)) + self._invalidate_root_caches(tensor_type) + return + + src = self._as_gpu_f32_2d(data, C) + + if env_ids is not None or _ids_gpu is not None: + if _ids_gpu is None: + _ids_gpu = self._env_ids_to_gpu_warp(env_ids) + K = _ids_gpu.shape[0] + if src.shape[0] == N: + binding.write(src, indices=_ids_gpu) + else: + scratch = self._get_write_scratch(tensor_type, binding) + binding.read(scratch) + wp.launch( + _scatter_rows_partial, + dim=(K, C), + inputs=[scratch, src, _ids_gpu], + device=self._device, + ) + binding.write(scratch, indices=_ids_gpu) + else: + mask_u8 = wp.from_numpy( + self._to_cpu_numpy(mask).astype(np.uint8), + device=self._device, + ) + binding.write(src, mask=mask_u8) + self._invalidate_root_caches(tensor_type) + + def _invalidate_root_caches(self, tensor_type: int) -> None: + """Force re-read from GPU on next property access after a binding write.""" + if tensor_type == TT.ROOT_POSE: + self.data._root_link_pose_w.timestamp = -1.0 + self.data._root_com_pose_w.timestamp = -1.0 + elif tensor_type == TT.ROOT_VELOCITY: + self.data._root_link_vel_w.timestamp = -1.0 + self.data._root_com_vel_w.timestamp = -1.0 + + def _write_flat_tensor(self, tensor_type: int, data, env_ids=None, joint_ids=None, _ids_gpu=None) -> None: + """Write a 2-D tensor to a binding, with optional env/joint index subsetting.""" + if isinstance(data, (int, float)): + return + binding = self._get_binding(tensor_type) + if binding is None: + return + from isaaclab_ovphysx.tensor_types import _CPU_ONLY_TYPES + + is_cpu_only = tensor_type in _CPU_ONLY_TYPES + + # CPU-only types or column scatter must go through numpy. + if is_cpu_only or joint_ids is not None: + target_device = "cpu" if is_cpu_only else self._device + np_data = self._to_cpu_numpy(data) + if joint_ids is not None: + if is_cpu_only: + full = np.zeros(binding.shape, dtype=np.float32) + binding.read(full) + else: + scratch = self._get_write_scratch(tensor_type, binding) + binding.read(scratch) + full = scratch.numpy() + jids = self._to_cpu_indices(joint_ids, np.intp) + if env_ids is not None: + eids = self._to_cpu_indices(env_ids, np.intp) + full[np.ix_(eids, jids)] = np_data.reshape(len(eids), len(jids), *np_data.shape[2:]) + else: + full[:, jids] = np_data.reshape(full.shape[0], len(jids), *np_data.shape[2:]) + binding.write(wp.from_numpy(full, dtype=wp.float32, device=target_device)) + elif env_ids is not None: + if is_cpu_only: + full = np.zeros(binding.shape, dtype=np.float32) + binding.read(full) + else: + scratch = self._get_write_scratch(tensor_type, binding) + binding.read(scratch) + full = scratch.numpy() + eids = self._to_cpu_indices(env_ids, np.intp) + full[eids] = np_data if np_data.shape[0] == len(eids) else np_data[eids] + flat = wp.from_numpy(full.astype(np.float32), dtype=wp.float32, device=target_device) + idx = _ids_gpu if _ids_gpu is not None else self._env_ids_to_gpu_warp(env_ids) + binding.write(flat, indices=idx) + else: + binding.write(wp.from_numpy(np_data.astype(np.float32), dtype=wp.float32, device=target_device)) + return + + # GPU path: data stays on device. + if env_ids is None and _ids_gpu is None: + binding.write(self._to_flat_f32(data)) + return + + N, C = binding.shape[0], binding.shape[1] + src = self._as_gpu_f32_2d(data, C) + if _ids_gpu is None: + _ids_gpu = self._env_ids_to_gpu_warp(env_ids) + K = _ids_gpu.shape[0] + if src.shape[0] == N: + binding.write(src, indices=_ids_gpu) + else: + scratch = self._get_write_scratch(tensor_type, binding) + binding.read(scratch) + wp.launch( + _scatter_rows_partial, + dim=(K, C), + inputs=[scratch, src, _ids_gpu], + device=self._device, + ) + binding.write(scratch, indices=_ids_gpu) + + def _write_flat_tensor_mask(self, tensor_type: int, data, env_mask=None, joint_mask=None) -> None: + """Write a 2-D tensor to a binding, with optional env/joint mask subsetting.""" + if isinstance(data, (int, float)): + return + binding = self._get_binding(tensor_type) + if binding is None: + return + from isaaclab_ovphysx.tensor_types import _CPU_ONLY_TYPES + + is_cpu_only = tensor_type in _CPU_ONLY_TYPES + + # CPU-only types or column-mask scatter must go through numpy. + if is_cpu_only or joint_mask is not None: + target_device = "cpu" if is_cpu_only else self._device + np_data = self._to_cpu_numpy(data) + if joint_mask is not None: + # GPU bindings cannot read into numpy directly; read into GPU + # scratch first, then pull to CPU for column scatter. + if is_cpu_only: + full = np.zeros(binding.shape, dtype=np.float32) + binding.read(full) + else: + scratch = self._get_write_scratch(tensor_type, binding) + binding.read(scratch) + full = scratch.numpy() + jmask = self._to_cpu_numpy(joint_mask).astype(bool) + cols = np.where(jmask)[0] + if env_mask is not None: + emask = self._to_cpu_numpy(env_mask).astype(bool) + rows = np.where(emask)[0] + full[rows[:, None], cols] = np_data[rows[:, None], cols] + else: + full[:, cols] = np_data[:, cols] + binding.write(wp.from_numpy(full.astype(np.float32), dtype=wp.float32, device=target_device)) + elif env_mask is not None: + flat = wp.from_numpy(np_data.astype(np.float32), dtype=wp.float32, device=target_device) + mask_u8 = wp.from_numpy( + self._to_cpu_numpy(env_mask).astype(np.uint8), + device=target_device, + ) + binding.write(flat, mask=mask_u8) + else: + binding.write(wp.from_numpy(np_data.astype(np.float32), dtype=wp.float32, device=target_device)) + return + + # GPU path: data stays on device. + if env_mask is None: + binding.write(self._to_flat_f32(data)) + return + + # Data is full [N, D], the binding API selects rows via the mask. + mask_u8 = wp.from_numpy( + self._to_cpu_numpy(env_mask).astype(np.uint8), + device=self._device, + ) + binding.write(self._to_flat_f32(data), mask=mask_u8) + + def _write_friction_column(self, data, env_ids=None, joint_ids=None) -> None: + """Write static friction coefficient into column 0 of DOF_FRICTION_PROPERTIES [N,D,3].""" + binding = self._get_binding(TT.DOF_FRICTION_PROPERTIES) + if binding is None: + return + full = np.zeros(binding.shape, dtype=np.float32) + binding.read(full) + if isinstance(data, (int, float)): + if env_ids is not None and joint_ids is not None: + eids = self._to_cpu_numpy(env_ids).astype(np.intp) + jids = self._to_cpu_indices(joint_ids, np.intp) + full[np.ix_(eids, jids, [0])] = data + elif env_ids is not None: + eids = self._to_cpu_numpy(env_ids).astype(np.intp) + full[eids, :, 0] = data + elif joint_ids is not None: + jids = self._to_cpu_indices(joint_ids, np.intp) + full[:, jids, 0] = data + else: + full[..., 0] = data + binding.write(wp.from_numpy(full.astype(np.float32), dtype=wp.float32, device="cpu")) + return + np_data = self._to_cpu_numpy(data) + if env_ids is not None and joint_ids is not None: + eids = self._to_cpu_numpy(env_ids).astype(np.intp) + jids = self._to_cpu_indices(joint_ids, np.intp) + full[np.ix_(eids, jids, [0])] = np_data.reshape(len(eids), len(jids), 1) + elif env_ids is not None: + eids = self._to_cpu_numpy(env_ids).astype(np.intp) + full[eids, :, 0] = np_data.reshape(len(eids), -1) + elif joint_ids is not None: + jids = self._to_cpu_indices(joint_ids, np.intp) + full[:, jids, 0] = np_data.reshape(full.shape[0], len(jids)) + else: + full[..., 0] = np_data.reshape(full.shape[0], full.shape[1]) + binding.write(wp.from_numpy(full.astype(np.float32), dtype=wp.float32, device="cpu")) + + def _write_friction_column_mask(self, data, env_mask=None, joint_mask=None) -> None: + """Write static friction coefficient via mask into column 0 of DOF_FRICTION_PROPERTIES.""" + binding = self._get_binding(TT.DOF_FRICTION_PROPERTIES) + if binding is None: + return + full = np.zeros(binding.shape, dtype=np.float32) + binding.read(full) + if isinstance(data, (int, float)): + new_col = np.full((full.shape[0], full.shape[1]), data, dtype=np.float32) + else: + new_col = self._to_cpu_numpy(data).reshape(full.shape[0], full.shape[1]) + if env_mask is not None: + emask = self._to_cpu_numpy(env_mask).astype(bool) + if joint_mask is not None: + jmask = self._to_cpu_numpy(joint_mask).astype(bool) + rows = np.where(emask)[0] + cols = np.where(jmask)[0] + full[rows[:, None], cols, 0] = new_col[rows[:, None], cols] + else: + full[emask, :, 0] = new_col[emask] + elif joint_mask is not None: + jmask = self._to_cpu_numpy(joint_mask).astype(bool) + full[:, jmask, 0] = new_col[:, jmask] + else: + full[..., 0] = new_col + binding.write(wp.from_numpy(full.astype(np.float32), dtype=wp.float32, device="cpu")) + + def _write_joint_subset(self, tensor_type: int, buffer: wp.array, joint_ids: list[int]) -> None: + """Write a full-width joint buffer into the simulation for an actuator's joints.""" + binding = self._get_binding(tensor_type) + if binding is None: + return + if not hasattr(self, "_write_dltensor_cache"): + self._write_dltensor_cache = {} + cache_key = (tensor_type, buffer.ptr) + cached = self._write_dltensor_cache.get(cache_key) + if cached is None: + flat = self._to_flat_f32(buffer) + from ovphysx._dlpack_utils import acquire_dltensor + + dl, keepalive = acquire_dltensor(flat) + self._write_dltensor_cache[cache_key] = (dl, keepalive, flat) + cached = self._write_dltensor_cache[cache_key] + binding.write(cached[0]) + + @staticmethod + def _to_cpu_numpy(data) -> np.ndarray: + """Convert data (warp, torch, numpy, scalar) to a CPU numpy array.""" + if isinstance(data, wp.array): + return data.numpy().astype(np.float32) + if isinstance(data, torch.Tensor): + return data.detach().cpu().numpy().astype(np.float32) + return np.asarray(data, dtype=np.float32) + + @staticmethod + def _to_cpu_indices(data, dtype=np.int32) -> np.ndarray: + """Convert index array (warp, torch, list, numpy) to CPU numpy int array.""" + if isinstance(data, torch.Tensor): + return data.detach().cpu().numpy().astype(dtype) + if isinstance(data, wp.array): + return data.numpy().astype(dtype) + return np.asarray(data, dtype=dtype) + + def _env_ids_to_gpu_warp(self, env_ids) -> wp.array: + """Convert env_ids to a GPU int32 warp array, with single-entry caching. + + The cache avoids repeated GPU -> CPU -> GPU round-trips when the same + ``env_ids`` object is passed to multiple binding writes in a single step + (e.g. reset writes root_pose, root_vel, joint_pos, joint_vel). A new + object identity (``id()``) or shape change invalidates the cache. + """ + if hasattr(env_ids, "data_ptr"): + key = (env_ids.data_ptr(), env_ids.shape[0]) + elif isinstance(env_ids, wp.array): + key = (env_ids.ptr, env_ids.shape[0]) + else: + key = None + + if key is not None and hasattr(self, "_ids_cache_key") and self._ids_cache_key == key: + return self._ids_cache_val + + result = wp.array(self._to_cpu_indices(env_ids, np.int32), device=self._device) + if key is not None: + self._ids_cache_key = key + self._ids_cache_val = result + return result + + def _set_target_into_buffer(self, buffer: wp.array, data, env_ids=None, joint_ids=None) -> None: + """Set user-provided target data into a warp command buffer. + + For the common case (no index subset), this uses wp.copy to stay on + the simulation device. Subset writes (specific env_ids or joint_ids) + fall back to CPU because warp does not support scatter indexing. + """ + # Fast path: all-joints shortcut. When joint_ids covers every joint + # and env_ids is None, the subset is equivalent to a full copy. + if joint_ids is not None and env_ids is None: + n_joints = buffer.shape[1] if len(buffer.shape) > 1 else 1 + if hasattr(joint_ids, "__len__") and len(joint_ids) == n_joints: + joint_ids = None + if env_ids is None and joint_ids is None: + src = self._to_flat_f32(data) + if isinstance(src, np.ndarray): + src = wp.from_numpy(src, dtype=wp.float32, device=buffer.device) + wp.copy(buffer, src) + else: + np_data = self._to_cpu_numpy(data) + buf_np = buffer.numpy() + env_idx = self._to_cpu_numpy(env_ids).astype(np.intp) if env_ids is not None else None + jnt_idx = self._to_cpu_numpy(joint_ids).astype(np.intp) if joint_ids is not None else None + if env_idx is not None and jnt_idx is not None: + buf_np[np.ix_(env_idx, jnt_idx)] = np_data + elif env_idx is not None: + buf_np[env_idx] = np_data + else: + buf_np[:, jnt_idx] = np_data + wp.copy(buffer, wp.from_numpy(buf_np, dtype=wp.float32, device=buffer.device)) + + def _set_target_into_buffer_mask(self, buffer: wp.array, data, env_mask=None, joint_mask=None) -> None: + """Set user-provided target data into a warp command buffer using masks.""" + if env_mask is None: + src = self._to_flat_f32(data) + if isinstance(src, np.ndarray): + src = wp.from_numpy(src, dtype=wp.float32, device=buffer.device) + wp.copy(buffer, src) + else: + np_data = self._to_cpu_numpy(data) + buf_np = buffer.numpy() + mask_np = self._to_cpu_numpy(env_mask).astype(bool) + buf_np[mask_np] = np_data[mask_np] + wp.copy(buffer, wp.from_numpy(buf_np, dtype=wp.float32, device=buffer.device)) + + """ + Internal helpers -- Utilities. + """ + + def _n_envs_index(self, env_ids): + """Return the number of environments from an env_ids argument.""" + if env_ids is None: + return self._num_instances + if isinstance(env_ids, (list, tuple)): + return len(env_ids) + return env_ids.shape[0] if hasattr(env_ids, "shape") else len(env_ids) + + def _nft(self): + """Return the number of fixed tendons (0 if none).""" + return getattr(self, "_num_fixed_tendons", 0) + + def _nst(self): + """Return the number of spatial tendons (0 if none).""" + return getattr(self, "_num_spatial_tendons", 0) + + def _resolve_joint_values(self, pattern_dict: dict[str, float], buffer: wp.array) -> None: + """Resolve a {pattern: value} dict into a per-joint buffer. + + Builds values on CPU then copies to buffer's device (GPU arrays' + .numpy() returns a read-only copy, not a writable view). + """ + buf_np = buffer.numpy() + modified = False + for pattern, value in pattern_dict.items(): + for j, name in enumerate(self._joint_names): + if re.fullmatch(pattern, name): + buf_np[:, j] = value + modified = True + if modified: + wp.copy(buffer, wp.from_numpy(buf_np, dtype=buffer.dtype, device=str(buffer.device))) diff --git a/source/isaaclab_ovphysx/isaaclab_ovphysx/assets/articulation/articulation_data.py b/source/isaaclab_ovphysx/isaaclab_ovphysx/assets/articulation/articulation_data.py new file mode 100644 index 000000000000..10c7e4b7ecd6 --- /dev/null +++ b/source/isaaclab_ovphysx/isaaclab_ovphysx/assets/articulation/articulation_data.py @@ -0,0 +1,1760 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Articulation data backed by ovphysx TensorBindingsAPI.""" + +from __future__ import annotations + +import warnings +from typing import Any + +import numpy as np +import warp as wp + +from isaaclab.assets.articulation.base_articulation_data import BaseArticulationData +from isaaclab.utils.buffers import TimestampedBufferWarp as TimestampedBuffer +from isaaclab.utils.warp import ProxyArray + +from isaaclab_ovphysx import tensor_types as TT + +from .kernels import ( + _compose_body_com_poses, + _compose_root_com_pose, + _compute_heading, + _copy_first_body, + _fd_joint_acc, + _projected_gravity, + _world_vel_to_body_ang, + _world_vel_to_body_lin, +) + + +class ArticulationData(BaseArticulationData): + """Data container for an articulation backed by ovphysx tensor bindings. + + This class contains the data for an articulation in the simulation. The data includes the state of + the root rigid body, the state of all the bodies in the articulation, and the joint state. The data is + stored in the simulation world frame unless otherwise specified. + + An articulation is comprised of multiple rigid bodies or links. For a rigid body, there are two frames + of reference that are used: + + - Actor frame: The frame of reference of the rigid body prim. This typically corresponds to the Xform prim + with the rigid body schema. + - Center of mass frame: The frame of reference of the center of mass of the rigid body. + + Depending on the settings, the two frames may not coincide with each other. In the robotics sense, the actor frame + can be interpreted as the link frame. + + Uses ovphysx :class:`TensorBinding` objects to lazily read simulation state into warp + arrays. Writes happen via the :class:`Articulation` class. + """ + + __backend_name__: str = "ovphysx" + """The name of the backend for the articulation data.""" + + def __init__(self, bindings: dict[int, Any], device: str, binding_getter=None): + """Initialize the articulation data. + + Args: + bindings: Mapping from ovphysx tensor type constant to a + live TensorBinding for this articulation. + device: The compute device (``"cpu"`` or ``"cuda:N"``). + binding_getter: Optional callable(tensor_type) -> TensorBinding + that lazily creates bindings on first access. When provided, + ``_get_binding()`` delegates to this instead of only checking + the static ``bindings`` dict. + """ + super().__init__(root_view=None, device=device) + self._bindings = bindings + self._binding_getter = binding_getter + self._sim_timestamp: float = 0.0 + self._is_primed = False + + # Metadata from an arbitrary articulation binding. + sample = next(iter(bindings.values())) + self._num_instances = sample.count + self._num_joints = sample.dof_count + self._num_bodies = sample.body_count + self._is_fixed_base = sample.is_fixed_base + + self.body_names = list(sample.body_names) + self.joint_names = list(sample.dof_names) + self.fixed_tendon_names: list[str] = [] + self.spatial_tendon_names: list[str] = [] + + self._num_fixed_tendons = 0 + self._num_spatial_tendons = 0 + + # Initialize parametric gravity and forward vectors (matching PhysX/Newton pattern). + # Guard against None sim context (e.g. mock/test environments). + from isaaclab.physics import PhysicsManager + + gravity = (0.0, 0.0, -9.81) + if PhysicsManager._sim is not None and hasattr(PhysicsManager._sim, "cfg"): + gravity = PhysicsManager._sim.cfg.gravity + gravity_np = np.array(gravity, dtype=np.float32) + gravity_mag = np.linalg.norm(gravity_np) + if gravity_mag == 0.0: + gravity_dir = np.array([0.0, 0.0, -1.0], dtype=np.float32) + else: + gravity_dir = gravity_np / gravity_mag + gravity_dir_tiled = np.tile(gravity_dir, (self._num_instances, 1)) + forward_tiled = np.tile(np.array([1.0, 0.0, 0.0], dtype=np.float32), (self._num_instances, 1)) + + self.GRAVITY_VEC_W = ProxyArray(wp.from_numpy(gravity_dir_tiled, dtype=wp.vec3f, device=device)) + self.FORWARD_VEC_B = ProxyArray(wp.from_numpy(forward_tiled, dtype=wp.vec3f, device=device)) + + def update(self, dt: float) -> None: + """Update the data for the articulation. + + Args: + dt: The time step for the update [s]. This must be a positive value. + """ + self._sim_timestamp += dt + + # Finite-difference joint acceleration from velocity. + if dt > 0.0 and self._previous_joint_vel is not None: + cur_vel = self.joint_vel + wp.launch( + _fd_joint_acc, + dim=(self._num_instances, self._num_joints), + inputs=[cur_vel, self._previous_joint_vel, 1.0 / dt], + outputs=[self._joint_acc.data], + device=self.device, + ) + self._joint_acc.timestamp = self._sim_timestamp + + @property + def is_primed(self) -> bool: + """Whether the articulation data is fully instantiated and ready to use.""" + return self._is_primed + + @is_primed.setter + def is_primed(self, value: bool) -> None: + """Set whether the articulation data is fully instantiated and ready to use. + + .. note:: + Once this quantity is set to True, it cannot be changed. + + Args: + value: The primed state. + + Raises: + ValueError: If the articulation data is already primed. + """ + if self._is_primed: + raise ValueError("The articulation data is already primed.") + self._is_primed = True + + """ + Names. + """ + + body_names: list[str] = None + """Body names in the order parsed by the simulation view.""" + + joint_names: list[str] = None + """Joint names in the order parsed by the simulation view.""" + + fixed_tendon_names: list[str] = None + """Fixed tendon names in the order parsed by the simulation view.""" + + spatial_tendon_names: list[str] = None + """Spatial tendon names in the order parsed by the simulation view.""" + + """ + Defaults - Initial state. + """ + + @property + def default_root_pose(self) -> ProxyArray: + """Default root pose ``[pos, quat]`` in the local environment frame. + + The position and quaternion are of the articulation root's actor frame. + Shape is (num_instances,), dtype = wp.transformf. In torch this resolves to (num_instances, 7). + """ + if self._default_root_pose_ta is None: + self._default_root_pose_ta = ProxyArray(self._default_root_pose) + return self._default_root_pose_ta + + @default_root_pose.setter + def default_root_pose(self, value: wp.array) -> None: + """Set the default root pose. + + Args: + value: The default root pose. Shape is (num_instances, 7). + + Raises: + ValueError: If the articulation data is already primed. + """ + if self.is_primed: + raise ValueError("The articulation data is already primed.") + self._default_root_pose.assign(value) + + @property + def default_root_vel(self) -> ProxyArray: + """Default root velocity ``[lin_vel, ang_vel]`` in the local environment frame. + + The linear and angular velocities are of the articulation root's center of mass frame. + Shape is (num_instances,), dtype = wp.spatial_vectorf. In torch this resolves to (num_instances, 6). + """ + if self._default_root_vel_ta is None: + self._default_root_vel_ta = ProxyArray(self._default_root_vel) + return self._default_root_vel_ta + + @default_root_vel.setter + def default_root_vel(self, value: wp.array) -> None: + """Set the default root velocity. + + Args: + value: The default root velocity. Shape is (num_instances, 6). + + Raises: + ValueError: If the articulation data is already primed. + """ + if self.is_primed: + raise ValueError("The articulation data is already primed.") + self._default_root_vel.assign(value) + + @property + def default_joint_pos(self) -> ProxyArray: + """Default joint positions of all joints [m or rad, depending on joint type]. + + Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to + (num_instances, num_joints). + + This quantity is configured through the :attr:`isaaclab.assets.ArticulationCfg.init_state` parameter. + """ + if self._default_joint_pos_ta is None: + self._default_joint_pos_ta = ProxyArray(self._default_joint_pos) + return self._default_joint_pos_ta + + @default_joint_pos.setter + def default_joint_pos(self, value: wp.array) -> None: + """Set the default joint positions. + + Args: + value: The default joint positions. Shape is (num_instances, num_joints). + + Raises: + ValueError: If the articulation data is already primed. + """ + if self.is_primed: + raise ValueError("The articulation data is already primed.") + self._default_joint_pos.assign(value) + + @property + def default_joint_vel(self) -> ProxyArray: + """Default joint velocities of all joints [m/s or rad/s, depending on joint type]. + + Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to + (num_instances, num_joints). + + This quantity is configured through the :attr:`isaaclab.assets.ArticulationCfg.init_state` parameter. + """ + if self._default_joint_vel_ta is None: + self._default_joint_vel_ta = ProxyArray(self._default_joint_vel) + return self._default_joint_vel_ta + + @default_joint_vel.setter + def default_joint_vel(self, value: wp.array) -> None: + """Set the default joint velocities. + + Args: + value: The default joint velocities. Shape is (num_instances, num_joints). + + Raises: + ValueError: If the articulation data is already primed. + """ + if self.is_primed: + raise ValueError("The articulation data is already primed.") + self._default_joint_vel.assign(value) + + """ + Joint commands -- Set into simulation. + """ + + @property + def joint_pos_target(self) -> ProxyArray: + """Joint position targets commanded by the user [m or rad, depending on joint type]. + + Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to + (num_instances, num_joints). + + For an implicit actuator model, the targets are directly set into the simulation. + For an explicit actuator model, the targets are used to compute the joint torques + (see :attr:`applied_torque`), which are then set into the simulation. + """ + if self._joint_pos_target_ta is None: + self._joint_pos_target_ta = ProxyArray(self._joint_pos_target) + return self._joint_pos_target_ta + + @property + def joint_vel_target(self) -> ProxyArray: + """Joint velocity targets commanded by the user [m/s or rad/s, depending on joint type]. + + Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to + (num_instances, num_joints). + + For an implicit actuator model, the targets are directly set into the simulation. + For an explicit actuator model, the targets are used to compute the joint torques + (see :attr:`applied_torque`), which are then set into the simulation. + """ + if self._joint_vel_target_ta is None: + self._joint_vel_target_ta = ProxyArray(self._joint_vel_target) + return self._joint_vel_target_ta + + @property + def joint_effort_target(self) -> ProxyArray: + """Joint effort targets commanded by the user [N or N*m, depending on joint type]. + + Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to + (num_instances, num_joints). + + For an implicit actuator model, the targets are directly set into the simulation. + For an explicit actuator model, the targets are used to compute the joint torques + (see :attr:`applied_torque`), which are then set into the simulation. + """ + if self._joint_effort_target_ta is None: + self._joint_effort_target_ta = ProxyArray(self._joint_effort_target) + return self._joint_effort_target_ta + + """ + Joint commands -- Explicit actuators. + """ + + @property + def computed_torque(self) -> ProxyArray: + """Joint torques computed from the actuator model (before clipping) [N*m]. + + Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to + (num_instances, num_joints). + + This quantity is the raw torque output from the actuator model, before any clipping is applied. + It is exposed for users who want to inspect the computations inside the actuator model. + For instance, to penalize the learning agent for a difference between the computed and applied torques. + """ + if self._computed_torque_ta is None: + self._computed_torque_ta = ProxyArray(self._computed_torque) + return self._computed_torque_ta + + @property + def applied_torque(self) -> ProxyArray: + """Joint torques applied from the actuator model (after clipping) [N*m]. + + Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to + (num_instances, num_joints). + + These torques are set into the simulation, after clipping the :attr:`computed_torque` based on the + actuator model. + """ + if self._applied_torque_ta is None: + self._applied_torque_ta = ProxyArray(self._applied_torque) + return self._applied_torque_ta + + """ + Joint properties + """ + + @property + def joint_stiffness(self) -> ProxyArray: + """Joint stiffness provided to the simulation. + + Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to + (num_instances, num_joints). + + In the case of explicit actuators, the value for the corresponding joints is zero. + """ + if self._joint_stiffness_ta is None: + self._joint_stiffness_ta = ProxyArray(self._joint_stiffness) + return self._joint_stiffness_ta + + @property + def joint_damping(self) -> ProxyArray: + """Joint damping provided to the simulation. + + Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to + (num_instances, num_joints). + + In the case of explicit actuators, the value for the corresponding joints is zero. + """ + if self._joint_damping_ta is None: + self._joint_damping_ta = ProxyArray(self._joint_damping) + return self._joint_damping_ta + + @property + def joint_armature(self) -> ProxyArray: + """Joint armature provided to the simulation. + + Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to + (num_instances, num_joints). + """ + if self._joint_armature_ta is None: + self._joint_armature_ta = ProxyArray(self._joint_armature) + return self._joint_armature_ta + + @property + def joint_friction_coeff(self) -> ProxyArray: + """Joint static friction coefficient provided to the simulation. + + Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to + (num_instances, num_joints). + """ + if self._joint_friction_coeff_ta is None: + self._joint_friction_coeff_ta = ProxyArray(self._joint_friction_coeff) + return self._joint_friction_coeff_ta + + @property + def joint_pos_limits(self) -> ProxyArray: + """Joint position limits provided to the simulation. + + Shape is (num_instances, num_joints), dtype = wp.vec2f. In torch this resolves to + (num_instances, num_joints, 2). + + The limits are in the order :math:`[lower, upper]`. + """ + if self._joint_pos_limits_ta is None: + self._joint_pos_limits_ta = ProxyArray(self._joint_pos_limits) + return self._joint_pos_limits_ta + + @property + def joint_vel_limits(self) -> ProxyArray: + """Joint maximum velocity provided to the simulation [m/s or rad/s, depending on joint type]. + + Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to + (num_instances, num_joints). + """ + if self._joint_vel_limits_ta is None: + self._joint_vel_limits_ta = ProxyArray(self._joint_vel_limits) + return self._joint_vel_limits_ta + + @property + def joint_effort_limits(self) -> ProxyArray: + """Joint maximum effort provided to the simulation [N or N*m, depending on joint type]. + + Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to + (num_instances, num_joints). + """ + if self._joint_effort_limits_ta is None: + self._joint_effort_limits_ta = ProxyArray(self._joint_effort_limits) + return self._joint_effort_limits_ta + + """ + Joint properties - Custom. + """ + + @property + def soft_joint_pos_limits(self) -> ProxyArray: + r"""Soft joint position limits for all joints. + + Shape is (num_instances, num_joints), dtype = wp.vec2f. In torch this resolves to + (num_instances, num_joints, 2). + + The limits are in the order :math:`[lower, upper]`. The soft joint position limits are computed as + a sub-region of the :attr:`joint_pos_limits` based on the + :attr:`~isaaclab.assets.ArticulationCfg.soft_joint_pos_limit_factor` parameter. + + Consider the joint position limits :math:`[lower, upper]` and the soft joint position limits + :math:`[soft\_lower, soft\_upper]`. The soft joint position limits are computed as: + + .. math:: + + soft\_lower = (lower + upper) / 2 - factor * (upper - lower) / 2 + soft\_upper = (lower + upper) / 2 + factor * (upper - lower) / 2 + + The soft joint position limits help specify a safety region around the joint limits. It isn't used by the + simulation, but is useful for learning agents to prevent the joint positions from violating the limits. + """ + if self._soft_joint_pos_limits_ta is None: + self._soft_joint_pos_limits_ta = ProxyArray(self._soft_joint_pos_limits) + return self._soft_joint_pos_limits_ta + + @property + def soft_joint_vel_limits(self) -> ProxyArray: + """Soft joint velocity limits for all joints. + + Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to + (num_instances, num_joints). + + These are obtained from the actuator model. It may differ from :attr:`joint_vel_limits` if the actuator model + has a variable velocity limit model. For instance, in a variable gear ratio actuator model. + """ + if self._soft_joint_vel_limits_ta is None: + self._soft_joint_vel_limits_ta = ProxyArray(self._soft_joint_vel_limits) + return self._soft_joint_vel_limits_ta + + @property + def gear_ratio(self) -> ProxyArray: + """Gear ratio for relating motor torques to applied joint torques. + + Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to + (num_instances, num_joints). + """ + if self._gear_ratio_ta is None: + self._gear_ratio_ta = ProxyArray(self._gear_ratio) + return self._gear_ratio_ta + + """ + Fixed tendon properties. + """ + + @property + def fixed_tendon_stiffness(self) -> ProxyArray: + """Fixed tendon stiffness provided to the simulation. + + Shape is (num_instances, num_fixed_tendons), dtype = wp.float32. In torch this resolves to + (num_instances, num_fixed_tendons). + """ + if self._fixed_tendon_stiffness_ta is None: + self._fixed_tendon_stiffness_ta = ProxyArray(self._fixed_tendon_stiffness) + return self._fixed_tendon_stiffness_ta + + @property + def fixed_tendon_damping(self) -> ProxyArray: + """Fixed tendon damping provided to the simulation. + + Shape is (num_instances, num_fixed_tendons), dtype = wp.float32. In torch this resolves to + (num_instances, num_fixed_tendons). + """ + if self._fixed_tendon_damping_ta is None: + self._fixed_tendon_damping_ta = ProxyArray(self._fixed_tendon_damping) + return self._fixed_tendon_damping_ta + + @property + def fixed_tendon_limit_stiffness(self) -> ProxyArray: + """Fixed tendon limit stiffness provided to the simulation. + + Shape is (num_instances, num_fixed_tendons), dtype = wp.float32. In torch this resolves to + (num_instances, num_fixed_tendons). + """ + if self._fixed_tendon_limit_stiffness_ta is None: + self._fixed_tendon_limit_stiffness_ta = ProxyArray(self._fixed_tendon_limit_stiffness) + return self._fixed_tendon_limit_stiffness_ta + + @property + def fixed_tendon_rest_length(self) -> ProxyArray: + """Fixed tendon rest length provided to the simulation. + + Shape is (num_instances, num_fixed_tendons), dtype = wp.float32. In torch this resolves to + (num_instances, num_fixed_tendons). + """ + if self._fixed_tendon_rest_length_ta is None: + self._fixed_tendon_rest_length_ta = ProxyArray(self._fixed_tendon_rest_length) + return self._fixed_tendon_rest_length_ta + + @property + def fixed_tendon_offset(self) -> ProxyArray: + """Fixed tendon offset provided to the simulation. + + Shape is (num_instances, num_fixed_tendons), dtype = wp.float32. In torch this resolves to + (num_instances, num_fixed_tendons). + """ + if self._fixed_tendon_offset_ta is None: + self._fixed_tendon_offset_ta = ProxyArray(self._fixed_tendon_offset) + return self._fixed_tendon_offset_ta + + @property + def fixed_tendon_pos_limits(self) -> ProxyArray: + """Fixed tendon position limits provided to the simulation. + + Shape is (num_instances, num_fixed_tendons), dtype = wp.vec2f. In torch this resolves to + (num_instances, num_fixed_tendons, 2). + """ + if self._fixed_tendon_pos_limits_ta is None: + self._fixed_tendon_pos_limits_ta = ProxyArray(self._fixed_tendon_pos_limits) + return self._fixed_tendon_pos_limits_ta + + """ + Spatial tendon properties. + """ + + @property + def spatial_tendon_stiffness(self) -> ProxyArray: + """Spatial tendon stiffness provided to the simulation. + + Shape is (num_instances, num_spatial_tendons), dtype = wp.float32. In torch this resolves to + (num_instances, num_spatial_tendons). + """ + if self._spatial_tendon_stiffness_ta is None: + self._spatial_tendon_stiffness_ta = ProxyArray(self._spatial_tendon_stiffness) + return self._spatial_tendon_stiffness_ta + + @property + def spatial_tendon_damping(self) -> ProxyArray: + """Spatial tendon damping provided to the simulation. + + Shape is (num_instances, num_spatial_tendons), dtype = wp.float32. In torch this resolves to + (num_instances, num_spatial_tendons). + """ + if self._spatial_tendon_damping_ta is None: + self._spatial_tendon_damping_ta = ProxyArray(self._spatial_tendon_damping) + return self._spatial_tendon_damping_ta + + @property + def spatial_tendon_limit_stiffness(self) -> ProxyArray: + """Spatial tendon limit stiffness provided to the simulation. + + Shape is (num_instances, num_spatial_tendons), dtype = wp.float32. In torch this resolves to + (num_instances, num_spatial_tendons). + """ + if self._spatial_tendon_limit_stiffness_ta is None: + self._spatial_tendon_limit_stiffness_ta = ProxyArray(self._spatial_tendon_limit_stiffness) + return self._spatial_tendon_limit_stiffness_ta + + @property + def spatial_tendon_offset(self) -> ProxyArray: + """Spatial tendon offset provided to the simulation. + + Shape is (num_instances, num_spatial_tendons), dtype = wp.float32. In torch this resolves to + (num_instances, num_spatial_tendons). + """ + if self._spatial_tendon_offset_ta is None: + self._spatial_tendon_offset_ta = ProxyArray(self._spatial_tendon_offset) + return self._spatial_tendon_offset_ta + + """ + Root state properties. + """ + + @property + def root_link_pose_w(self) -> ProxyArray: + """Root link pose ``[pos, quat]`` in simulation world frame. + Shape is (num_instances,), dtype = wp.transformf. In torch this resolves to (num_instances, 7). + + This quantity is the pose of the articulation root's actor frame relative to the world. + The orientation is provided in (x, y, z, w) format. + """ + self._read_transform_binding(TT.ROOT_POSE, self._root_link_pose_w) + if self._root_link_pose_w_ta is None: + self._root_link_pose_w_ta = ProxyArray(self._root_link_pose_w.data) + return self._root_link_pose_w_ta + + @property + def root_link_vel_w(self) -> ProxyArray: + """Root link velocity ``[lin_vel, ang_vel]`` in simulation world frame. + Shape is (num_instances,), dtype = wp.spatial_vectorf. In torch this resolves to (num_instances, 6). + + This quantity contains the linear and angular velocities of the articulation root's actor frame + relative to the world. + """ + # ovphysx ROOT_VELOCITY is COM velocity; link velocity comes from the first + # element of the per-link velocity tensor. + self._read_spatial_vector_binding(TT.LINK_VELOCITY, self._body_link_vel_w) + if self._root_link_vel_w.timestamp < self._sim_timestamp: + wp.launch( + _copy_first_body, + dim=self._num_instances, + inputs=[self._body_link_vel_w.data], + outputs=[self._root_link_vel_w.data], + device=self.device, + ) + self._root_link_vel_w.timestamp = self._sim_timestamp + if self._root_link_vel_w_ta is None: + self._root_link_vel_w_ta = ProxyArray(self._root_link_vel_w.data) + return self._root_link_vel_w_ta + + @property + def root_com_pose_w(self) -> ProxyArray: + """Root center of mass pose ``[pos, quat]`` in simulation world frame. + Shape is (num_instances,), dtype = wp.transformf. In torch this resolves to (num_instances, 7). + + This quantity is the pose of the articulation root's center of mass frame relative to the world. + The orientation is provided in (x, y, z, w) format. + """ + if self._root_com_pose_w.timestamp < self._sim_timestamp: + wp.launch( + _compose_root_com_pose, + dim=self._num_instances, + inputs=[self.root_link_pose_w, self.body_com_pose_b], + outputs=[self._root_com_pose_w.data], + device=self.device, + ) + self._root_com_pose_w.timestamp = self._sim_timestamp + if self._root_com_pose_w_ta is None: + self._root_com_pose_w_ta = ProxyArray(self._root_com_pose_w.data) + return self._root_com_pose_w_ta + + @property + def root_com_vel_w(self) -> ProxyArray: + """Root center of mass velocity ``[lin_vel, ang_vel]`` in simulation world frame. + Shape is (num_instances,), dtype = wp.spatial_vectorf. In torch this resolves to (num_instances, 6). + + This quantity contains the linear and angular velocities of the articulation root's center of mass frame + relative to the world. + """ + self._read_spatial_vector_binding(TT.ROOT_VELOCITY, self._root_com_vel_w) + if self._root_com_vel_w_ta is None: + self._root_com_vel_w_ta = ProxyArray(self._root_com_vel_w.data) + return self._root_com_vel_w_ta + + """ + Body state properties. + """ + + @property + def body_mass(self) -> ProxyArray: + """Body mass in the world frame [kg]. + + Shape is (num_instances, num_bodies), dtype = wp.float32. In torch this resolves to + (num_instances, num_bodies). + """ + if self._body_mass_ta is None: + self._body_mass_ta = ProxyArray(self._body_mass) + return self._body_mass_ta + + @property + def body_inertia(self) -> ProxyArray: + """Flattened body inertia in the world frame [kg*m^2]. + + Shape is (num_instances, num_bodies, 9), dtype = wp.float32. In torch this resolves to + (num_instances, num_bodies, 9). + + Stored as a flattened 3x3 inertia matrix per body. + """ + if self._body_inertia_ta is None: + self._body_inertia_ta = ProxyArray(self._body_inertia) + return self._body_inertia_ta + + @property + def body_link_pose_w(self) -> ProxyArray: + """Body link pose ``[pos, quat]`` in simulation world frame. + Shape is (num_instances, num_bodies), dtype = wp.transformf. In torch this resolves to + (num_instances, num_bodies, 7). + + This quantity is the pose of the articulation links' actor frame relative to the world. + The orientation is provided in (x, y, z, w) format. + """ + self._read_transform_binding(TT.LINK_POSE, self._body_link_pose_w) + if self._body_link_pose_w_ta is None: + self._body_link_pose_w_ta = ProxyArray(self._body_link_pose_w.data) + return self._body_link_pose_w_ta + + @property + def body_link_vel_w(self) -> ProxyArray: + """Body link velocity ``[lin_vel, ang_vel]`` in simulation world frame. + Shape is (num_instances, num_bodies), dtype = wp.spatial_vectorf. In torch this resolves to + (num_instances, num_bodies, 6). + + This quantity contains the linear and angular velocities of the articulation links' actor frame + relative to the world. + """ + self._read_spatial_vector_binding(TT.LINK_VELOCITY, self._body_link_vel_w) + if self._body_link_vel_w_ta is None: + self._body_link_vel_w_ta = ProxyArray(self._body_link_vel_w.data) + return self._body_link_vel_w_ta + + @property + def body_com_pose_w(self) -> ProxyArray: + """Body center of mass pose ``[pos, quat]`` in simulation world frame. + Shape is (num_instances, num_bodies), dtype = wp.transformf. In torch this resolves to + (num_instances, num_bodies, 7). + + This quantity is the pose of the center of mass frame of the articulation links relative to the world. + The orientation is provided in (x, y, z, w) format. + """ + if self._body_com_pose_w.timestamp < self._sim_timestamp: + wp.launch( + _compose_body_com_poses, + dim=(self._num_instances, self._num_bodies), + inputs=[self.body_link_pose_w, self.body_com_pose_b], + outputs=[self._body_com_pose_w.data], + device=self.device, + ) + self._body_com_pose_w.timestamp = self._sim_timestamp + if self._body_com_pose_w_ta is None: + self._body_com_pose_w_ta = ProxyArray(self._body_com_pose_w.data) + return self._body_com_pose_w_ta + + @property + def body_com_vel_w(self) -> ProxyArray: + """Body center of mass velocity ``[lin_vel, ang_vel]`` in simulation world frame. + Shape is (num_instances, num_bodies), dtype = wp.spatial_vectorf. In torch this resolves to + (num_instances, num_bodies, 6). + + This quantity contains the linear and angular velocities of the articulation links' center of mass frame + relative to the world. + + .. note:: + This is currently approximated using the link velocity. A proper COM velocity derivation + accounting for the COM offset is not yet implemented. + """ + return self.body_link_vel_w + + @property + def body_com_acc_w(self) -> ProxyArray: + """Acceleration of all bodies center of mass ``[lin_acc, ang_acc]`` [m/s^2, rad/s^2]. + Shape is (num_instances, num_bodies), dtype = wp.spatial_vectorf. In torch this resolves to + (num_instances, num_bodies, 6). + + All values are relative to the world. + """ + self._read_spatial_vector_binding(TT.LINK_ACCELERATION, self._body_com_acc_w) + if self._body_com_acc_w_ta is None: + self._body_com_acc_w_ta = ProxyArray(self._body_com_acc_w.data) + return self._body_com_acc_w_ta + + @property + def body_com_pose_b(self) -> ProxyArray: + """Center of mass pose ``[pos, quat]`` of all bodies in their respective body's link frames. + Shape is (num_instances, num_bodies), dtype = wp.transformf. In torch this resolves to + (num_instances, num_bodies, 7). + + This quantity is the pose of the center of mass frame of the rigid body relative to the body's link frame. + The orientation is provided in (x, y, z, w) format. + """ + self._read_transform_binding(TT.BODY_COM_POSE, self._body_com_pose_b) + if self._body_com_pose_b_ta is None: + self._body_com_pose_b_ta = ProxyArray(self._body_com_pose_b.data) + return self._body_com_pose_b_ta + + """ + Joint state properties. + """ + + @property + def joint_pos(self) -> ProxyArray: + """Joint positions of all joints [m or rad, depending on joint type]. + + Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to + (num_instances, num_joints). + """ + self._read_binding_into_buf(TT.DOF_POSITION, self._joint_pos_buf) + if self._joint_pos_ta is None: + self._joint_pos_ta = ProxyArray(self._joint_pos_buf.data) + return self._joint_pos_ta + + @property + def joint_vel(self) -> ProxyArray: + """Joint velocities of all joints [m/s or rad/s, depending on joint type]. + + Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to + (num_instances, num_joints). + """ + self._read_binding_into_buf(TT.DOF_VELOCITY, self._joint_vel_buf) + if self._joint_vel_ta is None: + self._joint_vel_ta = ProxyArray(self._joint_vel_buf.data) + return self._joint_vel_ta + + @property + def joint_acc(self) -> ProxyArray: + """Joint acceleration of all joints [m/s^2 or rad/s^2, depending on joint type]. + + Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to + (num_instances, num_joints). + + .. note:: + This quantity is computed via finite differencing of joint velocities. + """ + if self._joint_acc_ta is None: + self._joint_acc_ta = ProxyArray(self._joint_acc.data) + return self._joint_acc_ta + + """ + Derived Properties. + """ + + @property + def projected_gravity_b(self) -> ProxyArray: + """Projection of the gravity direction on base frame. + Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). + """ + if self._projected_gravity_b.timestamp < self._sim_timestamp: + wp.launch( + _projected_gravity, + dim=self._num_instances, + inputs=[self.GRAVITY_VEC_W, self.root_link_pose_w], + outputs=[self._projected_gravity_b.data], + device=self.device, + ) + self._projected_gravity_b.timestamp = self._sim_timestamp + if self._projected_gravity_b_ta is None: + self._projected_gravity_b_ta = ProxyArray(self._projected_gravity_b.data) + return self._projected_gravity_b_ta + + @property + def heading_w(self) -> ProxyArray: + """Yaw heading of the base frame (in radians). + Shape is (num_instances,), dtype = wp.float32. + + .. note:: + This quantity is computed by assuming that the forward-direction of the base + frame is along x-direction, i.e. :math:`(1, 0, 0)`. + """ + if self._heading_w.timestamp < self._sim_timestamp: + wp.launch( + _compute_heading, + dim=self._num_instances, + inputs=[self.FORWARD_VEC_B, self.root_link_pose_w], + outputs=[self._heading_w.data], + device=self.device, + ) + self._heading_w.timestamp = self._sim_timestamp + if self._heading_w_ta is None: + self._heading_w_ta = ProxyArray(self._heading_w.data) + return self._heading_w_ta + + @property + def root_link_lin_vel_b(self) -> ProxyArray: + """Root link linear velocity in base frame [m/s]. + Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). + + This quantity is the linear velocity of the articulation root's actor frame with respect to its actor frame. + """ + if self._root_link_lin_vel_b.timestamp < self._sim_timestamp: + wp.launch( + _world_vel_to_body_lin, + dim=self._num_instances, + inputs=[self.root_link_pose_w, self.root_link_vel_w], + outputs=[self._root_link_lin_vel_b.data], + device=self.device, + ) + self._root_link_lin_vel_b.timestamp = self._sim_timestamp + if self._root_link_lin_vel_b_ta is None: + self._root_link_lin_vel_b_ta = ProxyArray(self._root_link_lin_vel_b.data) + return self._root_link_lin_vel_b_ta + + @property + def root_link_ang_vel_b(self) -> ProxyArray: + """Root link angular velocity in base frame [rad/s]. + Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). + + This quantity is the angular velocity of the articulation root's actor frame with respect to its actor frame. + """ + if self._root_link_ang_vel_b.timestamp < self._sim_timestamp: + wp.launch( + _world_vel_to_body_ang, + dim=self._num_instances, + inputs=[self.root_link_pose_w, self.root_link_vel_w], + outputs=[self._root_link_ang_vel_b.data], + device=self.device, + ) + self._root_link_ang_vel_b.timestamp = self._sim_timestamp + if self._root_link_ang_vel_b_ta is None: + self._root_link_ang_vel_b_ta = ProxyArray(self._root_link_ang_vel_b.data) + return self._root_link_ang_vel_b_ta + + @property + def root_com_lin_vel_b(self) -> ProxyArray: + """Root center of mass linear velocity in base frame [m/s]. + Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). + + This quantity is the linear velocity of the articulation root's center of mass frame + with respect to its actor frame. + """ + if self._root_com_lin_vel_b.timestamp < self._sim_timestamp: + wp.launch( + _world_vel_to_body_lin, + dim=self._num_instances, + inputs=[self.root_link_pose_w, self.root_com_vel_w], + outputs=[self._root_com_lin_vel_b.data], + device=self.device, + ) + self._root_com_lin_vel_b.timestamp = self._sim_timestamp + if self._root_com_lin_vel_b_ta is None: + self._root_com_lin_vel_b_ta = ProxyArray(self._root_com_lin_vel_b.data) + return self._root_com_lin_vel_b_ta + + @property + def root_com_ang_vel_b(self) -> ProxyArray: + """Root center of mass angular velocity in base frame [rad/s]. + Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). + + This quantity is the angular velocity of the articulation root's center of mass frame + with respect to its actor frame. + """ + if self._root_com_ang_vel_b.timestamp < self._sim_timestamp: + wp.launch( + _world_vel_to_body_ang, + dim=self._num_instances, + inputs=[self.root_link_pose_w, self.root_com_vel_w], + outputs=[self._root_com_ang_vel_b.data], + device=self.device, + ) + self._root_com_ang_vel_b.timestamp = self._sim_timestamp + if self._root_com_ang_vel_b_ta is None: + self._root_com_ang_vel_b_ta = ProxyArray(self._root_com_ang_vel_b.data) + return self._root_com_ang_vel_b_ta + + """ + Sliced properties. + """ + + @property + def root_link_pos_w(self) -> ProxyArray: + """Root link position in simulation world frame. + Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). + + This quantity is the position of the actor frame of the root rigid body relative to the world. + """ + parent = self.root_link_pose_w + if self._root_link_pos_w_ta is None: + self._root_link_pos_w_ta = ProxyArray(self._get_pos_from_transform(parent.warp)) + return self._root_link_pos_w_ta + + @property + def root_link_quat_w(self) -> ProxyArray: + """Root link orientation (x, y, z, w) in simulation world frame. + Shape is (num_instances,), dtype = wp.quatf. In torch this resolves to (num_instances, 4). + + This quantity is the orientation of the actor frame of the root rigid body. + """ + parent = self.root_link_pose_w + if self._root_link_quat_w_ta is None: + self._root_link_quat_w_ta = ProxyArray(self._get_quat_from_transform(parent.warp)) + return self._root_link_quat_w_ta + + @property + def root_link_lin_vel_w(self) -> ProxyArray: + """Root linear velocity in simulation world frame [m/s]. + Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). + + This quantity is the linear velocity of the root rigid body's actor frame relative to the world. + """ + parent = self.root_link_vel_w + if self._root_link_lin_vel_w_ta is None: + self._root_link_lin_vel_w_ta = ProxyArray(self._get_lin_vel_from_spatial_vector(parent.warp)) + return self._root_link_lin_vel_w_ta + + @property + def root_link_ang_vel_w(self) -> ProxyArray: + """Root link angular velocity in simulation world frame [rad/s]. + Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). + + This quantity is the angular velocity of the actor frame of the root rigid body relative to the world. + """ + parent = self.root_link_vel_w + if self._root_link_ang_vel_w_ta is None: + self._root_link_ang_vel_w_ta = ProxyArray(self._get_ang_vel_from_spatial_vector(parent.warp)) + return self._root_link_ang_vel_w_ta + + @property + def root_com_pos_w(self) -> ProxyArray: + """Root center of mass position in simulation world frame. + Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). + + This quantity is the position of the center of mass frame of the root rigid body relative to the world. + """ + parent = self.root_com_pose_w + if self._root_com_pos_w_ta is None: + self._root_com_pos_w_ta = ProxyArray(self._get_pos_from_transform(parent.warp)) + return self._root_com_pos_w_ta + + @property + def root_com_quat_w(self) -> ProxyArray: + """Root center of mass orientation (x, y, z, w) in simulation world frame. + Shape is (num_instances,), dtype = wp.quatf. In torch this resolves to (num_instances, 4). + + This quantity is the orientation of the principal axes of inertia of the root rigid body relative to the world. + """ + parent = self.root_com_pose_w + if self._root_com_quat_w_ta is None: + self._root_com_quat_w_ta = ProxyArray(self._get_quat_from_transform(parent.warp)) + return self._root_com_quat_w_ta + + @property + def root_com_lin_vel_w(self) -> ProxyArray: + """Root center of mass linear velocity in simulation world frame [m/s]. + Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). + + This quantity is the linear velocity of the root rigid body's center of mass frame relative to the world. + """ + parent = self.root_com_vel_w + if self._root_com_lin_vel_w_ta is None: + self._root_com_lin_vel_w_ta = ProxyArray(self._get_lin_vel_from_spatial_vector(parent.warp)) + return self._root_com_lin_vel_w_ta + + @property + def root_com_ang_vel_w(self) -> ProxyArray: + """Root center of mass angular velocity in simulation world frame [rad/s]. + Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). + + This quantity is the angular velocity of the root rigid body's center of mass frame relative to the world. + """ + parent = self.root_com_vel_w + if self._root_com_ang_vel_w_ta is None: + self._root_com_ang_vel_w_ta = ProxyArray(self._get_ang_vel_from_spatial_vector(parent.warp)) + return self._root_com_ang_vel_w_ta + + @property + def body_link_pos_w(self) -> ProxyArray: + """Positions of all bodies in simulation world frame. + Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to + (num_instances, num_bodies, 3). + + This quantity is the position of the articulation bodies' actor frame relative to the world. + """ + parent = self.body_link_pose_w + if self._body_link_pos_w_ta is None: + self._body_link_pos_w_ta = ProxyArray(self._get_pos_from_transform(parent.warp)) + return self._body_link_pos_w_ta + + @property + def body_link_quat_w(self) -> ProxyArray: + """Orientation (x, y, z, w) of all bodies in simulation world frame. + Shape is (num_instances, num_bodies), dtype = wp.quatf. In torch this resolves to + (num_instances, num_bodies, 4). + + This quantity is the orientation of the articulation bodies' actor frame relative to the world. + """ + parent = self.body_link_pose_w + if self._body_link_quat_w_ta is None: + self._body_link_quat_w_ta = ProxyArray(self._get_quat_from_transform(parent.warp)) + return self._body_link_quat_w_ta + + @property + def body_link_lin_vel_w(self) -> ProxyArray: + """Linear velocity of all bodies in simulation world frame [m/s]. + Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to + (num_instances, num_bodies, 3). + + This quantity is the linear velocity of the articulation bodies' actor frame relative to the world. + """ + parent = self.body_link_vel_w + if self._body_link_lin_vel_w_ta is None: + self._body_link_lin_vel_w_ta = ProxyArray(self._get_lin_vel_from_spatial_vector(parent.warp)) + return self._body_link_lin_vel_w_ta + + @property + def body_link_ang_vel_w(self) -> ProxyArray: + """Angular velocity of all bodies in simulation world frame [rad/s]. + Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to + (num_instances, num_bodies, 3). + + This quantity is the angular velocity of the articulation bodies' actor frame relative to the world. + """ + parent = self.body_link_vel_w + if self._body_link_ang_vel_w_ta is None: + self._body_link_ang_vel_w_ta = ProxyArray(self._get_ang_vel_from_spatial_vector(parent.warp)) + return self._body_link_ang_vel_w_ta + + @property + def body_com_pos_w(self) -> ProxyArray: + """Positions of all bodies' center of mass in simulation world frame. + Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to + (num_instances, num_bodies, 3). + + This quantity is the position of the articulation bodies' center of mass frame. + """ + parent = self.body_com_pose_w + if self._body_com_pos_w_ta is None: + self._body_com_pos_w_ta = ProxyArray(self._get_pos_from_transform(parent.warp)) + return self._body_com_pos_w_ta + + @property + def body_com_quat_w(self) -> ProxyArray: + """Orientation (x, y, z, w) of the principal axes of inertia of all bodies in simulation world frame. + Shape is (num_instances, num_bodies), dtype = wp.quatf. In torch this resolves to + (num_instances, num_bodies, 4). + + This quantity is the orientation of the articulation bodies' principal axes of inertia. + """ + parent = self.body_com_pose_w + if self._body_com_quat_w_ta is None: + self._body_com_quat_w_ta = ProxyArray(self._get_quat_from_transform(parent.warp)) + return self._body_com_quat_w_ta + + @property + def body_com_lin_vel_w(self) -> ProxyArray: + """Linear velocity of all bodies in simulation world frame [m/s]. + Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to + (num_instances, num_bodies, 3). + + This quantity is the linear velocity of the articulation bodies' center of mass frame. + """ + parent = self.body_com_vel_w + if self._body_com_lin_vel_w_ta is None: + self._body_com_lin_vel_w_ta = ProxyArray(self._get_lin_vel_from_spatial_vector(parent.warp)) + return self._body_com_lin_vel_w_ta + + @property + def body_com_ang_vel_w(self) -> ProxyArray: + """Angular velocity of all bodies in simulation world frame [rad/s]. + Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to + (num_instances, num_bodies, 3). + + This quantity is the angular velocity of the articulation bodies' center of mass frame. + """ + parent = self.body_com_vel_w + if self._body_com_ang_vel_w_ta is None: + self._body_com_ang_vel_w_ta = ProxyArray(self._get_ang_vel_from_spatial_vector(parent.warp)) + return self._body_com_ang_vel_w_ta + + @property + def body_com_lin_acc_w(self) -> ProxyArray: + """Linear acceleration of all bodies in simulation world frame [m/s^2]. + Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to + (num_instances, num_bodies, 3). + + This quantity is the linear acceleration of the articulation bodies' center of mass frame. + """ + parent = self.body_com_acc_w + if self._body_com_lin_acc_w_ta is None: + self._body_com_lin_acc_w_ta = ProxyArray(self._get_lin_vel_from_spatial_vector(parent.warp)) + return self._body_com_lin_acc_w_ta + + @property + def body_com_ang_acc_w(self) -> ProxyArray: + """Angular acceleration of all bodies in simulation world frame [rad/s^2]. + Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to + (num_instances, num_bodies, 3). + + This quantity is the angular acceleration of the articulation bodies' center of mass frame. + """ + parent = self.body_com_acc_w + if self._body_com_ang_acc_w_ta is None: + self._body_com_ang_acc_w_ta = ProxyArray(self._get_ang_vel_from_spatial_vector(parent.warp)) + return self._body_com_ang_acc_w_ta + + @property + def body_com_pos_b(self) -> ProxyArray: + """Center of mass position of all of the bodies in their respective link frames. + Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to + (num_instances, num_bodies, 3). + + This quantity is the center of mass location relative to its body's link frame. + """ + parent = self.body_com_pose_b + if self._body_com_pos_b_ta is None: + self._body_com_pos_b_ta = ProxyArray(self._get_pos_from_transform(parent.warp)) + return self._body_com_pos_b_ta + + @property + def body_com_quat_b(self) -> ProxyArray: + """Orientation (x, y, z, w) of the principal axes of inertia of all of the bodies in their + respective link frames. + Shape is (num_instances, num_bodies), dtype = wp.quatf. In torch this resolves to + (num_instances, num_bodies, 4). + + This quantity is the orientation of the principal axes of inertia relative to its body's link frame. + """ + parent = self.body_com_pose_b + if self._body_com_quat_b_ta is None: + self._body_com_quat_b_ta = ProxyArray(self._get_quat_from_transform(parent.warp)) + return self._body_com_quat_b_ta + + """ + Deprecated in base class (required by ABC for backward compatibility). + """ + + @property + def default_root_state(self) -> ProxyArray: + """Deprecated. Use :attr:`default_root_pose` and :attr:`default_root_vel` instead.""" + warnings.warn( + "default_root_state is deprecated. Use default_root_pose and default_root_vel.", + DeprecationWarning, + stacklevel=2, + ) + if self._root_state_w_buf is None: + self._root_state_w_buf = wp.zeros( + self._num_instances, dtype=wp.types.vector(13, wp.float32), device=self.device + ) + if self._default_root_state_ta is None: + self._default_root_state_ta = ProxyArray(self._root_state_w_buf) + return self._default_root_state_ta + + @property + def root_state_w(self) -> ProxyArray: + """Deprecated. Use :attr:`root_link_pose_w` and :attr:`root_com_vel_w` instead.""" + warnings.warn( + "root_state_w is deprecated. Use root_link_pose_w and root_com_vel_w.", + DeprecationWarning, + stacklevel=2, + ) + return self.root_link_pose_w + + @property + def root_link_state_w(self) -> ProxyArray: + """Deprecated. Use :attr:`root_link_pose_w` and :attr:`root_link_vel_w` instead.""" + warnings.warn( + "root_link_state_w is deprecated. Use root_link_pose_w and root_link_vel_w.", + DeprecationWarning, + stacklevel=2, + ) + return self.root_link_pose_w + + @property + def root_com_state_w(self) -> ProxyArray: + """Deprecated. Use :attr:`root_com_pose_w` and :attr:`root_com_vel_w` instead.""" + warnings.warn( + "root_com_state_w is deprecated. Use root_com_pose_w and root_com_vel_w.", + DeprecationWarning, + stacklevel=2, + ) + return self.root_com_pose_w + + @property + def body_state_w(self) -> ProxyArray: + """Deprecated. Use :attr:`body_link_pose_w` and :attr:`body_com_vel_w` instead.""" + warnings.warn( + "body_state_w is deprecated. Use body_link_pose_w and body_com_vel_w.", + DeprecationWarning, + stacklevel=2, + ) + return self.body_link_pose_w + + @property + def body_link_state_w(self) -> ProxyArray: + """Deprecated. Use :attr:`body_link_pose_w` and :attr:`body_link_vel_w` instead.""" + warnings.warn( + "body_link_state_w is deprecated. Use body_link_pose_w and body_link_vel_w.", + DeprecationWarning, + stacklevel=2, + ) + return self.body_link_pose_w + + @property + def body_com_state_w(self) -> ProxyArray: + """Deprecated. Use :attr:`body_com_pose_w` and :attr:`body_com_vel_w` instead.""" + warnings.warn( + "body_com_state_w is deprecated. Use body_com_pose_w and body_com_vel_w.", + DeprecationWarning, + stacklevel=2, + ) + return self.body_com_pose_w + + """ + Internal helper. + """ + + def _create_buffers(self) -> None: # noqa: C901 + super()._create_buffers() + # Scratch buffers for _read_binding_into_* methods, allocated lazily + # on first use and reused every subsequent step to avoid per-step + # allocation overhead on the hot RL path. + self._read_scratch: dict = {} + + N = self._num_instances + D = self._num_joints + L = self._num_bodies + dev = self.device + + # -- Root state buffers + self._root_link_pose_w = TimestampedBuffer(N, dev, wp.transformf) + self._root_link_vel_w = TimestampedBuffer(N, dev, wp.spatial_vectorf) + self._root_com_pose_w = TimestampedBuffer(N, dev, wp.transformf) + self._root_com_vel_w = TimestampedBuffer(N, dev, wp.spatial_vectorf) + + # -- Body state buffers + self._body_link_pose_w = TimestampedBuffer((N, L), dev, wp.transformf) + self._body_link_vel_w = TimestampedBuffer((N, L), dev, wp.spatial_vectorf) + self._body_com_pose_b = TimestampedBuffer((N, L), dev, wp.transformf) + self._body_com_pose_w = TimestampedBuffer((N, L), dev, wp.transformf) + self._body_com_vel_w = TimestampedBuffer((N, L), dev, wp.spatial_vectorf) + self._body_com_acc_w = TimestampedBuffer((N, L), dev, wp.spatial_vectorf) + # -- Joint state buffers + self._joint_pos_buf = TimestampedBuffer((N, D), dev, wp.float32) + self._joint_vel_buf = TimestampedBuffer((N, D), dev, wp.float32) + self._joint_acc = TimestampedBuffer((N, D), dev, wp.float32) + self._previous_joint_vel = wp.zeros((N, D), dtype=wp.float32, device=dev) + + # -- Joint properties + self._joint_stiffness = wp.zeros((N, D), dtype=wp.float32, device=dev) + self._joint_damping = wp.zeros((N, D), dtype=wp.float32, device=dev) + self._joint_armature = wp.zeros((N, D), dtype=wp.float32, device=dev) + self._joint_friction_coeff = wp.zeros((N, D), dtype=wp.float32, device=dev) + self._joint_pos_limits = wp.zeros((N, D), dtype=wp.vec2f, device=dev) + self._joint_vel_limits = wp.zeros((N, D), dtype=wp.float32, device=dev) + self._joint_effort_limits = wp.zeros((N, D), dtype=wp.float32, device=dev) + + # -- Body properties + self._body_mass = wp.zeros((N, L), dtype=wp.float32, device=dev) + self._body_inertia = wp.zeros((N, L, 9), dtype=wp.float32, device=dev) + + # -- Soft limits / custom properties + self._soft_joint_pos_limits = wp.zeros((N, D), dtype=wp.vec2f, device=dev) + self._soft_joint_vel_limits = wp.zeros((N, D), dtype=wp.float32, device=dev) + self._gear_ratio = wp.ones((N, D), dtype=wp.float32, device=dev) + + # -- Command buffers + self._joint_pos_target = wp.zeros((N, D), dtype=wp.float32, device=dev) + self._joint_vel_target = wp.zeros((N, D), dtype=wp.float32, device=dev) + self._joint_effort_target = wp.zeros((N, D), dtype=wp.float32, device=dev) + self._computed_torque = wp.zeros((N, D), dtype=wp.float32, device=dev) + self._applied_torque = wp.zeros((N, D), dtype=wp.float32, device=dev) + + # -- Default state + self._default_root_pose = wp.zeros(N, dtype=wp.transformf, device=dev) + self._default_root_vel = wp.zeros(N, dtype=wp.spatial_vectorf, device=dev) + self._default_joint_pos = wp.zeros((N, D), dtype=wp.float32, device=dev) + self._default_joint_vel = wp.zeros((N, D), dtype=wp.float32, device=dev) + + # -- Derived property buffers + self._projected_gravity_b = TimestampedBuffer(N, dev, wp.vec3f) + self._heading_w = TimestampedBuffer(N, dev, wp.float32) + self._root_link_lin_vel_b = TimestampedBuffer(N, dev, wp.vec3f) + self._root_link_ang_vel_b = TimestampedBuffer(N, dev, wp.vec3f) + self._root_com_lin_vel_b = TimestampedBuffer(N, dev, wp.vec3f) + self._root_com_ang_vel_b = TimestampedBuffer(N, dev, wp.vec3f) + + # -- Deprecated combined state buffers + self._root_state_w_buf = None + self._root_link_state_w_buf = None + self._root_com_state_w_buf = None + self._body_state_w_buf = None + self._body_link_state_w_buf = None + self._body_com_state_w_buf = None + + # -- Tendon property buffers + T_fix = getattr(self, "_num_fixed_tendons", 0) + T_spa = getattr(self, "_num_spatial_tendons", 0) + if T_fix > 0: + self._fixed_tendon_stiffness = wp.zeros((N, T_fix), dtype=wp.float32, device=dev) + self._fixed_tendon_damping = wp.zeros((N, T_fix), dtype=wp.float32, device=dev) + self._fixed_tendon_limit_stiffness = wp.zeros((N, T_fix), dtype=wp.float32, device=dev) + self._fixed_tendon_rest_length = wp.zeros((N, T_fix), dtype=wp.float32, device=dev) + self._fixed_tendon_offset = wp.zeros((N, T_fix), dtype=wp.float32, device=dev) + self._fixed_tendon_pos_limits = wp.zeros((N, T_fix), dtype=wp.vec2f, device=dev) + else: + self._fixed_tendon_stiffness = None + self._fixed_tendon_damping = None + self._fixed_tendon_limit_stiffness = None + self._fixed_tendon_rest_length = None + self._fixed_tendon_offset = None + self._fixed_tendon_pos_limits = None + if T_spa > 0: + self._spatial_tendon_stiffness = wp.zeros((N, T_spa), dtype=wp.float32, device=dev) + self._spatial_tendon_damping = wp.zeros((N, T_spa), dtype=wp.float32, device=dev) + self._spatial_tendon_limit_stiffness = wp.zeros((N, T_spa), dtype=wp.float32, device=dev) + self._spatial_tendon_offset = wp.zeros((N, T_spa), dtype=wp.float32, device=dev) + else: + self._spatial_tendon_stiffness = None + self._spatial_tendon_damping = None + self._spatial_tendon_limit_stiffness = None + self._spatial_tendon_offset = None + + # Read initial joint properties from bindings + self._read_initial_properties() + + # Initialize ProxyArray wrappers (lazily created on first access) + self._pin_proxy_arrays() + + def _read_initial_properties(self) -> None: + """Read static/initial joint and body properties from ovphysx bindings. + + These are one-time reads at init. Property tensors (stiffness, + damping, limits, mass, etc.) are CPU-resident in PhysX even in GPU + mode, so we read them via CPU numpy buffers and then copy to the + simulation device. + """ + + # Property reads always use CPU numpy (property tensors are host-side). + def _read_cpu(tensor_type): + binding = self._get_binding(tensor_type) + if binding is None: + return None + np_buf = np.zeros(binding.shape, dtype=np.float32) + binding.read(np_buf) + return np_buf + + for tt, dst in [ + (TT.DOF_STIFFNESS, self._joint_stiffness), + (TT.DOF_DAMPING, self._joint_damping), + (TT.DOF_ARMATURE, self._joint_armature), + (TT.DOF_MAX_VELOCITY, self._joint_vel_limits), + (TT.DOF_MAX_FORCE, self._joint_effort_limits), + (TT.BODY_MASS, self._body_mass), + ]: + np_buf = _read_cpu(tt) + if np_buf is not None: + wp.copy(dst, wp.from_numpy(np_buf, dtype=wp.float32, device=self.device)) + + # Joint position limits: [N, D, 2] -> (N, D) wp.vec2f + np_lim = _read_cpu(TT.DOF_LIMIT) + if np_lim is not None: + self._joint_pos_limits = wp.from_numpy( + np_lim.reshape(self._num_instances, self._num_joints, 2), dtype=wp.vec2f, device=self.device + ) + + # Body inertia: [N, L, 9] + np_iner = _read_cpu(TT.BODY_INERTIA) + if np_iner is not None: + self._body_inertia = wp.from_numpy(np_iner, dtype=wp.float32, device=self.device) + + # Friction: [N, D, 3] -> extract static friction (column 0) + np_fric = _read_cpu(TT.DOF_FRICTION_PROPERTIES) + if np_fric is not None: + self._joint_friction_coeff = wp.from_numpy(np_fric[..., 0].copy(), dtype=wp.float32, device=self.device) + + # Fixed tendon properties (CPU-side, read once) + T_fix = getattr(self, "_num_fixed_tendons", 0) + if T_fix > 0: + for tt, dst in [ + (TT.FIXED_TENDON_STIFFNESS, self._fixed_tendon_stiffness), + (TT.FIXED_TENDON_DAMPING, self._fixed_tendon_damping), + (TT.FIXED_TENDON_LIMIT_STIFFNESS, self._fixed_tendon_limit_stiffness), + (TT.FIXED_TENDON_REST_LENGTH, self._fixed_tendon_rest_length), + (TT.FIXED_TENDON_OFFSET, self._fixed_tendon_offset), + ]: + np_buf = _read_cpu(tt) + if np_buf is not None and dst is not None: + wp.copy(dst, wp.from_numpy(np_buf, dtype=wp.float32, device=self.device)) + # Fixed tendon limits: [N, T, 2] -> (N, T) wp.vec2f + np_tlim = _read_cpu(TT.FIXED_TENDON_LIMIT) + if np_tlim is not None and self._fixed_tendon_pos_limits is not None: + self._fixed_tendon_pos_limits = wp.from_numpy( + np_tlim.reshape(self._num_instances, T_fix, 2), dtype=wp.vec2f, device=self.device + ) + + # Spatial tendon properties (CPU-side, read once) + T_spa = getattr(self, "_num_spatial_tendons", 0) + if T_spa > 0: + for tt, dst in [ + (TT.SPATIAL_TENDON_STIFFNESS, self._spatial_tendon_stiffness), + (TT.SPATIAL_TENDON_DAMPING, self._spatial_tendon_damping), + (TT.SPATIAL_TENDON_LIMIT_STIFFNESS, self._spatial_tendon_limit_stiffness), + (TT.SPATIAL_TENDON_OFFSET, self._spatial_tendon_offset), + ]: + np_buf = _read_cpu(tt) + if np_buf is not None and dst is not None: + wp.copy(dst, wp.from_numpy(np_buf, dtype=wp.float32, device=self.device)) + + def _pin_proxy_arrays(self) -> None: + """Create pinned ProxyArray wrappers for all data buffers. + + This is called once from :meth:`_create_buffers` during initialization. + All ``_ta`` fields are lazily populated on first property access. + """ + # -- Pinned ProxyArray cache (one per read property, lazily created on first access) + # Defaults + self._default_root_pose_ta: ProxyArray | None = None + self._default_root_vel_ta: ProxyArray | None = None + self._default_joint_pos_ta: ProxyArray | None = None + self._default_joint_vel_ta: ProxyArray | None = None + # Joint commands (set into simulation) + self._joint_pos_target_ta: ProxyArray | None = None + self._joint_vel_target_ta: ProxyArray | None = None + self._joint_effort_target_ta: ProxyArray | None = None + # Joint commands (explicit actuator model) + self._computed_torque_ta: ProxyArray | None = None + self._applied_torque_ta: ProxyArray | None = None + # Joint properties + self._joint_stiffness_ta: ProxyArray | None = None + self._joint_damping_ta: ProxyArray | None = None + self._joint_armature_ta: ProxyArray | None = None + self._joint_friction_coeff_ta: ProxyArray | None = None + self._joint_pos_limits_ta: ProxyArray | None = None + self._joint_vel_limits_ta: ProxyArray | None = None + self._joint_effort_limits_ta: ProxyArray | None = None + # Joint properties (custom) + self._soft_joint_pos_limits_ta: ProxyArray | None = None + self._soft_joint_vel_limits_ta: ProxyArray | None = None + self._gear_ratio_ta: ProxyArray | None = None + # Fixed tendon properties + self._fixed_tendon_stiffness_ta: ProxyArray | None = None + self._fixed_tendon_damping_ta: ProxyArray | None = None + self._fixed_tendon_limit_stiffness_ta: ProxyArray | None = None + self._fixed_tendon_rest_length_ta: ProxyArray | None = None + self._fixed_tendon_offset_ta: ProxyArray | None = None + self._fixed_tendon_pos_limits_ta: ProxyArray | None = None + # Spatial tendon properties + self._spatial_tendon_stiffness_ta: ProxyArray | None = None + self._spatial_tendon_damping_ta: ProxyArray | None = None + self._spatial_tendon_limit_stiffness_ta: ProxyArray | None = None + self._spatial_tendon_offset_ta: ProxyArray | None = None + # Root state (timestamped) + self._root_link_pose_w_ta: ProxyArray | None = None + self._root_link_vel_w_ta: ProxyArray | None = None + self._root_com_pose_w_ta: ProxyArray | None = None + self._root_com_vel_w_ta: ProxyArray | None = None + # Body state (timestamped) + self._body_link_pose_w_ta: ProxyArray | None = None + self._body_link_vel_w_ta: ProxyArray | None = None + self._body_com_pose_w_ta: ProxyArray | None = None + self._body_com_acc_w_ta: ProxyArray | None = None + self._body_com_pose_b_ta: ProxyArray | None = None + # Body properties + self._body_mass_ta: ProxyArray | None = None + self._body_inertia_ta: ProxyArray | None = None + # Joint state (timestamped) + self._joint_pos_ta: ProxyArray | None = None + self._joint_vel_ta: ProxyArray | None = None + self._joint_acc_ta: ProxyArray | None = None + # Derived properties (timestamped) + self._projected_gravity_b_ta: ProxyArray | None = None + self._heading_w_ta: ProxyArray | None = None + self._root_link_lin_vel_b_ta: ProxyArray | None = None + self._root_link_ang_vel_b_ta: ProxyArray | None = None + self._root_com_lin_vel_b_ta: ProxyArray | None = None + self._root_com_ang_vel_b_ta: ProxyArray | None = None + # Sliced properties (root link) + self._root_link_pos_w_ta: ProxyArray | None = None + self._root_link_quat_w_ta: ProxyArray | None = None + self._root_link_lin_vel_w_ta: ProxyArray | None = None + self._root_link_ang_vel_w_ta: ProxyArray | None = None + # Sliced properties (root com) + self._root_com_pos_w_ta: ProxyArray | None = None + self._root_com_quat_w_ta: ProxyArray | None = None + self._root_com_lin_vel_w_ta: ProxyArray | None = None + self._root_com_ang_vel_w_ta: ProxyArray | None = None + # Sliced properties (body link) + self._body_link_pos_w_ta: ProxyArray | None = None + self._body_link_quat_w_ta: ProxyArray | None = None + self._body_link_lin_vel_w_ta: ProxyArray | None = None + self._body_link_ang_vel_w_ta: ProxyArray | None = None + # Sliced properties (body com) + self._body_com_pos_w_ta: ProxyArray | None = None + self._body_com_quat_w_ta: ProxyArray | None = None + self._body_com_lin_vel_w_ta: ProxyArray | None = None + self._body_com_ang_vel_w_ta: ProxyArray | None = None + self._body_com_lin_acc_w_ta: ProxyArray | None = None + self._body_com_ang_acc_w_ta: ProxyArray | None = None + # Sliced properties (body com in body frame) + self._body_com_pos_b_ta: ProxyArray | None = None + self._body_com_quat_b_ta: ProxyArray | None = None + # Deprecated state-concat properties + self._default_root_state_ta: ProxyArray | None = None + + """ + Internal helpers -- Bindings. + """ + + def _get_binding(self, tensor_type: int): + """Return a binding, lazily creating it if a binding_getter was provided.""" + b = self._bindings.get(tensor_type) + if b is not None: + return b + if self._binding_getter is not None: + b = self._binding_getter(tensor_type) + if b is not None: + self._bindings[tensor_type] = b + return b + return None + + def _get_read_scratch(self, tensor_type: int) -> wp.array | None: + """Return a pre-allocated flat float32 scratch buffer for a binding. + + Allocated once on first use, then reused every step. CPU-only + bindings (body properties, DOF properties) get CPU scratch; GPU + bindings get GPU scratch. wp.copy handles cross-device transfer + when the destination buffer lives on a different device. + """ + if tensor_type in self._read_scratch: + return self._read_scratch[tensor_type] + binding = self._get_binding(tensor_type) + if binding is None: + return None + from isaaclab_ovphysx.tensor_types import _CPU_ONLY_TYPES + + dev = "cpu" if tensor_type in _CPU_ONLY_TYPES else self.device + buf = wp.zeros(binding.shape, dtype=wp.float32, device=dev) + self._read_scratch[tensor_type] = buf + return buf + + def _get_read_view(self, tensor_type: int, wp_array: wp.array, floats_per_elem: int = 0) -> wp.array | None: + """Return a stable float32 view of a warp buffer for reading from a binding. + + For structured-dtype buffers (transformf, spatial_vectorf), the view + reinterprets the same GPU memory as a flat float32 array matching the + binding's shape. For plain float32 buffers, returns the array as-is. + + The returned view is cached so that ``binding.read(view)`` sees the + same object on every call, enabling the binding's internal read cache. + """ + if not hasattr(self, "_read_view_cache"): + self._read_view_cache = {} + cache_key = (tensor_type, wp_array.ptr) + cached = self._read_view_cache.get(cache_key) + if cached is not None: + return cached + + binding = self._get_binding(tensor_type) + if binding is None: + self._read_view_cache[cache_key] = None + return None + + if floats_per_elem > 0: + view = wp.array( + ptr=wp_array.ptr, + shape=binding.shape, + dtype=wp.float32, + device=str(wp_array.device), + copy=False, + ) + else: + view = wp_array + + self._read_view_cache[cache_key] = view + return view + + def _read_binding_into_flat(self, tensor_type: int, wp_array: wp.array) -> None: + """Read a flat binding (no structured dtype) into an existing warp array. + + Reads directly into the target array -- no scratch buffer, no extra copy. + """ + binding = self._get_binding(tensor_type) + if binding is None: + return + binding.read(wp_array) + + def _read_binding_into_buf(self, tensor_type: int, buf: TimestampedBuffer) -> None: + """Read from an ovphysx binding into a TimestampedBuffer, skipping if fresh.""" + if buf.timestamp >= self._sim_timestamp: + return + view = self._get_read_view(tensor_type, buf.data) + if view is None: + return + self._get_binding(tensor_type).read(view) + buf.timestamp = self._sim_timestamp + + def _read_transform_binding(self, tensor_type: int, buf: TimestampedBuffer) -> None: + """Read a pose binding (float32 view of transformf buffer), skipping if fresh.""" + if buf.timestamp >= self._sim_timestamp: + return + view = self._get_read_view(tensor_type, buf.data, 7) + if view is None: + return + self._get_binding(tensor_type).read(view) + buf.timestamp = self._sim_timestamp + + def _read_spatial_vector_binding(self, tensor_type: int, buf: TimestampedBuffer) -> None: + """Read a velocity binding (float32 view of spatial_vectorf buffer), skipping if fresh.""" + if buf.timestamp >= self._sim_timestamp: + return + view = self._get_read_view(tensor_type, buf.data, 6) + if view is None: + return + self._get_binding(tensor_type).read(view) + buf.timestamp = self._sim_timestamp + + """ + Internal helpers -- Extraction. + """ + + def _get_pos_from_transform(self, transform: wp.array) -> wp.array: + return wp.array( + ptr=transform.ptr, + shape=transform.shape, + dtype=wp.vec3f, + strides=transform.strides, + device=self.device, + ) + + def _get_quat_from_transform(self, transform: wp.array) -> wp.array: + return wp.array( + ptr=transform.ptr + 3 * 4, + shape=transform.shape, + dtype=wp.quatf, + strides=transform.strides, + device=self.device, + ) + + def _get_lin_vel_from_spatial_vector(self, sv: wp.array) -> wp.array: + return wp.array( + ptr=sv.ptr, + shape=sv.shape, + dtype=wp.vec3f, + strides=sv.strides, + device=self.device, + ) + + def _get_ang_vel_from_spatial_vector(self, sv: wp.array) -> wp.array: + return wp.array( + ptr=sv.ptr + 3 * 4, + shape=sv.shape, + dtype=wp.vec3f, + strides=sv.strides, + device=self.device, + ) diff --git a/source/isaaclab_ovphysx/isaaclab_ovphysx/assets/articulation/kernels.py b/source/isaaclab_ovphysx/isaaclab_ovphysx/assets/articulation/kernels.py new file mode 100644 index 000000000000..b93c4e6d4b41 --- /dev/null +++ b/source/isaaclab_ovphysx/isaaclab_ovphysx/assets/articulation/kernels.py @@ -0,0 +1,217 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Warp kernels for the ovphysx articulation.""" + +import warp as wp + + +@wp.kernel +def _body_wrench_to_world( + force_b: wp.array(dtype=wp.vec3f, ndim=2), + torque_b: wp.array(dtype=wp.vec3f, ndim=2), + poses: wp.array(dtype=wp.transformf, ndim=2), + wrench_out: wp.array(dtype=wp.float32, ndim=3), +): + """Rotate body-frame force/torque to world frame and pack into [N, L, 9].""" + i, j = wp.tid() + q = wp.transform_get_rotation(poses[i, j]) + f_w = wp.quat_rotate(q, force_b[i, j]) + t_w = wp.quat_rotate(q, torque_b[i, j]) + wrench_out[i, j, 0] = f_w[0] + wrench_out[i, j, 1] = f_w[1] + wrench_out[i, j, 2] = f_w[2] + wrench_out[i, j, 3] = t_w[0] + wrench_out[i, j, 4] = t_w[1] + wrench_out[i, j, 5] = t_w[2] + p_w = wp.transform_get_translation(poses[i, j]) + wrench_out[i, j, 6] = p_w[0] + wrench_out[i, j, 7] = p_w[1] + wrench_out[i, j, 8] = p_w[2] + + +@wp.kernel +def _scatter_rows_partial( + dst: wp.array2d(dtype=wp.float32), + src: wp.array2d(dtype=wp.float32), + ids: wp.array(dtype=wp.int32), +): + """dst[ids[i], j] = src[i, j] -- scatter partial [K,C] into full [N,C] on GPU.""" + i, j = wp.tid() + dst[ids[i], j] = src[i, j] + + +@wp.func +def compute_soft_joint_pos_limits_func( + joint_pos_limits: wp.vec2f, + soft_limit_factor: wp.float32, +): + """Compute soft joint position limits from hard limits.""" + joint_pos_mean = (joint_pos_limits[0] + joint_pos_limits[1]) / 2.0 + joint_pos_range = joint_pos_limits[1] - joint_pos_limits[0] + return wp.vec2f( + joint_pos_mean - 0.5 * joint_pos_range * soft_limit_factor, + joint_pos_mean + 0.5 * joint_pos_range * soft_limit_factor, + ) + + +@wp.kernel +def update_soft_joint_pos_limits( + joint_pos_limits: wp.array2d(dtype=wp.vec2f), + soft_limit_factor: wp.float32, + soft_joint_pos_limits: wp.array2d(dtype=wp.vec2f), +): + """Update soft joint position limits from hard limits and a scale factor.""" + i, j = wp.tid() + soft_joint_pos_limits[i, j] = compute_soft_joint_pos_limits_func(joint_pos_limits[i, j], soft_limit_factor) + + +""" +Data-layer kernels (used by ArticulationData). +""" + + +@wp.kernel +def _fd_joint_acc( + cur_vel: wp.array2d(dtype=wp.float32), + prev_vel: wp.array2d(dtype=wp.float32), + inv_dt: float, + out: wp.array2d(dtype=wp.float32), +): + """Compute joint acceleration via finite differencing and update previous velocity. + + Args: + cur_vel: Current joint velocities. Shape is (num_envs, num_joints). + prev_vel: Previous joint velocities (updated in-place). Shape is (num_envs, num_joints). + inv_dt: Inverse time step (1/dt) [1/s]. + out: Output joint accelerations. Shape is (num_envs, num_joints). + """ + i, j = wp.tid() + out[i, j] = (cur_vel[i, j] - prev_vel[i, j]) * inv_dt + prev_vel[i, j] = cur_vel[i, j] + + +@wp.kernel +def _copy_first_body( + body_vel: wp.array(dtype=wp.spatial_vectorf, ndim=2), + root_vel: wp.array(dtype=wp.spatial_vectorf), +): + """Copy the first body's velocity to the root velocity buffer. + + Args: + body_vel: Body velocities. Shape is (num_envs, num_bodies). + root_vel: Output root velocities. Shape is (num_envs,). + """ + i = wp.tid() + root_vel[i] = body_vel[i, 0] + + +@wp.kernel +def _compose_root_com_pose( + link_pose: wp.array(dtype=wp.transformf), + com_pose_b: wp.array(dtype=wp.transformf, ndim=2), + com_pose_w: wp.array(dtype=wp.transformf), +): + """Compose root link pose with body-frame CoM offset to get world-frame root CoM pose. + + Args: + link_pose: Root link poses in world frame. Shape is (num_envs,). + com_pose_b: Body-frame CoM offsets. Shape is (num_envs, num_bodies). + com_pose_w: Output world-frame root CoM poses. Shape is (num_envs,). + """ + i = wp.tid() + com_pose_w[i] = wp.transform_multiply(link_pose[i], com_pose_b[i, 0]) + + +@wp.kernel +def _compose_body_com_poses( + link_pose: wp.array(dtype=wp.transformf, ndim=2), + com_pose_b: wp.array(dtype=wp.transformf, ndim=2), + com_pose_w: wp.array(dtype=wp.transformf, ndim=2), +): + """Compose body link poses with body-frame CoM offsets to get world-frame CoM poses. + + Args: + link_pose: Body link poses in world frame. Shape is (num_envs, num_bodies). + com_pose_b: Body-frame CoM offsets. Shape is (num_envs, num_bodies). + com_pose_w: Output world-frame body CoM poses. Shape is (num_envs, num_bodies). + """ + i, j = wp.tid() + com_pose_w[i, j] = wp.transform_multiply(link_pose[i, j], com_pose_b[i, j]) + + +@wp.kernel +def _projected_gravity( + gravity_vec_w: wp.array(dtype=wp.vec3f), + root_pose: wp.array(dtype=wp.transformf), + out: wp.array(dtype=wp.vec3f), +): + """Project world-frame gravity direction into the root body frame. + + Args: + gravity_vec_w: Gravity unit vector per instance in world frame. Shape is (num_envs,). + root_pose: Root link poses in world frame. Shape is (num_envs,). + out: Output projected gravity in body frame. Shape is (num_envs,). + """ + i = wp.tid() + q = wp.transform_get_rotation(root_pose[i]) + out[i] = wp.quat_rotate_inv(q, gravity_vec_w[i]) + + +@wp.kernel +def _compute_heading( + forward_vec_b: wp.array(dtype=wp.vec3f), + root_pose: wp.array(dtype=wp.transformf), + out: wp.array(dtype=wp.float32), +): + """Compute yaw heading angle from the forward direction rotated into the world frame. + + Args: + forward_vec_b: Forward direction in body frame per instance. Shape is (num_envs,). + root_pose: Root link poses in world frame. Shape is (num_envs,). + out: Output heading angles [rad]. Shape is (num_envs,). + """ + i = wp.tid() + q = wp.transform_get_rotation(root_pose[i]) + forward = wp.quat_rotate(q, forward_vec_b[i]) + out[i] = wp.atan2(forward[1], forward[0]) + + +@wp.kernel +def _world_vel_to_body_lin( + root_pose: wp.array(dtype=wp.transformf), + vel_w: wp.array(dtype=wp.spatial_vectorf), + out: wp.array(dtype=wp.vec3f), +): + """Rotate world-frame linear velocity into the root body frame. + + Args: + root_pose: Root link poses in world frame. Shape is (num_envs,). + vel_w: Spatial velocities in world frame. Shape is (num_envs,). + out: Output linear velocity in body frame. Shape is (num_envs,). + """ + i = wp.tid() + q = wp.transform_get_rotation(root_pose[i]) + lin = wp.spatial_top(vel_w[i]) + out[i] = wp.quat_rotate_inv(q, lin) + + +@wp.kernel +def _world_vel_to_body_ang( + root_pose: wp.array(dtype=wp.transformf), + vel_w: wp.array(dtype=wp.spatial_vectorf), + out: wp.array(dtype=wp.vec3f), +): + """Rotate world-frame angular velocity into the root body frame. + + Args: + root_pose: Root link poses in world frame. Shape is (num_envs,). + vel_w: Spatial velocities in world frame. Shape is (num_envs,). + out: Output angular velocity in body frame. Shape is (num_envs,). + """ + i = wp.tid() + q = wp.transform_get_rotation(root_pose[i]) + ang = wp.spatial_bottom(vel_w[i]) + out[i] = wp.quat_rotate_inv(q, ang) diff --git a/source/isaaclab_ovphysx/isaaclab_ovphysx/cloner/__init__.py b/source/isaaclab_ovphysx/isaaclab_ovphysx/cloner/__init__.py new file mode 100644 index 000000000000..3b9a12007792 --- /dev/null +++ b/source/isaaclab_ovphysx/isaaclab_ovphysx/cloner/__init__.py @@ -0,0 +1,8 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from .ovphysx_replicate import ovphysx_replicate + +__all__ = ["ovphysx_replicate"] diff --git a/source/isaaclab_ovphysx/isaaclab_ovphysx/cloner/ovphysx_replicate.py b/source/isaaclab_ovphysx/isaaclab_ovphysx/cloner/ovphysx_replicate.py new file mode 100644 index 000000000000..7c46a6060b88 --- /dev/null +++ b/source/isaaclab_ovphysx/isaaclab_ovphysx/cloner/ovphysx_replicate.py @@ -0,0 +1,103 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""OvPhysX replication hook for IsaacLab's cloning pipeline. + +Called by :func:`isaaclab.cloner.clone_from_template` in place of the PhysX +or Newton replicators. Unlike those replicators, ovphysx.PhysX does not exist +yet at this point in the scene setup — it is created lazily on the first +:meth:`~isaaclab_ovphysx.physics.OvPhysxManager.reset` call. + +This function records a *pending clone* on :class:`OvPhysxManager`. When +:meth:`~isaaclab_ovphysx.physics.OvPhysxManager._warmup_and_load` eventually +creates the ``PhysX`` instance and loads the USD stage (which contains only +``env_0`` physics — env_1..N are empty Xform containers), it replays every +pending clone via ``physx.clone(source, targets)`` to create the remaining +environments entirely inside the physics runtime without touching USD. +""" + +from __future__ import annotations + +import torch + +from pxr import Usd + + +def ovphysx_replicate( + stage: Usd.Stage, + sources: list[str], + destinations: list[str], + env_ids: torch.Tensor, + mapping: torch.Tensor, + positions: torch.Tensor | None = None, + quaternions: torch.Tensor | None = None, + device: str = "cpu", +) -> None: + """Record a physics clone for later execution by OvPhysxManager. + + Translates the generic IsaacLab source/destination/mapping representation + into ``(source_path, [target_paths])`` pairs and registers them on + :class:`~isaaclab_ovphysx.physics.OvPhysxManager`. The actual + ``physx.clone()`` calls happen in ``_warmup_and_load()`` after the USD + stage has been loaded. + + The ``positions`` parameter contains the 2-D grid world positions for all + environments. They are forwarded to the C++ clone plugin so that the + parent Xform prim for each clone (e.g. ``/World/envs/env_N``) is placed at + the correct grid location in Fabric. The exported USD stage only contains + ``env_0``; without explicit positions all clone parents would be created at + the origin, causing all articulations to pile up and the GPU solver to + diverge on the first warmup step. + + Args: + stage: USD stage (not modified by this function). + sources: Source prim paths (one per prototype). + destinations: Destination path templates with ``"{}"`` for env index. + env_ids: Environment indices tensor. + mapping: ``(num_sources, num_envs)`` bool tensor; True selects which + environments receive each source. + positions: World (x, y, z) positions for every environment, shape + ``[num_envs, 3]``. Used to place clone parent Xform prims in + Fabric at correct grid locations. + quaternions: Ignored — orientations are set at first reset. + device: Torch device (unused; kept for API compatibility). + """ + # Deferred import to avoid circular dependency at module load time. + from isaaclab_ovphysx.physics.ovphysx_manager import OvPhysxManager + + for i, src in enumerate(sources): + active_env_ids = env_ids[mapping[i]].tolist() + + # Exclude the source environment from its own target list. + # physx.clone() is only needed for *other* envs; the source env_0 is + # already loaded from USD. We detect self by matching the source path + # against the destination template. + pre, _, suf = destinations[i].partition("{}") + self_env_id: int | None = None + candidate = src.removeprefix(pre).removesuffix(suf) + if candidate.isdigit(): + self_env_id = int(candidate) + + # Build parallel (targets, parent_positions) lists for non-self envs. + # parent_positions[j] is the world (x,y,z) for the parent Xform of + # targets[j] (e.g. /World/envs/env_N). These positions are passed to + # the C++ clone plugin so that env_N Xform prims — absent from the + # exported USD stage — are created at the correct 2-D grid location + # rather than the origin. Without this, all clones pile up at env_0's + # position during the warmup physics step and the GPU solver diverges. + targets: list[str] = [] + parent_positions: list[tuple[float, float, float]] = [] + for e in active_env_ids: + if e == self_env_id: + continue + targets.append(destinations[i].format(e)) + if positions is not None and e < len(positions): + pos = positions[e] + parent_positions.append((float(pos[0]), float(pos[1]), float(pos[2]))) + else: + parent_positions.append((0.0, 0.0, 0.0)) + + if targets: + OvPhysxManager.register_clone(src, targets, parent_positions) diff --git a/source/isaaclab_ovphysx/isaaclab_ovphysx/physics/__init__.py b/source/isaaclab_ovphysx/isaaclab_ovphysx/physics/__init__.py new file mode 100644 index 000000000000..853ebc18725a --- /dev/null +++ b/source/isaaclab_ovphysx/isaaclab_ovphysx/physics/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""OvPhysX physics manager implementation.""" + +from isaaclab.utils.module import lazy_export + +lazy_export() diff --git a/source/isaaclab_ovphysx/isaaclab_ovphysx/physics/__init__.pyi b/source/isaaclab_ovphysx/isaaclab_ovphysx/physics/__init__.pyi new file mode 100644 index 000000000000..bfae28a137eb --- /dev/null +++ b/source/isaaclab_ovphysx/isaaclab_ovphysx/physics/__init__.pyi @@ -0,0 +1,12 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +__all__ = [ + "OvPhysxManager", + "OvPhysxCfg", +] + +from .ovphysx_manager import OvPhysxManager +from .ovphysx_manager_cfg import OvPhysxCfg diff --git a/source/isaaclab_ovphysx/isaaclab_ovphysx/physics/ovphysx_manager.py b/source/isaaclab_ovphysx/isaaclab_ovphysx/physics/ovphysx_manager.py new file mode 100644 index 000000000000..9063078e45b3 --- /dev/null +++ b/source/isaaclab_ovphysx/isaaclab_ovphysx/physics/ovphysx_manager.py @@ -0,0 +1,330 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""OvPhysX Manager for Isaac Lab. + +This module manages an ovphysx-based physics simulation lifecycle without Kit dependencies. +It exports the current USD stage to disk, loads it into ovphysx, and steps the simulation +using the ovphysx C/Python API. +""" + +from __future__ import annotations + +import atexit +import logging +import os +import tempfile +from typing import TYPE_CHECKING, Any, ClassVar + +from isaaclab.physics import PhysicsEvent, PhysicsManager + +if TYPE_CHECKING: + from isaaclab.sim.simulation_context import SimulationContext + + from .ovphysx_manager_cfg import OvPhysxCfg + +__all__ = ["OvPhysxManager"] + +logger = logging.getLogger(__name__) + + +class OvPhysxManager(PhysicsManager): + """Manages an ovphysx-backed physics simulation lifecycle. + + Unlike PhysxManager, this manager does not depend on Kit, Carbonite, or the + Omniverse timeline. It drives the simulation entirely through the ovphysx + Python wheel. + + Lifecycle: initialize() -> reset() -> step() (repeated) -> close() + """ + + _cfg: ClassVar[OvPhysxCfg | None] = None + _physx: ClassVar[Any] = None # ovphysx.PhysX (lazy import) + _usd_handle: ClassVar[Any] = None + _stage_path: ClassVar[str | None] = None + _warmup_done: ClassVar[bool] = False + _tmp_dir: ClassVar[tempfile.TemporaryDirectory | None] = None + # Pending (source, targets, parent_positions) triples registered by + # ovphysx_replicate() before the PhysX instance exists. Replayed via + # physx.clone() in _warmup_and_load(). + # parent_positions is a list of (x, y, z) tuples — one per target. + _pending_clones: ClassVar[list[tuple[str, list[str], list[tuple[float, float, float]]]]] = [] + _atexit_registered: ClassVar[bool] = False + + @classmethod + def register_clone( + cls, source: str, targets: list[str], parent_positions: list[tuple[float, float, float]] | None = None + ) -> None: + """Register a (source, targets, parent_positions) triple for replay via physx.clone(). + + Called by :func:`~isaaclab_ovphysx.cloner.ovphysx_replicate` during + scene setup, before the PhysX instance exists. The clone operations + are executed in :meth:`_warmup_and_load` immediately after + ``physx.add_usd()``. + + Args: + source: Source prim path (env_0 articulation root). + targets: Target prim paths for env_1..N. + parent_positions: World positions (x, y, z) for each target's parent + Xform prim (e.g. /World/envs/env_N). When provided the clone + plugin sets those transforms in Fabric so all environments start + at their correct grid locations, preventing solver divergence + during the warmup step. + """ + cls._pending_clones.append((source, targets, parent_positions or [])) + + @classmethod + def initialize(cls, sim_context: SimulationContext) -> None: + """Initialize the physics manager with simulation context. + + This stores the config and device but does not create the ovphysx + instance yet -- the USD stage may not be fully populated at this point. + The actual creation happens lazily in :meth:`reset`. + """ + super().initialize(sim_context) + cls._warmup_done = False + cls._physx = None + cls._usd_handle = None + cls._stage_path = None + cls._pending_clones = [] + + @classmethod + def reset(cls, soft: bool = False) -> None: + """Reset physics simulation. + + On the first (non-soft) reset the method: + - Exports the current USD stage to a temp file + - Creates the ovphysx.PhysX instance + - Loads the exported USD + - Warms up GPU buffers (if on CUDA) + - Dispatches PHYSICS_READY + """ + if not soft: + if not cls._warmup_done: + cls._warmup_and_load() + cls.dispatch_event(PhysicsEvent.PHYSICS_READY, payload={}) + + @classmethod + def forward(cls) -> None: + """No-op -- ovphysx does not have a fabric/rendering pipeline.""" + pass + + @classmethod + def step(cls) -> None: + """Step the simulation by one physics timestep.""" + if cls._physx is None: + return + dt = cls.get_physics_dt() + sim_time = PhysicsManager._sim_time + cls._physx.step_sync(dt=dt, sim_time=sim_time) + PhysicsManager._sim_time += dt + + @classmethod + def close(cls) -> None: + """Release ovphysx resources and clean up.""" + cls._release_physx() + + cls._usd_handle = None + cls._stage_path = None + cls._warmup_done = False + + if cls._tmp_dir is not None: + cls._tmp_dir.cleanup() + cls._tmp_dir = None + + super().close() + + @classmethod + def _release_physx(cls) -> None: + """Release the ovphysx instance if it exists. Safe to call multiple times. + + With ovphysx<=0.3.7 and Kit's pxr in the same process, physx.release() + deadlocks due to dual-Carbonite static destructor races. Skip the + native release and let os._exit() (registered via atexit) terminate the + process; GPU resources are reclaimed by the driver. + """ + if cls._physx is not None: + cls._physx = None + + @classmethod + def get_physx_instance(cls) -> Any: + """Return the underlying ovphysx.PhysX instance (or None if not yet created).""" + return cls._physx + + # ------------------------------------------------------------------ + # Internal helpers + # ------------------------------------------------------------------ + + @classmethod + def _warmup_and_load(cls) -> None: + """Export the USD stage, create the ovphysx instance, and load the scene.""" + sim = PhysicsManager._sim + if sim is None: + raise RuntimeError("OvPhysxManager: SimulationContext is not set.") + + device_str = PhysicsManager._device + if "cuda" in device_str: + parts = device_str.split(":") + gpu_index = int(parts[1]) if len(parts) > 1 else 0 + ovphysx_device = "gpu" + else: + gpu_index = 0 + ovphysx_device = "cpu" + + scene_prim = sim.stage.GetPrimAtPath(sim.cfg.physics_prim_path) + if scene_prim.IsValid() and ovphysx_device == "gpu": + cls._configure_physx_scene_prim(scene_prim, PhysicsManager._cfg) + + # Export the current USD stage to a temporary file so ovphysx can load it. + cls._tmp_dir = tempfile.TemporaryDirectory(prefix="isaaclab_ovphysx_") + stage_file = os.path.join(cls._tmp_dir.name, "scene.usda") + sim.stage.Export(stage_file) + cls._stage_path = stage_file + logger.info("OvPhysxManager: exported USD stage to %s", stage_file) + + # HACK (temporary): hide pxr from sys.modules during ovphysx bootstrap. + # IsaacSim's pxr reports version 0.25.5 (pip convention) while ovphysx + # expects 25.11 (OpenUSD release convention). Hiding pxr causes + # ovphysx.check_usd_compatibility() to skip the Python-side version + # check. This should go away once ovphysx ships a namespaced USD + # copy with isolated symbols (same "import pxr" API, no collision). + import sys as _sys + + _hidden_pxr = {k: _sys.modules.pop(k) for k in list(_sys.modules) if k == "pxr" or k.startswith("pxr.")} + try: + import ovphysx as _ovphysx_bootstrap + + _ovphysx_bootstrap.bootstrap() + finally: + _sys.modules.update(_hidden_pxr) + + import ovphysx + + cls._physx = ovphysx.PhysX(device=ovphysx_device, gpu_index=gpu_index) + + # Without worker threads the stepper runs simulate()+fetchResults() + # synchronously, blocking the calling thread for the full GPU step time. + # + # COMPAT(ovphysx<=0.3.7): The public 0.3.7 wheel exposes typed config + # setters (set_config_int32 etc.) rather than the Carbonite-settings-based + # set_setting() added in newer internal builds. This guard keeps both + # working. REVERT once the public wheel ships set_setting(). + if hasattr(cls._physx, "set_setting"): + cls._physx.set_setting("/persistent/physics/numThreads", "8") + cls._physx.set_setting("/physics/physxDispatcher", "true") + cls._physx.set_setting("/physics/updateToUsd", "false") + cls._physx.set_setting("/physics/updateVelocitiesToUsd", "false") + cls._physx.set_setting("/physics/updateParticlesToUsd", "false") + else: + cls._physx.set_config_int32(ovphysx.ConfigInt32.NUM_THREADS, 8) + + # FIXME(malesiani): re-evaluate this when carbonite ships an isolated copy. + # At process exit, two Carbonite instances are in memory: + # 1. ovphysx's bundled libcarb.so (RPATH $ORIGIN/../plugins/) + # 2. kit's libcarb.so (pulled in via LD_LIBRARY_PATH by Fabric/usdrt plugins) + # + # Why does kit's libcarb end up here even though we skip AppLauncher? + # Note: AppLauncher always starts the full Kit runtime — even headless=True + # still loads Kit. "Kitless" in IsaacLab means AppLauncher is not used at all. + # But we still import `pxr` from IsaacSim's Kit USD build. The moment `import pxr` runs, the Kit USD + # runtime loads Fabric infrastructure (omni.physx.fabric.plugin, usdrt.population.plugin) + # from kit's plugin directories, which are on LD_LIBRARY_PATH via setup_python_env.sh. + # Those plugins link against kit's libcarb.so, so kit's Carbonite lands in memory + # purely from `import pxr`, regardless of whether the Kit App is launched. + # + # Both Carbonite instances register C++ static destructors. At process exit those + # destructors race and segfault. The workaround is to release ovphysx cleanly + # (so GPU resources are freed) and then call os._exit() to skip the static destructor + # phase entirely. os._exit() terminates the process without running C++ atexit + # handlers or static destructors, sidestepping the conflict. + # + # Proper long-term fix: ovphysx ships a fully namespace-isolated Carbonite + # (different soname / hidden visibility) so its symbols never collide with kit's. + if not cls._atexit_registered: + + def _atexit_release_and_exit(): + # Skip physx.release() -- it deadlocks due to dual-Carbonite + # static destructor races (ovphysx's bundled libcarb vs Kit's). + # GPU resources are reclaimed by the driver at process exit. + os._exit(0) + + atexit.register(_atexit_release_and_exit) + cls._atexit_registered = True + + usd_handle, op_idx = cls._physx.add_usd(stage_file) + cls._physx.wait_op(op_idx) + cls._usd_handle = usd_handle + logger.info("OvPhysxManager: loaded USD into ovphysx (device=%s)", ovphysx_device) + + # Replay pending physics clones registered by ovphysx_replicate(). + # The USD stage contains only env_0's physics; env_1..N are empty + # Xform containers. physx.clone() creates the remaining environments + # in the physics runtime without modifying the USD file. + if cls._pending_clones: + # ovphysx_replicate() only registers pending clones when clone_usd=False, + # meaning the USD contains only env_0 physics and physx.clone() is required + # to populate env_1..N in the physics runtime. Execute unconditionally — + # no USD content heuristic is needed. + for source, targets, parent_positions in cls._pending_clones: + logger.info( + "OvPhysxManager: cloning %s -> %d targets (%s ... %s)", + source, + len(targets), + targets[0], + targets[-1], + ) + if parent_positions: + transforms = [(x, y, z, 0.0, 0.0, 0.0, 1.0) for x, y, z in parent_positions] + else: + transforms = None + op_idx = cls._physx.clone(source, targets, transforms) + cls._physx.wait_op(op_idx) + cls._pending_clones = [] + + if ovphysx_device == "gpu": + cls._physx.warmup_gpu() + + cls.dispatch_event(PhysicsEvent.MODEL_INIT, payload={}) + cls._warmup_done = True + + @staticmethod + def _configure_physx_scene_prim(scene_prim, cfg) -> None: + """Apply PhysxSceneAPI schema and GPU dynamics attributes to a scene prim. + + The PhysxSchema USD plugin may not be loaded in standalone ovphysx mode, + so we write the apiSchemas list entry and scene attributes directly via + raw Sdf metadata manipulation instead of using the high-level USD API. + + Without these attributes PhysX defaults to CPU broadphase even when + ovphysx is created with device="gpu". + """ + from pxr import Sdf + + schemas = Sdf.TokenListOp() + current = scene_prim.GetMetadata("apiSchemas") or Sdf.TokenListOp() + items = list(current.prependedItems) if current.prependedItems else [] + if "PhysxSceneAPI" not in items: + items.append("PhysxSceneAPI") + schemas.prependedItems = items + scene_prim.SetMetadata("apiSchemas", schemas) + scene_prim.CreateAttribute("physxScene:enableGPUDynamics", Sdf.ValueTypeNames.Bool).Set(True) + scene_prim.CreateAttribute("physxScene:broadphaseType", Sdf.ValueTypeNames.String).Set("GPU") + + if cfg is not None: + for attr, val in [ + ("gpuMaxRigidContactCount", cfg.gpu_max_rigid_contact_count), + ("gpuMaxRigidPatchCount", cfg.gpu_max_rigid_patch_count), + ("gpuFoundLostPairsCapacity", cfg.gpu_found_lost_pairs_capacity), + ("gpuFoundLostAggregatePairsCapacity", cfg.gpu_found_lost_aggregate_pairs_capacity), + ("gpuTotalAggregatePairsCapacity", cfg.gpu_total_aggregate_pairs_capacity), + ("gpuCollisionStackSize", cfg.gpu_collision_stack_size), + ]: + scene_prim.CreateAttribute(f"physxScene:{attr}", Sdf.ValueTypeNames.UInt).Set(val) + + # Propagate scene query support from SimulationCfg so omni.physx creates + # the scene with the correct query mode. OvPhysxCfg does not carry this field. + sim_cfg = PhysicsManager._sim.cfg if PhysicsManager._sim is not None else None + enable_sq = getattr(sim_cfg, "enable_scene_query_support", False) + scene_prim.CreateAttribute("physxScene:enableSceneQuerySupport", Sdf.ValueTypeNames.Bool).Set(enable_sq) diff --git a/source/isaaclab_ovphysx/isaaclab_ovphysx/physics/ovphysx_manager_cfg.py b/source/isaaclab_ovphysx/isaaclab_ovphysx/physics/ovphysx_manager_cfg.py new file mode 100644 index 000000000000..c74dc56209ea --- /dev/null +++ b/source/isaaclab_ovphysx/isaaclab_ovphysx/physics/ovphysx_manager_cfg.py @@ -0,0 +1,41 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Configuration for the OvPhysX physics manager.""" + +from __future__ import annotations + +from isaaclab.physics import PhysicsCfg +from isaaclab.utils import configclass + + +@configclass +class OvPhysxCfg(PhysicsCfg): + """Configuration for the ovphysx physics manager. + + PhysX scene-level parameters (solver iterations, GPU buffer sizes, etc.) are + read from the USD PhysicsScene prim. Only ovphysx-specific settings that are + not captured in USD live here. + """ + + class_type = "{DIR}.ovphysx_manager:OvPhysxManager" + + gpu_max_rigid_contact_count: int = 2**23 + """Size of the GPU rigid-body contact buffer.""" + + gpu_max_rigid_patch_count: int = 5 * 2**15 + """Size of the GPU rigid-body patch buffer.""" + + gpu_found_lost_pairs_capacity: int = 2**21 + """Capacity for GPU found/lost broadphase pairs.""" + + gpu_found_lost_aggregate_pairs_capacity: int = 2**25 + """Capacity for GPU found/lost *aggregate* broadphase pairs.""" + + gpu_total_aggregate_pairs_capacity: int = 2**21 + """Capacity for total GPU aggregate broadphase pairs.""" + + gpu_collision_stack_size: int = 2**26 + """GPU collision stack size in bytes.""" diff --git a/source/isaaclab_ovphysx/isaaclab_ovphysx/tensor_types.py b/source/isaaclab_ovphysx/isaaclab_ovphysx/tensor_types.py new file mode 100644 index 000000000000..44a5cadeeb0a --- /dev/null +++ b/source/isaaclab_ovphysx/isaaclab_ovphysx/tensor_types.py @@ -0,0 +1,334 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""IsaacLab re-exports of ovphysx TensorType with short backward-compat aliases. + +Import TensorType directly for new code: + from ovphysx.types import TensorType + +Or use the module-level short aliases (existing code pattern): + import isaaclab_ovphysx.tensor_types as TT + TT.DOF_STIFFNESS # resolves to TensorType.ARTICULATION_DOF_STIFFNESS + +ovphysx.types is pure Python with zero native dependencies, so this module is +always safe to import regardless of USD state or native library loading. +""" + +from ovphysx.types import TensorType # noqa: F401 — re-exported for new code + +_TT = TensorType # shorter reference for alias block + +# Short aliases -- existing code using ``TT.DOF_STIFFNESS`` etc. continues to work. +# All values are IntEnum members (== plain ints) of TensorType. + +# fmt: off -- aligned columns are intentional; do not reformat + +""" +Root state (GPU) +""" + +ROOT_POSE = _TT.ARTICULATION_ROOT_POSE +"""Root pose of each articulation instance. + +Shape is ``[N, 7]``, dtype ``float32`` (px, py, pz, qx, qy, qz, qw). +""" + +ROOT_VELOCITY = _TT.ARTICULATION_ROOT_VELOCITY +"""Root velocity of each articulation instance. + +Shape is ``[N, 6]``, dtype ``float32`` (vx, vy, vz, wx, wy, wz). +""" + +""" +Link (body) state (GPU) +""" + +LINK_POSE = _TT.ARTICULATION_LINK_POSE +"""Pose of every link (body) in each articulation instance. + +Shape is ``[N, L, 7]``, dtype ``float32``. +""" + +LINK_VELOCITY = _TT.ARTICULATION_LINK_VELOCITY +"""Velocity of every link (body) in each articulation instance. + +Shape is ``[N, L, 6]``, dtype ``float32``. +""" + +LINK_ACCELERATION = _TT.ARTICULATION_LINK_ACCELERATION +"""Acceleration of every link (body) in each articulation instance. + +Shape is ``[N, L, 6]``, dtype ``float32``. +""" + +""" +DOF state (GPU) +""" + +DOF_POSITION = _TT.ARTICULATION_DOF_POSITION +"""DOF (joint) positions. + +Shape is ``[N, D]``, dtype ``float32`` [m or rad]. +""" + +DOF_VELOCITY = _TT.ARTICULATION_DOF_VELOCITY +"""DOF (joint) velocities. + +Shape is ``[N, D]``, dtype ``float32`` [m/s or rad/s]. +""" + +""" +DOF command targets (GPU, write-only) +""" + +DOF_POSITION_TARGET = _TT.ARTICULATION_DOF_POSITION_TARGET +"""DOF position targets for the PD controller. + +Shape is ``[N, D]``, dtype ``float32``. +""" + +DOF_VELOCITY_TARGET = _TT.ARTICULATION_DOF_VELOCITY_TARGET +"""DOF velocity targets for the PD controller. + +Shape is ``[N, D]``, dtype ``float32``. +""" + +DOF_ACTUATION_FORCE = _TT.ARTICULATION_DOF_ACTUATION_FORCE +"""DOF actuation (effort) forces applied directly. + +Shape is ``[N, D]``, dtype ``float32`` [N or N·m]. +""" + +""" +DOF properties (CPU) +""" + +DOF_STIFFNESS = _TT.ARTICULATION_DOF_STIFFNESS +"""DOF stiffness (spring constant for PD controller). + +Shape is ``[N, D]``, dtype ``float32``. +""" + +DOF_DAMPING = _TT.ARTICULATION_DOF_DAMPING +"""DOF damping (damper constant for PD controller). + +Shape is ``[N, D]``, dtype ``float32``. +""" + +DOF_LIMIT = _TT.ARTICULATION_DOF_LIMIT +"""DOF position limits (lower, upper). + +Shape is ``[N, D, 2]``, dtype ``float32``. +""" + +DOF_MAX_VELOCITY = _TT.ARTICULATION_DOF_MAX_VELOCITY +"""DOF maximum velocity. + +Shape is ``[N, D]``, dtype ``float32``. +""" + +DOF_MAX_FORCE = _TT.ARTICULATION_DOF_MAX_FORCE +"""DOF maximum force. + +Shape is ``[N, D]``, dtype ``float32``. +""" + +DOF_ARMATURE = _TT.ARTICULATION_DOF_ARMATURE +"""DOF armature (added inertia on the diagonal of the joint-space mass matrix). + +Shape is ``[N, D]``, dtype ``float32``. +""" + +DOF_FRICTION_PROPERTIES = _TT.ARTICULATION_DOF_FRICTION_PROPERTIES +"""DOF friction properties (static, dynamic, viscous). + +Shape is ``[N, D, 3]``, dtype ``float32``. +""" + +""" +External wrench (GPU, write-only) +""" + +LINK_WRENCH = _TT.ARTICULATION_LINK_WRENCH +"""External wrench applied to each link. + +Shape is ``[N, L, 9]``, dtype ``float32`` (fx, fy, fz, tx, ty, tz, px, py, pz). +""" + +""" +Body properties (CPU) +""" + +BODY_MASS = _TT.ARTICULATION_BODY_MASS +"""Mass of each body (link). + +Shape is ``[N, L]``, dtype ``float32`` [kg]. +""" + +BODY_COM_POSE = _TT.ARTICULATION_BODY_COM_POSE +"""Center-of-mass pose of each body in local frame. + +Shape is ``[N, L, 7]``, dtype ``float32``. +""" + +BODY_INERTIA = _TT.ARTICULATION_BODY_INERTIA +"""Inertia tensor of each body. + +Shape is ``[N, L, 9]``, dtype ``float32`` [kg·m^2]. +""" + +BODY_INV_MASS = _TT.ARTICULATION_BODY_INV_MASS +"""Inverse mass of each body. + +Shape is ``[N, L]``, dtype ``float32``. +""" + +BODY_INV_INERTIA = _TT.ARTICULATION_BODY_INV_INERTIA +"""Inverse inertia tensor of each body. + +Shape is ``[N, L, 9]``, dtype ``float32``. +""" + +""" +Dynamics tensors (GPU) +""" + +JACOBIAN = _TT.ARTICULATION_JACOBIAN +"""Jacobian matrix of each articulation instance. + +Shape is ``[N, L, 6, D+6]``, dtype ``float32``. +""" + +MASS_MATRIX = _TT.ARTICULATION_MASS_MATRIX +"""Generalized mass (inertia) matrix. + +Shape is ``[N, D+6, D+6]``, dtype ``float32``. +""" + +CORIOLIS = _TT.ARTICULATION_CORIOLIS_AND_CENTRIFUGAL_FORCE +"""Coriolis and centrifugal force vector. + +Shape is ``[N, D]``, dtype ``float32``. +""" + +GRAVITY_FORCE = _TT.ARTICULATION_GRAVITY_FORCE +"""Generalized gravity force vector. + +Shape is ``[N, D]``, dtype ``float32``. +""" + +""" +Joint force feedback (GPU) +""" + +LINK_INCOMING_JOINT_FORCE = _TT.ARTICULATION_LINK_INCOMING_JOINT_FORCE +"""Incoming joint force (constraint force) on each link. + +Shape is ``[N, L, 6]``, dtype ``float32``. +""" + +DOF_PROJECTED_JOINT_FORCE = _TT.ARTICULATION_DOF_PROJECTED_JOINT_FORCE +"""DOF-projected joint force. + +Shape is ``[N, D]``, dtype ``float32``. +""" + +""" +Fixed tendon properties (CPU) +""" + +FIXED_TENDON_STIFFNESS = _TT.ARTICULATION_FIXED_TENDON_STIFFNESS +"""Stiffness of each fixed tendon. + +Shape is ``[N, T_fix]``, dtype ``float32``. +""" + +FIXED_TENDON_DAMPING = _TT.ARTICULATION_FIXED_TENDON_DAMPING +"""Damping of each fixed tendon. + +Shape is ``[N, T_fix]``, dtype ``float32``. +""" + +FIXED_TENDON_LIMIT_STIFFNESS = _TT.ARTICULATION_FIXED_TENDON_LIMIT_STIFFNESS +"""Limit stiffness of each fixed tendon. + +Shape is ``[N, T_fix]``, dtype ``float32``. +""" + +FIXED_TENDON_LIMIT = _TT.ARTICULATION_FIXED_TENDON_LIMIT +"""Position limits of each fixed tendon (lower, upper). + +Shape is ``[N, T_fix, 2]``, dtype ``float32``. +""" + +FIXED_TENDON_REST_LENGTH = _TT.ARTICULATION_FIXED_TENDON_REST_LENGTH +"""Rest length of each fixed tendon. + +Shape is ``[N, T_fix]``, dtype ``float32``. +""" + +FIXED_TENDON_OFFSET = _TT.ARTICULATION_FIXED_TENDON_OFFSET +"""Offset of each fixed tendon. + +Shape is ``[N, T_fix]``, dtype ``float32``. +""" + +""" +Spatial tendon properties (CPU) +""" + +SPATIAL_TENDON_STIFFNESS = _TT.ARTICULATION_SPATIAL_TENDON_STIFFNESS +"""Stiffness of each spatial tendon. + +Shape is ``[N, T_spa]``, dtype ``float32``. +""" + +SPATIAL_TENDON_DAMPING = _TT.ARTICULATION_SPATIAL_TENDON_DAMPING +"""Damping of each spatial tendon. + +Shape is ``[N, T_spa]``, dtype ``float32``. +""" + +SPATIAL_TENDON_LIMIT_STIFFNESS = _TT.ARTICULATION_SPATIAL_TENDON_LIMIT_STIFFNESS +"""Limit stiffness of each spatial tendon. + +Shape is ``[N, T_spa]``, dtype ``float32``. +""" + +SPATIAL_TENDON_OFFSET = _TT.ARTICULATION_SPATIAL_TENDON_OFFSET +"""Offset of each spatial tendon. + +Shape is ``[N, T_spa]``, dtype ``float32``. +""" + +# fmt: on +# DOF/body property tensor types are CPU-resident even in GPU simulations. +# Write helpers check this set to route data through CPU, not self._device. +_CPU_ONLY_TYPES: frozenset[TensorType] = frozenset( + { + DOF_STIFFNESS, + DOF_DAMPING, + DOF_LIMIT, + DOF_MAX_VELOCITY, + DOF_MAX_FORCE, + DOF_ARMATURE, + DOF_FRICTION_PROPERTIES, + BODY_MASS, + BODY_COM_POSE, + BODY_INERTIA, + BODY_INV_MASS, + BODY_INV_INERTIA, + FIXED_TENDON_STIFFNESS, + FIXED_TENDON_DAMPING, + FIXED_TENDON_LIMIT_STIFFNESS, + FIXED_TENDON_LIMIT, + FIXED_TENDON_REST_LENGTH, + FIXED_TENDON_OFFSET, + SPATIAL_TENDON_STIFFNESS, + SPATIAL_TENDON_DAMPING, + SPATIAL_TENDON_LIMIT_STIFFNESS, + SPATIAL_TENDON_OFFSET, + } +) diff --git a/source/isaaclab_ovphysx/isaaclab_ovphysx/test/__init__.py b/source/isaaclab_ovphysx/isaaclab_ovphysx/test/__init__.py new file mode 100644 index 000000000000..460a30569089 --- /dev/null +++ b/source/isaaclab_ovphysx/isaaclab_ovphysx/test/__init__.py @@ -0,0 +1,4 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause diff --git a/source/isaaclab_ovphysx/isaaclab_ovphysx/test/mock_interfaces/__init__.py b/source/isaaclab_ovphysx/isaaclab_ovphysx/test/mock_interfaces/__init__.py new file mode 100644 index 000000000000..2c6c0e67ffc4 --- /dev/null +++ b/source/isaaclab_ovphysx/isaaclab_ovphysx/test/mock_interfaces/__init__.py @@ -0,0 +1,6 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from .views import MockTensorBinding, MockOvPhysxBindingSet diff --git a/source/isaaclab_ovphysx/isaaclab_ovphysx/test/mock_interfaces/views/__init__.py b/source/isaaclab_ovphysx/isaaclab_ovphysx/test/mock_interfaces/views/__init__.py new file mode 100644 index 000000000000..6f133a18202c --- /dev/null +++ b/source/isaaclab_ovphysx/isaaclab_ovphysx/test/mock_interfaces/views/__init__.py @@ -0,0 +1,6 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from .mock_ovphysx_bindings import MockTensorBinding, MockOvPhysxBindingSet diff --git a/source/isaaclab_ovphysx/isaaclab_ovphysx/test/mock_interfaces/views/mock_ovphysx_bindings.py b/source/isaaclab_ovphysx/isaaclab_ovphysx/test/mock_interfaces/views/mock_ovphysx_bindings.py new file mode 100644 index 000000000000..29472ce74fd0 --- /dev/null +++ b/source/isaaclab_ovphysx/isaaclab_ovphysx/test/mock_interfaces/views/mock_ovphysx_bindings.py @@ -0,0 +1,276 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Mock implementations of ovphysx TensorBinding objects for unit testing.""" + +from __future__ import annotations + +import numpy as np + +from isaaclab_ovphysx import tensor_types as TT + + +class MockTensorBinding: + """Mock of ovphysx.TensorBinding that stores data in numpy arrays. + + Mimics the real TensorBinding API: ``read(tensor)`` fills the tensor from + the internal buffer, ``write(tensor, indices, mask)`` copies into it. + """ + + def __init__( + self, + tensor_type: int, + shape: tuple[int, ...], + count: int, + dof_count: int = 0, + body_count: int = 0, + joint_count: int = 0, + is_fixed_base: bool = False, + dof_names: list[str] | None = None, + body_names: list[str] | None = None, + joint_names: list[str] | None = None, + fixed_tendon_count: int = 0, + spatial_tendon_count: int = 0, + write_only: bool = False, + ): + self.tensor_type = tensor_type + self._shape = shape + self._count = count + self._dof_count = dof_count + self._body_count = body_count + self._joint_count = joint_count + self._is_fixed_base = is_fixed_base + self._dof_names = dof_names or [] + self._body_names = body_names or [] + self._joint_names = joint_names or [] + self._fixed_tendon_count = fixed_tendon_count + self._spatial_tendon_count = spatial_tendon_count + self._write_only = write_only + self._data = np.zeros(shape, dtype=np.float32) + + @property + def shape(self) -> tuple[int, ...]: + return self._shape + + @property + def ndim(self) -> int: + return len(self._shape) + + @property + def count(self) -> int: + return self._count + + @property + def dof_count(self) -> int: + return self._dof_count + + @property + def body_count(self) -> int: + return self._body_count + + @property + def joint_count(self) -> int: + return self._joint_count + + @property + def is_fixed_base(self) -> bool: + return self._is_fixed_base + + @property + def dof_names(self) -> list[str]: + return self._dof_names + + @property + def body_names(self) -> list[str]: + return self._body_names + + @property + def joint_names(self) -> list[str]: + return self._joint_names + + @property + def fixed_tendon_count(self) -> int: + return self._fixed_tendon_count + + @property + def spatial_tendon_count(self) -> int: + return self._spatial_tendon_count + + def read(self, tensor) -> None: + """Copy internal data into the provided array (numpy or warp).""" + if self._write_only: + raise RuntimeError("write-only tensor binding does not support read()") + try: + import warp as wp + + if isinstance(tensor, wp.array): + tmp = wp.from_numpy(self._data, dtype=wp.float32, device=tensor.device) + wp.copy(tensor, tmp) + return + except ImportError: + pass + np_dst = np.asarray(tensor) + np.copyto(np_dst, self._data.reshape(np_dst.shape)) + + @staticmethod + def _to_numpy(arr) -> np.ndarray: + """Convert warp/torch/numpy array to numpy, handling GPU arrays.""" + try: + import warp as wp + + if isinstance(arr, wp.array): + return arr.numpy() + except ImportError: + pass + try: + import torch + + if isinstance(arr, torch.Tensor): + return arr.detach().cpu().numpy() + except ImportError: + pass + return np.asarray(arr) + + def write(self, tensor, indices=None, mask=None) -> None: + """Copy from the provided array (numpy or warp) into internal data.""" + np_src = self._to_numpy(tensor).astype(np.float32) + if indices is not None: + idx = self._to_numpy(indices) + if np_src.shape[0] == self._data.shape[0]: + self._data[idx] = np_src[idx] + else: + self._data[idx] = np_src.reshape(len(idx), *self._data.shape[1:]) + elif mask is not None: + np_mask = self._to_numpy(mask).astype(bool) + self._data[np_mask] = np_src[np_mask] + else: + np.copyto(self._data, np_src.reshape(self._data.shape)) + + def destroy(self) -> None: + pass + + def set_random_data(self, low: float = -1.0, high: float = 1.0) -> None: + """Fill internal buffer with random data.""" + self._data = np.random.uniform(low, high, self._shape).astype(np.float32) + + +class MockOvPhysxBindingSet: + """Factory that creates a full set of MockTensorBinding objects + for a given articulation configuration. + + Mirrors the tensor types that ``Articulation._initialize_impl`` creates. + """ + + def __init__( + self, + num_instances: int, + num_joints: int, + num_bodies: int, + is_fixed_base: bool = False, + joint_names: list[str] | None = None, + body_names: list[str] | None = None, + num_fixed_tendons: int = 0, + num_spatial_tendons: int = 0, + ): + N = num_instances + D = num_joints + L = num_bodies + T_fix = num_fixed_tendons + T_spa = num_spatial_tendons + + if joint_names is None: + joint_names = [f"joint_{i}" for i in range(D)] + if body_names is None: + body_names = [f"body_{i}" for i in range(L)] + + common = dict( + count=N, + dof_count=D, + body_count=L, + joint_count=D, + is_fixed_base=is_fixed_base, + dof_names=joint_names, + body_names=body_names, + joint_names=joint_names, + fixed_tendon_count=T_fix, + spatial_tendon_count=T_spa, + ) + + self.bindings: dict[int, MockTensorBinding] = { + TT.ROOT_POSE: MockTensorBinding(TT.ROOT_POSE, (N, 7), **common), + TT.ROOT_VELOCITY: MockTensorBinding(TT.ROOT_VELOCITY, (N, 6), **common), + TT.LINK_POSE: MockTensorBinding(TT.LINK_POSE, (N, L, 7), **common), + TT.LINK_VELOCITY: MockTensorBinding(TT.LINK_VELOCITY, (N, L, 6), **common), + TT.LINK_ACCELERATION: MockTensorBinding(TT.LINK_ACCELERATION, (N, L, 6), **common), + TT.DOF_POSITION: MockTensorBinding(TT.DOF_POSITION, (N, D), **common), + TT.DOF_VELOCITY: MockTensorBinding(TT.DOF_VELOCITY, (N, D), **common), + TT.DOF_POSITION_TARGET: MockTensorBinding(TT.DOF_POSITION_TARGET, (N, D), **common), + TT.DOF_VELOCITY_TARGET: MockTensorBinding(TT.DOF_VELOCITY_TARGET, (N, D), **common), + TT.DOF_ACTUATION_FORCE: MockTensorBinding(TT.DOF_ACTUATION_FORCE, (N, D), **common), + TT.DOF_STIFFNESS: MockTensorBinding(TT.DOF_STIFFNESS, (N, D), **common), + TT.DOF_DAMPING: MockTensorBinding(TT.DOF_DAMPING, (N, D), **common), + TT.DOF_LIMIT: MockTensorBinding(TT.DOF_LIMIT, (N, D, 2), **common), + TT.DOF_MAX_VELOCITY: MockTensorBinding(TT.DOF_MAX_VELOCITY, (N, D), **common), + TT.DOF_MAX_FORCE: MockTensorBinding(TT.DOF_MAX_FORCE, (N, D), **common), + TT.DOF_ARMATURE: MockTensorBinding(TT.DOF_ARMATURE, (N, D), **common), + TT.DOF_FRICTION_PROPERTIES: MockTensorBinding(TT.DOF_FRICTION_PROPERTIES, (N, D, 3), **common), + TT.LINK_WRENCH: MockTensorBinding(TT.LINK_WRENCH, (N, L, 9), write_only=True, **common), + TT.BODY_MASS: MockTensorBinding(TT.BODY_MASS, (N, L), **common), + TT.BODY_COM_POSE: MockTensorBinding(TT.BODY_COM_POSE, (N, L, 7), **common), + TT.BODY_INERTIA: MockTensorBinding(TT.BODY_INERTIA, (N, L, 9), **common), + TT.BODY_INV_MASS: MockTensorBinding(TT.BODY_INV_MASS, (N, L), **common), + TT.BODY_INV_INERTIA: MockTensorBinding(TT.BODY_INV_INERTIA, (N, L, 9), **common), + TT.LINK_INCOMING_JOINT_FORCE: MockTensorBinding(TT.LINK_INCOMING_JOINT_FORCE, (N, L, 6), **common), + TT.DOF_PROJECTED_JOINT_FORCE: MockTensorBinding(TT.DOF_PROJECTED_JOINT_FORCE, (N, D), **common), + } + + # Fixed tendon bindings (only when tendons are present) + if T_fix > 0: + self.bindings.update( + { + TT.FIXED_TENDON_STIFFNESS: MockTensorBinding(TT.FIXED_TENDON_STIFFNESS, (N, T_fix), **common), + TT.FIXED_TENDON_DAMPING: MockTensorBinding(TT.FIXED_TENDON_DAMPING, (N, T_fix), **common), + TT.FIXED_TENDON_LIMIT_STIFFNESS: MockTensorBinding( + TT.FIXED_TENDON_LIMIT_STIFFNESS, (N, T_fix), **common + ), + TT.FIXED_TENDON_LIMIT: MockTensorBinding(TT.FIXED_TENDON_LIMIT, (N, T_fix, 2), **common), + TT.FIXED_TENDON_REST_LENGTH: MockTensorBinding(TT.FIXED_TENDON_REST_LENGTH, (N, T_fix), **common), + TT.FIXED_TENDON_OFFSET: MockTensorBinding(TT.FIXED_TENDON_OFFSET, (N, T_fix), **common), + } + ) + + # Spatial tendon bindings + if T_spa > 0: + self.bindings.update( + { + TT.SPATIAL_TENDON_STIFFNESS: MockTensorBinding(TT.SPATIAL_TENDON_STIFFNESS, (N, T_spa), **common), + TT.SPATIAL_TENDON_DAMPING: MockTensorBinding(TT.SPATIAL_TENDON_DAMPING, (N, T_spa), **common), + TT.SPATIAL_TENDON_LIMIT_STIFFNESS: MockTensorBinding( + TT.SPATIAL_TENDON_LIMIT_STIFFNESS, (N, T_spa), **common + ), + TT.SPATIAL_TENDON_OFFSET: MockTensorBinding(TT.SPATIAL_TENDON_OFFSET, (N, T_spa), **common), + } + ) + + def set_random_data(self) -> None: + """Fill all bindings with random data.""" + for b in self.bindings.values(): + if not b._write_only: + b.set_random_data() + lim = self.bindings[TT.DOF_LIMIT] + lim._data[..., 0] = -3.14 + lim._data[..., 1] = 3.14 + for tt in (TT.ROOT_POSE, TT.LINK_POSE, TT.BODY_COM_POSE): + b = self.bindings[tt] + b._data[..., 3:6] = 0.0 + b._data[..., 6] = 1.0 + self.bindings[TT.BODY_MASS]._data = np.abs(self.bindings[TT.BODY_MASS]._data) + 0.1 + self.bindings[TT.DOF_MAX_VELOCITY]._data = np.abs(self.bindings[TT.DOF_MAX_VELOCITY]._data) + 1.0 + self.bindings[TT.DOF_MAX_FORCE]._data = np.abs(self.bindings[TT.DOF_MAX_FORCE]._data) + 1.0 + # Set sensible defaults for fixed tendon limits + if TT.FIXED_TENDON_LIMIT in self.bindings: + tlim = self.bindings[TT.FIXED_TENDON_LIMIT] + tlim._data[..., 0] = -1.0 + tlim._data[..., 1] = 1.0 diff --git a/source/isaaclab_ovphysx/pyproject.toml b/source/isaaclab_ovphysx/pyproject.toml new file mode 100644 index 000000000000..31dce8d230ec --- /dev/null +++ b/source/isaaclab_ovphysx/pyproject.toml @@ -0,0 +1,3 @@ +[build-system] +requires = ["setuptools<82.0.0", "wheel", "toml"] +build-backend = "setuptools.build_meta" diff --git a/source/isaaclab_ovphysx/setup.py b/source/isaaclab_ovphysx/setup.py new file mode 100644 index 000000000000..4898806285dd --- /dev/null +++ b/source/isaaclab_ovphysx/setup.py @@ -0,0 +1,53 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Installation script for the 'isaaclab_ovphysx' python package.""" + +import os + +import toml +from setuptools import setup + +EXTENSION_PATH = os.path.dirname(os.path.realpath(__file__)) +EXTENSION_TOML_DATA = toml.load(os.path.join(EXTENSION_PATH, "config", "extension.toml")) + +INSTALL_REQUIRES: list[str] = [] + +EXTRAS_REQUIRE = { + "ovphysx": ["ovphysx"], +} + +setup( + name="isaaclab_ovphysx", + author="Isaac Lab Project Developers", + maintainer="Isaac Lab Project Developers", + url=EXTENSION_TOML_DATA["package"]["repository"], + version=EXTENSION_TOML_DATA["package"]["version"], + description=EXTENSION_TOML_DATA["package"]["description"], + keywords=EXTENSION_TOML_DATA["package"]["keywords"], + license="BSD-3-Clause", + include_package_data=True, + package_data={"": ["*.pyi"]}, + python_requires=">=3.11", + install_requires=INSTALL_REQUIRES, + extras_require=EXTRAS_REQUIRE, + packages=[ + "isaaclab_ovphysx", + "isaaclab_ovphysx.assets", + "isaaclab_ovphysx.assets.articulation", + "isaaclab_ovphysx.cloner", + "isaaclab_ovphysx.physics", + "isaaclab_ovphysx.test", + "isaaclab_ovphysx.test.mock_interfaces", + "isaaclab_ovphysx.test.mock_interfaces.views", + ], + classifiers=[ + "Natural Language :: English", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Isaac Sim :: 6.0.0", + ], + zip_safe=False, +) diff --git a/source/isaaclab_ovphysx/test/__init__.py b/source/isaaclab_ovphysx/test/__init__.py new file mode 100644 index 000000000000..460a30569089 --- /dev/null +++ b/source/isaaclab_ovphysx/test/__init__.py @@ -0,0 +1,4 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause diff --git a/source/isaaclab_ovphysx/test/assets/__init__.py b/source/isaaclab_ovphysx/test/assets/__init__.py new file mode 100644 index 000000000000..460a30569089 --- /dev/null +++ b/source/isaaclab_ovphysx/test/assets/__init__.py @@ -0,0 +1,4 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause diff --git a/source/isaaclab_ovphysx/test/assets/test_articulation.py b/source/isaaclab_ovphysx/test/assets/test_articulation.py new file mode 100644 index 000000000000..52998a2ec5f6 --- /dev/null +++ b/source/isaaclab_ovphysx/test/assets/test_articulation.py @@ -0,0 +1,116 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Unit tests for ovphysx articulation helpers.""" + +from __future__ import annotations + +from types import SimpleNamespace + +import pytest +import warp as wp + +from pxr import Sdf, Usd, UsdPhysics + +# The CI isaaclab_ov* pattern unintentionally collects isaaclab_ovphysx tests, +# but the ovphysx wheel is not installed in that environment. Skip gracefully +# so the isaaclab_ov CI pipeline is not blocked by an unrelated dependency. +pytest.importorskip("ovphysx.types", reason="ovphysx wheel not installed") + +from isaaclab_ovphysx.assets.articulation.articulation import Articulation # noqa: E402 +from isaaclab_ovphysx.physics import OvPhysxManager # noqa: E402 +from isaaclab_ovphysx.test.mock_interfaces.views import MockOvPhysxBindingSet # noqa: E402 + +wp.init() + + +def _define_tendon_joint(stage: Usd.Stage, path: str, schema_name: str) -> None: + """Define a revolute joint prim with a tendon schema marker.""" + joint = UsdPhysics.RevoluteJoint.Define(stage, path) + schemas = Sdf.TokenListOp() + schemas.explicitItems = [schema_name] + joint.GetPrim().SetMetadata("apiSchemas", schemas) + + +def _make_articulation_root_stage(tmp_path) -> str: + """Create a stage with one relevant articulation subtree and unrelated joints elsewhere.""" + stage = Usd.Stage.CreateInMemory() + stage.DefinePrim("/World", "Xform") + stage.DefinePrim("/World/envs", "Xform") + stage.DefinePrim("/World/envs/env_0", "Xform") + stage.DefinePrim("/World/envs/env_0/Robot", "Xform") + stage.DefinePrim("/World/envs/env_0/Robot/root", "Xform") + stage.DefinePrim("/World/unrelated", "Xform") + + _define_tendon_joint( + stage, + "/World/envs/env_0/Robot/root/fixed_joint", + "PhysxTendonAxisRootAPI:inst0", + ) + _define_tendon_joint( + stage, + "/World/envs/env_0/Robot/root/spatial_joint", + "PhysxTendonAttachmentRootAPI:inst0", + ) + _define_tendon_joint( + stage, + "/World/unrelated/unrelated_fixed_joint", + "PhysxTendonAxisRootAPI:inst0", + ) + _define_tendon_joint( + stage, + "/World/unrelated/unrelated_spatial_joint", + "PhysxTendonAttachmentLeafAPI:inst0", + ) + + stage_path = tmp_path / "scene.usda" + stage.Export(str(stage_path)) + return str(stage_path) + + +def _make_articulation_shell() -> Articulation: + """Create a minimal ovphysx articulation shell for tendon processing tests.""" + articulation = object.__new__(Articulation) + bindings = MockOvPhysxBindingSet( + num_instances=1, + num_joints=2, + num_bodies=2, + num_fixed_tendons=1, + num_spatial_tendons=1, + ) + object.__setattr__(articulation, "_bindings", bindings.bindings) + object.__setattr__(articulation, "_articulation_root_path", "/World/envs/env_0/Robot/root") + object.__setattr__(articulation, "_initialize_handle", None) + object.__setattr__(articulation, "_invalidate_initialize_handle", None) + object.__setattr__(articulation, "_prim_deletion_handle", None) + object.__setattr__(articulation, "_debug_vis_handle", None) + object.__setattr__( + articulation, + "_data", + SimpleNamespace( + _num_fixed_tendons=0, + _num_spatial_tendons=0, + fixed_tendon_names=[], + spatial_tendon_names=[], + ), + ) + return articulation + + +def test_process_tendons_scopes_to_articulation_root(tmp_path): + """Tendon discovery should ignore joints that live outside the current articulation subtree.""" + articulation = _make_articulation_shell() + stage_path = _make_articulation_root_stage(tmp_path) + old_stage_path = OvPhysxManager._stage_path + OvPhysxManager._stage_path = stage_path + try: + articulation._process_tendons() + finally: + OvPhysxManager._stage_path = old_stage_path + + assert articulation.fixed_tendon_names == ["fixed_joint"] + assert articulation.spatial_tendon_names == ["spatial_joint"] + assert articulation._data.fixed_tendon_names == ["fixed_joint"] + assert articulation._data.spatial_tendon_names == ["spatial_joint"] diff --git a/source/isaaclab_ovphysx/test/assets/test_articulation_data.py b/source/isaaclab_ovphysx/test/assets/test_articulation_data.py new file mode 100644 index 000000000000..16bb99a4d6c4 --- /dev/null +++ b/source/isaaclab_ovphysx/test/assets/test_articulation_data.py @@ -0,0 +1,42 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Unit tests for ovphysx articulation data helpers.""" + +import numpy as np +import pytest +import warp as wp + +# The CI isaaclab_ov* pattern unintentionally collects isaaclab_ovphysx tests, +# but the ovphysx wheel is not installed in that environment. Skip gracefully +# so the isaaclab_ov CI pipeline is not blocked by an unrelated dependency. +pytest.importorskip("ovphysx.types", reason="ovphysx wheel not installed") + +from isaaclab_ovphysx import tensor_types as TT # noqa: E402 +from isaaclab_ovphysx.assets.articulation.articulation_data import ArticulationData +from isaaclab_ovphysx.test.mock_interfaces.views import MockOvPhysxBindingSet + +wp.init() + + +class TestArticulationData: + """Unit tests for deterministic ArticulationData behavior.""" + + def test_joint_acc_uses_inverse_dt(self): + """Finite-difference joint acceleration should divide by ``dt``.""" + mock_bindings = MockOvPhysxBindingSet(num_instances=1, num_joints=2, num_bodies=1) + data = ArticulationData(mock_bindings.bindings, device="cpu") + data._create_buffers() + + mock_bindings.bindings[TT.DOF_VELOCITY]._data[...] = np.array([[1.0, -2.0]], dtype=np.float32) + + data.update(dt=0.25) + + np.testing.assert_allclose( + data.joint_acc.warp.numpy(), + np.array([[4.0, -8.0]], dtype=np.float32), + atol=1e-6, + err_msg="Joint acceleration should be computed as delta_velocity / dt.", + ) diff --git a/source/isaaclab_ovphysx/test/physics/__init__.py b/source/isaaclab_ovphysx/test/physics/__init__.py new file mode 100644 index 000000000000..460a30569089 --- /dev/null +++ b/source/isaaclab_ovphysx/test/physics/__init__.py @@ -0,0 +1,4 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause diff --git a/source/isaaclab_ovphysx/test/sensors/__init__.py b/source/isaaclab_ovphysx/test/sensors/__init__.py new file mode 100644 index 000000000000..460a30569089 --- /dev/null +++ b/source/isaaclab_ovphysx/test/sensors/__init__.py @@ -0,0 +1,4 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause diff --git a/source/isaaclab_ovphysx/test/sensors/check_contact_sensor.py b/source/isaaclab_ovphysx/test/sensors/check_contact_sensor.py new file mode 100644 index 000000000000..8bcd9f0941f6 --- /dev/null +++ b/source/isaaclab_ovphysx/test/sensors/check_contact_sensor.py @@ -0,0 +1,38 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Contact sensor parity tests for the ovphysx backend. + +Mirrors the structure of isaaclab_physx/test/sensors/check_contact_sensor.py. +Contact sensors are not yet supported by the ovphysx backend, so all tests +are skipped with an explanatory message. +""" + +import pytest + + +def test_contact_sensor_creation(): + """Verify contact sensor can be created on the ovphysx backend.""" + pytest.skip("Contact sensor not yet supported by ovphysx backend.") + + +def test_contact_sensor_data_reading(): + """Verify contact sensor data can be read after a simulation step.""" + pytest.skip("Contact sensor not yet supported by ovphysx backend.") + + +def test_contact_sensor_reset(): + """Verify contact sensor state resets correctly.""" + pytest.skip("Contact sensor not yet supported by ovphysx backend.") + + +def test_contact_sensor_air_time_tracking(): + """Verify contact sensor air time tracking.""" + pytest.skip("Contact sensor not yet supported by ovphysx backend.") + + +def test_contact_sensor_friction_forces(): + """Verify contact sensor friction force reporting.""" + pytest.skip("Contact sensor not yet supported by ovphysx backend.") diff --git a/source/isaaclab_physx/benchmark/assets/benchmark_articulation.py b/source/isaaclab_physx/benchmark/assets/benchmark_articulation.py index 190d9e7ee165..60969e714da0 100644 --- a/source/isaaclab_physx/benchmark/assets/benchmark_articulation.py +++ b/source/isaaclab_physx/benchmark/assets/benchmark_articulation.py @@ -39,6 +39,7 @@ parser.add_argument("--mode", type=str, default="all", help="Benchmark mode (all, torch_list, torch_tensor)") parser.add_argument("--output_dir", type=str, default=".", help="Output directory for results") parser.add_argument("--backend", type=str, default="json", choices=["json", "osmo", "omniperf"], help="Metrics backend") +parser.add_argument("--no_shape_checks", action="store_true", help="Disable shape/dtype assertions") # append AppLauncher cli args AppLauncher.add_app_launcher_args(parser) @@ -63,7 +64,7 @@ _mock_physics_sim_view = MagicMock() _mock_physics_sim_view.get_gravity.return_value = (0.0, 0.0, -9.81) -from isaacsim.core.simulation_manager import SimulationManager +from isaaclab_physx.physics import PhysxManager as SimulationManager SimulationManager.get_physics_sim_view = MagicMock(return_value=_mock_physics_sim_view) import warp as wp @@ -124,6 +125,7 @@ def create_test_articulation( object.__setattr__(articulation, "_root_view", mock_view) object.__setattr__(articulation, "_device", device) + object.__setattr__(articulation, "_check_shapes", not args.no_shape_checks) # Create ArticulationData instance (SimulationManager already mocked at module level) data = ArticulationData(mock_view, device) @@ -138,21 +140,62 @@ def create_test_articulation( # Set up other required attributes object.__setattr__(articulation, "actuators", {}) object.__setattr__(articulation, "_has_implicit_actuators", False) - object.__setattr__(articulation, "_ALL_INDICES", torch.arange(num_instances, dtype=torch.int32, device=device)) - object.__setattr__(articulation, "_ALL_BODY_INDICES", torch.arange(num_bodies, dtype=torch.int32, device=device)) - object.__setattr__(articulation, "_ALL_JOINT_INDICES", torch.arange(num_joints, dtype=torch.int32, device=device)) + + # Use warp arrays for _ALL_* indices (matching real _create_buffers) + import numpy as np + + all_indices_wp = wp.array(np.arange(num_instances, dtype=np.int32), device=device) + all_joint_indices_wp = wp.array(np.arange(num_joints, dtype=np.int32), device=device) + all_body_indices_wp = wp.array(np.arange(num_bodies, dtype=np.int32), device=device) + object.__setattr__(articulation, "_ALL_INDICES", all_indices_wp) + object.__setattr__(articulation, "_ALL_JOINT_INDICES", all_joint_indices_wp) + object.__setattr__(articulation, "_ALL_BODY_INDICES", all_body_indices_wp) # Warp arrays for set_external_force_and_torque - all_indices = torch.arange(num_instances, dtype=torch.int32, device=device) - all_body_indices = torch.arange(num_bodies, dtype=torch.int32, device=device) - object.__setattr__(articulation, "_ALL_INDICES_WP", wp.from_torch(all_indices, dtype=wp.int32)) - object.__setattr__(articulation, "_ALL_BODY_INDICES_WP", wp.from_torch(all_body_indices, dtype=wp.int32)) + object.__setattr__(articulation, "_ALL_INDICES_WP", all_indices_wp) + object.__setattr__(articulation, "_ALL_BODY_INDICES_WP", all_body_indices_wp) # Initialize joint targets object.__setattr__(articulation, "_joint_pos_target_sim", torch.zeros(num_instances, num_joints, device=device)) object.__setattr__(articulation, "_joint_vel_target_sim", torch.zeros(num_instances, num_joints, device=device)) object.__setattr__(articulation, "_joint_effort_target_sim", torch.zeros(num_instances, num_joints, device=device)) + # Cached .view() wrappers + object.__setattr__(articulation, "_root_link_pose_w_f32", None) + object.__setattr__(articulation, "_root_com_vel_w_f32", None) + object.__setattr__(articulation, "_root_link_vel_w_f32", None) + + # Pre-allocated pinned CPU buffers for PhysX TensorAPI writes + N, J, B = num_instances, num_joints, num_bodies + object.__setattr__(articulation, "_cpu_env_ids_all", wp.zeros(N, dtype=wp.int32, device="cpu", pinned=True)) + wp.copy(articulation._cpu_env_ids_all, all_indices_wp) + object.__setattr__( + articulation, "_cpu_joint_stiffness", wp.zeros((N, J), dtype=wp.float32, device="cpu", pinned=True) + ) + object.__setattr__( + articulation, "_cpu_joint_damping", wp.zeros((N, J), dtype=wp.float32, device="cpu", pinned=True) + ) + object.__setattr__( + articulation, "_cpu_joint_pos_limits", wp.zeros((N, J, 2), dtype=wp.float32, device="cpu", pinned=True) + ) + object.__setattr__( + articulation, "_cpu_joint_vel_limits", wp.zeros((N, J), dtype=wp.float32, device="cpu", pinned=True) + ) + object.__setattr__( + articulation, "_cpu_joint_effort_limits", wp.zeros((N, J), dtype=wp.float32, device="cpu", pinned=True) + ) + object.__setattr__( + articulation, "_cpu_joint_armature", wp.zeros((N, J), dtype=wp.float32, device="cpu", pinned=True) + ) + object.__setattr__( + articulation, "_cpu_joint_friction_props", wp.zeros((N, J, 3), dtype=wp.float32, device="cpu", pinned=True) + ) + object.__setattr__(articulation, "_cpu_body_mass", wp.zeros((N, B), dtype=wp.float32, device="cpu", pinned=True)) + object.__setattr__(articulation, "_cpu_body_coms", wp.zeros((N, B, 7), dtype=wp.float32, device="cpu", pinned=True)) + object.__setattr__( + articulation, "_cpu_body_inertia", wp.zeros((N, B, 9), dtype=wp.float32, device="cpu", pinned=True) + ) + return articulation, mock_view, None @@ -857,6 +900,62 @@ def gen_set_external_force_and_torque_torch_tensor(config: MethodBenchmarkRunner ] +# ============================================================================= +# Fill-Ratio Benchmarks (5%, 95%, 100% of env_ids filled) +# ============================================================================= + +FILL_RATIOS = {"5pct": 0.05, "95pct": 0.95, "100pct": 1.0} + + +def _make_fill_ratio_generator(base_gen_fn, fill_ratio): + """Create a generator that subsets env_ids to a given fill ratio. + + Only env_ids are subsetted — joint_ids and body_ids remain full-range. + Data tensors keyed on env count are sliced to match. + """ + + def generator(config): + n = max(1, int(config.num_instances * fill_ratio)) + base_inputs = base_gen_fn(config) + inputs = {} + for key, val in base_inputs.items(): + if key == "env_ids": + inputs[key] = ( + torch.randperm(config.num_instances, device=config.device)[:n].sort().values.to(torch.int32) + ) + elif isinstance(val, torch.Tensor) and val.dim() >= 1 and val.shape[0] == config.num_instances: + inputs[key] = val[:n] + else: + inputs[key] = val + return inputs + + return generator + + +def _build_fill_benchmarks(): + """Auto-generate fill-ratio benchmark definitions from the torch_tensor generators.""" + fill_benchmarks = [] + for bm in BENCHMARKS: + if "torch_tensor" not in bm.input_generators: + continue + base_gen = bm.input_generators["torch_tensor"] + generators = {} + for suffix, ratio in FILL_RATIOS.items(): + generators[f"tensor_{suffix}"] = _make_fill_ratio_generator(base_gen, ratio) + fill_benchmarks.append( + MethodBenchmarkDefinition( + name=bm.name, + method_name=bm.method_name, + input_generators=generators, + category=f"{bm.category}_fill", + ) + ) + return fill_benchmarks + + +FILL_BENCHMARKS = _build_fill_benchmarks() + + def main(): """Main entry point for the benchmarking script.""" config = MethodBenchmarkRunnerConfig( @@ -892,6 +991,12 @@ def main(): ) runner.run_benchmarks(BENCHMARKS, articulation) + + print("\n" + "=" * 80) + print("Fill-Ratio Benchmarks (env_ids at 5%, 95%, 100% fill)") + print("=" * 80) + + runner.run_benchmarks(FILL_BENCHMARKS, articulation) runner.finalize() # Close the simulation app diff --git a/source/isaaclab_physx/benchmark/assets/benchmark_articulation_data.py b/source/isaaclab_physx/benchmark/assets/benchmark_articulation_data.py index 3cdca6665a86..f463f73ea6aa 100644 --- a/source/isaaclab_physx/benchmark/assets/benchmark_articulation_data.py +++ b/source/isaaclab_physx/benchmark/assets/benchmark_articulation_data.py @@ -60,7 +60,7 @@ _mock_physics_sim_view = MagicMock() _mock_physics_sim_view.get_gravity.return_value = (0.0, 0.0, -9.81) -from isaacsim.core.simulation_manager import SimulationManager +from isaaclab_physx.physics import PhysxManager as SimulationManager SimulationManager.get_physics_sim_view = MagicMock(return_value=_mock_physics_sim_view) @@ -131,7 +131,6 @@ "spatial_tendon_damping", "spatial_tendon_limit_stiffness", "spatial_tendon_offset", - "body_incoming_joint_wrench_b", } # Removed default_* properties that raise RuntimeError diff --git a/source/isaaclab_physx/benchmark/assets/benchmark_rigid_object.py b/source/isaaclab_physx/benchmark/assets/benchmark_rigid_object.py index c4411325d223..cf76cf6e8489 100644 --- a/source/isaaclab_physx/benchmark/assets/benchmark_rigid_object.py +++ b/source/isaaclab_physx/benchmark/assets/benchmark_rigid_object.py @@ -61,7 +61,7 @@ _mock_physics_sim_view = MagicMock() _mock_physics_sim_view.get_gravity.return_value = (0.0, 0.0, -9.81) -from isaacsim.core.simulation_manager import SimulationManager +from isaaclab_physx.physics import PhysxManager as SimulationManager SimulationManager.get_physics_sim_view = MagicMock(return_value=_mock_physics_sim_view) @@ -481,6 +481,62 @@ def gen_external_force_and_torque_torch_tensor(config: MethodBenchmarkRunnerConf ] +# ============================================================================= +# Fill-Ratio Benchmarks (5%, 95%, 100% of env_ids filled) +# ============================================================================= + +FILL_RATIOS = {"5pct": 0.05, "95pct": 0.95, "100pct": 1.0} + + +def _make_fill_ratio_generator(base_gen_fn, fill_ratio): + """Create a generator that subsets env_ids to a given fill ratio. + + Only env_ids are subsetted — body_ids remain full-range. + Data tensors keyed on env count are sliced to match. + """ + + def generator(config): + n = max(1, int(config.num_instances * fill_ratio)) + base_inputs = base_gen_fn(config) + inputs = {} + for key, val in base_inputs.items(): + if key == "env_ids": + inputs[key] = ( + torch.randperm(config.num_instances, device=config.device)[:n].sort().values.to(torch.int32) + ) + elif isinstance(val, torch.Tensor) and val.dim() >= 1 and val.shape[0] == config.num_instances: + inputs[key] = val[:n] + else: + inputs[key] = val + return inputs + + return generator + + +def _build_fill_benchmarks(): + """Auto-generate fill-ratio benchmark definitions from existing generators.""" + fill_benchmarks = [] + for bm in BENCHMARKS: + generators = {} + if "torch_tensor" in bm.input_generators: + base_gen = bm.input_generators["torch_tensor"] + for suffix, ratio in FILL_RATIOS.items(): + generators[f"tensor_{suffix}"] = _make_fill_ratio_generator(base_gen, ratio) + if generators: + fill_benchmarks.append( + MethodBenchmarkDefinition( + name=bm.name, + method_name=bm.method_name, + input_generators=generators, + category=f"{bm.category}_fill", + ) + ) + return fill_benchmarks + + +FILL_BENCHMARKS = _build_fill_benchmarks() + + def main(): """Main entry point for the benchmarking script.""" config = MethodBenchmarkRunnerConfig( @@ -512,6 +568,12 @@ def main(): ) runner.run_benchmarks(BENCHMARKS, rigid_object) + + print("\n" + "=" * 80) + print("Fill-Ratio Benchmarks (env_ids at 5%, 95%, 100% fill)") + print("=" * 80) + + runner.run_benchmarks(FILL_BENCHMARKS, rigid_object) runner.finalize() # Close the simulation app diff --git a/source/isaaclab_physx/benchmark/assets/benchmark_rigid_object_collection.py b/source/isaaclab_physx/benchmark/assets/benchmark_rigid_object_collection.py index a244d3b52cae..dc69c349adf4 100644 --- a/source/isaaclab_physx/benchmark/assets/benchmark_rigid_object_collection.py +++ b/source/isaaclab_physx/benchmark/assets/benchmark_rigid_object_collection.py @@ -56,7 +56,7 @@ _mock_physics_sim_view = MagicMock() _mock_physics_sim_view.get_gravity.return_value = (0.0, 0.0, -9.81) -from isaacsim.core.simulation_manager import SimulationManager +from isaaclab_physx.physics import PhysxManager as SimulationManager SimulationManager.get_physics_sim_view = MagicMock(return_value=_mock_physics_sim_view) @@ -382,6 +382,62 @@ def gen_inertias_torch_tensor(config: MethodBenchmarkRunnerConfig) -> dict: ] +# ============================================================================= +# Fill-Ratio Benchmarks (5%, 95%, 100% of env_ids filled) +# ============================================================================= + +FILL_RATIOS = {"5pct": 0.05, "95pct": 0.95, "100pct": 1.0} + + +def _make_fill_ratio_generator(base_gen_fn, fill_ratio): + """Create a generator that subsets env_ids to a given fill ratio. + + Only env_ids are subsetted — body_ids remain full-range. + Data tensors keyed on env count are sliced to match. + """ + + def generator(config): + n = max(1, int(config.num_instances * fill_ratio)) + base_inputs = base_gen_fn(config) + inputs = {} + for key, val in base_inputs.items(): + if key == "env_ids": + inputs[key] = ( + torch.randperm(config.num_instances, device=config.device)[:n].sort().values.to(torch.int32) + ) + elif isinstance(val, torch.Tensor) and val.dim() >= 1 and val.shape[0] == config.num_instances: + inputs[key] = val[:n] + else: + inputs[key] = val + return inputs + + return generator + + +def _build_fill_benchmarks(): + """Auto-generate fill-ratio benchmark definitions from existing generators.""" + fill_benchmarks = [] + for bm in BENCHMARKS: + generators = {} + if "torch_tensor" in bm.input_generators: + base_gen = bm.input_generators["torch_tensor"] + for suffix, ratio in FILL_RATIOS.items(): + generators[f"tensor_{suffix}"] = _make_fill_ratio_generator(base_gen, ratio) + if generators: + fill_benchmarks.append( + MethodBenchmarkDefinition( + name=bm.name, + method_name=bm.method_name, + input_generators=generators, + category=f"{bm.category}_fill", + ) + ) + return fill_benchmarks + + +FILL_BENCHMARKS = _build_fill_benchmarks() + + def main(): """Main entry point for the benchmarking script.""" config = MethodBenchmarkRunnerConfig( @@ -415,6 +471,12 @@ def main(): ) runner.run_benchmarks(BENCHMARKS, collection) + + print("\n" + "=" * 80) + print("Fill-Ratio Benchmarks (env_ids at 5%, 95%, 100% fill)") + print("=" * 80) + + runner.run_benchmarks(FILL_BENCHMARKS, collection) runner.finalize() # Close the simulation app diff --git a/source/isaaclab_physx/benchmark/assets/benchmark_rigid_object_collection_data.py b/source/isaaclab_physx/benchmark/assets/benchmark_rigid_object_collection_data.py index 1506c9443af8..0b0327e9bf3c 100644 --- a/source/isaaclab_physx/benchmark/assets/benchmark_rigid_object_collection_data.py +++ b/source/isaaclab_physx/benchmark/assets/benchmark_rigid_object_collection_data.py @@ -59,7 +59,7 @@ _mock_physics_sim_view = MagicMock() _mock_physics_sim_view.get_gravity.return_value = (0.0, 0.0, -9.81) -from isaacsim.core.simulation_manager import SimulationManager +from isaaclab_physx.physics import PhysxManager as SimulationManager SimulationManager.get_physics_sim_view = MagicMock(return_value=_mock_physics_sim_view) diff --git a/source/isaaclab_physx/benchmark/assets/benchmark_rigid_object_data.py b/source/isaaclab_physx/benchmark/assets/benchmark_rigid_object_data.py index acd413e84704..9c0d65da2da3 100644 --- a/source/isaaclab_physx/benchmark/assets/benchmark_rigid_object_data.py +++ b/source/isaaclab_physx/benchmark/assets/benchmark_rigid_object_data.py @@ -57,7 +57,7 @@ _mock_physics_sim_view = MagicMock() _mock_physics_sim_view.get_gravity.return_value = (0.0, 0.0, -9.81) -from isaacsim.core.simulation_manager import SimulationManager +from isaaclab_physx.physics import PhysxManager as SimulationManager SimulationManager.get_physics_sim_view = MagicMock(return_value=_mock_physics_sim_view) diff --git a/source/isaaclab_physx/changelog.d/.gitkeep b/source/isaaclab_physx/changelog.d/.gitkeep new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/source/isaaclab_physx/changelog.d/clone-plan-visualizer-cleanup.skip b/source/isaaclab_physx/changelog.d/clone-plan-visualizer-cleanup.skip new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/source/isaaclab_physx/changelog.d/mtrepte-expand_viz_markers.skip b/source/isaaclab_physx/changelog.d/mtrepte-expand_viz_markers.skip new file mode 100644 index 000000000000..4f6915f6b47b --- /dev/null +++ b/source/isaaclab_physx/changelog.d/mtrepte-expand_viz_markers.skip @@ -0,0 +1,2 @@ +Marker visualization changes are covered by the isaaclab fragment. +Marker visualization changes are covered by the isaaclab fragment. diff --git a/source/isaaclab_physx/changelog.d/pr-5458-merge-develop.rst b/source/isaaclab_physx/changelog.d/pr-5458-merge-develop.rst new file mode 100644 index 000000000000..1fe6a600bb99 --- /dev/null +++ b/source/isaaclab_physx/changelog.d/pr-5458-merge-develop.rst @@ -0,0 +1,16 @@ +Added +^^^^^ + +* Added :class:`~isaaclab_physx.sensors.JointWrenchSensor` for reading PhysX + incoming joint reaction wrenches as split force [N] and torque [N·m] buffers. + The sensor accepts asset prim paths whose articulation root is nested below + the configured prim and converts PhysX's native body-frame wrench to the + shared child-side joint-frame convention. + +Removed +^^^^^^^ + +* Removed ``ArticulationData.body_incoming_joint_wrench_b``. Add + :class:`~isaaclab.sensors.JointWrenchSensorCfg` to the scene and read + :attr:`~isaaclab.sensors.JointWrenchSensorData.force` and + :attr:`~isaaclab.sensors.JointWrenchSensorData.torque` instead. diff --git a/source/isaaclab_physx/changelog.d/rschmitt_decouple_renderer_camera.rst b/source/isaaclab_physx/changelog.d/rschmitt_decouple_renderer_camera.rst new file mode 100644 index 000000000000..eada0bbb809c --- /dev/null +++ b/source/isaaclab_physx/changelog.d/rschmitt_decouple_renderer_camera.rst @@ -0,0 +1,4 @@ +Changed +^^^^^^^^ + +* Modified the isaac rtx renderer to use the new patterns from renderer/camera decoupling. diff --git a/source/isaaclab_physx/config/extension.toml b/source/isaaclab_physx/config/extension.toml index 996af61314e5..5c63b0e6322f 100644 --- a/source/isaaclab_physx/config/extension.toml +++ b/source/isaaclab_physx/config/extension.toml @@ -1,7 +1,7 @@ [package] # Note: Semantic Versioning is used: https://semver.org/ -version = "0.5.13" +version = "0.5.29" # Description title = "PhysX simulation interfaces for IsaacLab core package" diff --git a/source/isaaclab_physx/docs/CHANGELOG.rst b/source/isaaclab_physx/docs/CHANGELOG.rst index 6ea71fa755c2..14425eb74869 100644 --- a/source/isaaclab_physx/docs/CHANGELOG.rst +++ b/source/isaaclab_physx/docs/CHANGELOG.rst @@ -1,6 +1,307 @@ Changelog --------- +0.5.29 (2026-04-30) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Added fused :meth:`~isaaclab_physx.assets.Articulation.write_joint_state_to_sim_index` + that writes joint position and velocity in a single kernel launch instead of two. +* Cached ``.view(wp.float32)`` results in root pose/velocity writers and wrench + composer views in ``write_data_to_sim`` to avoid per-call wrapper allocations. +* Pre-allocated pinned CPU buffers for all joint property and body property writers, + replacing per-call ``wp.clone(device="cpu")`` allocations with ``wp.copy`` into + reusable pinned memory. + + +0.5.28 (2026-04-29) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed camera observation hang when a visualizer (e.g. KitVisualizer for XR + teleop) is active and ``--enable_cameras`` is set. + :func:`~isaaclab_physx.renderers.isaac_rtx_renderer_utils.ensure_isaac_rtx_render_update` + now performs the initial ``app.update()`` on the very first call for a new + :class:`~isaaclab.sim.SimulationContext`, even when a visualizer reports that + it pumps the Kit app loop, because the visualizer has not had a chance to pump + yet at that point. + + +0.5.27 (2026-04-27) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed ``Simulation view object is invalidated and cannot be used again to call + getDofVelocities`` raised on the first ``scene.update()`` after ``sim.reset()`` + with recent Isaac Sim ``develop`` builds. Isaac Sim's + ``isaacsim.core.simulation_manager.SimulationManager`` recently became reactive + to timeline ``STOP`` events (after its ``_on_stop`` was decorated with + ``@staticmethod`` upstream), and its ``invalidate_physics()`` was clobbering + the shared ``omni.physics.tensors`` simulation view that + :class:`~isaaclab_physx.physics.PhysxManager` and PhysX articulation views + rely on. The ``isaaclab_physx`` package init now disables the original Isaac + Sim ``SimulationManager``'s default timeline/stage callbacks via + ``enable_all_default_callbacks(False)`` before swapping the module attribute, + so :class:`PhysxManager` is the single owner of the simulation lifecycle. + + +0.5.26 (2026-04-27) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed ``import isaaclab_physx`` eagerly importing ``isaacsim``, ``omni``, + and ``carb`` backend modules when used for pure-data config loading before + ``SimulationApp`` has launched. The ``SimulationManager`` patch now checks + ``sys.modules`` lazily instead of force-importing the target module, allowing + env-cfg classes that reference :class:`~isaaclab_physx.physics.PhysxCfg` to + be constructed without a running Kit instance (regression caught by + ``test_env_cfg_no_forbidden_imports``). + +Changed +^^^^^^^ + +* Migrated :func:`~isaaclab_physx.renderers.kit_viewport_utils.set_kit_renderer_camera_view` + off the deprecated ``isaacsim.core.utils.viewports.set_camera_view`` to + ``isaacsim.core.rendering_manager.ViewportManager.set_camera_view``, matching the + pattern used by the Kit perspective video helper. + + +0.5.25 (2026-04-27) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Updated imports of the PhysX tensors API from ``omni.physics.tensors.impl.api`` to + ``omni.physics.tensors.api`` to track the upstream Isaac Sim module relocation + (the ``impl`` submodule was removed). +* Migrated the PhysX scene data provider, PhysX asset micro-benchmarks, and cross-backend asset + interface tests off ``isaacsim.core.simulation_manager.SimulationManager`` to + :class:`~isaaclab_physx.physics.PhysxManager` (imported as ``SimulationManager`` to mirror the + Newton backend's ``NewtonManager as SimulationManager`` convention). +* Updated optional-extension enablement and Kit perspective capture helpers to use non-deprecated + Isaac Sim module paths (``isaacsim.core.experimental.utils.app`` and ``isaacsim.core.rendering_manager``). + + +0.5.24 (2026-04-24) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Updated :class:`~isaaclab_physx.sim.views.FabricFrameView` to match the new + :class:`~isaaclab.sim.views.BaseFrameView` ProxyArray return contract. See + the ``isaaclab`` 4.6.15 changelog for migration guidance. + + +0.5.23 (2026-04-24) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Properties on the following data classes now return + :class:`~isaaclab.utils.warp.ProxyArray` instead of raw ``wp.array``: + :class:`~isaaclab_physx.assets.articulation.ArticulationData`, + :class:`~isaaclab_physx.assets.rigid_object.RigidObjectData`, + :class:`~isaaclab_physx.assets.rigid_object_collection.RigidObjectCollectionData`, + :class:`~isaaclab_physx.assets.deformable_object.DeformableObjectData`, + :class:`~isaaclab_physx.sensors.contact_sensor.ContactSensorData`, + :class:`~isaaclab_physx.sensors.frame_transformer.FrameTransformerData`, + :class:`~isaaclab_physx.sensors.imu.ImuData`, and + :class:`~isaaclab_physx.sensors.pva.PvaData`. + Use ``.torch`` for a cached zero-copy ``torch.Tensor`` view, or ``.warp`` for + the underlying ``wp.array``. Implicit torch operations (arithmetic, + ``torch.*`` functions) work during the deprecation period but emit a warning. + + +0.5.22 (2026-04-23) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed ``RuntimeError: NewtonWarpRenderer requires a Newton model but the scene data provider + returned None`` when a Direct env (e.g. ``ShadowHandVisionEnv``, ``CartpoleCameraEnv``) + uses ``physx`` physics with the ``newton_warp`` renderer. The + :class:`~isaaclab_physx.scene_data_providers.PhysxSceneDataProvider` now falls back to a + USD-traversal Newton build when the cloner-time prebuilt artifact is absent, and stashes + the freshly built artifact on the simulation context so subsequent providers reuse it. + + +0.5.21 (2026-04-22) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :class:`~isaaclab_physx.sim.views.XformPrimView` providing the PhysX/Fabric + backend implementation for xform prim views. + +Changed +^^^^^^^ + +* Renamed :class:`~isaaclab_physx.sim.views.FabricXformPrimView` to + :class:`~isaaclab_physx.sim.views.FabricFrameView`. Old name is kept as a deprecated alias. + + +0.5.20 (2026-04-21) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Updated ``write_data_to_sim`` in :class:`~isaaclab_physx.assets.Articulation`, + :class:`~isaaclab_physx.assets.RigidObject`, and :class:`~isaaclab_physx.assets.RigidObjectCollection` + to use the dual-buffer :class:`~isaaclab.utils.wrench_composer.WrenchComposer`. Composed wrenches are + applied to PhysX with ``is_global=False`` after body-frame composition. + + +0.5.19 (2026-04-20) +~~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed Newton ``shape_color`` not reflecting the post-clone USD stage when the + PhysX scene data provider builds or reloads the Newton model by calling + :func:`~isaaclab.sim.utils.newton_model_utils.replace_newton_shape_colors` on + the artifact, per-environment, and filtered Newton models in + :class:`~isaaclab_physx.scene_data_providers.PhysxSceneDataProvider`. + +0.5.18 (2026-04-16) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed flaky first-frame textured rendering by replacing the event-based RTX + streaming subscription with a synchronous + ``UsdContext.get_stage_streaming_status()`` query in + :func:`~isaaclab_physx.renderers.isaac_rtx_renderer_utils.ensure_isaac_rtx_render_update`. + + +0.5.17 (2026-04-14) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :class:`~isaaclab_physx.sim.schemas.DeformableBodyPropertiesCfg` with + namespace-aware property routing. Properties are organized into + ``omniphysics:``, ``physxDeformableBody:``, and ``physxCollision:`` prefixed + parent classes, allowing correct USD attribute mapping for the updated PhysX + deformable body schema. +* Added :func:`~isaaclab_physx.sim.schemas.define_deformable_body_properties` and + :func:`~isaaclab_physx.sim.schemas.modify_deformable_body_properties` to + ``isaaclab_physx.sim.schemas``, supporting both surface and volume deformable + types via the ``deformable_type`` parameter. +* Added :class:`~isaaclab_physx.sim.spawners.materials.DeformableBodyMaterialCfg` + and :class:`~isaaclab_physx.sim.spawners.materials.SurfaceDeformableBodyMaterialCfg` + with namespace-aware property routing for ``omniphysics:`` and + ``physxDeformableBody:`` material attributes. +* Added :class:`~isaaclab_physx.sim.spawners.spawner_cfg.DeformableObjectSpawnerCfg` + for configuring deformable body properties and materials when spawning. +* Added surface deformable body support to + :class:`~isaaclab_physx.assets.DeformableObject`. The asset now detects whether + the deformable is a surface or volume type based on the applied material API + and creates the appropriate PhysX tensor view + (``create_surface_deformable_body_view`` vs ``create_volume_deformable_body_view``). + +Changed +^^^^^^^ + +* Changed :attr:`~isaaclab_physx.assets.DeformableObject.root_view` return type + from ``physx.SoftBodyView`` to ``physx.DeformableBodyView`` to align with the + updated PhysX API. +* Changed :attr:`~isaaclab_physx.assets.DeformableObject.material_physx_view` + return type from ``physx.SoftBodyMaterialView`` to + ``physx.DeformableMaterialView``. +* Changed deformable body root prim discovery to check for + ``OmniPhysicsDeformableBodyAPI`` instead of ``PhysxDeformableBodyAPI``. +* Changed material prim discovery to check for ``OmniPhysicsDeformableMaterialAPI`` + instead of ``PhysxDeformableBodyMaterialAPI``. +* Changed PhysX view API calls to use updated method names: + ``get_simulation_nodal_positions``, ``set_simulation_nodal_positions``, + ``set_simulation_nodal_velocities``, ``get_simulation_nodal_kinematic_targets``, + ``set_simulation_nodal_kinematic_targets``. +* Changed property accessors to use updated PhysX view attributes: + ``max_simulation_elements_per_body``, ``max_collision_elements_per_body``, + ``max_simulation_nodes_per_body``, ``max_collision_nodes_per_body``. +* Changed kinematic target operations to raise ``ValueError`` when called on + surface deformable bodies, which do not support kinematic targets. + + +0.5.16 (2026-04-13) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Renamed the PhysX IMU sensor implementation to + :class:`~isaaclab_physx.sensors.Pva`. The ``isaaclab_physx.sensors.imu`` + module now contains a new lightweight IMU sensor that only provides angular + velocity and linear acceleration. +* Changed :class:`~isaaclab_physx.sensors.Pva` to no longer accept a + ``gravity_bias`` parameter. Linear acceleration is now pure finite + differencing of velocity without any gravity contribution. +* Changed :class:`~isaaclab_physx.sensors.Imu` to unconditionally include + gravity in accelerometer readings. The gravity vector is queried from the + PhysX simulation at initialization instead of being user-configured. + +Added +^^^^^ + +* Added :class:`~isaaclab_physx.sensors.Imu` PhysX backend for the new + lightweight IMU sensor with simplified Warp kernels that only compute + angular velocity and linear acceleration. + +Fixed +^^^^^ + +* Fixed unused ``body_pos`` variable in the IMU Warp kernel. +* Fixed ``phsyx`` typo in :class:`~isaaclab.sensors.pva.BasePva` docstring. + + +0.5.15 (2026-04-13) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :meth:`~isaaclab_physx.assets.RigidObject.set_material_properties_index`, + :meth:`~isaaclab_physx.assets.RigidObject.set_material_properties_mask`, + :meth:`~isaaclab_physx.assets.Articulation.set_material_properties_index`, + :meth:`~isaaclab_physx.assets.Articulation.set_material_properties_mask`, + :meth:`~isaaclab_physx.assets.RigidObjectCollection.set_material_properties_index`, and + :meth:`~isaaclab_physx.assets.RigidObjectCollection.set_material_properties_mask` + methods for setting collision shape material properties (friction, restitution). + These methods follow the standard ``_index``/``_mask`` pattern, providing a unified + API across PhysX and Newton backends. + + +0.5.14 (2026-04-06) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed the simulation training loop not pausing when the Kit GUI timeline is + paused. :meth:`~isaaclab_physx.physics.PhysxManager.wait_for_playing` now + blocks and keeps the GUI responsive until the timeline is resumed or stopped. +* Fixed articulation visualization freezing after pausing and unpausing the + simulation through the headed GUI in Isaac Sim 5.1+. Articulation meshes now + remain visually updated after resuming. + + 0.5.13 (2026-03-25) ~~~~~~~~~~~~~~~~~~~ diff --git a/source/isaaclab_physx/isaaclab_physx/__init__.py b/source/isaaclab_physx/isaaclab_physx/__init__.py index a9f5f5bf9d94..b7bfc7481300 100644 --- a/source/isaaclab_physx/isaaclab_physx/__init__.py +++ b/source/isaaclab_physx/isaaclab_physx/__init__.py @@ -21,17 +21,79 @@ def _patch_isaacsim_simulation_manager(): - """Patch Isaac Sim's SimulationManager to use PhysxManager. + """Patch Isaac Sim's ``SimulationManager`` to use :class:`PhysxManager`. - This ensures all code that imports from isaacsim.core.simulation_manager - will use our PhysxManager instead, preventing duplicate callback registration. + This redirects future ``from isaacsim.core.simulation_manager import SimulationManager`` + consumers to :class:`isaaclab_physx.physics.PhysxManager`, but the original + Isaac Sim ``SimulationManager`` class has *already* registered timeline + (PLAY/STOP) and stage (OPENED/CLOSED) subscriptions during its extension + startup. Those subscriptions live on the original class, not the module + attribute, so swapping the attribute alone is not enough. + + Starting with Isaac Sim 6.0.0-alpha.180 (commit ``8df6beeb0`` on + ``develop``, "hmazhar/autofix_bugs"), the original + ``SimulationManager._on_stop``/``_on_play``/``_on_stage_*`` methods were + decorated with ``@staticmethod`` so they finally fire correctly from the + Carb event subscriptions. Before that fix they were silently broken (the + subscriptions invoked them as bound methods, so the ``event`` argument was + being passed as ``self``/``cls`` and the bodies never executed). + + The newly-working ``_on_stop`` calls + ``SimulationManager.invalidate_physics()``, which calls + ``view.invalidate()`` on its ``omni.physics.tensors`` simulation view. + Because ``omni.physics.tensors.create_simulation_view("warp", stage_id=...)`` + returns the same underlying SimulationView per stage_id, that invalidation + also wrecks the view that :class:`PhysxManager` (and any articulation + ``_root_view`` derived from it) relies on. The result is the runtime error + ``Simulation view object is invalidated and cannot be used again to call + getDofVelocities`` on the very first ``scene.update()`` after + ``sim.reset()``. + + To prevent this, we disable the original class's default callbacks here + *before* swapping the module attribute, so :class:`PhysxManager` becomes + the single owner of the simulation lifecycle. + + This function is intentionally lazy: it only patches if + ``isaacsim.core.simulation_manager`` is already present in ``sys.modules``. + In the normal production flow Kit loads that module during extension startup, + before any user script imports :mod:`isaaclab_physx`, so the condition is + true and the patch fires on time. If :mod:`isaaclab_physx` happens to be + imported for pure config loading before Kit has launched (e.g. in + ``test_env_cfg_no_forbidden_imports``), the module is absent and this + function is a no-op — which is correct, because no callbacks have been + registered yet. """ - if "isaacsim.core.simulation_manager" in sys.modules: - original_module = sys.modules["isaacsim.core.simulation_manager"] - from .physics.physx_manager import PhysxManager, IsaacEvents + original_module = sys.modules.get("isaacsim.core.simulation_manager") + if original_module is None: + return + + from .physics.physx_manager import IsaacEvents, PhysxManager + + # Tear down the original Isaac Sim SimulationManager's default timeline / + # stage subscriptions so they cannot invalidate the omni.physics.tensors + # view that PhysxManager owns. ``enable_all_default_callbacks(False)`` + # covers warm_start (PLAY), on_stop (STOP), stage_open (OPENED) and + # stage_close (CLOSED). Older Isaac Sim builds may not expose this API, so + # fall back gracefully. + original_class = getattr(original_module, "SimulationManager", None) + if original_class is not None and original_class is not PhysxManager: + try: + original_class.enable_all_default_callbacks(False) + except Exception: + # Defensive: API changed or original class never finished startup. + # Manually clear the subscription handles if they exist so any + # remaining references go through the dead-callback path. + for attr in ( + "_default_callback_warm_start", + "_default_callback_on_stop", + "_default_callback_stage_open", + "_default_callback_stage_close", + ): + if hasattr(original_class, attr): + setattr(original_class, attr, None) - original_module.SimulationManager = PhysxManager - original_module.IsaacEvents = IsaacEvents + original_module.SimulationManager = PhysxManager + original_module.IsaacEvents = IsaacEvents _patch_isaacsim_simulation_manager() diff --git a/source/isaaclab_physx/isaaclab_physx/assets/articulation/articulation.py b/source/isaaclab_physx/isaaclab_physx/assets/articulation/articulation.py index cf7d1f95d5ca..913914e29f30 100644 --- a/source/isaaclab_physx/isaaclab_physx/assets/articulation/articulation.py +++ b/source/isaaclab_physx/isaaclab_physx/assets/articulation/articulation.py @@ -35,7 +35,7 @@ from .articulation_data import ArticulationData if TYPE_CHECKING: - import omni.physics.tensors.impl.api as physx + import omni.physics.tensors.api as physx from isaaclab.assets.articulation.articulation_cfg import ArticulationCfg @@ -237,30 +237,22 @@ def write_data_to_sim(self): # write external wrench if self._instantaneous_wrench_composer.active or self._permanent_wrench_composer.active: if self._instantaneous_wrench_composer.active: - # Compose instantaneous wrench with permanent wrench - self._instantaneous_wrench_composer.add_forces_and_torques_index( - forces=self._permanent_wrench_composer.composed_force, - torques=self._permanent_wrench_composer.composed_torque, - body_ids=self._ALL_BODY_INDICES, - env_ids=self._ALL_INDICES, - ) - # Apply both instantaneous and permanent wrench to the simulation - self.root_view.apply_forces_and_torques_at_position( - force_data=self._instantaneous_wrench_composer.composed_force.flatten().view(wp.float32), - torque_data=self._instantaneous_wrench_composer.composed_torque.flatten().view(wp.float32), - position_data=None, - indices=self._ALL_INDICES, - is_global=False, - ) + composer = self._instantaneous_wrench_composer + composer.add_raw_buffers_from(self._permanent_wrench_composer) + get_force_data = self._get_inst_wrench_force_f32 + get_torque_data = self._get_inst_wrench_torque_f32 else: - # Apply permanent wrench to the simulation - self.root_view.apply_forces_and_torques_at_position( - force_data=self._permanent_wrench_composer.composed_force.flatten().view(wp.float32), - torque_data=self._permanent_wrench_composer.composed_torque.flatten().view(wp.float32), - position_data=None, - indices=self._ALL_INDICES, - is_global=False, - ) + composer = self._permanent_wrench_composer + get_force_data = self._get_perm_wrench_force_f32 + get_torque_data = self._get_perm_wrench_torque_f32 + composer.compose_to_body_frame() + self.root_view.apply_forces_and_torques_at_position( + force_data=get_force_data(), + torque_data=get_torque_data(), + position_data=None, + indices=self._ALL_INDICES, + is_global=False, + ) self._instantaneous_wrench_composer.reset() # apply actuator models @@ -382,7 +374,7 @@ def write_root_pose_to_sim_index( The root pose comprises of the cartesian position and quaternion orientation in (x, y, z, w). .. note:: - This method expect partial data. + This method expects partial data. .. tip:: For maximum performance we recommend using the index method. This is because in PhysX, the tensor API @@ -406,7 +398,7 @@ def write_root_pose_to_sim_mask( The root pose comprises of the cartesian position and quaternion orientation in (x, y, z, w). .. note:: - This method expect full data. + This method expects full data. .. tip:: For maximum performance we recommend using the index method. This is because in PhysX, the tensor API @@ -431,7 +423,7 @@ def write_root_link_pose_to_sim_index( The root pose comprises of the cartesian position and quaternion orientation in (x, y, z, w). .. note:: - This method expect partial data or full data. + This method expects partial data or full data. .. tip:: For maximum performance we recommend using the index method. This is because in PhysX, the tensor API @@ -460,8 +452,6 @@ def write_root_link_pose_to_sim_index( ], outputs=[ self.data.root_link_pose_w, - None, # self.data._root_link_state_w.data, - None, # self.data._root_state_w.data, ], device=self.device, ) @@ -475,7 +465,7 @@ def write_root_link_pose_to_sim_index( self.data._body_link_state_w.timestamp = -1.0 self.data._body_com_state_w.timestamp = -1.0 # set into simulation - self.root_view.set_root_transforms(self.data._root_link_pose_w.data.view(wp.float32), indices=env_ids) + self.root_view.set_root_transforms(self._get_root_link_pose_w_f32(), indices=env_ids) def write_root_link_pose_to_sim_mask( self, @@ -488,7 +478,7 @@ def write_root_link_pose_to_sim_mask( The root pose comprises of the cartesian position and quaternion orientation in (x, y, z, w). .. note:: - This method expect full data. + This method expects full data. .. tip:: For maximum performance we recommend using the index method. This is because in PhysX, the tensor API @@ -517,7 +507,7 @@ def write_root_com_pose_to_sim_index( The orientation is the orientation of the principal axes of inertia. .. note:: - This method expect partial data or full data. + This method expects partial data or full data. .. tip:: For maximum performance we recommend using the index method. This is because in PhysX, the tensor API @@ -550,9 +540,6 @@ def write_root_com_pose_to_sim_index( outputs=[ self.data.root_com_pose_w, self.data.root_link_pose_w, - None, # self.data._root_com_state_w.data, - None, # self.data._root_link_state_w.data, - None, # self.data._root_state_w.data, ], device=self.device, ) @@ -567,7 +554,7 @@ def write_root_com_pose_to_sim_index( self.data._body_link_state_w.timestamp = -1.0 self.data._body_com_state_w.timestamp = -1.0 # set into simulation - self.root_view.set_root_transforms(self.data._root_link_pose_w.data.view(wp.float32), indices=env_ids) + self.root_view.set_root_transforms(self._get_root_link_pose_w_f32(), indices=env_ids) def write_root_com_pose_to_sim_mask( self, @@ -581,7 +568,7 @@ def write_root_com_pose_to_sim_mask( The orientation is the orientation of the principal axes of inertia. .. note:: - This method expect full data. + This method expects full data. .. tip:: For maximum performance we recommend using the index method. This is because in PhysX, the tensor API @@ -611,7 +598,7 @@ def write_root_velocity_to_sim_index( This sets the velocity of the root's center of mass rather than the root's frame. .. note:: - This method expect partial data. + This method expects partial data. .. tip:: For maximum performance we recommend using the index method. This is because in PhysX, the tensor API @@ -638,7 +625,7 @@ def write_root_velocity_to_sim_mask( This sets the velocity of the root's center of mass rather than the root's frame. .. note:: - This method expect full data. + This method expects full data. .. tip:: For maximum performance we recommend using the index method. This is because in PhysX, the tensor API @@ -666,7 +653,7 @@ def write_root_com_velocity_to_sim_index( This sets the velocity of the root's center of mass rather than the root's frame. .. note:: - This method expect partial data or full data. + This method expects partial data or full data. .. tip:: For maximum performance we recommend using the index method. This is because in PhysX, the tensor API @@ -697,8 +684,6 @@ def write_root_com_velocity_to_sim_index( outputs=[ self.data.root_com_vel_w, self.data.body_com_acc_w, - None, # self.data._root_state_w.data, - None, # self.data._root_com_state_w.data, ], device=self.device, ) @@ -706,7 +691,7 @@ def write_root_com_velocity_to_sim_index( self.data._root_state_w.timestamp = -1.0 self.data._root_com_state_w.timestamp = -1.0 # set into simulation - self.root_view.set_root_velocities(self.data._root_com_vel_w.data.view(wp.float32), indices=env_ids) + self.root_view.set_root_velocities(self._get_root_com_vel_w_f32(), indices=env_ids) def write_root_com_velocity_to_sim_mask( self, @@ -722,7 +707,7 @@ def write_root_com_velocity_to_sim_mask( This sets the velocity of the root's center of mass rather than the root's frame. .. note:: - This method expect full data. + This method expects full data. .. tip:: For maximum performance we recommend using the index method. This is because in PhysX, the tensor API @@ -753,7 +738,7 @@ def write_root_link_velocity_to_sim_index( This sets the velocity of the root's frame rather than the root's center of mass. .. note:: - This method expect partial data or full data. + This method expects partial data or full data. .. tip:: For maximum performance we recommend using the index method. This is because in PhysX, the tensor API @@ -788,9 +773,6 @@ def write_root_link_velocity_to_sim_index( self.data.root_link_vel_w, self.data.root_com_vel_w, self.data.body_com_acc_w, - None, # self.data._root_link_state_w.data, - None, # self.data._root_state_w.data, - None, # self.data._root_com_state_w.data, ], device=self.device, ) @@ -799,7 +781,7 @@ def write_root_link_velocity_to_sim_index( self.data._root_state_w.timestamp = -1.0 self.data._root_com_state_w.timestamp = -1.0 # set into simulation - self.root_view.set_root_velocities(self.data._root_link_vel_w.data.view(wp.float32), indices=env_ids) + self.root_view.set_root_velocities(self._get_root_link_vel_w_f32(), indices=env_ids) def write_root_link_velocity_to_sim_mask( self, @@ -815,7 +797,7 @@ def write_root_link_velocity_to_sim_mask( This sets the velocity of the root's frame rather than the root's center of mass. .. note:: - This method expect full data. + This method expects full data. .. tip:: For maximum performance we recommend using the index method. This is because in PhysX, the tensor API @@ -831,6 +813,71 @@ def write_root_link_velocity_to_sim_mask( # Set full data to True to ensure the the right code path is taken inside the kernel. self.write_root_link_velocity_to_sim_index(root_velocity=root_velocity, env_ids=env_ids, full_data=True) + def write_joint_state_to_sim_index( + self, + *, + position: torch.Tensor | wp.array, + velocity: torch.Tensor | wp.array, + joint_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, + full_data: bool = False, + ): + """Write joint positions and velocities in a single fused kernel launch. + + .. note:: + This method expects partial data or full data. + + .. tip:: + For maximum performance we recommend using the index method. This is because in PhysX, the tensor API + is only supporting indexing, hence masks need to be converted to indices. + + Args: + position: Joint positions. Shape is (len(env_ids), len(joint_ids)) or (num_instances, num_joints). + velocity: Joint velocities. Shape is (len(env_ids), len(joint_ids)) or (num_instances, num_joints). + joint_ids: Joint indices. If None, then all joints are used. + env_ids: Environment indices. If None, then all indices are used. + full_data: Whether to expect full data. Defaults to False. + """ + # resolve all indices + env_ids = self._resolve_env_ids(env_ids) + joint_ids = self._resolve_joint_ids(joint_ids) + if full_data: + self.assert_shape_and_dtype(position, (self.num_instances, self.num_joints), wp.float32, "position") + self.assert_shape_and_dtype(velocity, (self.num_instances, self.num_joints), wp.float32, "velocity") + else: + self.assert_shape_and_dtype(position, (env_ids.shape[0], joint_ids.shape[0]), wp.float32, "position") + self.assert_shape_and_dtype(velocity, (env_ids.shape[0], joint_ids.shape[0]), wp.float32, "velocity") + wp.launch( + articulation_kernels.write_joint_state_data, + dim=(env_ids.shape[0], joint_ids.shape[0]), + inputs=[ + position, + velocity, + env_ids, + joint_ids, + full_data, + ], + outputs=[ + self.data.joint_pos, + self.data.joint_vel, + self.data._previous_joint_vel, + self.data.joint_acc, + ], + device=self.device, + ) + # Invalidate buffers + self.data._body_com_vel_w.timestamp = -1.0 + self.data._body_link_vel_w.timestamp = -1.0 + self.data._body_com_pose_b.timestamp = -1.0 + self.data._body_com_pose_w.timestamp = -1.0 + self.data._body_link_pose_w.timestamp = -1.0 + self.data._body_state_w.timestamp = -1.0 + self.data._body_link_state_w.timestamp = -1.0 + self.data._body_com_state_w.timestamp = -1.0 + # set into simulation + self.root_view.set_dof_positions(self.data._joint_pos.data, indices=env_ids) + self.root_view.set_dof_velocities(self.data._joint_vel.data, indices=env_ids) + def write_joint_state_to_sim_mask( self, *, @@ -842,7 +889,7 @@ def write_joint_state_to_sim_mask( """Write joint positions and velocities over selected environment mask into the simulation. .. note:: - This method expect full data. + This method expects full data. .. tip:: For maximum performance we recommend using the index method. This is because in PhysX, the tensor API @@ -854,9 +901,12 @@ def write_joint_state_to_sim_mask( joint_mask: Joint mask. If None, then all joints are used. env_mask: Environment mask. If None, then all the instances are updated. Shape is (num_instances,). """ - # set into simulation - self.write_joint_position_to_sim_mask(position=position, env_mask=env_mask, joint_mask=joint_mask) - self.write_joint_velocity_to_sim_mask(velocity=velocity, env_mask=env_mask, joint_mask=joint_mask) + # resolve masks to indices (PhysX only supports index-based TensorAPI) + env_ids = self._resolve_env_mask(env_mask) + joint_ids = self._resolve_joint_mask(joint_mask) + self.write_joint_state_to_sim_index( + position=position, velocity=velocity, joint_ids=joint_ids, env_ids=env_ids, full_data=True + ) def write_joint_position_to_sim_index( self, @@ -869,7 +919,7 @@ def write_joint_position_to_sim_index( """Write joint positions over selected environment indices into the simulation. .. note:: - This method expect partial data or full data. + This method expects partial data or full data. .. tip:: For maximum performance we recommend using the index method. This is because in PhysX, the tensor API @@ -926,7 +976,7 @@ def write_joint_position_to_sim_mask( """Write joint positions over selected environment mask into the simulation. .. note:: - This method expect full data. + This method expects full data. .. tip:: For maximum performance we recommend using the index method. This is because in PhysX, the tensor API @@ -954,7 +1004,7 @@ def write_joint_velocity_to_sim_index( """Write joint velocities to the simulation. .. note:: - This method expect partial data or full data. + This method expects partial data or full data. .. tip:: For maximum performance we recommend using the index method. This is because in PhysX, the tensor API @@ -1003,7 +1053,7 @@ def write_joint_velocity_to_sim_mask( """Write joint velocities over selected environment mask into the simulation. .. note:: - This method expect full data. + This method expects full data. .. tip:: For maximum performance we recommend using the index method. This is because in PhysX, the tensor API @@ -1035,7 +1085,7 @@ def write_joint_stiffness_to_sim_index( """Write joint stiffness over selected environment indices into the simulation. .. note:: - This method expect partial data or full data. + This method expects partial data or full data. .. tip:: For maximum performance we recommend using the index method. This is because in PhysX, the tensor API @@ -1086,7 +1136,8 @@ def write_joint_stiffness_to_sim_index( ) # Set into simulation, note that when updating "model" properties with PhysX we need to do it on CPU. cpu_env_ids = self._get_cpu_env_ids(env_ids) - self.root_view.set_dof_stiffnesses(wp.clone(self.data._joint_stiffness, device="cpu"), indices=cpu_env_ids) + wp.copy(self._cpu_joint_stiffness, self.data._joint_stiffness) + self.root_view.set_dof_stiffnesses(self._cpu_joint_stiffness, indices=cpu_env_ids) def write_joint_stiffness_to_sim_mask( self, @@ -1098,7 +1149,7 @@ def write_joint_stiffness_to_sim_mask( """Write joint stiffness over selected environment mask into the simulation. .. note:: - This method expect full data. + This method expects full data. .. tip:: For maximum performance we recommend using the index method. This is because in PhysX, the tensor API @@ -1180,7 +1231,8 @@ def write_joint_damping_to_sim_index( ) # Set into simulation, note that when updating "model" properties with PhysX we need to do it on CPU. cpu_env_ids = self._get_cpu_env_ids(env_ids) - self.root_view.set_dof_dampings(wp.clone(self.data._joint_damping, device="cpu"), indices=cpu_env_ids) + wp.copy(self._cpu_joint_damping, self.data._joint_damping) + self.root_view.set_dof_dampings(self._cpu_joint_damping, indices=cpu_env_ids) def write_joint_damping_to_sim_mask( self, @@ -1280,7 +1332,8 @@ def write_joint_position_limit_to_sim_index( logger.info(violation_message) # Set into simulation, note that when updating "model" properties with PhysX we need to do it on CPU. cpu_env_ids = self._get_cpu_env_ids(env_ids) - self.root_view.set_dof_limits(wp.clone(self.data._joint_pos_limits, device="cpu"), indices=cpu_env_ids) + wp.copy(self._cpu_joint_pos_limits, self.data._joint_pos_limits) + self.root_view.set_dof_limits(self._cpu_joint_pos_limits, indices=cpu_env_ids) def write_joint_position_limit_to_sim_mask( self, @@ -1384,7 +1437,8 @@ def write_joint_velocity_limit_to_sim_index( ) # Set into simulation, note that when updating "model" properties with PhysX we need to do it on CPU. cpu_env_ids = self._get_cpu_env_ids(env_ids) - self.root_view.set_dof_max_velocities(wp.clone(self.data._joint_vel_limits, device="cpu"), indices=cpu_env_ids) + wp.copy(self._cpu_joint_vel_limits, self.data._joint_vel_limits) + self.root_view.set_dof_max_velocities(self._cpu_joint_vel_limits, indices=cpu_env_ids) def write_joint_velocity_limit_to_sim_mask( self, @@ -1485,7 +1539,8 @@ def write_joint_effort_limit_to_sim_index( ) # Set into simulation, note that when updating "model" properties with PhysX we need to do it on CPU. cpu_env_ids = self._get_cpu_env_ids(env_ids) - self.root_view.set_dof_max_forces(wp.clone(self.data._joint_effort_limits, device="cpu"), indices=cpu_env_ids) + wp.copy(self._cpu_joint_effort_limits, self.data._joint_effort_limits) + self.root_view.set_dof_max_forces(self._cpu_joint_effort_limits, indices=cpu_env_ids) def write_joint_effort_limit_to_sim_mask( self, @@ -1584,7 +1639,8 @@ def write_joint_armature_to_sim_index( if isinstance(env_ids, torch.Tensor): env_ids = wp.from_torch(env_ids, dtype=wp.int32) cpu_env_ids = self._get_cpu_env_ids(env_ids) - self.root_view.set_dof_armatures(wp.clone(self.data._joint_armature, device="cpu"), indices=cpu_env_ids) + wp.copy(self._cpu_joint_armature, self.data._joint_armature) + self.root_view.set_dof_armatures(self._cpu_joint_armature, indices=cpu_env_ids) def write_joint_armature_to_sim_mask( self, @@ -1723,7 +1779,8 @@ def write_joint_friction_coefficient_to_sim_index( ) # Set into simulation, note that when updating "model" properties with PhysX we need to do it on CPU. cpu_env_ids = self._get_cpu_env_ids(env_ids) - self.root_view.set_dof_friction_properties(wp.clone(friction_props, device="cpu"), indices=cpu_env_ids) + wp.copy(self._cpu_joint_friction_props, friction_props) + self.root_view.set_dof_friction_properties(self._cpu_joint_friction_props, indices=cpu_env_ids) def write_joint_friction_coefficient_to_sim_mask( self, @@ -1840,7 +1897,8 @@ def write_joint_dynamic_friction_coefficient_to_sim_index( ) # Set into simulation, note that when updating "model" properties with PhysX we need to do it on CPU. cpu_env_ids = self._get_cpu_env_ids(env_ids) - self.root_view.set_dof_friction_properties(wp.clone(friction_props, device="cpu"), indices=cpu_env_ids) + wp.copy(self._cpu_joint_friction_props, friction_props) + self.root_view.set_dof_friction_properties(self._cpu_joint_friction_props, indices=cpu_env_ids) def write_joint_dynamic_friction_coefficient_to_sim_mask( self, @@ -1940,7 +1998,8 @@ def write_joint_viscous_friction_coefficient_to_sim_index( ) # Set into simulation, note that when updating "model" properties with PhysX we need to do it on CPU. cpu_env_ids = self._get_cpu_env_ids(env_ids) - self.root_view.set_dof_friction_properties(wp.clone(friction_props, device="cpu"), indices=cpu_env_ids) + wp.copy(self._cpu_joint_friction_props, friction_props) + self.root_view.set_dof_friction_properties(self._cpu_joint_friction_props, indices=cpu_env_ids) def write_joint_viscous_friction_coefficient_to_sim_mask( self, @@ -2027,7 +2086,8 @@ def set_masses_index( # Set into simulation, note that when updating "model" properties with PhysX we need to do it on CPU. cpu_env_ids = self._get_cpu_env_ids(env_ids) - self.root_view.set_masses(wp.clone(self.data._body_mass, device="cpu"), indices=cpu_env_ids) + wp.copy(self._cpu_body_mass, self.data._body_mass) + self.root_view.set_masses(self._cpu_body_mass, indices=cpu_env_ids) def set_masses_mask( self, @@ -2106,12 +2166,11 @@ def set_coms_index( # Set into simulation, note that when updating "model" properties with PhysX we need to do it on CPU. # Convert from wp.transformf to flat (N, M, 7) array for PhysX cpu_env_ids = self._get_cpu_env_ids(env_ids) - body_com_flat = ( - wp.clone(self.data._body_com_pose_b.data, device="cpu") - .view(wp.float32) - .reshape((self.num_instances, self.num_bodies, 7)) + wp.copy( + self._cpu_body_coms, + self.data._body_com_pose_b.data.view(wp.float32).reshape((self.num_instances, self.num_bodies, 7)), ) - self.root_view.set_coms(body_com_flat, indices=cpu_env_ids) + self.root_view.set_coms(self._cpu_body_coms, indices=cpu_env_ids) def set_coms_mask( self, @@ -2189,7 +2248,8 @@ def set_inertias_index( ) # Set into simulation, note that when updating "model" properties with PhysX we need to do it on CPU. cpu_env_ids = self._get_cpu_env_ids(env_ids) - self.root_view.set_inertias(wp.clone(self.data._body_inertia, device="cpu"), indices=cpu_env_ids) + wp.copy(self._cpu_body_inertia, self.data._body_inertia) + self.root_view.set_inertias(self._cpu_body_inertia, indices=cpu_env_ids) def set_inertias_mask( self, @@ -3088,12 +3148,12 @@ def write_fixed_tendon_properties_to_sim_index( env_ids = self._resolve_env_ids(env_ids) # Write fixed tendon properties to the simulation. self.root_view.set_fixed_tendon_properties( - self.data.fixed_tendon_stiffness, - self.data.fixed_tendon_damping, - self.data.fixed_tendon_limit_stiffness, - self.data.fixed_tendon_pos_limits, - self.data.fixed_tendon_rest_length, - self.data.fixed_tendon_offset, + self.data.fixed_tendon_stiffness.warp, + self.data.fixed_tendon_damping.warp, + self.data.fixed_tendon_limit_stiffness.warp, + self.data.fixed_tendon_pos_limits.warp, + self.data.fixed_tendon_rest_length.warp, + self.data.fixed_tendon_offset.warp, indices=env_ids, ) @@ -3545,10 +3605,10 @@ def write_spatial_tendon_properties_to_sim_index( env_ids = wp.array(env_ids, dtype=wp.int32, device=self.device) # Write spatial tendon properties to the simulation. self.root_view.set_spatial_tendon_properties( - self.data.spatial_tendon_stiffness, - self.data.spatial_tendon_damping, - self.data.spatial_tendon_limit_stiffness, - self.data.spatial_tendon_offset, + self.data.spatial_tendon_stiffness.warp, + self.data.spatial_tendon_damping.warp, + self.data.spatial_tendon_limit_stiffness.warp, + self.data.spatial_tendon_offset.warp, indices=env_ids, ) @@ -3680,6 +3740,35 @@ def _create_buffers(self): device=self.device, ) + # Cached .view(wp.float32) wrappers for structured warp arrays. + # These avoid per-call wp.array metadata allocation in writers. + # Reset to None each time _create_buffers runs (during initialization). + self._root_link_pose_w_f32: wp.array | None = None + self._root_com_vel_w_f32: wp.array | None = None + self._root_link_vel_w_f32: wp.array | None = None + # Cached wrench views for write_data_to_sim + self._inst_wrench_force_f32: wp.array | None = None + self._inst_wrench_torque_f32: wp.array | None = None + self._perm_wrench_force_f32: wp.array | None = None + self._perm_wrench_torque_f32: wp.array | None = None + + # Pre-allocated pinned CPU buffers for PhysX TensorAPI writes. + # PhysX requires CPU arrays for "model" property updates (stiffness, damping, etc.). + # Pinned memory enables DMA fast path and avoids per-call malloc. + N, J, B = self.num_instances, self.num_joints, self.num_bodies + self._cpu_env_ids_all = wp.zeros(N, dtype=wp.int32, device="cpu", pinned=True) + wp.copy(self._cpu_env_ids_all, self._ALL_INDICES) + self._cpu_joint_stiffness = wp.zeros((N, J), dtype=wp.float32, device="cpu", pinned=True) + self._cpu_joint_damping = wp.zeros((N, J), dtype=wp.float32, device="cpu", pinned=True) + self._cpu_joint_pos_limits = wp.zeros((N, J, 2), dtype=wp.float32, device="cpu", pinned=True) + self._cpu_joint_vel_limits = wp.zeros((N, J), dtype=wp.float32, device="cpu", pinned=True) + self._cpu_joint_effort_limits = wp.zeros((N, J), dtype=wp.float32, device="cpu", pinned=True) + self._cpu_joint_armature = wp.zeros((N, J), dtype=wp.float32, device="cpu", pinned=True) + self._cpu_joint_friction_props = wp.zeros((N, J, 3), dtype=wp.float32, device="cpu", pinned=True) + self._cpu_body_mass = wp.zeros((N, B), dtype=wp.float32, device="cpu", pinned=True) + self._cpu_body_coms = wp.zeros((N, B, 7), dtype=wp.float32, device="cpu", pinned=True) + self._cpu_body_inertia = wp.zeros((N, B, 9), dtype=wp.float32, device="cpu", pinned=True) + def _process_cfg(self): """Post processing of configuration parameters.""" # default state @@ -3768,14 +3857,14 @@ def _process_actuators_cfg(self): joint_ids=joint_ids, num_envs=self.num_instances, device=self.device, - stiffness=wp.to_torch(self._data.joint_stiffness)[:, joint_ids], - damping=wp.to_torch(self._data.joint_damping)[:, joint_ids], - armature=wp.to_torch(self._data.joint_armature)[:, joint_ids], - friction=wp.to_torch(self._data.joint_friction_coeff)[:, joint_ids], - dynamic_friction=wp.to_torch(self._data.joint_dynamic_friction_coeff)[:, joint_ids], - viscous_friction=wp.to_torch(self._data.joint_viscous_friction_coeff)[:, joint_ids], - effort_limit=wp.to_torch(self._data.joint_effort_limits)[:, joint_ids].clone(), - velocity_limit=wp.to_torch(self._data.joint_vel_limits)[:, joint_ids], + stiffness=self._data.joint_stiffness.torch[:, joint_ids], + damping=self._data.joint_damping.torch[:, joint_ids], + armature=self._data.joint_armature.torch[:, joint_ids], + friction=self._data.joint_friction_coeff.torch[:, joint_ids], + dynamic_friction=self._data.joint_dynamic_friction_coeff.torch[:, joint_ids], + viscous_friction=self._data.joint_viscous_friction_coeff.torch[:, joint_ids], + effort_limit=self._data.joint_effort_limits.torch[:, joint_ids].clone(), + velocity_limit=self._data.joint_vel_limits.torch[:, joint_ids], ) # store actuator group self.actuators[actuator_name] = actuator @@ -3957,16 +4046,16 @@ def _apply_actuator_model(self): # prepare input for actuator model based on cached data # TODO : A tensor dict would be nice to do the indexing of all tensors together control_action = ArticulationActions( - joint_positions=wp.to_torch(self._data.joint_pos_target)[:, actuator.joint_indices], - joint_velocities=wp.to_torch(self._data.joint_vel_target)[:, actuator.joint_indices], - joint_efforts=wp.to_torch(self._data.joint_effort_target)[:, actuator.joint_indices], + joint_positions=self._data.joint_pos_target.torch[:, actuator.joint_indices], + joint_velocities=self._data.joint_vel_target.torch[:, actuator.joint_indices], + joint_efforts=self._data.joint_effort_target.torch[:, actuator.joint_indices], joint_indices=actuator.joint_indices, ) # compute joint command from the actuator model control_action = actuator.compute( control_action, - joint_pos=wp.to_torch(self._data.joint_pos)[:, actuator.joint_indices], - joint_vel=wp.to_torch(self._data.joint_vel)[:, actuator.joint_indices], + joint_pos=self._data.joint_pos.torch[:, actuator.joint_indices], + joint_vel=self._data.joint_vel.torch[:, actuator.joint_indices], ) # update targets (these are set into the simulation) joint_indices = actuator.joint_indices @@ -4026,8 +4115,8 @@ def _validate_cfg(self): """ # check that the default values are within the limits joint_pos_limits = wp.to_torch(wp.clone(self.root_view.get_dof_limits(), device=self.device))[0] - out_of_range = wp.to_torch(self._data.default_joint_pos)[0] < joint_pos_limits[:, 0] - out_of_range |= wp.to_torch(self._data.default_joint_pos)[0] > joint_pos_limits[:, 1] + out_of_range = self._data.default_joint_pos.torch[0] < joint_pos_limits[:, 0] + out_of_range |= self._data.default_joint_pos.torch[0] > joint_pos_limits[:, 1] violated_indices = torch.nonzero(out_of_range, as_tuple=False).squeeze(-1) # throw error if any of the default joint positions are out of the limits if len(violated_indices) > 0: @@ -4036,14 +4125,14 @@ def _validate_cfg(self): for idx in violated_indices: joint_name = self.data.joint_names[idx] joint_limit = joint_pos_limits[idx] - joint_pos = wp.to_torch(self._data.default_joint_pos)[0, idx] + joint_pos = self._data.default_joint_pos.torch[0, idx] # add to message msg += f"\t- '{joint_name}': {joint_pos:.3f} not in [{joint_limit[0]:.3f}, {joint_limit[1]:.3f}]\n" raise ValueError(msg) # check that the default joint velocities are within the limits joint_max_vel = wp.to_torch(wp.clone(self.root_view.get_dof_max_velocities(), device=self.device))[0] - out_of_range = torch.abs(wp.to_torch(self._data.default_joint_vel)[0]) > joint_max_vel + out_of_range = torch.abs(self._data.default_joint_vel.torch[0]) > joint_max_vel violated_indices = torch.nonzero(out_of_range, as_tuple=False).squeeze(-1) if len(violated_indices) > 0: # prepare message for violated joints @@ -4051,7 +4140,7 @@ def _validate_cfg(self): for idx in violated_indices: joint_name = self.data.joint_names[idx] joint_limit = [-joint_max_vel[idx], joint_max_vel[idx]] - joint_vel = wp.to_torch(self._data.default_joint_vel)[0, idx] + joint_vel = self._data.default_joint_vel.torch[0, idx] # add to message msg += f"\t- '{joint_name}': {joint_vel:.3f} not in [{joint_limit[0]:.3f}, {joint_limit[1]:.3f}]\n" raise ValueError(msg) @@ -4082,23 +4171,23 @@ def format_limits(_, v: tuple[float, float]) -> str: # -- gains # Use data properties which have already been cloned and stored during initialization # This avoids issues with indexedarray or empty arrays from root_view - stiffnesses = wp.to_torch(self.data.joint_stiffness)[0].cpu().tolist() - dampings = wp.to_torch(self.data.joint_damping)[0].cpu().tolist() + stiffnesses = self.data.joint_stiffness.torch[0].cpu().tolist() + dampings = self.data.joint_damping.torch[0].cpu().tolist() # -- properties - armatures = wp.to_torch(self.data.joint_armature)[0].cpu().tolist() + armatures = self.data.joint_armature.torch[0].cpu().tolist() # For friction, use the individual components from data - friction_coeff = wp.to_torch(self.data.joint_friction_coeff)[0].cpu() - dynamic_friction_coeff = wp.to_torch(self.data.joint_dynamic_friction_coeff)[0].cpu() - viscous_friction_coeff = wp.to_torch(self.data.joint_viscous_friction_coeff)[0].cpu() + friction_coeff = self.data.joint_friction_coeff.torch[0].cpu() + dynamic_friction_coeff = self.data.joint_dynamic_friction_coeff.torch[0].cpu() + viscous_friction_coeff = self.data.joint_viscous_friction_coeff.torch[0].cpu() static_frictions = friction_coeff.tolist() dynamic_frictions = dynamic_friction_coeff.tolist() viscous_frictions = viscous_friction_coeff.tolist() # -- limits # joint_pos_limits is vec2f array, convert to torch and extract [lower, upper] pairs - position_limits_torch = wp.to_torch(self.data.joint_pos_limits)[0].cpu() # shape: (num_joints, 2) + position_limits_torch = self.data.joint_pos_limits.torch[0].cpu() # shape: (num_joints, 2) position_limits = [tuple(pos_limit.tolist()) for pos_limit in position_limits_torch] - velocity_limits = wp.to_torch(self.data.joint_vel_limits)[0].cpu().tolist() - effort_limits = wp.to_torch(self.data.joint_effort_limits)[0].cpu().tolist() + velocity_limits = self.data.joint_vel_limits.torch[0].cpu().tolist() + effort_limits = self.data.joint_effort_limits.torch[0].cpu().tolist() # create table for term information joint_table = PrettyTable() joint_table.title = f"Simulation Joint Information (Prim path: {self.cfg.prim_path})" @@ -4139,15 +4228,15 @@ def format_limits(_, v: tuple[float, float]) -> str: if self.num_fixed_tendons > 0: # -- gains # Use data properties which have already been cloned and stored during initialization - ft_stiffnesses = wp.to_torch(self.data.fixed_tendon_stiffness)[0].cpu().tolist() - ft_dampings = wp.to_torch(self.data.fixed_tendon_damping)[0].cpu().tolist() + ft_stiffnesses = self.data.fixed_tendon_stiffness.torch[0].cpu().tolist() + ft_dampings = self.data.fixed_tendon_damping.torch[0].cpu().tolist() # -- limits - ft_limit_stiffnesses = wp.to_torch(self.data.fixed_tendon_limit_stiffness)[0].cpu().tolist() + ft_limit_stiffnesses = self.data.fixed_tendon_limit_stiffness.torch[0].cpu().tolist() # fixed_tendon_pos_limits is vec2f array - ft_limits_torch = wp.to_torch(self.data.fixed_tendon_pos_limits)[0].cpu() + ft_limits_torch = self.data.fixed_tendon_pos_limits.torch[0].cpu() ft_limits = [tuple(limit.tolist()) for limit in ft_limits_torch] - ft_rest_lengths = wp.to_torch(self.data.fixed_tendon_rest_length)[0].cpu().tolist() - ft_offsets = wp.to_torch(self.data.fixed_tendon_offset)[0].cpu().tolist() + ft_rest_lengths = self.data.fixed_tendon_rest_length.torch[0].cpu().tolist() + ft_offsets = self.data.fixed_tendon_offset.torch[0].cpu().tolist() # create table for term information tendon_table = PrettyTable() tendon_table.title = f"Simulation Fixed Tendon Information (Prim path: {self.cfg.prim_path})" @@ -4191,11 +4280,11 @@ def format_limits(_, v: tuple[float, float]) -> str: if self.num_spatial_tendons > 0: # -- gains # Use data properties which have already been cloned and stored during initialization - st_stiffnesses = wp.to_torch(self.data.spatial_tendon_stiffness)[0].cpu().tolist() - st_dampings = wp.to_torch(self.data.spatial_tendon_damping)[0].cpu().tolist() + st_stiffnesses = self.data.spatial_tendon_stiffness.torch[0].cpu().tolist() + st_dampings = self.data.spatial_tendon_damping.torch[0].cpu().tolist() # -- limits - st_limit_stiffnesses = wp.to_torch(self.data.spatial_tendon_limit_stiffness)[0].cpu().tolist() - st_offsets = wp.to_torch(self.data.spatial_tendon_offset)[0].cpu().tolist() + st_limit_stiffnesses = self.data.spatial_tendon_limit_stiffness.torch[0].cpu().tolist() + st_offsets = self.data.spatial_tendon_offset.torch[0].cpu().tolist() # create table for term information tendon_table = PrettyTable() tendon_table.title = f"Simulation Spatial Tendon Information (Prim path: {self.cfg.prim_path})" @@ -4224,17 +4313,23 @@ def format_limits(_, v: tuple[float, float]) -> str: ) def _get_cpu_env_ids(self, env_ids: wp.array | torch.Tensor) -> wp.array: - """ - Get the CPU environment indices. + """Get the CPU environment indices. + + For the full-index case (all environments), returns the pre-allocated + pinned CPU buffer. For partial indices (e.g. during partial resets), clones to CPU. Args: env_ids: Environment indices. Returns: - A warp array of environment indices. + A warp array of environment indices on CPU. """ if isinstance(env_ids, torch.Tensor): env_ids = wp.from_torch(env_ids, dtype=wp.int32) + # Fast path: if these are all indices, use pre-allocated pinned buffer + if env_ids.ptr == self._ALL_INDICES.ptr: + return self._cpu_env_ids_all + # Slow path: partial indices (reset), clone to CPU return wp.clone(env_ids, device="cpu") def _resolve_env_mask(self, env_mask: wp.array | None) -> torch.Tensor | wp.array: @@ -4256,12 +4351,55 @@ def _resolve_env_mask(self, env_mask: wp.array | None) -> torch.Tensor | wp.arra env_ids = self._ALL_INDICES return env_ids + def _get_root_link_pose_w_f32(self) -> wp.array: + """Get a cached float32 view of root_link_pose_w for PhysX TensorAPI. Invalidated in ``_create_buffers``.""" + if self._root_link_pose_w_f32 is None: + self._root_link_pose_w_f32 = self.data._root_link_pose_w.data.view(wp.float32) + return self._root_link_pose_w_f32 + + def _get_root_com_vel_w_f32(self) -> wp.array: + """Get a cached float32 view of root_com_vel_w for PhysX TensorAPI. Invalidated in ``_create_buffers``.""" + if self._root_com_vel_w_f32 is None: + self._root_com_vel_w_f32 = self.data._root_com_vel_w.data.view(wp.float32) + return self._root_com_vel_w_f32 + + def _get_root_link_vel_w_f32(self) -> wp.array: + """Get a cached float32 view of root_link_vel_w for PhysX TensorAPI. Invalidated in ``_create_buffers``.""" + if self._root_link_vel_w_f32 is None: + self._root_link_vel_w_f32 = self.data._root_link_vel_w.data.view(wp.float32) + return self._root_link_vel_w_f32 + + def _get_inst_wrench_force_f32(self) -> wp.array: + """Get a cached flattened float32 view of instantaneous wrench force. Invalidated in ``_create_buffers``.""" + if self._inst_wrench_force_f32 is None: + self._inst_wrench_force_f32 = self._instantaneous_wrench_composer.out_force_b.warp.flatten().view( + wp.float32 + ) + return self._inst_wrench_force_f32 + + def _get_inst_wrench_torque_f32(self) -> wp.array: + """Get a cached flattened float32 view of instantaneous wrench torque. Invalidated in ``_create_buffers``.""" + if self._inst_wrench_torque_f32 is None: + self._inst_wrench_torque_f32 = self._instantaneous_wrench_composer.out_torque_b.warp.flatten().view( + wp.float32 + ) + return self._inst_wrench_torque_f32 + + def _get_perm_wrench_force_f32(self) -> wp.array: + """Get a cached flattened float32 view of permanent wrench force. Invalidated in ``_create_buffers``.""" + if self._perm_wrench_force_f32 is None: + self._perm_wrench_force_f32 = self._permanent_wrench_composer.out_force_b.warp.flatten().view(wp.float32) + return self._perm_wrench_force_f32 + + def _get_perm_wrench_torque_f32(self) -> wp.array: + """Get a cached flattened float32 view of permanent wrench torque. Invalidated in ``_create_buffers``.""" + if self._perm_wrench_torque_f32 is None: + self._perm_wrench_torque_f32 = self._permanent_wrench_composer.out_torque_b.warp.flatten().view(wp.float32) + return self._perm_wrench_torque_f32 + def _resolve_env_ids(self, env_ids: Sequence[int] | torch.Tensor | wp.array | None) -> wp.array: """Resolve environment indices to a warp array. - .. note:: - We need to convert torch tensors to warp arrays since the TensorAPI views only support warp arrays. - Args: env_ids: Environment indices. If None, then all indices are used. @@ -4271,7 +4409,6 @@ def _resolve_env_ids(self, env_ids: Sequence[int] | torch.Tensor | wp.array | No if (env_ids is None) or (env_ids == slice(None)): return self._ALL_INDICES if isinstance(env_ids, torch.Tensor): - # Convert int64 to int32 if needed, as warp expects int32 if env_ids.dtype == torch.int64: env_ids = env_ids.to(torch.int32) return wp.from_torch(env_ids, dtype=wp.int32) @@ -4299,9 +4436,6 @@ def _resolve_joint_mask(self, joint_mask: wp.array | None) -> torch.Tensor | wp. def _resolve_joint_ids(self, joint_ids: Sequence[int] | torch.Tensor | wp.array | None) -> wp.array | torch.Tensor: """Resolve joint indices to a warp array or tensor. - .. note:: - We do not need to convert torch tensors to warp arrays since they never get passed to the TensorAPI views. - Args: joint_ids: Joint indices. If None, then all indices are used. @@ -4312,6 +4446,10 @@ def _resolve_joint_ids(self, joint_ids: Sequence[int] | torch.Tensor | wp.array return wp.array(joint_ids, dtype=wp.int32, device=self.device) if (joint_ids is None) or (joint_ids == slice(None)): return self._ALL_JOINT_INDICES + if isinstance(joint_ids, torch.Tensor): + if joint_ids.dtype == torch.int64: + joint_ids = joint_ids.to(torch.int32) + return wp.from_torch(joint_ids, dtype=wp.int32) return joint_ids def _resolve_body_mask(self, body_mask: wp.array | None) -> torch.Tensor | wp.array: @@ -4344,6 +4482,10 @@ def _resolve_body_ids(self, body_ids: Sequence[int] | torch.Tensor | wp.array | return wp.array(body_ids, dtype=wp.int32, device=self.device) if (body_ids is None) or (body_ids == slice(None)): return self._ALL_BODY_INDICES + if isinstance(body_ids, torch.Tensor): + if body_ids.dtype == torch.int64: + body_ids = body_ids.to(torch.int32) + return wp.from_torch(body_ids, dtype=wp.int32) return body_ids def _resolve_fixed_tendon_mask(self, fixed_tendon_mask: wp.array | None) -> torch.Tensor | wp.array: @@ -4556,14 +4698,11 @@ def write_joint_state_to_sim( joint_ids: Sequence[int] | torch.Tensor | wp.array | None = None, env_ids: Sequence[int] | torch.Tensor | wp.array | None = None, ): - """Deprecated, same as :meth:`write_joint_position_to_sim_index` and - :meth:`write_joint_velocity_to_sim_index`.""" + """Deprecated, same as :meth:`write_joint_state_to_sim_index`.""" warnings.warn( "The function 'write_joint_state_to_sim' will be deprecated in a future release. Please" - " use 'write_joint_position_to_sim_index' and 'write_joint_velocity_to_sim_index' instead.", + " use 'write_joint_state_to_sim_index' instead.", DeprecationWarning, stacklevel=2, ) - # set into simulation - self.write_joint_position_to_sim_index(position=position, joint_ids=joint_ids, env_ids=env_ids) - self.write_joint_velocity_to_sim_index(velocity=velocity, joint_ids=joint_ids, env_ids=env_ids) + self.write_joint_state_to_sim_index(position=position, velocity=velocity, joint_ids=joint_ids, env_ids=env_ids) diff --git a/source/isaaclab_physx/isaaclab_physx/assets/articulation/articulation_data.py b/source/isaaclab_physx/isaaclab_physx/assets/articulation/articulation_data.py index 42190a28f473..8c2056d9cbfa 100644 --- a/source/isaaclab_physx/isaaclab_physx/assets/articulation/articulation_data.py +++ b/source/isaaclab_physx/isaaclab_physx/assets/articulation/articulation_data.py @@ -15,13 +15,14 @@ from isaaclab.assets.articulation.base_articulation_data import BaseArticulationData from isaaclab.utils.buffers import TimestampedBufferWarp as TimestampedBuffer from isaaclab.utils.math import normalize +from isaaclab.utils.warp import ProxyArray from isaaclab_physx.assets import kernels as shared_kernels from isaaclab_physx.assets.articulation import kernels as articulation_kernels from isaaclab_physx.physics import PhysxManager as SimulationManager if TYPE_CHECKING: - import omni.physics.tensors.impl.api as physx + import omni.physics.tensors.api as physx # import logger logger = logging.getLogger(__name__) @@ -43,6 +44,21 @@ class ArticulationData(BaseArticulationData): Depending on the settings, the two frames may not coincide with each other. In the robotics sense, the actor frame can be interpreted as the link frame. + + .. note:: + **Pull-to-refresh model.** PhysX state properties are *not* automatically updated each + simulation step. Each property getter pulls fresh data from the PhysX tensor API on first + access per timestamp, then caches the result until the next step. This differs from the + Newton backend, where buffers are refreshed automatically by the simulation. + + .. note:: + **ProxyArray pointer stability.** Each :class:`ProxyArray` wrapper is created once on the + first property access and reused thereafter. This is safe because the PhysX tensor API + returns views into stable, pre-allocated GPU buffers whose device pointer does not change + across simulation steps. The ``wp.array`` Python objects returned by getters like + ``get_root_transforms()`` are new wrappers each call, but they alias the same underlying + GPU memory. Sub-view properties (``root_pos_w``, ``root_quat_w``, etc.) similarly wrap + pointer offsets into these stable buffers and are therefore also safe to cache. """ __backend_name__: str = "physx" @@ -75,8 +91,8 @@ def __init__(self, root_view: physx.ArticulationView, device: str): forward_vec = torch.tensor((1.0, 0.0, 0.0), device=self.device).repeat(self._root_view.count, 1) # Initialize constants - self.GRAVITY_VEC_W = wp.from_torch(gravity_dir, dtype=wp.vec3f) - self.FORWARD_VEC_B = wp.from_torch(forward_vec, dtype=wp.vec3f) + self.GRAVITY_VEC_W = ProxyArray(wp.from_torch(gravity_dir, dtype=wp.vec3f)) + self.FORWARD_VEC_B = ProxyArray(wp.from_torch(forward_vec, dtype=wp.vec3f)) self._create_buffers() @@ -135,13 +151,15 @@ def update(self, dt: float) -> None: """ @property - def default_root_pose(self) -> wp.array: + def default_root_pose(self) -> ProxyArray: """Default root pose ``[pos, quat]`` in the local environment frame. The position and quaternion are of the articulation root's actor frame. Shape is (num_instances,), dtype = wp.transformf. In torch this resolves to (num_instances, 7). """ - return self._default_root_pose + if self._default_root_pose_ta is None: + self._default_root_pose_ta = ProxyArray(self._default_root_pose) + return self._default_root_pose_ta @default_root_pose.setter def default_root_pose(self, value: wp.array) -> None: @@ -158,13 +176,15 @@ def default_root_pose(self, value: wp.array) -> None: self._default_root_pose.assign(value) @property - def default_root_vel(self) -> wp.array: + def default_root_vel(self) -> ProxyArray: """Default root velocity ``[lin_vel, ang_vel]`` in the local environment frame. The linear and angular velocities are of the articulation root's center of mass frame. Shape is (num_instances,), dtype = wp.spatial_vectorf. In torch this resolves to (num_instances, 6). """ - return self._default_root_vel + if self._default_root_vel_ta is None: + self._default_root_vel_ta = ProxyArray(self._default_root_vel) + return self._default_root_vel_ta @default_root_vel.setter def default_root_vel(self, value: wp.array) -> None: @@ -181,14 +201,16 @@ def default_root_vel(self, value: wp.array) -> None: self._default_root_vel.assign(value) @property - def default_joint_pos(self) -> wp.array: + def default_joint_pos(self) -> ProxyArray: """Default joint positions of all joints. Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to (num_instances, num_joints). This quantity is configured through the :attr:`isaaclab.assets.ArticulationCfg.init_state` parameter. """ - return self._default_joint_pos + if self._default_joint_pos_ta is None: + self._default_joint_pos_ta = ProxyArray(self._default_joint_pos) + return self._default_joint_pos_ta @default_joint_pos.setter def default_joint_pos(self, value: wp.array) -> None: @@ -205,14 +227,16 @@ def default_joint_pos(self, value: wp.array) -> None: self._default_joint_pos.assign(value) @property - def default_joint_vel(self) -> wp.array: + def default_joint_vel(self) -> ProxyArray: """Default joint velocities of all joints. Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to (num_instances, num_joints). This quantity is configured through the :attr:`isaaclab.assets.ArticulationCfg.init_state` parameter. """ - return self._default_joint_vel + if self._default_joint_vel_ta is None: + self._default_joint_vel_ta = ProxyArray(self._default_joint_vel) + return self._default_joint_vel_ta @default_joint_vel.setter def default_joint_vel(self, value: wp.array) -> None: @@ -233,7 +257,7 @@ def default_joint_vel(self, value: wp.array) -> None: """ @property - def joint_pos_target(self) -> wp.array: + def joint_pos_target(self) -> ProxyArray: """Joint position targets commanded by the user. Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to (num_instances, num_joints). @@ -242,10 +266,12 @@ def joint_pos_target(self) -> wp.array: For an explicit actuator model, the targets are used to compute the joint torques (see :attr:`applied_torque`), which are then set into the simulation. """ - return self._joint_pos_target + if self._joint_pos_target_ta is None: + self._joint_pos_target_ta = ProxyArray(self._joint_pos_target) + return self._joint_pos_target_ta @property - def joint_vel_target(self) -> wp.array: + def joint_vel_target(self) -> ProxyArray: """Joint velocity targets commanded by the user. Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to (num_instances, num_joints). @@ -254,10 +280,12 @@ def joint_vel_target(self) -> wp.array: For an explicit actuator model, the targets are used to compute the joint torques (see :attr:`applied_torque`), which are then set into the simulation. """ - return self._joint_vel_target + if self._joint_vel_target_ta is None: + self._joint_vel_target_ta = ProxyArray(self._joint_vel_target) + return self._joint_vel_target_ta @property - def joint_effort_target(self) -> wp.array: + def joint_effort_target(self) -> ProxyArray: """Joint effort targets commanded by the user. Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to (num_instances, num_joints). @@ -266,14 +294,16 @@ def joint_effort_target(self) -> wp.array: For an explicit actuator model, the targets are used to compute the joint torques (see :attr:`applied_torque`), which are then set into the simulation. """ - return self._joint_effort_target + if self._joint_effort_target_ta is None: + self._joint_effort_target_ta = ProxyArray(self._joint_effort_target) + return self._joint_effort_target_ta """ Joint commands -- Explicit actuators. """ @property - def computed_torque(self) -> wp.array: + def computed_torque(self) -> ProxyArray: """Joint torques computed from the actuator model (before clipping). Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to (num_instances, num_joints). @@ -282,10 +312,12 @@ def computed_torque(self) -> wp.array: It is exposed for users who want to inspect the computations inside the actuator model. For instance, to penalize the learning agent for a difference between the computed and applied torques. """ - return self._computed_torque + if self._computed_torque_ta is None: + self._computed_torque_ta = ProxyArray(self._computed_torque) + return self._computed_torque_ta @property - def applied_torque(self) -> wp.array: + def applied_torque(self) -> ProxyArray: """Joint torques applied from the actuator model (after clipping). Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to (num_instances, num_joints). @@ -293,66 +325,80 @@ def applied_torque(self) -> wp.array: These torques are set into the simulation, after clipping the :attr:`computed_torque` based on the actuator model. """ - return self._applied_torque + if self._applied_torque_ta is None: + self._applied_torque_ta = ProxyArray(self._applied_torque) + return self._applied_torque_ta """ Joint properties """ @property - def joint_stiffness(self) -> wp.array: + def joint_stiffness(self) -> ProxyArray: """Joint stiffness provided to the simulation. Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to (num_instances, num_joints). In the case of explicit actuators, the value for the corresponding joints is zero. """ - return self._joint_stiffness + if self._joint_stiffness_ta is None: + self._joint_stiffness_ta = ProxyArray(self._joint_stiffness) + return self._joint_stiffness_ta @property - def joint_damping(self) -> wp.array: + def joint_damping(self) -> ProxyArray: """Joint damping provided to the simulation. Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to (num_instances, num_joints). In the case of explicit actuators, the value for the corresponding joints is zero. """ - return self._joint_damping + if self._joint_damping_ta is None: + self._joint_damping_ta = ProxyArray(self._joint_damping) + return self._joint_damping_ta @property - def joint_armature(self) -> wp.array: + def joint_armature(self) -> ProxyArray: """Joint armature provided to the simulation. Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to (num_instances, num_joints). """ - return self._joint_armature + if self._joint_armature_ta is None: + self._joint_armature_ta = ProxyArray(self._joint_armature) + return self._joint_armature_ta @property - def joint_friction_coeff(self) -> wp.array: + def joint_friction_coeff(self) -> ProxyArray: """Joint static friction coefficient provided to the simulation. Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to (num_instances, num_joints). """ - return self._joint_friction_coeff + if self._joint_friction_coeff_ta is None: + self._joint_friction_coeff_ta = ProxyArray(self._joint_friction_coeff) + return self._joint_friction_coeff_ta @property - def joint_dynamic_friction_coeff(self) -> wp.array: + def joint_dynamic_friction_coeff(self) -> ProxyArray: """Joint dynamic friction coefficient provided to the simulation. Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to (num_instances, num_joints). """ - return self._joint_dynamic_friction_coeff + if self._joint_dynamic_friction_coeff_ta is None: + self._joint_dynamic_friction_coeff_ta = ProxyArray(self._joint_dynamic_friction_coeff) + return self._joint_dynamic_friction_coeff_ta @property - def joint_viscous_friction_coeff(self) -> wp.array: + def joint_viscous_friction_coeff(self) -> ProxyArray: """Joint viscous friction coefficient provided to the simulation. Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to (num_instances, num_joints). """ - return self._joint_viscous_friction_coeff + if self._joint_viscous_friction_coeff_ta is None: + self._joint_viscous_friction_coeff_ta = ProxyArray(self._joint_viscous_friction_coeff) + return self._joint_viscous_friction_coeff_ta @property - def joint_pos_limits(self) -> wp.array: + def joint_pos_limits(self) -> ProxyArray: """Joint position limits provided to the simulation. Shape is (num_instances, num_joints), dtype = wp.vec2f. In torch this resolves to @@ -360,30 +406,36 @@ def joint_pos_limits(self) -> wp.array: The limits are in the order :math:`[lower, upper]`. """ - return self._joint_pos_limits + if self._joint_pos_limits_ta is None: + self._joint_pos_limits_ta = ProxyArray(self._joint_pos_limits) + return self._joint_pos_limits_ta @property - def joint_vel_limits(self) -> wp.array: + def joint_vel_limits(self) -> ProxyArray: """Joint maximum velocity provided to the simulation. Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to (num_instances, num_joints). """ - return self._joint_vel_limits + if self._joint_vel_limits_ta is None: + self._joint_vel_limits_ta = ProxyArray(self._joint_vel_limits) + return self._joint_vel_limits_ta @property - def joint_effort_limits(self) -> wp.array: + def joint_effort_limits(self) -> ProxyArray: """Joint maximum effort provided to the simulation. Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to (num_instances, num_joints). """ - return self._joint_effort_limits + if self._joint_effort_limits_ta is None: + self._joint_effort_limits_ta = ProxyArray(self._joint_effort_limits) + return self._joint_effort_limits_ta """ Joint properties - Custom. """ @property - def soft_joint_pos_limits(self) -> wp.array: + def soft_joint_pos_limits(self) -> ProxyArray: r"""Soft joint positions limits for all joints. Shape is (num_instances, num_joints), dtype = wp.vec2f. In torch this resolves to @@ -404,10 +456,12 @@ def soft_joint_pos_limits(self) -> wp.array: The soft joint position limits help specify a safety region around the joint limits. It isn't used by the simulation, but is useful for learning agents to prevent the joint positions from violating the limits. """ - return self._soft_joint_pos_limits + if self._soft_joint_pos_limits_ta is None: + self._soft_joint_pos_limits_ta = ProxyArray(self._soft_joint_pos_limits) + return self._soft_joint_pos_limits_ta @property - def soft_joint_vel_limits(self) -> wp.array: + def soft_joint_vel_limits(self) -> ProxyArray: """Soft joint velocity limits for all joints. Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to (num_instances, num_joints). @@ -415,120 +469,144 @@ def soft_joint_vel_limits(self) -> wp.array: These are obtained from the actuator model. It may differ from :attr:`joint_vel_limits` if the actuator model has a variable velocity limit model. For instance, in a variable gear ratio actuator model. """ - return self._soft_joint_vel_limits + if self._soft_joint_vel_limits_ta is None: + self._soft_joint_vel_limits_ta = ProxyArray(self._soft_joint_vel_limits) + return self._soft_joint_vel_limits_ta @property - def gear_ratio(self) -> wp.array: + def gear_ratio(self) -> ProxyArray: """Gear ratio for relating motor torques to applied Joint torques. Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to (num_instances, num_joints). """ - return self._gear_ratio + if self._gear_ratio_ta is None: + self._gear_ratio_ta = ProxyArray(self._gear_ratio) + return self._gear_ratio_ta """ Fixed tendon properties. """ @property - def fixed_tendon_stiffness(self) -> wp.array: + def fixed_tendon_stiffness(self) -> ProxyArray: """Fixed tendon stiffness provided to the simulation. Shape is (num_instances, num_fixed_tendons), dtype = wp.float32. In torch this resolves to (num_instances, num_fixed_tendons). """ - return self._fixed_tendon_stiffness + if self._fixed_tendon_stiffness_ta is None: + self._fixed_tendon_stiffness_ta = ProxyArray(self._fixed_tendon_stiffness) + return self._fixed_tendon_stiffness_ta @property - def fixed_tendon_damping(self) -> wp.array: + def fixed_tendon_damping(self) -> ProxyArray: """Fixed tendon damping provided to the simulation. Shape is (num_instances, num_fixed_tendons), dtype = wp.float32. In torch this resolves to (num_instances, num_fixed_tendons). """ - return self._fixed_tendon_damping + if self._fixed_tendon_damping_ta is None: + self._fixed_tendon_damping_ta = ProxyArray(self._fixed_tendon_damping) + return self._fixed_tendon_damping_ta @property - def fixed_tendon_limit_stiffness(self) -> wp.array: + def fixed_tendon_limit_stiffness(self) -> ProxyArray: """Fixed tendon limit stiffness provided to the simulation. Shape is (num_instances, num_fixed_tendons), dtype = wp.float32. In torch this resolves to (num_instances, num_fixed_tendons). """ - return self._fixed_tendon_limit_stiffness + if self._fixed_tendon_limit_stiffness_ta is None: + self._fixed_tendon_limit_stiffness_ta = ProxyArray(self._fixed_tendon_limit_stiffness) + return self._fixed_tendon_limit_stiffness_ta @property - def fixed_tendon_rest_length(self) -> wp.array: + def fixed_tendon_rest_length(self) -> ProxyArray: """Fixed tendon rest length provided to the simulation. Shape is (num_instances, num_fixed_tendons), dtype = wp.float32. In torch this resolves to (num_instances, num_fixed_tendons). """ - return self._fixed_tendon_rest_length + if self._fixed_tendon_rest_length_ta is None: + self._fixed_tendon_rest_length_ta = ProxyArray(self._fixed_tendon_rest_length) + return self._fixed_tendon_rest_length_ta @property - def fixed_tendon_offset(self) -> wp.array: + def fixed_tendon_offset(self) -> ProxyArray: """Fixed tendon offset provided to the simulation. Shape is (num_instances, num_fixed_tendons), dtype = wp.float32. In torch this resolves to (num_instances, num_fixed_tendons). """ - return self._fixed_tendon_offset + if self._fixed_tendon_offset_ta is None: + self._fixed_tendon_offset_ta = ProxyArray(self._fixed_tendon_offset) + return self._fixed_tendon_offset_ta @property - def fixed_tendon_pos_limits(self) -> wp.array: + def fixed_tendon_pos_limits(self) -> ProxyArray: """Fixed tendon position limits provided to the simulation. Shape is (num_instances, num_fixed_tendons), dtype = wp.vec2f. In torch this resolves to (num_instances, num_fixed_tendons, 2). """ - return self._fixed_tendon_pos_limits + if self._fixed_tendon_pos_limits_ta is None: + self._fixed_tendon_pos_limits_ta = ProxyArray(self._fixed_tendon_pos_limits) + return self._fixed_tendon_pos_limits_ta """ Spatial tendon properties. """ @property - def spatial_tendon_stiffness(self) -> wp.array: + def spatial_tendon_stiffness(self) -> ProxyArray: """Spatial tendon stiffness provided to the simulation. Shape is (num_instances, num_spatial_tendons), dtype = wp.float32. In torch this resolves to (num_instances, num_spatial_tendons). """ - return self._spatial_tendon_stiffness + if self._spatial_tendon_stiffness_ta is None: + self._spatial_tendon_stiffness_ta = ProxyArray(self._spatial_tendon_stiffness) + return self._spatial_tendon_stiffness_ta @property - def spatial_tendon_damping(self) -> wp.array: + def spatial_tendon_damping(self) -> ProxyArray: """Spatial tendon damping provided to the simulation. Shape is (num_instances, num_spatial_tendons), dtype = wp.float32. In torch this resolves to (num_instances, num_spatial_tendons). """ - return self._spatial_tendon_damping + if self._spatial_tendon_damping_ta is None: + self._spatial_tendon_damping_ta = ProxyArray(self._spatial_tendon_damping) + return self._spatial_tendon_damping_ta @property - def spatial_tendon_limit_stiffness(self) -> wp.array: + def spatial_tendon_limit_stiffness(self) -> ProxyArray: """Spatial tendon limit stiffness provided to the simulation. Shape is (num_instances, num_spatial_tendons), dtype = wp.float32. In torch this resolves to (num_instances, num_spatial_tendons). """ - return self._spatial_tendon_limit_stiffness + if self._spatial_tendon_limit_stiffness_ta is None: + self._spatial_tendon_limit_stiffness_ta = ProxyArray(self._spatial_tendon_limit_stiffness) + return self._spatial_tendon_limit_stiffness_ta @property - def spatial_tendon_offset(self) -> wp.array: + def spatial_tendon_offset(self) -> ProxyArray: """Spatial tendon offset provided to the simulation. Shape is (num_instances, num_spatial_tendons), dtype = wp.float32. In torch this resolves to (num_instances, num_spatial_tendons). """ - return self._spatial_tendon_offset + if self._spatial_tendon_offset_ta is None: + self._spatial_tendon_offset_ta = ProxyArray(self._spatial_tendon_offset) + return self._spatial_tendon_offset_ta """ Root state properties. """ @property - def root_link_pose_w(self) -> wp.array: + def root_link_pose_w(self) -> ProxyArray: """Root link pose ``[pos, quat]`` in simulation world frame. Shape is (num_instances,), dtype = wp.transformf. In torch this resolves to (num_instances, 7). @@ -540,10 +618,12 @@ def root_link_pose_w(self) -> wp.array: self._root_link_pose_w.data = self._root_view.get_root_transforms().view(wp.transformf) self._root_link_pose_w.timestamp = self._sim_timestamp - return self._root_link_pose_w.data + if self._root_link_pose_w_ta is None: + self._root_link_pose_w_ta = ProxyArray(self._root_link_pose_w.data) + return self._root_link_pose_w_ta @property - def root_link_vel_w(self) -> wp.array: + def root_link_vel_w(self) -> ProxyArray: """Root link velocity ``[lin_vel, ang_vel]`` in simulation world frame. Shape is (num_instances,), dtype = wp.spatial_vectorf. In torch this resolves to (num_instances, 6). @@ -566,10 +646,12 @@ def root_link_vel_w(self) -> wp.array: ) self._root_link_vel_w.timestamp = self._sim_timestamp - return self._root_link_vel_w.data + if self._root_link_vel_w_ta is None: + self._root_link_vel_w_ta = ProxyArray(self._root_link_vel_w.data) + return self._root_link_vel_w_ta @property - def root_com_pose_w(self) -> wp.array: + def root_com_pose_w(self) -> ProxyArray: """Root center of mass pose ``[pos, quat]`` in simulation world frame. Shape is (num_instances,), dtype = wp.transformf. In torch this resolves to (num_instances, 7). @@ -592,10 +674,12 @@ def root_com_pose_w(self) -> wp.array: ) self._root_com_pose_w.timestamp = self._sim_timestamp - return self._root_com_pose_w.data + if self._root_com_pose_w_ta is None: + self._root_com_pose_w_ta = ProxyArray(self._root_com_pose_w.data) + return self._root_com_pose_w_ta @property - def root_com_vel_w(self) -> wp.array: + def root_com_vel_w(self) -> ProxyArray: """Root center of mass velocity ``[lin_vel, ang_vel]`` in simulation world frame. Shape is (num_instances,), dtype = wp.spatial_vectorf. In torch this resolves to (num_instances, 6). @@ -606,33 +690,39 @@ def root_com_vel_w(self) -> wp.array: self._root_com_vel_w.data = self._root_view.get_root_velocities().view(wp.spatial_vectorf) self._root_com_vel_w.timestamp = self._sim_timestamp - return self._root_com_vel_w.data + if self._root_com_vel_w_ta is None: + self._root_com_vel_w_ta = ProxyArray(self._root_com_vel_w.data) + return self._root_com_vel_w_ta """ Body state properties. """ @property - def body_mass(self) -> wp.array: + def body_mass(self) -> ProxyArray: """Body mass in the world frame. Shape is (num_instances, num_bodies), dtype = wp.float32. In torch this resolves to (num_instances, num_bodies). """ self._body_mass.assign(self._root_view.get_masses()) - return self._body_mass + if self._body_mass_ta is None: + self._body_mass_ta = ProxyArray(self._body_mass) + return self._body_mass_ta @property - def body_inertia(self) -> wp.array: + def body_inertia(self) -> ProxyArray: """Flattened body inertia in the world frame. Shape is (num_instances, num_bodies, 9), dtype = wp.float32. In torch this resolves to (num_instances, num_bodies, 9). """ self._body_inertia.assign(self._root_view.get_inertias()) - return self._body_inertia + if self._body_inertia_ta is None: + self._body_inertia_ta = ProxyArray(self._body_inertia) + return self._body_inertia_ta @property - def body_link_pose_w(self) -> wp.array: + def body_link_pose_w(self) -> ProxyArray: """Body link pose ``[pos, quat]`` in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.transformf. In torch this resolves to (num_instances, num_bodies, 7). @@ -647,10 +737,12 @@ def body_link_pose_w(self) -> wp.array: self._body_link_pose_w.data = self._root_view.get_link_transforms().view(wp.transformf) self._body_link_pose_w.timestamp = self._sim_timestamp - return self._body_link_pose_w.data + if self._body_link_pose_w_ta is None: + self._body_link_pose_w_ta = ProxyArray(self._body_link_pose_w.data) + return self._body_link_pose_w_ta @property - def body_link_vel_w(self) -> wp.array: + def body_link_vel_w(self) -> ProxyArray: """Body link velocity ``[lin_vel, ang_vel]`` in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.spatial_vectorf. In torch this resolves to (num_instances, num_bodies, 6). @@ -674,10 +766,12 @@ def body_link_vel_w(self) -> wp.array: ) self._body_link_vel_w.timestamp = self._sim_timestamp - return self._body_link_vel_w.data + if self._body_link_vel_w_ta is None: + self._body_link_vel_w_ta = ProxyArray(self._body_link_vel_w.data) + return self._body_link_vel_w_ta @property - def body_com_pose_w(self) -> wp.array: + def body_com_pose_w(self) -> ProxyArray: """Body center of mass pose ``[pos, quat]`` in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.transformf. In torch this resolves to (num_instances, num_bodies, 7). @@ -700,10 +794,12 @@ def body_com_pose_w(self) -> wp.array: ) self._body_com_pose_w.timestamp = self._sim_timestamp - return self._body_com_pose_w.data + if self._body_com_pose_w_ta is None: + self._body_com_pose_w_ta = ProxyArray(self._body_com_pose_w.data) + return self._body_com_pose_w_ta @property - def body_com_vel_w(self) -> wp.array: + def body_com_vel_w(self) -> ProxyArray: """Body center of mass velocity ``[lin_vel, ang_vel]`` in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.spatial_vectorf. In torch this resolves to (num_instances, num_bodies, 6). @@ -715,10 +811,12 @@ def body_com_vel_w(self) -> wp.array: self._body_com_vel_w.data = self._root_view.get_link_velocities().view(wp.spatial_vectorf) self._body_com_vel_w.timestamp = self._sim_timestamp - return self._body_com_vel_w.data + if self._body_com_vel_w_ta is None: + self._body_com_vel_w_ta = ProxyArray(self._body_com_vel_w.data) + return self._body_com_vel_w_ta @property - def body_com_acc_w(self): + def body_com_acc_w(self) -> ProxyArray: """Acceleration of all bodies center of mass ``[lin_acc, ang_acc]``. Shape is (num_instances, num_bodies), dtype = wp.spatial_vectorf. In torch this resolves to (num_instances, num_bodies, 6). @@ -730,10 +828,12 @@ def body_com_acc_w(self): self._body_com_acc_w.data = self._root_view.get_link_accelerations().view(wp.spatial_vectorf) self._body_com_acc_w.timestamp = self._sim_timestamp - return self._body_com_acc_w.data + if self._body_com_acc_w_ta is None: + self._body_com_acc_w_ta = ProxyArray(self._body_com_acc_w.data) + return self._body_com_acc_w_ta @property - def body_com_pose_b(self) -> wp.array: + def body_com_pose_b(self) -> ProxyArray: """Center of mass pose ``[pos, quat]`` of all bodies in their respective body's link frames. Shape is (num_instances, num_bodies), dtype = wp.transformf. In torch this resolves to (num_instances, num_bodies, 7). @@ -746,39 +846,16 @@ def body_com_pose_b(self) -> wp.array: self._body_com_pose_b.data.assign(self._root_view.get_coms().view(wp.transformf)) self._body_com_pose_b.timestamp = self._sim_timestamp - return self._body_com_pose_b.data - - @property - def body_incoming_joint_wrench_b(self) -> wp.array: - """Joint reaction wrench applied to each body through its incoming joint, expressed in that body's frame. - - Shape is (num_instances, num_bodies, 6). All body reaction wrenches are provided including the root body to the - world of an articulation. - - .. note:: - PhysX expresses this wrench in the frame of ``body1`` as defined in the USD joint, which corresponds to - the child body's own frame when the USD convention is ``body0`` = parent, ``body1`` = child. - - For more information on joint wrenches, please check the `PhysX documentation`_ and the underlying - `PhysX Tensor API`_. - - .. _`PhysX documentation`: https://nvidia-omniverse.github.io/PhysX/physx/5.5.1/docs/Articulations.html#link-incoming-joint-force - .. _`PhysX Tensor API`: https://docs.omniverse.nvidia.com/kit/docs/omni_physics/latest/extensions/runtime/source/omni.physics.tensors/docs/api/python.html#omni.physics.tensors.impl.api.ArticulationView.get_link_incoming_joint_force - """ - - if self._body_incoming_joint_wrench_b.timestamp < self._sim_timestamp: - self._body_incoming_joint_wrench_b.data = self._root_view.get_link_incoming_joint_force().view( - wp.spatial_vectorf - ) - self._body_incoming_joint_wrench_b.timestamp = self._sim_timestamp - return self._body_incoming_joint_wrench_b.data + if self._body_com_pose_b_ta is None: + self._body_com_pose_b_ta = ProxyArray(self._body_com_pose_b.data) + return self._body_com_pose_b_ta """ Joint state properties. """ @property - def joint_pos(self) -> wp.array: + def joint_pos(self) -> ProxyArray: """Joint positions of all joints. Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to (num_instances, num_joints). @@ -787,10 +864,12 @@ def joint_pos(self) -> wp.array: # read data from simulation and set the buffer data and timestamp self._joint_pos.data = self._root_view.get_dof_positions() self._joint_pos.timestamp = self._sim_timestamp - return self._joint_pos.data + if self._joint_pos_ta is None: + self._joint_pos_ta = ProxyArray(self._joint_pos.data) + return self._joint_pos_ta @property - def joint_vel(self) -> wp.array: + def joint_vel(self) -> ProxyArray: """Joint velocities of all joints. Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to (num_instances, num_joints). @@ -799,10 +878,12 @@ def joint_vel(self) -> wp.array: # read data from simulation and set the buffer data and timestamp self._joint_vel.data = self._root_view.get_dof_velocities() self._joint_vel.timestamp = self._sim_timestamp - return self._joint_vel.data + if self._joint_vel_ta is None: + self._joint_vel_ta = ProxyArray(self._joint_vel.data) + return self._joint_vel_ta @property - def joint_acc(self) -> wp.array: + def joint_acc(self) -> ProxyArray: """Joint acceleration of all joints. Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to (num_instances, num_joints). @@ -824,14 +905,16 @@ def joint_acc(self) -> wp.array: device=self.device, ) self._joint_acc.timestamp = self._sim_timestamp - return self._joint_acc.data + if self._joint_acc_ta is None: + self._joint_acc_ta = ProxyArray(self._joint_acc.data) + return self._joint_acc_ta """ Derived Properties. """ @property - def projected_gravity_b(self): + def projected_gravity_b(self) -> ProxyArray: """Projection of the gravity direction on base frame. Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3).""" if self._projected_gravity_b.timestamp < self._sim_timestamp: @@ -843,10 +926,12 @@ def projected_gravity_b(self): device=self.device, ) self._projected_gravity_b.timestamp = self._sim_timestamp - return self._projected_gravity_b.data + if self._projected_gravity_b_ta is None: + self._projected_gravity_b_ta = ProxyArray(self._projected_gravity_b.data) + return self._projected_gravity_b_ta @property - def heading_w(self): + def heading_w(self) -> ProxyArray: """Yaw heading of the base frame (in radians). Shape is (num_instances,), dtype = wp.float32. .. note:: @@ -862,10 +947,12 @@ def heading_w(self): device=self.device, ) self._heading_w.timestamp = self._sim_timestamp - return self._heading_w.data + if self._heading_w_ta is None: + self._heading_w_ta = ProxyArray(self._heading_w.data) + return self._heading_w_ta @property - def root_link_lin_vel_b(self) -> wp.array: + def root_link_lin_vel_b(self) -> ProxyArray: """Root link linear velocity in base frame. Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). @@ -880,10 +967,12 @@ def root_link_lin_vel_b(self) -> wp.array: device=self.device, ) self._root_link_lin_vel_b.timestamp = self._sim_timestamp - return self._root_link_lin_vel_b.data + if self._root_link_lin_vel_b_ta is None: + self._root_link_lin_vel_b_ta = ProxyArray(self._root_link_lin_vel_b.data) + return self._root_link_lin_vel_b_ta @property - def root_link_ang_vel_b(self) -> wp.array: + def root_link_ang_vel_b(self) -> ProxyArray: """Root link angular velocity in base frame. Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). @@ -898,10 +987,12 @@ def root_link_ang_vel_b(self) -> wp.array: device=self.device, ) self._root_link_ang_vel_b.timestamp = self._sim_timestamp - return self._root_link_ang_vel_b.data + if self._root_link_ang_vel_b_ta is None: + self._root_link_ang_vel_b_ta = ProxyArray(self._root_link_ang_vel_b.data) + return self._root_link_ang_vel_b_ta @property - def root_com_lin_vel_b(self) -> wp.array: + def root_com_lin_vel_b(self) -> ProxyArray: """Root center of mass linear velocity in base frame. Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). @@ -917,10 +1008,12 @@ def root_com_lin_vel_b(self) -> wp.array: device=self.device, ) self._root_com_lin_vel_b.timestamp = self._sim_timestamp - return self._root_com_lin_vel_b.data + if self._root_com_lin_vel_b_ta is None: + self._root_com_lin_vel_b_ta = ProxyArray(self._root_com_lin_vel_b.data) + return self._root_com_lin_vel_b_ta @property - def root_com_ang_vel_b(self) -> wp.array: + def root_com_ang_vel_b(self) -> ProxyArray: """Root center of mass angular velocity in base frame. Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). @@ -936,196 +1029,274 @@ def root_com_ang_vel_b(self) -> wp.array: device=self.device, ) self._root_com_ang_vel_b.timestamp = self._sim_timestamp - return self._root_com_ang_vel_b.data + if self._root_com_ang_vel_b_ta is None: + self._root_com_ang_vel_b_ta = ProxyArray(self._root_com_ang_vel_b.data) + return self._root_com_ang_vel_b_ta """ Sliced properties. """ @property - def root_link_pos_w(self) -> wp.array: + def root_link_pos_w(self) -> ProxyArray: """Root link position in simulation world frame. Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). This quantity is the position of the actor frame of the root rigid body relative to the world. """ - return self._get_pos_from_transform(self.root_link_pose_w) + # Access parent property to trigger its getter call (PhysX is pull-on-demand) + parent = self.root_link_pose_w + if self._root_link_pos_w_ta is None: + self._root_link_pos_w_ta = ProxyArray(self._get_pos_from_transform(parent.warp)) + return self._root_link_pos_w_ta @property - def root_link_quat_w(self) -> wp.array: + def root_link_quat_w(self) -> ProxyArray: """Root link orientation (x, y, z, w) in simulation world frame. Shape is (num_instances,), dtype = wp.quatf. In torch this resolves to (num_instances, 4). This quantity is the orientation of the actor frame of the root rigid body. """ - return self._get_quat_from_transform(self.root_link_pose_w) + # Access parent property to trigger its getter call (PhysX is pull-on-demand) + parent = self.root_link_pose_w + if self._root_link_quat_w_ta is None: + self._root_link_quat_w_ta = ProxyArray(self._get_quat_from_transform(parent.warp)) + return self._root_link_quat_w_ta @property - def root_link_lin_vel_w(self) -> wp.array: + def root_link_lin_vel_w(self) -> ProxyArray: """Root linear velocity in simulation world frame. Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). This quantity is the linear velocity of the root rigid body's actor frame relative to the world. """ - return self._get_lin_vel_from_spatial_vector(self.root_link_vel_w) + # Access parent property to trigger its getter call (PhysX is pull-on-demand) + parent = self.root_link_vel_w + if self._root_link_lin_vel_w_ta is None: + self._root_link_lin_vel_w_ta = ProxyArray(self._get_lin_vel_from_spatial_vector(parent.warp)) + return self._root_link_lin_vel_w_ta @property - def root_link_ang_vel_w(self) -> wp.array: + def root_link_ang_vel_w(self) -> ProxyArray: """Root link angular velocity in simulation world frame. Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). This quantity is the angular velocity of the actor frame of the root rigid body relative to the world. """ - return self._get_ang_vel_from_spatial_vector(self.root_link_vel_w) + # Access parent property to trigger its getter call (PhysX is pull-on-demand) + parent = self.root_link_vel_w + if self._root_link_ang_vel_w_ta is None: + self._root_link_ang_vel_w_ta = ProxyArray(self._get_ang_vel_from_spatial_vector(parent.warp)) + return self._root_link_ang_vel_w_ta @property - def root_com_pos_w(self) -> wp.array: + def root_com_pos_w(self) -> ProxyArray: """Root center of mass position in simulation world frame. Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). This quantity is the position of the center of mass frame of the root rigid body relative to the world. """ - return self._get_pos_from_transform(self.root_com_pose_w) + # Access parent property to trigger its getter call (PhysX is pull-on-demand) + parent = self.root_com_pose_w + if self._root_com_pos_w_ta is None: + self._root_com_pos_w_ta = ProxyArray(self._get_pos_from_transform(parent.warp)) + return self._root_com_pos_w_ta @property - def root_com_quat_w(self) -> wp.array: + def root_com_quat_w(self) -> ProxyArray: """Root center of mass orientation (x, y, z, w) in simulation world frame. Shape is (num_instances,), dtype = wp.quatf. In torch this resolves to (num_instances, 4). This quantity is the orientation of the principal axes of inertia of the root rigid body relative to the world. """ - return self._get_quat_from_transform(self.root_com_pose_w) + # Access parent property to trigger its getter call (PhysX is pull-on-demand) + parent = self.root_com_pose_w + if self._root_com_quat_w_ta is None: + self._root_com_quat_w_ta = ProxyArray(self._get_quat_from_transform(parent.warp)) + return self._root_com_quat_w_ta @property - def root_com_lin_vel_w(self) -> wp.array: + def root_com_lin_vel_w(self) -> ProxyArray: """Root center of mass linear velocity in simulation world frame. Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). This quantity is the linear velocity of the root rigid body's center of mass frame relative to the world. """ - return self._get_lin_vel_from_spatial_vector(self.root_com_vel_w) + # Access parent property to trigger its getter call (PhysX is pull-on-demand) + parent = self.root_com_vel_w + if self._root_com_lin_vel_w_ta is None: + self._root_com_lin_vel_w_ta = ProxyArray(self._get_lin_vel_from_spatial_vector(parent.warp)) + return self._root_com_lin_vel_w_ta @property - def root_com_ang_vel_w(self) -> wp.array: + def root_com_ang_vel_w(self) -> ProxyArray: """Root center of mass angular velocity in simulation world frame. Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). This quantity is the angular velocity of the root rigid body's center of mass frame relative to the world. """ - return self._get_ang_vel_from_spatial_vector(self.root_com_vel_w) + # Access parent property to trigger its getter call (PhysX is pull-on-demand) + parent = self.root_com_vel_w + if self._root_com_ang_vel_w_ta is None: + self._root_com_ang_vel_w_ta = ProxyArray(self._get_ang_vel_from_spatial_vector(parent.warp)) + return self._root_com_ang_vel_w_ta @property - def body_link_pos_w(self) -> wp.array: + def body_link_pos_w(self) -> ProxyArray: """Positions of all bodies in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to (num_instances, num_bodies, 3). This quantity is the position of the articulation bodies' actor frame relative to the world. """ - return self._get_pos_from_transform(self.body_link_pose_w) + # Access parent property to trigger its getter call (PhysX is pull-on-demand) + parent = self.body_link_pose_w + if self._body_link_pos_w_ta is None: + self._body_link_pos_w_ta = ProxyArray(self._get_pos_from_transform(parent.warp)) + return self._body_link_pos_w_ta @property - def body_link_quat_w(self) -> wp.array: + def body_link_quat_w(self) -> ProxyArray: """Orientation (x, y, z, w) of all bodies in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.quatf. In torch this resolves to (num_instances, num_bodies, 4). This quantity is the orientation of the articulation bodies' actor frame relative to the world. """ - return self._get_quat_from_transform(self.body_link_pose_w) + # Access parent property to trigger its getter call (PhysX is pull-on-demand) + parent = self.body_link_pose_w + if self._body_link_quat_w_ta is None: + self._body_link_quat_w_ta = ProxyArray(self._get_quat_from_transform(parent.warp)) + return self._body_link_quat_w_ta @property - def body_link_lin_vel_w(self) -> wp.array: + def body_link_lin_vel_w(self) -> ProxyArray: """Linear velocity of all bodies in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to (num_instances, num_bodies, 3). This quantity is the linear velocity of the articulation bodies' actor frame relative to the world. """ - return self._get_lin_vel_from_spatial_vector(self.body_link_vel_w) + # Access parent property to trigger its getter call (PhysX is pull-on-demand) + parent = self.body_link_vel_w + if self._body_link_lin_vel_w_ta is None: + self._body_link_lin_vel_w_ta = ProxyArray(self._get_lin_vel_from_spatial_vector(parent.warp)) + return self._body_link_lin_vel_w_ta @property - def body_link_ang_vel_w(self) -> wp.array: + def body_link_ang_vel_w(self) -> ProxyArray: """Angular velocity of all bodies in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to (num_instances, num_bodies, 3). This quantity is the angular velocity of the articulation bodies' actor frame relative to the world. """ - return self._get_ang_vel_from_spatial_vector(self.body_link_vel_w) + # Access parent property to trigger its getter call (PhysX is pull-on-demand) + parent = self.body_link_vel_w + if self._body_link_ang_vel_w_ta is None: + self._body_link_ang_vel_w_ta = ProxyArray(self._get_ang_vel_from_spatial_vector(parent.warp)) + return self._body_link_ang_vel_w_ta @property - def body_com_pos_w(self) -> wp.array: + def body_com_pos_w(self) -> ProxyArray: """Positions of all bodies' center of mass in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to (num_instances, num_bodies, 3). This quantity is the position of the articulation bodies' center of mass frame. """ - return self._get_pos_from_transform(self.body_com_pose_w) + # Access parent property to trigger its getter call (PhysX is pull-on-demand) + parent = self.body_com_pose_w + if self._body_com_pos_w_ta is None: + self._body_com_pos_w_ta = ProxyArray(self._get_pos_from_transform(parent.warp)) + return self._body_com_pos_w_ta @property - def body_com_quat_w(self) -> wp.array: + def body_com_quat_w(self) -> ProxyArray: """Orientation (x, y, z, w) of the principal axes of inertia of all bodies in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.quatf. In torch this resolves to (num_instances, num_bodies, 4). This quantity is the orientation of the articulation bodies' principal axes of inertia. """ - return self._get_quat_from_transform(self.body_com_pose_w) + # Access parent property to trigger its getter call (PhysX is pull-on-demand) + parent = self.body_com_pose_w + if self._body_com_quat_w_ta is None: + self._body_com_quat_w_ta = ProxyArray(self._get_quat_from_transform(parent.warp)) + return self._body_com_quat_w_ta @property - def body_com_lin_vel_w(self) -> wp.array: + def body_com_lin_vel_w(self) -> ProxyArray: """Linear velocity of all bodies in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to (num_instances, num_bodies, 3). This quantity is the linear velocity of the articulation bodies' center of mass frame. """ - return self._get_lin_vel_from_spatial_vector(self.body_com_vel_w) + # Access parent property to trigger its getter call (PhysX is pull-on-demand) + parent = self.body_com_vel_w + if self._body_com_lin_vel_w_ta is None: + self._body_com_lin_vel_w_ta = ProxyArray(self._get_lin_vel_from_spatial_vector(parent.warp)) + return self._body_com_lin_vel_w_ta @property - def body_com_ang_vel_w(self) -> wp.array: + def body_com_ang_vel_w(self) -> ProxyArray: """Angular velocity of all bodies in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to (num_instances, num_bodies, 3). This quantity is the angular velocity of the articulation bodies' center of mass frame. """ - return self._get_ang_vel_from_spatial_vector(self.body_com_vel_w) + # Access parent property to trigger its getter call (PhysX is pull-on-demand) + parent = self.body_com_vel_w + if self._body_com_ang_vel_w_ta is None: + self._body_com_ang_vel_w_ta = ProxyArray(self._get_ang_vel_from_spatial_vector(parent.warp)) + return self._body_com_ang_vel_w_ta @property - def body_com_lin_acc_w(self) -> wp.array: + def body_com_lin_acc_w(self) -> ProxyArray: """Linear acceleration of all bodies in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to (num_instances, num_bodies, 3). This quantity is the linear acceleration of the articulation bodies' center of mass frame. """ - return self._get_lin_vel_from_spatial_vector(self.body_com_acc_w) + # Access parent property to trigger its getter call (PhysX is pull-on-demand) + parent = self.body_com_acc_w + if self._body_com_lin_acc_w_ta is None: + self._body_com_lin_acc_w_ta = ProxyArray(self._get_lin_vel_from_spatial_vector(parent.warp)) + return self._body_com_lin_acc_w_ta @property - def body_com_ang_acc_w(self) -> wp.array: + def body_com_ang_acc_w(self) -> ProxyArray: """Angular acceleration of all bodies in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to (num_instances, num_bodies, 3). This quantity is the angular acceleration of the articulation bodies' center of mass frame. """ - return self._get_ang_vel_from_spatial_vector(self.body_com_acc_w) + # Access parent property to trigger its getter call (PhysX is pull-on-demand) + parent = self.body_com_acc_w + if self._body_com_ang_acc_w_ta is None: + self._body_com_ang_acc_w_ta = ProxyArray(self._get_ang_vel_from_spatial_vector(parent.warp)) + return self._body_com_ang_acc_w_ta @property - def body_com_pos_b(self) -> wp.array: + def body_com_pos_b(self) -> ProxyArray: """Center of mass position of all of the bodies in their respective link frames. Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to (num_instances, num_bodies, 3). This quantity is the center of mass location relative to its body's link frame. """ - return self._get_pos_from_transform(self.body_com_pose_b) + # Access parent property to trigger its getter call (PhysX is pull-on-demand) + parent = self.body_com_pose_b + if self._body_com_pos_b_ta is None: + self._body_com_pos_b_ta = ProxyArray(self._get_pos_from_transform(parent.warp)) + return self._body_com_pos_b_ta @property - def body_com_quat_b(self) -> wp.array: + def body_com_quat_b(self) -> ProxyArray: """Orientation (x, y, z, w) of the principal axes of inertia of all of the bodies in their respective link frames. Shape is (num_instances, num_bodies), dtype = wp.quatf. In torch this resolves to @@ -1133,7 +1304,11 @@ def body_com_quat_b(self) -> wp.array: This quantity is the orientation of the principal axes of inertia relative to its body's link frame. """ - return self._get_quat_from_transform(self.body_com_pose_b) + # Access parent property to trigger its getter call (PhysX is pull-on-demand) + parent = self.body_com_pose_b + if self._body_com_quat_b_ta is None: + self._body_com_quat_b_ta = ProxyArray(self._get_quat_from_transform(parent.warp)) + return self._body_com_quat_b_ta def _create_buffers(self) -> None: super()._create_buffers() @@ -1180,9 +1355,6 @@ def _create_buffers(self) -> None: self._joint_pos = TimestampedBuffer((self._num_instances, self._num_joints), self.device, wp.float32) self._joint_vel = TimestampedBuffer((self._num_instances, self._num_joints), self.device, wp.float32) self._joint_acc = TimestampedBuffer((self._num_instances, self._num_joints), self.device, wp.float32) - self._body_incoming_joint_wrench_b = TimestampedBuffer( - (self._num_instances, self._num_bodies, self._num_joints), self.device, wp.spatial_vectorf - ) # -- derived properties (these are cached to avoid repeated memory allocations) self._projected_gravity_b = TimestampedBuffer((self._num_instances), self.device, wp.vec3f) self._heading_w = TimestampedBuffer((self._num_instances), self.device, wp.float32) @@ -1292,6 +1464,115 @@ def _create_buffers(self) -> None: self._body_inertia = wp.clone(self._root_view.get_inertias(), device=self.device) self._default_root_state = None + # Initialize ProxyArray wrappers + self._pin_proxy_arrays() + + def _pin_proxy_arrays(self) -> None: + """Create pinned ProxyArray wrappers for all data buffers. + + This is called once from :meth:`_create_buffers` during initialization. + PhysX tensor API buffers have stable GPU pointers across simulation steps, + so no rebinding is needed (unlike Newton). + """ + # -- Pinned ProxyArray cache (one per read property, lazily created on first access) + # Defaults + self._default_root_pose_ta: ProxyArray | None = None + self._default_root_vel_ta: ProxyArray | None = None + self._default_joint_pos_ta: ProxyArray | None = None + self._default_joint_vel_ta: ProxyArray | None = None + # Joint commands (set into simulation) + self._joint_pos_target_ta: ProxyArray | None = None + self._joint_vel_target_ta: ProxyArray | None = None + self._joint_effort_target_ta: ProxyArray | None = None + # Joint commands (explicit actuator model) + self._computed_torque_ta: ProxyArray | None = None + self._applied_torque_ta: ProxyArray | None = None + # Joint properties + self._joint_stiffness_ta: ProxyArray | None = None + self._joint_damping_ta: ProxyArray | None = None + self._joint_armature_ta: ProxyArray | None = None + self._joint_friction_coeff_ta: ProxyArray | None = None + self._joint_dynamic_friction_coeff_ta: ProxyArray | None = None + self._joint_viscous_friction_coeff_ta: ProxyArray | None = None + self._joint_pos_limits_ta: ProxyArray | None = None + self._joint_vel_limits_ta: ProxyArray | None = None + self._joint_effort_limits_ta: ProxyArray | None = None + # Joint properties (custom) + self._soft_joint_pos_limits_ta: ProxyArray | None = None + self._soft_joint_vel_limits_ta: ProxyArray | None = None + self._gear_ratio_ta: ProxyArray | None = None + # Fixed tendon properties + self._fixed_tendon_stiffness_ta: ProxyArray | None = None + self._fixed_tendon_damping_ta: ProxyArray | None = None + self._fixed_tendon_limit_stiffness_ta: ProxyArray | None = None + self._fixed_tendon_rest_length_ta: ProxyArray | None = None + self._fixed_tendon_offset_ta: ProxyArray | None = None + self._fixed_tendon_pos_limits_ta: ProxyArray | None = None + # Spatial tendon properties + self._spatial_tendon_stiffness_ta: ProxyArray | None = None + self._spatial_tendon_damping_ta: ProxyArray | None = None + self._spatial_tendon_limit_stiffness_ta: ProxyArray | None = None + self._spatial_tendon_offset_ta: ProxyArray | None = None + # Root state (timestamped) + self._root_link_pose_w_ta: ProxyArray | None = None + self._root_link_vel_w_ta: ProxyArray | None = None + self._root_com_pose_w_ta: ProxyArray | None = None + self._root_com_vel_w_ta: ProxyArray | None = None + # Body state (timestamped) + self._body_link_pose_w_ta: ProxyArray | None = None + self._body_link_vel_w_ta: ProxyArray | None = None + self._body_com_pose_w_ta: ProxyArray | None = None + self._body_com_vel_w_ta: ProxyArray | None = None + self._body_com_acc_w_ta: ProxyArray | None = None + self._body_com_pose_b_ta: ProxyArray | None = None + # Body properties + self._body_mass_ta: ProxyArray | None = None + self._body_inertia_ta: ProxyArray | None = None + # Joint state (timestamped) + self._joint_pos_ta: ProxyArray | None = None + self._joint_vel_ta: ProxyArray | None = None + self._joint_acc_ta: ProxyArray | None = None + # Derived properties (timestamped) + self._projected_gravity_b_ta: ProxyArray | None = None + self._heading_w_ta: ProxyArray | None = None + self._root_link_lin_vel_b_ta: ProxyArray | None = None + self._root_link_ang_vel_b_ta: ProxyArray | None = None + self._root_com_lin_vel_b_ta: ProxyArray | None = None + self._root_com_ang_vel_b_ta: ProxyArray | None = None + # Sliced properties (root link) + self._root_link_pos_w_ta: ProxyArray | None = None + self._root_link_quat_w_ta: ProxyArray | None = None + self._root_link_lin_vel_w_ta: ProxyArray | None = None + self._root_link_ang_vel_w_ta: ProxyArray | None = None + # Sliced properties (root com) + self._root_com_pos_w_ta: ProxyArray | None = None + self._root_com_quat_w_ta: ProxyArray | None = None + self._root_com_lin_vel_w_ta: ProxyArray | None = None + self._root_com_ang_vel_w_ta: ProxyArray | None = None + # Sliced properties (body link) + self._body_link_pos_w_ta: ProxyArray | None = None + self._body_link_quat_w_ta: ProxyArray | None = None + self._body_link_lin_vel_w_ta: ProxyArray | None = None + self._body_link_ang_vel_w_ta: ProxyArray | None = None + # Sliced properties (body com) + self._body_com_pos_w_ta: ProxyArray | None = None + self._body_com_quat_w_ta: ProxyArray | None = None + self._body_com_lin_vel_w_ta: ProxyArray | None = None + self._body_com_ang_vel_w_ta: ProxyArray | None = None + self._body_com_lin_acc_w_ta: ProxyArray | None = None + self._body_com_ang_acc_w_ta: ProxyArray | None = None + # Sliced properties (body com in body frame) + self._body_com_pos_b_ta: ProxyArray | None = None + self._body_com_quat_b_ta: ProxyArray | None = None + # Deprecated state-concat properties + self._default_root_state_ta: ProxyArray | None = None + self._root_state_w_ta: ProxyArray | None = None + self._root_link_state_w_ta: ProxyArray | None = None + self._root_com_state_w_ta: ProxyArray | None = None + self._body_state_w_ta: ProxyArray | None = None + self._body_link_state_w_ta: ProxyArray | None = None + self._body_com_state_w_ta: ProxyArray | None = None + """ Internal helpers. """ @@ -1369,7 +1650,7 @@ def _get_ang_vel_from_spatial_vector(self, spatial_vector: wp.array) -> wp.array """ @property - def default_root_state(self) -> wp.array: + def default_root_state(self) -> ProxyArray: """Default root state ``[pos, quat, lin_vel, ang_vel]`` in the local environment frame. @@ -1398,10 +1679,12 @@ def default_root_state(self) -> wp.array: ], device=self.device, ) - return self._default_root_state + if self._default_root_state_ta is None: + self._default_root_state_ta = ProxyArray(self._default_root_state) + return self._default_root_state_ta @property - def root_state_w(self) -> wp.array: + def root_state_w(self) -> ProxyArray: """Deprecated, same as :attr:`root_link_pose_w` and :attr:`root_com_vel_w`.""" warnings.warn( "The `root_state_w` property will be deprecated in a IsaacLab 4.0. Please use `root_link_pose_w` and " @@ -1424,10 +1707,12 @@ def root_state_w(self) -> wp.array: ) self._root_state_w.timestamp = self._sim_timestamp - return self._root_state_w.data + if self._root_state_w_ta is None: + self._root_state_w_ta = ProxyArray(self._root_state_w.data) + return self._root_state_w_ta @property - def root_link_state_w(self) -> wp.array: + def root_link_state_w(self) -> ProxyArray: """Deprecated, same as :attr:`root_link_pose_w` and :attr:`root_link_vel_w`.""" warnings.warn( "The `root_link_state_w` property will be deprecated in a IsaacLab 4.0. Please use `root_link_pose_w` and " @@ -1450,10 +1735,12 @@ def root_link_state_w(self) -> wp.array: ) self._root_link_state_w.timestamp = self._sim_timestamp - return self._root_link_state_w.data + if self._root_link_state_w_ta is None: + self._root_link_state_w_ta = ProxyArray(self._root_link_state_w.data) + return self._root_link_state_w_ta @property - def root_com_state_w(self) -> wp.array: + def root_com_state_w(self) -> ProxyArray: """Deprecated, same as :attr:`root_com_pose_w` and :attr:`root_com_vel_w`.""" warnings.warn( "The `root_com_state_w` property will be deprecated in a IsaacLab 4.0. Please use `root_com_pose_w` and " @@ -1476,10 +1763,12 @@ def root_com_state_w(self) -> wp.array: ) self._root_com_state_w.timestamp = self._sim_timestamp - return self._root_com_state_w.data + if self._root_com_state_w_ta is None: + self._root_com_state_w_ta = ProxyArray(self._root_com_state_w.data) + return self._root_com_state_w_ta @property - def body_state_w(self): + def body_state_w(self) -> ProxyArray: """State of all bodies `[pos, quat, lin_vel, ang_vel]` in simulation world frame. Shape is (num_instances, num_bodies, 13). @@ -1507,10 +1796,12 @@ def body_state_w(self): ) self._body_state_w.timestamp = self._sim_timestamp - return self._body_state_w.data + if self._body_state_w_ta is None: + self._body_state_w_ta = ProxyArray(self._body_state_w.data) + return self._body_state_w_ta @property - def body_link_state_w(self): + def body_link_state_w(self) -> ProxyArray: """State of all bodies' link frame`[pos, quat, lin_vel, ang_vel]` in simulation world frame. Shape is (num_instances, num_bodies, 13). @@ -1537,10 +1828,12 @@ def body_link_state_w(self): ) self._body_link_state_w.timestamp = self._sim_timestamp - return self._body_link_state_w.data + if self._body_link_state_w_ta is None: + self._body_link_state_w_ta = ProxyArray(self._body_link_state_w.data) + return self._body_link_state_w_ta @property - def body_com_state_w(self): + def body_com_state_w(self) -> ProxyArray: """State of all bodies center of mass `[pos, quat, lin_vel, ang_vel]` in simulation world frame. Shape is (num_instances, num_bodies, 13). @@ -1569,4 +1862,6 @@ def body_com_state_w(self): ) self._body_com_state_w.timestamp = self._sim_timestamp - return self._body_com_state_w.data + if self._body_com_state_w_ta is None: + self._body_com_state_w_ta = ProxyArray(self._body_com_state_w.data) + return self._body_com_state_w_ta diff --git a/source/isaaclab_physx/isaaclab_physx/assets/articulation/kernels.py b/source/isaaclab_physx/isaaclab_physx/assets/articulation/kernels.py index b9516356d836..5686c864dd94 100644 --- a/source/isaaclab_physx/isaaclab_physx/assets/articulation/kernels.py +++ b/source/isaaclab_physx/isaaclab_physx/assets/articulation/kernels.py @@ -101,6 +101,47 @@ def write_joint_vel_data( joint_acc[env_ids[i], joint_ids[j]] = 0.0 +@wp.kernel +def write_joint_state_data( + pos_data: wp.array2d(dtype=wp.float32), + vel_data: wp.array2d(dtype=wp.float32), + env_ids: wp.array(dtype=wp.int32), + joint_ids: wp.array(dtype=wp.int32), + full_data: bool, + joint_pos: wp.array2d(dtype=wp.float32), + joint_vel: wp.array2d(dtype=wp.float32), + prev_joint_vel: wp.array2d(dtype=wp.float32), + joint_acc: wp.array2d(dtype=wp.float32), +): + """Write joint position and velocity data in a single kernel launch. + + Args: + pos_data: Input joint positions. Shape is (num_envs, num_joints) if full_data, + otherwise (num_selected_envs, num_selected_joints). + vel_data: Input joint velocities. Shape is (num_envs, num_joints) if full_data, + otherwise (num_selected_envs, num_selected_joints). + env_ids: Environment indices. Shape is (num_selected_envs,). + joint_ids: Joint indices. Shape is (num_selected_joints,). + full_data: If True, data has full (num_envs, num_joints) shape and env_ids/joint_ids + index into it. If False, data is pre-sliced and indexed by thread position. + joint_pos: Output joint positions. Shape is (num_envs, num_joints). + joint_vel: Output joint velocities. Shape is (num_envs, num_joints). + prev_joint_vel: Output previous joint velocities. Shape is (num_envs, num_joints). + joint_acc: Output joint accelerations (reset to 0). Shape is (num_envs, num_joints). + """ + i, j = wp.tid() + if full_data: + p = pos_data[env_ids[i], joint_ids[j]] + v = vel_data[env_ids[i], joint_ids[j]] + else: + p = pos_data[i, j] + v = vel_data[i, j] + joint_pos[env_ids[i], joint_ids[j]] = p + joint_vel[env_ids[i], joint_ids[j]] = v + prev_joint_vel[env_ids[i], joint_ids[j]] = v + joint_acc[env_ids[i], joint_ids[j]] = 0.0 + + @wp.kernel def write_joint_limit_data_to_buffer( in_data: wp.array2d(dtype=wp.vec2f), diff --git a/source/isaaclab_physx/isaaclab_physx/assets/deformable_object/deformable_object.py b/source/isaaclab_physx/isaaclab_physx/assets/deformable_object/deformable_object.py index 34dafff38a0e..a240cb8203b5 100644 --- a/source/isaaclab_physx/isaaclab_physx/assets/deformable_object/deformable_object.py +++ b/source/isaaclab_physx/isaaclab_physx/assets/deformable_object/deformable_object.py @@ -14,13 +14,14 @@ import torch import warp as wp -import omni.physics.tensors.impl.api as physx +import omni.physics.tensors.api as physx from pxr import UsdShade import isaaclab.sim as sim_utils import isaaclab.utils.math as math_utils from isaaclab.assets.asset_base import AssetBase from isaaclab.markers import VisualizationMarkers +from isaaclab.utils.warp import ProxyArray from isaaclab_physx.physics import PhysxManager as SimulationManager @@ -55,7 +56,7 @@ class DeformableObject(AssetBase): The state of a deformable object comprises of its nodal positions and velocities, and not the object's root position and orientation. The nodal positions and velocities are in the simulation frame. - Soft bodies can be `partially kinematic`_, where some nodes are driven by kinematic targets, and the rest are + Volume deformables can be `partially kinematic`_, where some nodes are driven by kinematic targets, and the rest are simulated. The kinematic targets are the desired positions of the nodes, and the simulation drives the nodes towards these targets. This is useful for partial control of the object, such as moving a stuffed animal's head while the rest of the body is simulated. @@ -80,6 +81,8 @@ def __init__(self, cfg: DeformableObjectCfg): super().__init__(cfg) # Register custom vec6f type for nodal state validation. self._DTYPE_TO_TORCH_TRAILING_DIMS = {**self._DTYPE_TO_TORCH_TRAILING_DIMS, vec6f: (6,)} + # initialize deformable type to None, should be set to either surface or volume on initialization + self._deformable_type: str | None = None """ Properties @@ -102,7 +105,7 @@ def num_bodies(self) -> int: return 1 @property - def root_view(self) -> physx.SoftBodyView: + def root_view(self) -> physx.DeformableBodyView: """Deformable body view for the asset. .. note:: @@ -111,7 +114,7 @@ def root_view(self) -> physx.SoftBodyView: return self._root_physx_view @property - def root_physx_view(self) -> physx.SoftBodyView: + def root_physx_view(self) -> physx.DeformableBodyView: """Deprecated property. Please use :attr:`root_view` instead.""" logger.warning( "The `root_physx_view` property will be deprecated in a future release. Please use `root_view` instead." @@ -119,7 +122,7 @@ def root_physx_view(self) -> physx.SoftBodyView: return self.root_view @property - def material_physx_view(self) -> physx.SoftBodyMaterialView | None: + def material_physx_view(self) -> physx.DeformableMaterialView | None: """Deformable material view for the asset (PhysX). This view is optional and may not be available if the material is not bound to the deformable body. @@ -133,22 +136,22 @@ def material_physx_view(self) -> physx.SoftBodyMaterialView | None: @property def max_sim_elements_per_body(self) -> int: """The maximum number of simulation mesh elements per deformable body.""" - return self.root_view.max_sim_elements_per_body + return self.root_view.max_simulation_elements_per_body @property def max_collision_elements_per_body(self) -> int: """The maximum number of collision mesh elements per deformable body.""" - return self.root_view.max_elements_per_body + return self.root_view.max_collision_elements_per_body @property def max_sim_vertices_per_body(self) -> int: """The maximum number of simulation mesh vertices per deformable body.""" - return self.root_view.max_sim_vertices_per_body + return self.root_view.max_simulation_nodes_per_body @property def max_collision_vertices_per_body(self) -> int: """The maximum number of collision mesh vertices per deformable body.""" - return self.root_view.max_vertices_per_body + return self.root_view.max_collision_nodes_per_body """ Operations. @@ -264,7 +267,7 @@ def write_nodal_pos_to_sim_index( self._data._nodal_state_w.timestamp = -1.0 self._data._root_pos_w.timestamp = -1.0 # set into simulation - self.root_view.set_sim_nodal_positions(self._data._nodal_pos_w.data.view(wp.float32), indices=env_ids) + self.root_view.set_simulation_nodal_positions(self._get_nodal_pos_w_f32(), indices=env_ids) def write_nodal_pos_to_sim_mask( self, @@ -332,7 +335,7 @@ def write_nodal_velocity_to_sim_index( self._data._nodal_state_w.timestamp = -1.0 self._data._root_vel_w.timestamp = -1.0 # set into simulation - self.root_view.set_sim_nodal_velocities(self._data._nodal_vel_w.data.view(wp.float32), indices=env_ids) + self.root_view.set_simulation_nodal_velocities(self._get_nodal_vel_w_f32(), indices=env_ids) def write_nodal_velocity_to_sim_mask( self, @@ -377,6 +380,9 @@ def write_nodal_kinematic_target_to_sim_index( env_ids: Environment indices. If None, then all indices are used. full_data: Whether to expect full data. Defaults to False. """ + if self._deformable_type != "volume": + raise ValueError("Kinematic targets can only be set for volume deformable bodies.") + # resolve env_ids env_ids = self._resolve_env_ids(env_ids) if full_data: @@ -401,7 +407,9 @@ def write_nodal_kinematic_target_to_sim_index( device=self.device, ) # set into simulation - self.root_view.set_sim_kinematic_targets(self._data.nodal_kinematic_target.view(wp.float32), indices=env_ids) + self.root_view.set_simulation_nodal_kinematic_targets( + self._data.nodal_kinematic_target.warp.view(wp.float32), indices=env_ids + ) def write_nodal_kinematic_target_to_sim_mask( self, @@ -519,14 +527,45 @@ def transform_nodal_pos( Internal helper. """ + def _get_nodal_pos_w_f32(self) -> wp.array: + """Get a cached float32 view of nodal_pos_w for PhysX TensorAPI. + + Safe because ``DeformableObjectData`` copies into a stable pre-allocated + buffer via ``wp.copy`` (the pointer never changes). + Invalidated in ``_create_buffers``. + """ + if self._nodal_pos_w_f32 is None: + self._nodal_pos_w_f32 = self._data._nodal_pos_w.data.view(wp.float32) + return self._nodal_pos_w_f32 + + def _get_nodal_vel_w_f32(self) -> wp.array: + """Get a cached float32 view of nodal_vel_w for PhysX TensorAPI. + + Safe because ``DeformableObjectData`` copies into a stable pre-allocated + buffer via ``wp.copy`` (the pointer never changes). + Invalidated in ``_create_buffers``. + """ + if self._nodal_vel_w_f32 is None: + self._nodal_vel_w_f32 = self._data._nodal_vel_w.data.view(wp.float32) + return self._nodal_vel_w_f32 + def _resolve_env_ids(self, env_ids): - """Resolve environment indices to a warp int32 array.""" - if env_ids is None or (isinstance(env_ids, slice) and env_ids == slice(None)): + """Resolve environment indices to a warp array. + + Args: + env_ids: Environment indices. If None, then all indices are used. + + Returns: + A warp array of environment indices. + """ + if (env_ids is None) or (env_ids == slice(None)): return self._ALL_INDICES - elif isinstance(env_ids, list): + if isinstance(env_ids, torch.Tensor): + if env_ids.dtype == torch.int64: + env_ids = env_ids.to(torch.int32) + return wp.from_torch(env_ids, dtype=wp.int32) + if isinstance(env_ids, list): return wp.array(env_ids, dtype=wp.int32, device=self.device) - elif isinstance(env_ids, torch.Tensor): - return wp.from_torch(env_ids.to(torch.int32), dtype=wp.int32) return env_ids def _initialize_impl(self): @@ -541,13 +580,13 @@ def _initialize_impl(self): # find deformable root prims root_prims = sim_utils.get_all_matching_child_prims( template_prim_path, - predicate=lambda prim: "PhysxDeformableBodyAPI" in prim.GetAppliedSchemas(), + predicate=lambda prim: "OmniPhysicsDeformableBodyAPI" in prim.GetAppliedSchemas(), traverse_instance_prims=False, ) if len(root_prims) == 0: raise RuntimeError( f"Failed to find a deformable body when resolving '{self.cfg.prim_path}'." - " Please ensure that the prim has 'PhysxDeformableBodyAPI' applied." + " Please ensure that the prim has 'OmniPhysicsDeformableBodyAPI' applied." ) if len(root_prims) > 1: raise RuntimeError( @@ -571,27 +610,71 @@ def _initialize_impl(self): if len(material_paths) > 0: for mat_path in material_paths: mat_prim = root_prim.GetStage().GetPrimAtPath(mat_path) - if "PhysxDeformableBodyMaterialAPI" in mat_prim.GetAppliedSchemas(): + if "OmniPhysicsDeformableMaterialAPI" in mat_prim.GetAppliedSchemas(): material_prim = mat_prim + # determine deformable material type + if "PhysxSurfaceDeformableMaterialAPI" in mat_prim.GetAppliedSchemas(): + self._deformable_type = "surface" + elif "PhysxDeformableMaterialAPI" in mat_prim.GetAppliedSchemas(): + self._deformable_type = "volume" break + if material_prim is None: - logger.info( + logger.warning( f"Failed to find a deformable material binding for '{root_prim.GetPath().pathString}'." - " The material properties will be set to default values and are not modifiable at runtime." - " If you want to modify the material properties, please ensure that the material is bound" - " to the deformable body." + " The material properties will be set to default values and are not modifiable " + "at runtime. If you want to modify the material properties, please ensure that the material is " + "bound to the deformable body." ) + # fall back to prim hierarchy heuristic when material type detection was inconclusive + if self._deformable_type is None: + # volume deformables must have a tetmesh in the hierarchy + has_tetmesh = ( + len(sim_utils.get_all_matching_child_prims(root_prim.GetPath(), lambda p: p.GetTypeName() == "TetMesh")) + > 0 + ) + if has_tetmesh: + self._deformable_type = "volume" + else: + # surface deformables must have a mesh in the hierarchy + has_mesh = ( + len( + sim_utils.get_all_matching_child_prims(root_prim.GetPath(), lambda p: p.GetTypeName() == "Mesh") + ) + > 0 + ) + if has_mesh: + self._deformable_type = "surface" + # resolve root path back into regex expression # -- root prim expression root_prim_path = root_prim.GetPath().pathString root_prim_path_expr = self.cfg.prim_path + root_prim_path[len(template_prim_path) :] # -- object view - self._root_physx_view = self._physics_sim_view.create_soft_body_view(root_prim_path_expr.replace(".*", "*")) + if self._deformable_type == "surface": + # surface deformable + self._root_physx_view = self._physics_sim_view.create_surface_deformable_body_view( + root_prim_path_expr.replace(".*", "*") + ) + elif self._deformable_type == "volume": + # volume deformable + self._root_physx_view = self._physics_sim_view.create_volume_deformable_body_view( + root_prim_path_expr.replace(".*", "*") + ) + else: + raise RuntimeError( + f"Failed to determine deformable material type for '{root_prim.GetPath().pathString}'." + " Please ensure that the material has either 'PhysxSurfaceDeformableMaterialAPI' or " + "'PhysxDeformableMaterialAPI' applied, or that a valid tetmesh is found under the root prim." + ) # Return if the asset is not found if self._root_physx_view._backend is None: raise RuntimeError(f"Failed to create deformable body at: {self.cfg.prim_path}. Please check PhysX logs.") + # Check validity of deformables in view + if not self._root_physx_view.check(): + logger.warning(f"Deformable body view is not valid for: {self.cfg.prim_path}. Please check PhysX logs.") # resolve material path back into regex expression if material_prim is not None: @@ -604,7 +687,7 @@ def _initialize_impl(self): else: material_prim_path_expr = material_prim_path # -- material view - self._material_physx_view = self._physics_sim_view.create_soft_body_material_view( + self._material_physx_view = self._physics_sim_view.create_deformable_material_view( material_prim_path_expr.replace(".*", "*") ) else: @@ -638,10 +721,15 @@ def _create_buffers(self): # constants self._ALL_INDICES = wp.array(np.arange(self.num_instances, dtype=np.int32), device=self.device) + # Cached .view(wp.float32) wrappers for structured warp arrays. + # Safe because DeformableObjectData uses wp.copy into stable buffers. + self._nodal_pos_w_f32: wp.array | None = None + self._nodal_vel_w_f32: wp.array | None = None + # default state # we use the initial nodal positions at spawn time as the default state # note: these are all in the simulation frame - nodal_positions_raw = self.root_view.get_sim_nodal_positions() # (N, V, 3) float32 + nodal_positions_raw = self.root_view.get_simulation_nodal_positions() # (N, V, 3) float32 nodal_positions = nodal_positions_raw.view(wp.vec3f).reshape( (self.num_instances, self.max_sim_vertices_per_body) ) @@ -649,31 +737,35 @@ def _create_buffers(self): (self.num_instances, self.max_sim_vertices_per_body), dtype=wp.vec3f, device=self.device ) # compute default nodal state as vec6f - self._data.default_nodal_state_w = wp.zeros( + default_nodal_state = wp.zeros( (self.num_instances, self.max_sim_vertices_per_body), dtype=vec6f, device=self.device ) wp.launch( compute_nodal_state_w, dim=(self.num_instances, self.max_sim_vertices_per_body), inputs=[nodal_positions, nodal_velocities], - outputs=[self._data.default_nodal_state_w], - device=self.device, - ) - - # kinematic targets — allocate our own buffer and copy from PhysX - kinematic_raw = self.root_view.get_sim_kinematic_targets() # (N, V, 4) float32 - kinematic_view = kinematic_raw.view(wp.vec4f).reshape((self.num_instances, self.max_sim_vertices_per_body)) - self._data.nodal_kinematic_target = wp.zeros( - (self.num_instances, self.max_sim_vertices_per_body), dtype=wp.vec4f, device=self.device - ) - wp.copy(self._data.nodal_kinematic_target, kinematic_view) - # set all nodes as non-kinematic targets by default (flag = 1.0) - wp.launch( - set_kinematic_flags_to_one, - dim=(self.num_instances * self.max_sim_vertices_per_body,), - inputs=[self._data.nodal_kinematic_target.reshape((self.num_instances * self.max_sim_vertices_per_body,))], + outputs=[default_nodal_state], device=self.device, ) + self._data.default_nodal_state_w = ProxyArray(default_nodal_state) + + # kinematic targets (only for volume deformables, surface deformables do not support kinematic targets) + if self._deformable_type == "volume": + # kinematic targets — allocate our own buffer and copy from PhysX + kinematic_raw = self.root_view.get_simulation_nodal_kinematic_targets() # (N, V, 4) float32 + kinematic_view = kinematic_raw.view(wp.vec4f).reshape((self.num_instances, self.max_sim_vertices_per_body)) + kinematic_target = wp.zeros( + (self.num_instances, self.max_sim_vertices_per_body), dtype=wp.vec4f, device=self.device + ) + wp.copy(kinematic_target, kinematic_view) + # set all nodes as non-kinematic targets by default (flag = 1.0) + wp.launch( + set_kinematic_flags_to_one, + dim=(self.num_instances * self.max_sim_vertices_per_body,), + inputs=[kinematic_target.reshape((self.num_instances * self.max_sim_vertices_per_body,))], + device=self.device, + ) + self._data.nodal_kinematic_target = ProxyArray(kinematic_target) """ Internal simulation callbacks. @@ -692,10 +784,12 @@ def _set_debug_vis_impl(self, debug_vis: bool): self.target_visualizer.set_visibility(False) def _debug_vis_callback(self, event): - # check where to visualize - kinematic_target_torch = wp.to_torch(self.data.nodal_kinematic_target) - targets_enabled = kinematic_target_torch[:, :, 3] == 0.0 - num_enabled = int(torch.sum(targets_enabled).item()) + # check where to visualize, kinematic targets only supported for volume deformables + num_enabled = 0 + if self._deformable_type == "volume": + kinematic_target_torch = self.data.nodal_kinematic_target.torch + targets_enabled = kinematic_target_torch[:, :, 3] == 0.0 + num_enabled = int(torch.sum(targets_enabled).item()) # get positions if any targets are enabled if num_enabled == 0: # create a marker below the ground diff --git a/source/isaaclab_physx/isaaclab_physx/assets/deformable_object/deformable_object_data.py b/source/isaaclab_physx/isaaclab_physx/assets/deformable_object/deformable_object_data.py index 9e7e82499167..30307c1b08ff 100644 --- a/source/isaaclab_physx/isaaclab_physx/assets/deformable_object/deformable_object_data.py +++ b/source/isaaclab_physx/isaaclab_physx/assets/deformable_object/deformable_object_data.py @@ -7,9 +7,10 @@ import warp as wp -import omni.physics.tensors.impl.api as physx +import omni.physics.tensors.api as physx from isaaclab.utils.buffers import TimestampedBufferWarp as TimestampedBuffer +from isaaclab.utils.warp import ProxyArray from .kernels import compute_mean_vec3f_over_vertices, compute_nodal_state_w, vec6f @@ -34,7 +35,7 @@ class DeformableObjectData: is older than the current simulation timestamp. The timestamp is updated whenever the data is updated. """ - def __init__(self, root_view: physx.SoftBodyView, device: str): + def __init__(self, root_view: physx.DeformableBodyView, device: str): """Initializes the deformable object data. Args: @@ -46,13 +47,13 @@ def __init__(self, root_view: physx.SoftBodyView, device: str): # Set the root deformable body view # note: this is stored as a weak reference to avoid circular references between the asset class # and the data container. This is important to avoid memory leaks. - self._root_view: physx.SoftBodyView = weakref.proxy(root_view) + self._root_view: physx.DeformableBodyView = weakref.proxy(root_view) # Store dimensions self._num_instances = root_view.count - self._max_sim_vertices = root_view.max_sim_vertices_per_body - self._max_sim_elements = root_view.max_sim_elements_per_body - self._max_collision_elements = root_view.max_elements_per_body + self._max_sim_vertices = root_view.max_simulation_nodes_per_body + self._max_sim_elements = root_view.max_simulation_elements_per_body + self._max_collision_elements = root_view.max_collision_elements_per_body # Set initial time stamp self._sim_timestamp = 0.0 @@ -62,29 +63,17 @@ def __init__(self, root_view: physx.SoftBodyView, device: str): self._nodal_pos_w = TimestampedBuffer((self._num_instances, self._max_sim_vertices), device, wp.vec3f) self._nodal_vel_w = TimestampedBuffer((self._num_instances, self._max_sim_vertices), device, wp.vec3f) self._nodal_state_w = TimestampedBuffer((self._num_instances, self._max_sim_vertices), device, vec6f) - # -- mesh element-wise rotations - self._sim_element_quat_w = TimestampedBuffer((self._num_instances, self._max_sim_elements), device, wp.quatf) - self._collision_element_quat_w = TimestampedBuffer( - (self._num_instances, self._max_collision_elements), device, wp.quatf - ) - # -- mesh element-wise deformation gradients - self._sim_element_deform_gradient_w = TimestampedBuffer( - (self._num_instances, self._max_sim_elements, 3, 3), device, wp.float32 - ) - self._collision_element_deform_gradient_w = TimestampedBuffer( - (self._num_instances, self._max_collision_elements, 3, 3), device, wp.float32 - ) - # -- mesh element-wise stresses - self._sim_element_stress_w = TimestampedBuffer( - (self._num_instances, self._max_sim_elements, 3, 3), device, wp.float32 - ) - self._collision_element_stress_w = TimestampedBuffer( - (self._num_instances, self._max_collision_elements, 3, 3), device, wp.float32 - ) # -- derived: root pos/vel self._root_pos_w = TimestampedBuffer((self._num_instances,), device, wp.vec3f) self._root_vel_w = TimestampedBuffer((self._num_instances,), device, wp.vec3f) + # -- Pinned ProxyArray cache (one per read property, lazily created on first access) + self._nodal_pos_w_ta: ProxyArray | None = None + self._nodal_vel_w_ta: ProxyArray | None = None + self._nodal_state_w_ta: ProxyArray | None = None + self._root_pos_w_ta: ProxyArray | None = None + self._root_vel_w_ta: ProxyArray | None = None + def update(self, dt: float): """Updates the data for the deformable object. @@ -98,7 +87,7 @@ def update(self, dt: float): # Defaults. ## - default_nodal_state_w: wp.array = None + default_nodal_state_w: ProxyArray = None """Default nodal state ``[nodal_pos, nodal_vel]`` in simulation world frame. Shape is (num_instances, max_sim_vertices_per_body) with dtype vec6f. """ @@ -107,7 +96,7 @@ def update(self, dt: float): # Kinematic commands ## - nodal_kinematic_target: wp.array = None + nodal_kinematic_target: ProxyArray = None """Simulation mesh kinematic targets for the deformable bodies. Shape is (num_instances, max_sim_vertices_per_body) with dtype vec4f. @@ -122,32 +111,44 @@ def update(self, dt: float): ## @property - def nodal_pos_w(self) -> wp.array: + def nodal_pos_w(self) -> ProxyArray: """Nodal positions in simulation world frame. Shape is (num_instances, max_sim_vertices_per_body) vec3f.""" if self._nodal_pos_w.timestamp < self._sim_timestamp: - # get_sim_nodal_positions() returns (N, V, 3) float32 — view as (N, V) vec3f - self._nodal_pos_w.data = ( - self._root_view.get_sim_nodal_positions() + # get_simulation_nodal_positions() returns (N, V, 3) float32 — view as (N, V) vec3f + src = ( + self._root_view.get_simulation_nodal_positions() .view(wp.vec3f) .reshape((self._num_instances, self._max_sim_vertices)) ) + wp.copy(self._nodal_pos_w.data, src) self._nodal_pos_w.timestamp = self._sim_timestamp - return self._nodal_pos_w.data + # Rebind ProxyArray since .data was replaced with a new wp.array + if self._nodal_pos_w_ta is not None: + self._nodal_pos_w_ta = ProxyArray(self._nodal_pos_w.data) + if self._nodal_pos_w_ta is None: + self._nodal_pos_w_ta = ProxyArray(self._nodal_pos_w.data) + return self._nodal_pos_w_ta @property - def nodal_vel_w(self) -> wp.array: + def nodal_vel_w(self) -> ProxyArray: """Nodal velocities in simulation world frame. Shape is (num_instances, max_sim_vertices_per_body) vec3f.""" if self._nodal_vel_w.timestamp < self._sim_timestamp: - self._nodal_vel_w.data = ( - self._root_view.get_sim_nodal_velocities() + src = ( + self._root_view.get_simulation_nodal_velocities() .view(wp.vec3f) .reshape((self._num_instances, self._max_sim_vertices)) ) + wp.copy(self._nodal_vel_w.data, src) self._nodal_vel_w.timestamp = self._sim_timestamp - return self._nodal_vel_w.data + # Rebind ProxyArray since .data was replaced with a new wp.array + if self._nodal_vel_w_ta is not None: + self._nodal_vel_w_ta = ProxyArray(self._nodal_vel_w.data) + if self._nodal_vel_w_ta is None: + self._nodal_vel_w_ta = ProxyArray(self._nodal_vel_w.data) + return self._nodal_vel_w_ta @property - def nodal_state_w(self) -> wp.array: + def nodal_state_w(self) -> ProxyArray: """Nodal state ``[nodal_pos, nodal_vel]`` in simulation world frame. Shape is (num_instances, max_sim_vertices_per_body) vec6f. """ @@ -160,96 +161,16 @@ def nodal_state_w(self) -> wp.array: device=self.device, ) self._nodal_state_w.timestamp = self._sim_timestamp - return self._nodal_state_w.data - - @property - def sim_element_quat_w(self) -> wp.array: - """Simulation mesh element-wise rotations as quaternions for the deformable bodies in simulation world frame. - Shape is (num_instances, max_sim_elements_per_body, 4). - - The rotations are stored as quaternions in the order (x, y, z, w). - """ - if self._sim_element_quat_w.timestamp < self._sim_timestamp: - self._sim_element_quat_w.data = ( - self._root_view.get_sim_element_rotations() - .reshape((self._num_instances, self._max_sim_elements, 4)) - .view(wp.quatf) - ) - self._sim_element_quat_w.timestamp = self._sim_timestamp - return self._sim_element_quat_w.data - - @property - def collision_element_quat_w(self) -> wp.array: - """Collision mesh element-wise rotations as quaternions for the deformable bodies in simulation world frame. - Shape is (num_instances, max_collision_elements_per_body, 4). - - The rotations are stored as quaternions in the order (x, y, z, w). - """ - if self._collision_element_quat_w.timestamp < self._sim_timestamp: - self._collision_element_quat_w.data = ( - self._root_view.get_element_rotations() - .reshape((self._num_instances, self._max_collision_elements, 4)) - .view(wp.quatf) - ) - self._collision_element_quat_w.timestamp = self._sim_timestamp - return self._collision_element_quat_w.data - - @property - def sim_element_deform_gradient_w(self) -> wp.array: - """Simulation mesh element-wise second-order deformation gradient tensors for the deformable bodies - in simulation world frame. Shape is (num_instances, max_sim_elements_per_body, 3, 3). - """ - if self._sim_element_deform_gradient_w.timestamp < self._sim_timestamp: - self._sim_element_deform_gradient_w.data = self._root_view.get_sim_element_deformation_gradients().reshape( - (self._num_instances, self._max_sim_elements, 3, 3) - ) - self._sim_element_deform_gradient_w.timestamp = self._sim_timestamp - return self._sim_element_deform_gradient_w.data - - @property - def collision_element_deform_gradient_w(self) -> wp.array: - """Collision mesh element-wise second-order deformation gradient tensors for the deformable bodies - in simulation world frame. Shape is (num_instances, max_collision_elements_per_body, 3, 3). - """ - if self._collision_element_deform_gradient_w.timestamp < self._sim_timestamp: - self._collision_element_deform_gradient_w.data = ( - self._root_view.get_element_deformation_gradients().reshape( - (self._num_instances, self._max_collision_elements, 3, 3) - ) - ) - self._collision_element_deform_gradient_w.timestamp = self._sim_timestamp - return self._collision_element_deform_gradient_w.data - - @property - def sim_element_stress_w(self) -> wp.array: - """Simulation mesh element-wise second-order Cauchy stress tensors for the deformable bodies - in simulation world frame. Shape is (num_instances, max_sim_elements_per_body, 3, 3). - """ - if self._sim_element_stress_w.timestamp < self._sim_timestamp: - self._sim_element_stress_w.data = self._root_view.get_sim_element_stresses().reshape( - (self._num_instances, self._max_sim_elements, 3, 3) - ) - self._sim_element_stress_w.timestamp = self._sim_timestamp - return self._sim_element_stress_w.data - - @property - def collision_element_stress_w(self) -> wp.array: - """Collision mesh element-wise second-order Cauchy stress tensors for the deformable bodies - in simulation world frame. Shape is (num_instances, max_collision_elements_per_body, 3, 3). - """ - if self._collision_element_stress_w.timestamp < self._sim_timestamp: - self._collision_element_stress_w.data = self._root_view.get_element_stresses().reshape( - (self._num_instances, self._max_collision_elements, 3, 3) - ) - self._collision_element_stress_w.timestamp = self._sim_timestamp - return self._collision_element_stress_w.data + if self._nodal_state_w_ta is None: + self._nodal_state_w_ta = ProxyArray(self._nodal_state_w.data) + return self._nodal_state_w_ta ## # Derived properties. ## @property - def root_pos_w(self) -> wp.array: + def root_pos_w(self) -> ProxyArray: """Root position from nodal positions of the simulation mesh for the deformable bodies in simulation world frame. Shape is (num_instances, 3). @@ -264,10 +185,12 @@ def root_pos_w(self) -> wp.array: device=self.device, ) self._root_pos_w.timestamp = self._sim_timestamp - return self._root_pos_w.data + if self._root_pos_w_ta is None: + self._root_pos_w_ta = ProxyArray(self._root_pos_w.data) + return self._root_pos_w_ta @property - def root_vel_w(self) -> wp.array: + def root_vel_w(self) -> ProxyArray: """Root velocity from vertex velocities for the deformable bodies in simulation world frame. Shape is (num_instances, 3). @@ -282,4 +205,6 @@ def root_vel_w(self) -> wp.array: device=self.device, ) self._root_vel_w.timestamp = self._sim_timestamp - return self._root_vel_w.data + if self._root_vel_w_ta is None: + self._root_vel_w_ta = ProxyArray(self._root_vel_w.data) + return self._root_vel_w_ta diff --git a/source/isaaclab_physx/isaaclab_physx/assets/kernels.py b/source/isaaclab_physx/isaaclab_physx/assets/kernels.py index 383bd41d0928..d54f395739ae 100644 --- a/source/isaaclab_physx/isaaclab_physx/assets/kernels.py +++ b/source/isaaclab_physx/isaaclab_physx/assets/kernels.py @@ -469,14 +469,9 @@ def set_root_link_pose_to_sim( env_ids: wp.array(dtype=wp.int32), from_mask: bool, root_link_pose_w: wp.array(dtype=wp.transformf), - root_link_state_w: wp.array(dtype=vec13f), - root_state_w: wp.array(dtype=vec13f), ): """Write root link pose data to simulation buffers. - This kernel writes root link poses from the input array to the output buffers - and optionally updates the corresponding state vectors. - Args: data: Input array of root link poses. Shape is (num_envs,) or (num_selected_envs,) depending on from_mask. @@ -484,25 +479,13 @@ def set_root_link_pose_to_sim( from_mask: Input flag indicating whether to use masked indexing. If True, env_ids are used to index into data. If False, data is indexed sequentially. root_link_pose_w: Output array where root link poses are written. Shape is (num_envs,). - root_link_state_w: Output array where root link states are updated (pose portion). - Shape is (num_envs,). Can be None if not needed. - root_state_w: Output array where root states are updated (pose portion). - Shape is (num_envs,). Can be None if not needed. """ # If from mask, then we get complete data. Otherwise, we get partial data. i = wp.tid() if from_mask: root_link_pose_w[env_ids[i]] = data[env_ids[i]] - if root_link_state_w: - root_link_state_w[env_ids[i]] = set_state_transforms_func(root_link_state_w[env_ids[i]], data[env_ids[i]]) - if root_state_w: - root_state_w[env_ids[i]] = set_state_transforms_func(root_state_w[env_ids[i]], data[env_ids[i]]) else: root_link_pose_w[env_ids[i]] = data[i] - if root_link_state_w: - root_link_state_w[env_ids[i]] = set_state_transforms_func(root_link_state_w[env_ids[i]], data[i]) - if root_state_w: - root_state_w[env_ids[i]] = set_state_transforms_func(root_state_w[env_ids[i]], data[i]) @wp.kernel @@ -513,15 +496,11 @@ def set_root_com_pose_to_sim( from_mask: bool, root_com_pose_w: wp.array(dtype=wp.transformf), root_link_pose_w: wp.array(dtype=wp.transformf), - root_com_state_w: wp.array(dtype=vec13f), - root_link_state_w: wp.array(dtype=vec13f), - root_state_w: wp.array(dtype=vec13f), ): """Write root COM pose data to simulation buffers. - This kernel writes root COM poses from the input array to the output buffers, - computes the corresponding link pose from the COM pose, and optionally updates - the corresponding state vectors. + This kernel writes root COM poses from the input array to the output buffers + and computes the corresponding link pose from the COM pose. Args: data: Input array of root COM poses. Shape is (num_envs,) or (num_selected_envs,) @@ -534,33 +513,17 @@ def set_root_com_pose_to_sim( root_com_pose_w: Output array where root COM poses are written. Shape is (num_envs,). root_link_pose_w: Output array where root link poses (derived from COM) are written. Shape is (num_envs,). - root_com_state_w: Output array where root COM states are updated (pose portion). - Shape is (num_envs,). Can be None if not needed. - root_link_state_w: Output array where root link states are updated (pose portion). - Shape is (num_envs,). Can be None if not needed. - root_state_w: Output array where root states are updated (pose portion). - Shape is (num_envs,). Can be None if not needed. """ i = wp.tid() # If from mask, then we get complete data. Otherwise, we get partial data. if from_mask: root_com_pose_w[env_ids[i]] = data[env_ids[i]] - if root_com_state_w: - root_com_state_w[env_ids[i]] = set_state_transforms_func(root_com_state_w[env_ids[i]], data[env_ids[i]]) else: root_com_pose_w[env_ids[i]] = data[i] - if root_com_state_w: - root_com_state_w[env_ids[i]] = set_state_transforms_func(root_com_state_w[env_ids[i]], data[i]) # Get the com pose in the link frame root_link_pose_w[env_ids[i]] = get_com_pose_in_link_frame_func( root_com_pose_w[env_ids[i]], body_com_pose_b[env_ids[i], 0] ) - if root_link_state_w: - root_link_state_w[env_ids[i]] = set_state_transforms_func( - root_link_state_w[env_ids[i]], root_link_pose_w[env_ids[i]] - ) - if root_state_w: - root_state_w[env_ids[i]] = set_state_transforms_func(root_state_w[env_ids[i]], root_link_pose_w[env_ids[i]]) @wp.kernel @@ -571,14 +534,11 @@ def set_root_com_velocity_to_sim( from_mask: bool, root_com_velocity_w: wp.array(dtype=wp.spatial_vectorf), body_acc_w: wp.array2d(dtype=wp.spatial_vectorf), - root_state_w: wp.array(dtype=vec13f), - root_com_state_w: wp.array(dtype=vec13f), ): """Write root COM velocity data to simulation buffers. - This kernel writes root COM velocities from the input array to the output buffers, - optionally updates the corresponding state vectors, and zeros out the body - acceleration buffer to prevent reporting stale values. + This kernel writes root COM velocities from the input array to the output buffers + and zeros out the body acceleration buffer to prevent reporting stale values. Args: data: Input array of root COM spatial velocities. Shape is (num_envs,) or @@ -590,25 +550,13 @@ def set_root_com_velocity_to_sim( root_com_velocity_w: Output array where root COM velocities are written. Shape is (num_envs,). body_acc_w: Output array where body accelerations are zeroed. Shape is (num_envs, num_bodies). - root_state_w: Output array where root states are updated (velocity portion). - Shape is (num_envs,). Can be None if not needed. - root_com_state_w: Output array where root COM states are updated (velocity portion). - Shape is (num_envs,). Can be None if not needed. """ i = wp.tid() # If from mask, then we get complete data. Otherwise, we get partial data. if from_mask: root_com_velocity_w[env_ids[i]] = data[env_ids[i]] - if root_state_w: - root_state_w[env_ids[i]] = set_state_velocities_func(root_state_w[env_ids[i]], data[env_ids[i]]) - if root_com_state_w: - root_com_state_w[env_ids[i]] = set_state_velocities_func(root_com_state_w[env_ids[i]], data[env_ids[i]]) else: root_com_velocity_w[env_ids[i]] = data[i] - if root_state_w: - root_state_w[env_ids[i]] = set_state_velocities_func(root_state_w[env_ids[i]], data[i]) - if root_com_state_w: - root_com_state_w[env_ids[i]] = set_state_velocities_func(root_com_state_w[env_ids[i]], data[i]) # Make the acceleration zero to prevent reporting old values for j in range(num_bodies): body_acc_w[env_ids[i], j] = wp.spatial_vectorf(0.0, 0.0, 0.0, 0.0, 0.0, 0.0) @@ -625,15 +573,12 @@ def set_root_link_velocity_to_sim( root_link_velocity_w: wp.array(dtype=wp.spatial_vectorf), root_com_velocity_w: wp.array(dtype=wp.spatial_vectorf), body_acc_w: wp.array2d(dtype=wp.spatial_vectorf), - root_link_state_w: wp.array(dtype=vec13f), - root_state_w: wp.array(dtype=vec13f), - root_com_state_w: wp.array(dtype=vec13f), ): """Write root link velocity data to simulation buffers. This kernel writes root link velocities from the input array to the output buffers, - computes the corresponding COM velocity from the link velocity, optionally updates - the corresponding state vectors, and zeros out the body acceleration buffer. + computes the corresponding COM velocity from the link velocity, and zeros out the + body acceleration buffer. Args: data: Input array of root link spatial velocities. Shape is (num_envs,) or @@ -651,33 +596,17 @@ def set_root_link_velocity_to_sim( are written. Shape is (num_envs,). body_acc_w: Output array where body accelerations are zeroed. Shape is (num_envs, num_bodies). - root_link_state_w: Output array where root link states are updated (velocity portion). - Shape is (num_envs,). Can be None if not needed. - root_state_w: Output array where root states are updated (velocity portion). - Shape is (num_envs,). Can be None if not needed. - root_com_state_w: Output array where root COM states are updated (velocity portion). - Shape is (num_envs,). Can be None if not needed. """ # If from mask, then we get complete data. Otherwise, we get partial data. i = wp.tid() if from_mask: root_link_velocity_w[env_ids[i]] = data[env_ids[i]] - if root_link_state_w: - root_link_state_w[env_ids[i]] = set_state_velocities_func(root_link_state_w[env_ids[i]], data[env_ids[i]]) else: root_link_velocity_w[env_ids[i]] = data[i] - if root_link_state_w: - root_link_state_w[env_ids[i]] = set_state_velocities_func(root_link_state_w[env_ids[i]], data[i]) # Get the link velocity in the com frame root_com_velocity_w[env_ids[i]] = get_link_velocity_in_com_frame_func( root_link_velocity_w[env_ids[i]], link_pose_w[env_ids[i]], body_com_pose_b[env_ids[i], 0] ) - if root_com_state_w: - root_com_state_w[env_ids[i]] = set_state_velocities_func( - root_com_state_w[env_ids[i]], root_com_velocity_w[env_ids[i]] - ) - if root_state_w: - root_state_w[env_ids[i]] = set_state_velocities_func(root_state_w[env_ids[i]], root_com_velocity_w[env_ids[i]]) # Make the acceleration zero to prevent reporting old values for j in range(num_bodies): body_acc_w[env_ids[i], j] = wp.spatial_vectorf(0.0, 0.0, 0.0, 0.0, 0.0, 0.0) @@ -695,14 +624,9 @@ def set_body_link_pose_to_sim( body_ids: wp.array(dtype=wp.int32), from_mask: bool, body_link_pose_w: wp.array2d(dtype=wp.transformf), - body_link_state_w: wp.array2d(dtype=vec13f), - body_state_w: wp.array2d(dtype=vec13f), ): """Write body link pose data to simulation buffers. - This kernel writes body link poses from the input array to the output buffers - and optionally updates the corresponding state vectors, for each body in each environment. - Args: data: Input array of body link poses. Shape is (num_envs, num_bodies) or (num_selected_envs, num_selected_bodies) depending on from_mask. @@ -711,32 +635,12 @@ def set_body_link_pose_to_sim( from_mask: Input flag indicating whether to use masked indexing. body_link_pose_w: Output array where body link poses are written. Shape is (num_envs, num_bodies). - body_link_state_w: Output array where body link states are updated (pose portion). - Shape is (num_envs, num_bodies). Can be None if not needed. - body_state_w: Output array where body states are updated (pose portion). - Shape is (num_envs, num_bodies). Can be None if not needed. """ i, j = wp.tid() if from_mask: body_link_pose_w[env_ids[i], body_ids[j]] = data[env_ids[i], body_ids[j]] - if body_link_state_w: - body_link_state_w[env_ids[i], body_ids[j]] = set_state_transforms_func( - body_link_state_w[env_ids[i], body_ids[j]], data[env_ids[i], body_ids[j]] - ) - if body_state_w: - body_state_w[env_ids[i], body_ids[j]] = set_state_transforms_func( - body_state_w[env_ids[i], body_ids[j]], data[env_ids[i], body_ids[j]] - ) else: body_link_pose_w[env_ids[i], body_ids[j]] = data[i, j] - if body_link_state_w: - body_link_state_w[env_ids[i], body_ids[j]] = set_state_transforms_func( - body_link_state_w[env_ids[i], body_ids[j]], data[i, j] - ) - if body_state_w: - body_state_w[env_ids[i], body_ids[j]] = set_state_transforms_func( - body_state_w[env_ids[i], body_ids[j]], data[i, j] - ) @wp.kernel @@ -748,15 +652,12 @@ def set_body_com_pose_to_sim( from_mask: bool, body_com_pose_w: wp.array2d(dtype=wp.transformf), body_link_pose_w: wp.array2d(dtype=wp.transformf), - body_com_state_w: wp.array2d(dtype=vec13f), - body_link_state_w: wp.array2d(dtype=vec13f), - body_state_w: wp.array2d(dtype=vec13f), ): """Write body COM pose data to simulation buffers. - This kernel writes body COM poses from the input array to the output buffers, - computes the corresponding link poses from the COM poses, and optionally updates - the corresponding state vectors, for each body in each environment. + This kernel writes body COM poses from the input array to the output buffers + and computes the corresponding link poses from the COM poses, for each body + in each environment. Args: data: Input array of body COM poses. Shape is (num_envs, num_bodies) or @@ -770,38 +671,16 @@ def set_body_com_pose_to_sim( Shape is (num_envs, num_bodies). body_link_pose_w: Output array where body link poses (derived from COM) are written. Shape is (num_envs, num_bodies). - body_com_state_w: Output array where body COM states are updated (pose portion). - Shape is (num_envs, num_bodies). Can be None if not needed. - body_link_state_w: Output array where body link states are updated (pose portion). - Shape is (num_envs, num_bodies). Can be None if not needed. - body_state_w: Output array where body states are updated (pose portion). - Shape is (num_envs, num_bodies). Can be None if not needed. """ i, j = wp.tid() if from_mask: body_com_pose_w[env_ids[i], body_ids[j]] = data[env_ids[i], body_ids[j]] - if body_com_state_w: - body_com_state_w[env_ids[i], body_ids[j]] = set_state_transforms_func( - body_com_state_w[env_ids[i], body_ids[j]], data[env_ids[i], body_ids[j]] - ) else: body_com_pose_w[env_ids[i], body_ids[j]] = data[i, j] - if body_com_state_w: - body_com_state_w[env_ids[i], body_ids[j]] = set_state_transforms_func( - body_com_state_w[env_ids[i], body_ids[j]], data[i, j] - ) # Get the link pose from com pose body_link_pose_w[env_ids[i], body_ids[j]] = get_com_pose_in_link_frame_func( body_com_pose_w[env_ids[i], body_ids[j]], body_com_pose_b[env_ids[i], body_ids[j]] ) - if body_link_state_w: - body_link_state_w[env_ids[i], body_ids[j]] = set_state_transforms_func( - body_link_state_w[env_ids[i], body_ids[j]], body_link_pose_w[env_ids[i], body_ids[j]] - ) - if body_state_w: - body_state_w[env_ids[i], body_ids[j]] = set_state_transforms_func( - body_state_w[env_ids[i], body_ids[j]], body_link_pose_w[env_ids[i], body_ids[j]] - ) @wp.kernel @@ -812,14 +691,11 @@ def set_body_com_velocity_to_sim( from_mask: bool, body_com_velocity_w: wp.array2d(dtype=wp.spatial_vectorf), body_acc_w: wp.array2d(dtype=wp.spatial_vectorf), - body_state_w: wp.array2d(dtype=vec13f), - body_com_state_w: wp.array2d(dtype=vec13f), ): """Write body COM velocity data to simulation buffers. - This kernel writes body COM velocities from the input array to the output buffers, - optionally updates the corresponding state vectors, and zeros out the body - acceleration buffer, for each body in each environment. + This kernel writes body COM velocities from the input array to the output buffers + and zeros out the body acceleration buffer, for each body in each environment. Args: data: Input array of body COM spatial velocities. Shape is (num_envs, num_bodies) or @@ -831,32 +707,12 @@ def set_body_com_velocity_to_sim( Shape is (num_envs, num_bodies). body_acc_w: Output array where body accelerations are zeroed. Shape is (num_envs, num_bodies). - body_state_w: Output array where body states are updated (velocity portion). - Shape is (num_envs, num_bodies). Can be None if not needed. - body_com_state_w: Output array where body COM states are updated (velocity portion). - Shape is (num_envs, num_bodies). Can be None if not needed. """ i, j = wp.tid() if from_mask: body_com_velocity_w[env_ids[i], body_ids[j]] = data[env_ids[i], body_ids[j]] - if body_state_w: - body_state_w[env_ids[i], body_ids[j]] = set_state_velocities_func( - body_state_w[env_ids[i], body_ids[j]], data[env_ids[i], body_ids[j]] - ) - if body_com_state_w: - body_com_state_w[env_ids[i], body_ids[j]] = set_state_velocities_func( - body_com_state_w[env_ids[i], body_ids[j]], data[env_ids[i], body_ids[j]] - ) else: body_com_velocity_w[env_ids[i], body_ids[j]] = data[i, j] - if body_state_w: - body_state_w[env_ids[i], body_ids[j]] = set_state_velocities_func( - body_state_w[env_ids[i], body_ids[j]], data[i, j] - ) - if body_com_state_w: - body_com_state_w[env_ids[i], body_ids[j]] = set_state_velocities_func( - body_com_state_w[env_ids[i], body_ids[j]], data[i, j] - ) # Make the acceleration zero to prevent reporting old values body_acc_w[env_ids[i], body_ids[j]] = wp.spatial_vectorf(0.0, 0.0, 0.0, 0.0, 0.0, 0.0) @@ -872,15 +728,12 @@ def set_body_link_velocity_to_sim( body_link_velocity_w: wp.array2d(dtype=wp.spatial_vectorf), body_com_velocity_w: wp.array2d(dtype=wp.spatial_vectorf), body_acc_w: wp.array2d(dtype=wp.spatial_vectorf), - body_link_state_w: wp.array2d(dtype=vec13f), - body_state_w: wp.array2d(dtype=vec13f), - body_com_state_w: wp.array2d(dtype=vec13f), ): """Write body link velocity data to simulation buffers. This kernel writes body link velocities from the input array to the output buffers, - computes the corresponding COM velocities from the link velocities, optionally updates - the corresponding state vectors, and zeros out the body acceleration buffer. + computes the corresponding COM velocities from the link velocities, and zeros out + the body acceleration buffer. Args: data: Input array of body link spatial velocities. Shape is (num_envs, num_bodies) @@ -898,40 +751,18 @@ def set_body_link_velocity_to_sim( are written. Shape is (num_envs, num_bodies). body_acc_w: Output array where body accelerations are zeroed. Shape is (num_envs, num_bodies). - body_link_state_w: Output array where body link states are updated (velocity portion). - Shape is (num_envs, num_bodies). Can be None if not needed. - body_state_w: Output array where body states are updated (velocity portion). - Shape is (num_envs, num_bodies). Can be None if not needed. - body_com_state_w: Output array where body COM states are updated (velocity portion). - Shape is (num_envs, num_bodies). Can be None if not needed. """ i, j = wp.tid() if from_mask: body_link_velocity_w[env_ids[i], body_ids[j]] = data[env_ids[i], body_ids[j]] - if body_link_state_w: - body_link_state_w[env_ids[i], body_ids[j]] = set_state_velocities_func( - body_link_state_w[env_ids[i], body_ids[j]], data[env_ids[i], body_ids[j]] - ) else: body_link_velocity_w[env_ids[i], body_ids[j]] = data[i, j] - if body_link_state_w: - body_link_state_w[env_ids[i], body_ids[j]] = set_state_velocities_func( - body_link_state_w[env_ids[i], body_ids[j]], data[i, j] - ) # Get the link velocity in the com frame body_com_velocity_w[env_ids[i], body_ids[j]] = get_link_velocity_in_com_frame_func( body_link_velocity_w[env_ids[i], body_ids[j]], body_link_pose_w[env_ids[i], body_ids[j]], body_com_pose_b[env_ids[i], body_ids[j]], ) - if body_com_state_w: - body_com_state_w[env_ids[i], body_ids[j]] = set_state_velocities_func( - body_com_state_w[env_ids[i], body_ids[j]], body_com_velocity_w[env_ids[i], body_ids[j]] - ) - if body_state_w: - body_state_w[env_ids[i], body_ids[j]] = set_state_velocities_func( - body_state_w[env_ids[i], body_ids[j]], body_com_velocity_w[env_ids[i], body_ids[j]] - ) # Make the acceleration zero to prevent reporting old values body_acc_w[env_ids[i], body_ids[j]] = wp.spatial_vectorf(0.0, 0.0, 0.0, 0.0, 0.0, 0.0) diff --git a/source/isaaclab_physx/isaaclab_physx/assets/rigid_object/rigid_object.py b/source/isaaclab_physx/isaaclab_physx/assets/rigid_object/rigid_object.py index b549da96b787..930b8836859a 100644 --- a/source/isaaclab_physx/isaaclab_physx/assets/rigid_object/rigid_object.py +++ b/source/isaaclab_physx/isaaclab_physx/assets/rigid_object/rigid_object.py @@ -26,7 +26,7 @@ from .rigid_object_data import RigidObjectData if TYPE_CHECKING: - import omni.physics.tensors.impl.api as physx + import omni.physics.tensors.api as physx from isaaclab.assets.rigid_object.rigid_object_cfg import RigidObjectCfg @@ -150,30 +150,22 @@ def write_data_to_sim(self) -> None: # write external wrench if self._instantaneous_wrench_composer.active or self._permanent_wrench_composer.active: if self._instantaneous_wrench_composer.active: - # Compose instantaneous wrench with permanent wrench - self._instantaneous_wrench_composer.add_forces_and_torques_index( - forces=self._permanent_wrench_composer.composed_force, - torques=self._permanent_wrench_composer.composed_torque, - body_ids=self._ALL_BODY_INDICES, - env_ids=self._ALL_INDICES, - ) - # Apply both instantaneous and permanent wrench to the simulation - self.root_view.apply_forces_and_torques_at_position( - force_data=self._instantaneous_wrench_composer.composed_force.flatten().view(wp.float32), - torque_data=self._instantaneous_wrench_composer.composed_torque.flatten().view(wp.float32), - position_data=None, - indices=self._ALL_INDICES, - is_global=False, - ) + composer = self._instantaneous_wrench_composer + composer.add_raw_buffers_from(self._permanent_wrench_composer) + get_force_data = self._get_inst_wrench_force_f32 + get_torque_data = self._get_inst_wrench_torque_f32 else: - # Apply permanent wrench to the simulation - self.root_view.apply_forces_and_torques_at_position( - force_data=self._permanent_wrench_composer.composed_force.flatten().view(wp.float32), - torque_data=self._permanent_wrench_composer.composed_torque.flatten().view(wp.float32), - position_data=None, - indices=self._ALL_INDICES, - is_global=False, - ) + composer = self._permanent_wrench_composer + get_force_data = self._get_perm_wrench_force_f32 + get_torque_data = self._get_perm_wrench_torque_f32 + composer.compose_to_body_frame() + self.root_view.apply_forces_and_torques_at_position( + force_data=get_force_data(), + torque_data=get_torque_data(), + position_data=None, + indices=self._ALL_INDICES, + is_global=False, + ) self._instantaneous_wrench_composer.reset() def update(self, dt: float) -> None: @@ -342,8 +334,6 @@ def write_root_link_pose_to_sim_index( ], outputs=[ self.data.root_link_pose_w, - None, # self.data._root_link_state_w.data, - None, # self.data._root_state_w.data, ], device=self.device, ) @@ -353,7 +343,7 @@ def write_root_link_pose_to_sim_index( self.data._root_state_w.timestamp = -1.0 self.data._root_com_state_w.timestamp = -1.0 # set into simulation - self.root_view.set_transforms(self.data._root_link_pose_w.data.view(wp.float32), indices=env_ids) + self.root_view.set_transforms(self._get_root_link_pose_w_f32(), indices=env_ids) def write_root_link_pose_to_sim_mask( self, @@ -426,9 +416,6 @@ def write_root_com_pose_to_sim_index( outputs=[ self.data.root_com_pose_w, self.data.root_link_pose_w, - None, # self.data._root_com_state_w.data, - None, # self.data._root_link_state_w.data, - None, # self.data._root_state_w.data, ], device=self.device, ) @@ -437,7 +424,7 @@ def write_root_com_pose_to_sim_index( self.data._root_link_state_w.timestamp = -1.0 self.data._root_state_w.timestamp = -1.0 # set into simulation - self.root_view.set_transforms(self.data._root_link_pose_w.data.view(wp.float32), indices=env_ids) + self.root_view.set_transforms(self._get_root_link_pose_w_f32(), indices=env_ids) def write_root_com_pose_to_sim_mask( self, @@ -514,8 +501,6 @@ def write_root_com_velocity_to_sim_index( outputs=[ self.data.root_com_vel_w, self.data.body_com_acc_w, - None, # self.data._root_state_w.data, - None, # self.data._root_com_state_w.data, ], device=self.device, ) @@ -525,7 +510,7 @@ def write_root_com_velocity_to_sim_index( self.data._root_com_state_w.timestamp = -1.0 self.data._root_state_w.timestamp = -1.0 # set into simulation - self.root_view.set_velocities(self.data._root_com_vel_w.data.view(wp.float32), indices=env_ids) + self.root_view.set_velocities(self._get_root_com_vel_w_f32(), indices=env_ids) def write_root_com_velocity_to_sim_mask( self, @@ -608,9 +593,6 @@ def write_root_link_velocity_to_sim_index( self.data.root_link_vel_w, self.data.root_com_vel_w, self.data.body_com_acc_w, - None, # self.data._root_link_state_w.data, - None, # self.data._root_state_w.data, - None, # self.data._root_com_state_w.data, ], device=self.device, ) @@ -619,7 +601,7 @@ def write_root_link_velocity_to_sim_index( self.data._root_state_w.timestamp = -1.0 self.data._root_com_state_w.timestamp = -1.0 # set into simulation - self.root_view.set_velocities(self.data._root_com_vel_w.data.view(wp.float32), indices=env_ids) + self.root_view.set_velocities(self._get_root_com_vel_w_f32(), indices=env_ids) def write_root_link_velocity_to_sim_mask( self, @@ -704,11 +686,9 @@ def set_masses_index( ) # Set into simulation, note that when updating "model" properties with PhysX we need to do it on CPU. - if isinstance(env_ids, wp.array): - cpu_env_ids = wp.clone(env_ids, device="cpu") - else: - cpu_env_ids = wp.clone(wp.from_torch(env_ids, dtype=wp.int32), device="cpu") - self.root_view.set_masses(wp.clone(self.data._body_mass, device="cpu"), indices=cpu_env_ids) + cpu_env_ids = self._get_cpu_env_ids(env_ids) + wp.copy(self._cpu_body_mass, self.data._body_mass) + self.root_view.set_masses(self._cpu_body_mass, indices=cpu_env_ids) def set_masses_mask( self, @@ -791,7 +771,8 @@ def set_coms_index( ) # Set into simulation, note that when updating "model" properties with PhysX we need to do it on CPU. cpu_env_ids = self._get_cpu_env_ids(env_ids) - self.root_view.set_coms(wp.clone(self.data._body_com_pose_b.data, device="cpu"), indices=cpu_env_ids) + wp.copy(self._cpu_body_coms, self.data._body_com_pose_b.data) + self.root_view.set_coms(self._cpu_body_coms, indices=cpu_env_ids) def set_coms_mask( self, @@ -873,11 +854,9 @@ def set_inertias_index( device=self.device, ) # Set into simulation, note that when updating "model" properties with PhysX we need to do it on CPU. - if isinstance(env_ids, wp.array): - cpu_env_ids = wp.clone(env_ids, device="cpu") - else: - cpu_env_ids = wp.clone(wp.from_torch(env_ids, dtype=wp.int32), device="cpu") - self.root_view.set_inertias(wp.clone(self.data._body_inertia, device="cpu").flatten(), indices=cpu_env_ids) + cpu_env_ids = self._get_cpu_env_ids(env_ids) + wp.copy(self._cpu_body_inertia, self.data._body_inertia) + self.root_view.set_inertias(self._cpu_body_inertia.flatten(), indices=cpu_env_ids) def set_inertias_mask( self, @@ -992,6 +971,27 @@ def _create_buffers(self): # set information about rigid body into data self._data.body_names = self.body_names + # Cached .view(wp.float32) wrappers for structured warp arrays. + # These avoid per-call wp.array metadata allocation in writers. + # Reset to None each time _create_buffers runs (during initialization). + self._root_link_pose_w_f32: wp.array | None = None + self._root_com_vel_w_f32: wp.array | None = None + # Cached wrench views for write_data_to_sim + self._inst_wrench_force_f32: wp.array | None = None + self._inst_wrench_torque_f32: wp.array | None = None + self._perm_wrench_force_f32: wp.array | None = None + self._perm_wrench_torque_f32: wp.array | None = None + + # Pre-allocated pinned CPU buffers for PhysX TensorAPI writes. + # PhysX requires CPU arrays for "model" property updates (masses, coms, inertias). + # Pinned memory enables DMA fast path and avoids per-call malloc. + N, B = self.num_instances, self.num_bodies + self._cpu_env_ids_all = wp.zeros(N, dtype=wp.int32, device="cpu", pinned=True) + wp.copy(self._cpu_env_ids_all, self._ALL_INDICES) + self._cpu_body_mass = wp.zeros((N, B), dtype=wp.float32, device="cpu", pinned=True) + self._cpu_body_coms = wp.zeros((N, B, 7), dtype=wp.float32, device="cpu", pinned=True) + self._cpu_body_inertia = wp.zeros((N, B, 9), dtype=wp.float32, device="cpu", pinned=True) + def _process_cfg(self) -> None: """Post processing of configuration parameters.""" # default state @@ -1039,24 +1039,65 @@ def _resolve_body_mask(self, body_mask: wp.array | None) -> torch.Tensor | wp.ar return body_ids def _get_cpu_env_ids(self, env_ids: wp.array | torch.Tensor) -> wp.array: - """Get the CPU environment indices. + """Get CPU environment indices. Uses pre-allocated pinned buffer for full-index case. Args: env_ids: Environment indices. Returns: - A warp array of environment indices. + A warp array of environment indices on CPU. """ if isinstance(env_ids, torch.Tensor): env_ids = wp.from_torch(env_ids, dtype=wp.int32) + # Fast path: if these are all indices, use pre-allocated pinned buffer + if env_ids.ptr == self._ALL_INDICES.ptr: + return self._cpu_env_ids_all + # Slow path: partial indices (reset), clone to CPU return wp.clone(env_ids, device="cpu") + def _get_root_link_pose_w_f32(self) -> wp.array: + """Get a cached float32 view of root_link_pose_w for PhysX TensorAPI. Invalidated in ``_create_buffers``.""" + if self._root_link_pose_w_f32 is None: + self._root_link_pose_w_f32 = self.data._root_link_pose_w.data.view(wp.float32) + return self._root_link_pose_w_f32 + + def _get_root_com_vel_w_f32(self) -> wp.array: + """Get a cached float32 view of root_com_vel_w for PhysX TensorAPI. Invalidated in ``_create_buffers``.""" + if self._root_com_vel_w_f32 is None: + self._root_com_vel_w_f32 = self.data._root_com_vel_w.data.view(wp.float32) + return self._root_com_vel_w_f32 + + def _get_inst_wrench_force_f32(self) -> wp.array: + """Get a cached flattened float32 view of instantaneous wrench force. Invalidated in ``_create_buffers``.""" + if self._inst_wrench_force_f32 is None: + self._inst_wrench_force_f32 = self._instantaneous_wrench_composer.out_force_b.warp.flatten().view( + wp.float32 + ) + return self._inst_wrench_force_f32 + + def _get_inst_wrench_torque_f32(self) -> wp.array: + """Get a cached flattened float32 view of instantaneous wrench torque. Invalidated in ``_create_buffers``.""" + if self._inst_wrench_torque_f32 is None: + self._inst_wrench_torque_f32 = self._instantaneous_wrench_composer.out_torque_b.warp.flatten().view( + wp.float32 + ) + return self._inst_wrench_torque_f32 + + def _get_perm_wrench_force_f32(self) -> wp.array: + """Get a cached flattened float32 view of permanent wrench force. Invalidated in ``_create_buffers``.""" + if self._perm_wrench_force_f32 is None: + self._perm_wrench_force_f32 = self._permanent_wrench_composer.out_force_b.warp.flatten().view(wp.float32) + return self._perm_wrench_force_f32 + + def _get_perm_wrench_torque_f32(self) -> wp.array: + """Get a cached flattened float32 view of permanent wrench torque. Invalidated in ``_create_buffers``.""" + if self._perm_wrench_torque_f32 is None: + self._perm_wrench_torque_f32 = self._permanent_wrench_composer.out_torque_b.warp.flatten().view(wp.float32) + return self._perm_wrench_torque_f32 + def _resolve_env_ids(self, env_ids: Sequence[int] | torch.Tensor | wp.array | None) -> wp.array | torch.Tensor: """Resolve environment indices to a warp array or tensor. - .. note:: - We need to convert torch tensors to warp arrays since the TensorAPI views only support warp arrays. - Args: env_ids: Environment indices. If None, then all indices are used. @@ -1065,28 +1106,31 @@ def _resolve_env_ids(self, env_ids: Sequence[int] | torch.Tensor | wp.array | No """ if (env_ids is None) or (env_ids == slice(None)): return self._ALL_INDICES - elif isinstance(env_ids, list): - return wp.array(env_ids, dtype=wp.int32, device=self.device) if isinstance(env_ids, torch.Tensor): - return wp.from_torch(env_ids.to(torch.int32), dtype=wp.int32) + if env_ids.dtype == torch.int64: + env_ids = env_ids.to(torch.int32) + return wp.from_torch(env_ids, dtype=wp.int32) + if isinstance(env_ids, list): + return wp.array(env_ids, dtype=wp.int32, device=self.device) return env_ids def _resolve_body_ids(self, body_ids: Sequence[int] | torch.Tensor | wp.array | None) -> wp.array | torch.Tensor: """Resolve body indices to a warp array or tensor. - .. note:: - We do not need to convert torch tensors to warp arrays since they never get passed to the TensorAPI views. - Args: body_ids: Body indices. If None, then all indices are used. Returns: A warp array of body indices or a tensor of body indices. """ + if isinstance(body_ids, list): + return wp.array(body_ids, dtype=wp.int32, device=self.device) if (body_ids is None) or (body_ids == slice(None)): return self._ALL_BODY_INDICES - elif isinstance(body_ids, list): - return wp.array(body_ids, dtype=wp.int32, device=self.device) + if isinstance(body_ids, torch.Tensor): + if body_ids.dtype == torch.int64: + body_ids = body_ids.to(torch.int32) + return wp.from_torch(body_ids, dtype=wp.int32) return body_ids """ diff --git a/source/isaaclab_physx/isaaclab_physx/assets/rigid_object/rigid_object_data.py b/source/isaaclab_physx/isaaclab_physx/assets/rigid_object/rigid_object_data.py index 0a6157585c59..a8e674dc6bf8 100644 --- a/source/isaaclab_physx/isaaclab_physx/assets/rigid_object/rigid_object_data.py +++ b/source/isaaclab_physx/isaaclab_physx/assets/rigid_object/rigid_object_data.py @@ -15,12 +15,13 @@ from isaaclab.assets.rigid_object.base_rigid_object_data import BaseRigidObjectData from isaaclab.utils.buffers import TimestampedBufferWarp as TimestampedBuffer from isaaclab.utils.math import normalize +from isaaclab.utils.warp import ProxyArray from isaaclab_physx.assets import kernels as shared_kernels from isaaclab_physx.physics import PhysxManager as SimulationManager if TYPE_CHECKING: - import omni.physics.tensors.impl.api as physx + import omni.physics.tensors.api as physx # import logger logger = logging.getLogger(__name__) @@ -45,6 +46,16 @@ class RigidObjectData(BaseRigidObjectData): The data is lazily updated, meaning that the data is only updated when it is accessed. This is useful when the data is expensive to compute or retrieve. The data is updated when the timestamp of the buffer is older than the current simulation timestamp. The timestamp is updated whenever the data is updated. + + .. note:: + **Pull-to-refresh model.** Properties pull fresh data from the PhysX tensor API on first + access per timestamp and cache the result. This differs from Newton, where buffers are + refreshed automatically by the simulation. + + .. note:: + **ProxyArray pointer stability.** Each :class:`ProxyArray` wrapper is created once and + reused because the PhysX tensor API returns views into stable, pre-allocated GPU buffers + whose device pointer does not change across simulation steps. """ __backend_name__: str = "physx" @@ -78,8 +89,8 @@ def __init__(self, root_view: physx.RigidBodyView, device: str): forward_vec = torch.tensor((1.0, 0.0, 0.0), device=self.device).repeat(self._root_view.count, 1) # Initialize constants - self.GRAVITY_VEC_W = wp.from_torch(gravity_dir, dtype=wp.vec3f) - self.FORWARD_VEC_B = wp.from_torch(forward_vec, dtype=wp.vec3f) + self.GRAVITY_VEC_W = ProxyArray(wp.from_torch(gravity_dir, dtype=wp.vec3f)) + self.FORWARD_VEC_B = ProxyArray(wp.from_torch(forward_vec, dtype=wp.vec3f)) self._create_buffers() @@ -126,13 +137,15 @@ def update(self, dt: float) -> None: """ @property - def default_root_pose(self) -> wp.array: + def default_root_pose(self) -> ProxyArray: """Default root pose ``[pos, quat]`` in local environment frame. Shape is (num_instances,), dtype = wp.transformf. In torch this resolves to (num_instances, 7). The position and quaternion are of the rigid body's actor frame. """ - return self._default_root_pose + if self._default_root_pose_ta is None: + self._default_root_pose_ta = ProxyArray(self._default_root_pose) + return self._default_root_pose_ta @default_root_pose.setter def default_root_pose(self, value: wp.array) -> None: @@ -149,13 +162,15 @@ def default_root_pose(self, value: wp.array) -> None: self._default_root_pose.assign(value) @property - def default_root_vel(self) -> wp.array: + def default_root_vel(self) -> ProxyArray: """Default root velocity ``[lin_vel, ang_vel]`` in local environment frame. Shape is (num_instances,), dtype = wp.spatial_vectorf. In torch this resolves to (num_instances, 6). The linear and angular velocities are of the rigid body's center of mass frame. """ - return self._default_root_vel + if self._default_root_vel_ta is None: + self._default_root_vel_ta = ProxyArray(self._default_root_vel) + return self._default_root_vel_ta @default_root_vel.setter def default_root_vel(self, value: wp.array) -> None: @@ -176,7 +191,7 @@ def default_root_vel(self, value: wp.array) -> None: """ @property - def root_link_pose_w(self) -> wp.array: + def root_link_pose_w(self) -> ProxyArray: """Root link pose ``[pos, quat]`` in simulation world frame. Shape is (num_instances,), dtype = wp.transformf. In torch this resolves to (num_instances, 7). @@ -188,10 +203,12 @@ def root_link_pose_w(self) -> wp.array: self._root_link_pose_w.data = self._root_view.get_transforms().view(wp.transformf) self._root_link_pose_w.timestamp = self._sim_timestamp - return self._root_link_pose_w.data + if self._root_link_pose_w_ta is None: + self._root_link_pose_w_ta = ProxyArray(self._root_link_pose_w.data) + return self._root_link_pose_w_ta @property - def root_link_vel_w(self) -> wp.array: + def root_link_vel_w(self) -> ProxyArray: """Root link velocity ``[lin_vel, ang_vel]`` in simulation world frame. Shape is (num_instances,), dtype = wp.spatial_vectorf. In torch this resolves to (num_instances, 6). @@ -215,10 +232,12 @@ def root_link_vel_w(self) -> wp.array: ) self._root_link_vel_w.timestamp = self._sim_timestamp - return self._root_link_vel_w.data + if self._root_link_vel_w_ta is None: + self._root_link_vel_w_ta = ProxyArray(self._root_link_vel_w.data) + return self._root_link_vel_w_ta @property - def root_com_pose_w(self) -> wp.array: + def root_com_pose_w(self) -> ProxyArray: """Root center of mass pose ``[pos, quat]`` in simulation world frame. Shape is (num_instances,), dtype = wp.transformf. In torch this resolves to (num_instances, 7). @@ -241,10 +260,12 @@ def root_com_pose_w(self) -> wp.array: ) self._root_com_pose_w.timestamp = self._sim_timestamp - return self._root_com_pose_w.data + if self._root_com_pose_w_ta is None: + self._root_com_pose_w_ta = ProxyArray(self._root_com_pose_w.data) + return self._root_com_pose_w_ta @property - def root_com_vel_w(self) -> wp.array: + def root_com_vel_w(self) -> ProxyArray: """Root center of mass velocity ``[lin_vel, ang_vel]`` in simulation world frame. Shape is (num_instances,), dtype = wp.spatial_vectorf. In torch this resolves to (num_instances, 6). @@ -255,72 +276,90 @@ def root_com_vel_w(self) -> wp.array: self._root_com_vel_w.data = self._root_view.get_velocities().view(wp.spatial_vectorf) self._root_com_vel_w.timestamp = self._sim_timestamp - return self._root_com_vel_w.data + if self._root_com_vel_w_ta is None: + self._root_com_vel_w_ta = ProxyArray(self._root_com_vel_w.data) + return self._root_com_vel_w_ta """ Body state properties. """ @property - def body_mass(self) -> wp.array: + def body_mass(self) -> ProxyArray: """Mass of all bodies in the simulation world frame. Shape is (num_instances, 1), dtype = wp.float32. In torch this resolves to (num_instances, 1). """ - return self._body_mass + if self._body_mass_ta is None: + self._body_mass_ta = ProxyArray(self._body_mass) + return self._body_mass_ta @property - def body_inertia(self) -> wp.array: + def body_inertia(self) -> ProxyArray: """Inertia of all bodies in the simulation world frame. Shape is (num_instances, 1, 9), dtype = wp.float32. In torch this resolves to (num_instances, 1, 9). """ - return self._body_inertia + if self._body_inertia_ta is None: + self._body_inertia_ta = ProxyArray(self._body_inertia) + return self._body_inertia_ta @property - def body_link_pose_w(self) -> wp.array: + def body_link_pose_w(self) -> ProxyArray: """Body link pose ``[pos, quat]`` in simulation world frame. Shape is (num_instances, 1), dtype = wp.transformf. In torch this resolves to (num_instances, 1, 7). This quantity is the pose of the actor frame of the rigid body relative to the world. The orientation is provided in (x, y, z, w) format. """ - return self.root_link_pose_w.reshape((self._num_instances, 1)) + parent = self.root_link_pose_w + if self._body_link_pose_w_ta is None: + self._body_link_pose_w_ta = ProxyArray(parent.warp.reshape((self._num_instances, 1))) + return self._body_link_pose_w_ta @property - def body_link_vel_w(self) -> wp.array: + def body_link_vel_w(self) -> ProxyArray: """Body link velocity ``[lin_vel, ang_vel]`` in simulation world frame. Shape is (num_instances, 1), dtype = wp.spatial_vectorf. In torch this resolves to (num_instances, 1, 6). This quantity contains the linear and angular velocities of the actor frame of the root rigid body relative to the world. """ - return self.root_link_vel_w.reshape((self._num_instances, 1)) + parent = self.root_link_vel_w + if self._body_link_vel_w_ta is None: + self._body_link_vel_w_ta = ProxyArray(parent.warp.reshape((self._num_instances, 1))) + return self._body_link_vel_w_ta @property - def body_com_pose_w(self) -> wp.array: + def body_com_pose_w(self) -> ProxyArray: """Body center of mass pose ``[pos, quat]`` in simulation world frame. Shape is (num_instances, 1), dtype = wp.transformf. In torch this resolves to (num_instances, 1, 7). This quantity is the pose of the center of mass frame of the rigid body relative to the world. The orientation is provided in (x, y, z, w) format. """ - return self.root_com_pose_w.reshape((self._num_instances, 1)) + parent = self.root_com_pose_w + if self._body_com_pose_w_ta is None: + self._body_com_pose_w_ta = ProxyArray(parent.warp.reshape((self._num_instances, 1))) + return self._body_com_pose_w_ta @property - def body_com_vel_w(self) -> wp.array: + def body_com_vel_w(self) -> ProxyArray: """Body center of mass velocity ``[lin_vel, ang_vel]`` in simulation world frame. Shape is (num_instances, 1), dtype = wp.spatial_vectorf. In torch this resolves to (num_instances, 1, 6). This quantity contains the linear and angular velocities of the root rigid body's center of mass frame relative to the world. """ - return self.root_com_vel_w.reshape((self._num_instances, 1)) + parent = self.root_com_vel_w + if self._body_com_vel_w_ta is None: + self._body_com_vel_w_ta = ProxyArray(parent.warp.reshape((self._num_instances, 1))) + return self._body_com_vel_w_ta @property - def body_com_acc_w(self) -> wp.array: + def body_com_acc_w(self) -> ProxyArray: """Acceleration of all bodies ``[lin_acc, ang_acc]`` in the simulation world frame. Shape is (num_instances, 1), dtype = wp.spatial_vectorf. In torch this resolves to (num_instances, 1, 6). @@ -332,10 +371,12 @@ def body_com_acc_w(self) -> wp.array: ) self._body_com_acc_w.timestamp = self._sim_timestamp - return self._body_com_acc_w.data + if self._body_com_acc_w_ta is None: + self._body_com_acc_w_ta = ProxyArray(self._body_com_acc_w.data) + return self._body_com_acc_w_ta @property - def body_com_pose_b(self) -> wp.array: + def body_com_pose_b(self) -> ProxyArray: """Center of mass pose ``[pos, quat]`` of all bodies in their respective body's link frames. Shape is (num_instances, 1), dtype = wp.transformf. In torch this resolves to (num_instances, 1, 7). @@ -349,14 +390,16 @@ def body_com_pose_b(self) -> wp.array: ) self._body_com_pose_b.timestamp = self._sim_timestamp - return self._body_com_pose_b.data + if self._body_com_pose_b_ta is None: + self._body_com_pose_b_ta = ProxyArray(self._body_com_pose_b.data) + return self._body_com_pose_b_ta """ Derived Properties. """ @property - def projected_gravity_b(self) -> wp.array: + def projected_gravity_b(self) -> ProxyArray: """Projection of the gravity direction on base frame. Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). @@ -370,10 +413,12 @@ def projected_gravity_b(self) -> wp.array: device=self.device, ) self._projected_gravity_b.timestamp = self._sim_timestamp - return self._projected_gravity_b.data + if self._projected_gravity_b_ta is None: + self._projected_gravity_b_ta = ProxyArray(self._projected_gravity_b.data) + return self._projected_gravity_b_ta @property - def heading_w(self) -> wp.array: + def heading_w(self) -> ProxyArray: """Yaw heading of the base frame (in radians). Shape is (num_instances,), dtype = wp.float32. In torch this resolves to (num_instances,). @@ -391,10 +436,12 @@ def heading_w(self) -> wp.array: device=self.device, ) self._heading_w.timestamp = self._sim_timestamp - return self._heading_w.data + if self._heading_w_ta is None: + self._heading_w_ta = ProxyArray(self._heading_w.data) + return self._heading_w_ta @property - def root_link_lin_vel_b(self) -> wp.array: + def root_link_lin_vel_b(self) -> ProxyArray: """Root link linear velocity in base frame. Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). @@ -410,10 +457,12 @@ def root_link_lin_vel_b(self) -> wp.array: device=self.device, ) self._root_link_lin_vel_b.timestamp = self._sim_timestamp - return self._root_link_lin_vel_b.data + if self._root_link_lin_vel_b_ta is None: + self._root_link_lin_vel_b_ta = ProxyArray(self._root_link_lin_vel_b.data) + return self._root_link_lin_vel_b_ta @property - def root_link_ang_vel_b(self) -> wp.array: + def root_link_ang_vel_b(self) -> ProxyArray: """Root link angular velocity in base frame. Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). @@ -429,10 +478,12 @@ def root_link_ang_vel_b(self) -> wp.array: device=self.device, ) self._root_link_ang_vel_b.timestamp = self._sim_timestamp - return self._root_link_ang_vel_b.data + if self._root_link_ang_vel_b_ta is None: + self._root_link_ang_vel_b_ta = ProxyArray(self._root_link_ang_vel_b.data) + return self._root_link_ang_vel_b_ta @property - def root_com_lin_vel_b(self) -> wp.array: + def root_com_lin_vel_b(self) -> ProxyArray: """Root center of mass linear velocity in base frame. Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). @@ -448,10 +499,12 @@ def root_com_lin_vel_b(self) -> wp.array: device=self.device, ) self._root_com_lin_vel_b.timestamp = self._sim_timestamp - return self._root_com_lin_vel_b.data + if self._root_com_lin_vel_b_ta is None: + self._root_com_lin_vel_b_ta = ProxyArray(self._root_com_lin_vel_b.data) + return self._root_com_lin_vel_b_ta @property - def root_com_ang_vel_b(self) -> wp.array: + def root_com_ang_vel_b(self) -> ProxyArray: """Root center of mass angular velocity in base frame. Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). @@ -467,192 +520,254 @@ def root_com_ang_vel_b(self) -> wp.array: device=self.device, ) self._root_com_ang_vel_b.timestamp = self._sim_timestamp - return self._root_com_ang_vel_b.data + if self._root_com_ang_vel_b_ta is None: + self._root_com_ang_vel_b_ta = ProxyArray(self._root_com_ang_vel_b.data) + return self._root_com_ang_vel_b_ta """ Sliced properties. """ @property - def root_link_pos_w(self) -> wp.array: + def root_link_pos_w(self) -> ProxyArray: """Root link position in simulation world frame. Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). This quantity is the position of the actor frame of the root rigid body relative to the world. """ - return self._get_pos_from_transform(self.root_link_pose_w) + parent = self.root_link_pose_w + if self._root_link_pos_w_ta is None: + self._root_link_pos_w_ta = ProxyArray(self._get_pos_from_transform(parent.warp)) + return self._root_link_pos_w_ta @property - def root_link_quat_w(self) -> wp.array: + def root_link_quat_w(self) -> ProxyArray: """Root link orientation (x, y, z, w) in simulation world frame. Shape is (num_instances,), dtype = wp.quatf. In torch this resolves to (num_instances, 4). This quantity is the orientation of the actor frame of the root rigid body. """ - return self._get_quat_from_transform(self.root_link_pose_w) + parent = self.root_link_pose_w + if self._root_link_quat_w_ta is None: + self._root_link_quat_w_ta = ProxyArray(self._get_quat_from_transform(parent.warp)) + return self._root_link_quat_w_ta @property - def root_link_lin_vel_w(self) -> wp.array: + def root_link_lin_vel_w(self) -> ProxyArray: """Root linear velocity in simulation world frame. Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). This quantity is the linear velocity of the root rigid body's actor frame relative to the world. """ - return self._get_lin_vel_from_spatial_vector(self.root_link_vel_w) + parent = self.root_link_vel_w + if self._root_link_lin_vel_w_ta is None: + self._root_link_lin_vel_w_ta = ProxyArray(self._get_lin_vel_from_spatial_vector(parent.warp)) + return self._root_link_lin_vel_w_ta @property - def root_link_ang_vel_w(self) -> wp.array: + def root_link_ang_vel_w(self) -> ProxyArray: """Root link angular velocity in simulation world frame. Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). This quantity is the angular velocity of the actor frame of the root rigid body relative to the world. """ - return self._get_ang_vel_from_spatial_vector(self.root_link_vel_w) + parent = self.root_link_vel_w + if self._root_link_ang_vel_w_ta is None: + self._root_link_ang_vel_w_ta = ProxyArray(self._get_ang_vel_from_spatial_vector(parent.warp)) + return self._root_link_ang_vel_w_ta @property - def root_com_pos_w(self) -> wp.array: + def root_com_pos_w(self) -> ProxyArray: """Root center of mass position in simulation world frame. Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). This quantity is the position of the center of mass frame of the root rigid body relative to the world. """ - return self._get_pos_from_transform(self.root_com_pose_w) + parent = self.root_com_pose_w + if self._root_com_pos_w_ta is None: + self._root_com_pos_w_ta = ProxyArray(self._get_pos_from_transform(parent.warp)) + return self._root_com_pos_w_ta @property - def root_com_quat_w(self) -> wp.array: + def root_com_quat_w(self) -> ProxyArray: """Root center of mass orientation (x, y, z, w) in simulation world frame. Shape is (num_instances,), dtype = wp.quatf. In torch this resolves to (num_instances, 4). This quantity is the orientation of the principal axes of inertia of the root rigid body relative to the world. """ - return self._get_quat_from_transform(self.root_com_pose_w) + parent = self.root_com_pose_w + if self._root_com_quat_w_ta is None: + self._root_com_quat_w_ta = ProxyArray(self._get_quat_from_transform(parent.warp)) + return self._root_com_quat_w_ta @property - def root_com_lin_vel_w(self) -> wp.array: + def root_com_lin_vel_w(self) -> ProxyArray: """Root center of mass linear velocity in simulation world frame. Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). This quantity is the linear velocity of the root rigid body's center of mass frame relative to the world. """ - return self._get_lin_vel_from_spatial_vector(self.root_com_vel_w) + parent = self.root_com_vel_w + if self._root_com_lin_vel_w_ta is None: + self._root_com_lin_vel_w_ta = ProxyArray(self._get_lin_vel_from_spatial_vector(parent.warp)) + return self._root_com_lin_vel_w_ta @property - def root_com_ang_vel_w(self) -> wp.array: + def root_com_ang_vel_w(self) -> ProxyArray: """Root center of mass angular velocity in simulation world frame. Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). This quantity is the angular velocity of the root rigid body's center of mass frame relative to the world. """ - return self._get_ang_vel_from_spatial_vector(self.root_com_vel_w) + parent = self.root_com_vel_w + if self._root_com_ang_vel_w_ta is None: + self._root_com_ang_vel_w_ta = ProxyArray(self._get_ang_vel_from_spatial_vector(parent.warp)) + return self._root_com_ang_vel_w_ta @property - def body_link_pos_w(self) -> wp.array: + def body_link_pos_w(self) -> ProxyArray: """Positions of all bodies in simulation world frame. Shape is (num_instances, 1), dtype = wp.vec3f. In torch this resolves to (num_instances, 1, 3). This quantity is the position of the rigid bodies' actor frame relative to the world. """ - return self._get_pos_from_transform(self.body_link_pose_w) + parent = self.body_link_pose_w + if self._body_link_pos_w_ta is None: + self._body_link_pos_w_ta = ProxyArray(self._get_pos_from_transform(parent.warp)) + return self._body_link_pos_w_ta @property - def body_link_quat_w(self) -> wp.array: + def body_link_quat_w(self) -> ProxyArray: """Orientation (x, y, z, w) of all bodies in simulation world frame. Shape is (num_instances, 1), dtype = wp.quatf. In torch this resolves to (num_instances, 1, 4). This quantity is the orientation of the rigid bodies' actor frame relative to the world. """ - return self._get_quat_from_transform(self.body_link_pose_w) + parent = self.body_link_pose_w + if self._body_link_quat_w_ta is None: + self._body_link_quat_w_ta = ProxyArray(self._get_quat_from_transform(parent.warp)) + return self._body_link_quat_w_ta @property - def body_link_lin_vel_w(self) -> wp.array: + def body_link_lin_vel_w(self) -> ProxyArray: """Linear velocity of all bodies in simulation world frame. Shape is (num_instances, 1), dtype = wp.vec3f. In torch this resolves to (num_instances, 1, 3). This quantity is the linear velocity of the rigid bodies' actor frame relative to the world. """ - return self._get_lin_vel_from_spatial_vector(self.body_link_vel_w) + parent = self.body_link_vel_w + if self._body_link_lin_vel_w_ta is None: + self._body_link_lin_vel_w_ta = ProxyArray(self._get_lin_vel_from_spatial_vector(parent.warp)) + return self._body_link_lin_vel_w_ta @property - def body_link_ang_vel_w(self) -> wp.array: + def body_link_ang_vel_w(self) -> ProxyArray: """Angular velocity of all bodies in simulation world frame. Shape is (num_instances, 1), dtype = wp.vec3f. In torch this resolves to (num_instances, 1, 3). This quantity is the angular velocity of the rigid bodies' actor frame relative to the world. """ - return self._get_ang_vel_from_spatial_vector(self.body_link_vel_w) + parent = self.body_link_vel_w + if self._body_link_ang_vel_w_ta is None: + self._body_link_ang_vel_w_ta = ProxyArray(self._get_ang_vel_from_spatial_vector(parent.warp)) + return self._body_link_ang_vel_w_ta @property - def body_com_pos_w(self) -> wp.array: + def body_com_pos_w(self) -> ProxyArray: """Positions of all bodies' center of mass in simulation world frame. Shape is (num_instances, 1), dtype = wp.vec3f. In torch this resolves to (num_instances, 1, 3). This quantity is the position of the rigid bodies' center of mass frame. """ - return self._get_pos_from_transform(self.body_com_pose_w) + parent = self.body_com_pose_w + if self._body_com_pos_w_ta is None: + self._body_com_pos_w_ta = ProxyArray(self._get_pos_from_transform(parent.warp)) + return self._body_com_pos_w_ta @property - def body_com_quat_w(self) -> wp.array: + def body_com_quat_w(self) -> ProxyArray: """Orientation (x, y, z, w) of the principal axes of inertia of all bodies in simulation world frame. Shape is (num_instances, 1), dtype = wp.quatf. In torch this resolves to (num_instances, 1, 4). This quantity is the orientation of the principal axes of inertia of the rigid bodies. """ - return self._get_quat_from_transform(self.body_com_pose_w) + parent = self.body_com_pose_w + if self._body_com_quat_w_ta is None: + self._body_com_quat_w_ta = ProxyArray(self._get_quat_from_transform(parent.warp)) + return self._body_com_quat_w_ta @property - def body_com_lin_vel_w(self) -> wp.array: + def body_com_lin_vel_w(self) -> ProxyArray: """Linear velocity of all bodies in simulation world frame. Shape is (num_instances, 1), dtype = wp.vec3f. In torch this resolves to (num_instances, 1, 3). This quantity is the linear velocity of the rigid bodies' center of mass frame. """ - return self._get_lin_vel_from_spatial_vector(self.body_com_vel_w) + parent = self.body_com_vel_w + if self._body_com_lin_vel_w_ta is None: + self._body_com_lin_vel_w_ta = ProxyArray(self._get_lin_vel_from_spatial_vector(parent.warp)) + return self._body_com_lin_vel_w_ta @property - def body_com_ang_vel_w(self) -> wp.array: + def body_com_ang_vel_w(self) -> ProxyArray: """Angular velocity of all bodies in simulation world frame. Shape is (num_instances, 1), dtype = wp.vec3f. In torch this resolves to (num_instances, 1, 3). This quantity is the angular velocity of the rigid bodies' center of mass frame. """ - return self._get_ang_vel_from_spatial_vector(self.body_com_vel_w) + parent = self.body_com_vel_w + if self._body_com_ang_vel_w_ta is None: + self._body_com_ang_vel_w_ta = ProxyArray(self._get_ang_vel_from_spatial_vector(parent.warp)) + return self._body_com_ang_vel_w_ta @property - def body_com_lin_acc_w(self) -> wp.array: + def body_com_lin_acc_w(self) -> ProxyArray: """Linear acceleration of all bodies in simulation world frame. Shape is (num_instances, 1), dtype = wp.vec3f. In torch this resolves to (num_instances, 1, 3). This quantity is the linear acceleration of the rigid bodies' center of mass frame. """ - return self._get_lin_vel_from_spatial_vector(self.body_com_acc_w) + parent = self.body_com_acc_w + if self._body_com_lin_acc_w_ta is None: + self._body_com_lin_acc_w_ta = ProxyArray(self._get_lin_vel_from_spatial_vector(parent.warp)) + return self._body_com_lin_acc_w_ta @property - def body_com_ang_acc_w(self) -> wp.array: + def body_com_ang_acc_w(self) -> ProxyArray: """Angular acceleration of all bodies in simulation world frame. Shape is (num_instances, 1), dtype = wp.vec3f. In torch this resolves to (num_instances, 1, 3). This quantity is the angular acceleration of the rigid bodies' center of mass frame. """ - return self._get_ang_vel_from_spatial_vector(self.body_com_acc_w) + parent = self.body_com_acc_w + if self._body_com_ang_acc_w_ta is None: + self._body_com_ang_acc_w_ta = ProxyArray(self._get_ang_vel_from_spatial_vector(parent.warp)) + return self._body_com_ang_acc_w_ta @property - def body_com_pos_b(self) -> wp.array: + def body_com_pos_b(self) -> ProxyArray: """Center of mass position of all of the bodies in their respective link frames. Shape is (num_instances, 1), dtype = wp.vec3f. In torch this resolves to (num_instances, 1, 3). This quantity is the center of mass location relative to its body's link frame. """ - return self._get_pos_from_transform(self.body_com_pose_b) + parent = self.body_com_pose_b + if self._body_com_pos_b_ta is None: + self._body_com_pos_b_ta = ProxyArray(self._get_pos_from_transform(parent.warp)) + return self._body_com_pos_b_ta @property - def body_com_quat_b(self) -> wp.array: + def body_com_quat_b(self) -> ProxyArray: """Orientation (x, y, z, w) of the principal axes of inertia of all of the bodies in their respective link frames. Shape is (num_instances, 1), dtype = wp.quatf. In torch this resolves to (num_instances, 1, 4). This quantity is the orientation of the principal axes of inertia relative to its body's link frame. """ - return self._get_quat_from_transform(self.body_com_pose_b) + parent = self.body_com_pose_b + if self._body_com_quat_b_ta is None: + self._body_com_quat_b_ta = ProxyArray(self._get_quat_from_transform(parent.warp)) + return self._body_com_quat_b_ta def _create_buffers(self) -> None: super()._create_buffers() @@ -689,11 +804,81 @@ def _create_buffers(self) -> None: (self._num_instances, 1, 9) ) + # Initialize ProxyArray wrappers + self._pin_proxy_arrays() + + def _pin_proxy_arrays(self) -> None: + """Create pinned ProxyArray wrappers for all data buffers. + + This is called once from :meth:`_create_buffers` during initialization. + PhysX tensor API buffers have stable GPU pointers across simulation steps, + so no rebinding is needed (unlike Newton). + """ + # -- Pinned ProxyArray cache (one per read property, lazily created on first access) + # Defaults + self._default_root_pose_ta: ProxyArray | None = None + self._default_root_vel_ta: ProxyArray | None = None + # Root state (timestamped) + self._root_link_pose_w_ta: ProxyArray | None = None + self._root_link_vel_w_ta: ProxyArray | None = None + self._root_com_pose_w_ta: ProxyArray | None = None + self._root_com_vel_w_ta: ProxyArray | None = None + # Body properties + self._body_mass_ta: ProxyArray | None = None + self._body_inertia_ta: ProxyArray | None = None + # Body state (reshaped from root) + self._body_link_pose_w_ta: ProxyArray | None = None + self._body_link_vel_w_ta: ProxyArray | None = None + self._body_com_pose_w_ta: ProxyArray | None = None + self._body_com_vel_w_ta: ProxyArray | None = None + self._body_com_acc_w_ta: ProxyArray | None = None + self._body_com_pose_b_ta: ProxyArray | None = None + # Derived properties (timestamped) + self._projected_gravity_b_ta: ProxyArray | None = None + self._heading_w_ta: ProxyArray | None = None + self._root_link_lin_vel_b_ta: ProxyArray | None = None + self._root_link_ang_vel_b_ta: ProxyArray | None = None + self._root_com_lin_vel_b_ta: ProxyArray | None = None + self._root_com_ang_vel_b_ta: ProxyArray | None = None + # Sliced properties (root link) + self._root_link_pos_w_ta: ProxyArray | None = None + self._root_link_quat_w_ta: ProxyArray | None = None + self._root_link_lin_vel_w_ta: ProxyArray | None = None + self._root_link_ang_vel_w_ta: ProxyArray | None = None + # Sliced properties (root com) + self._root_com_pos_w_ta: ProxyArray | None = None + self._root_com_quat_w_ta: ProxyArray | None = None + self._root_com_lin_vel_w_ta: ProxyArray | None = None + self._root_com_ang_vel_w_ta: ProxyArray | None = None + # Sliced properties (body link) + self._body_link_pos_w_ta: ProxyArray | None = None + self._body_link_quat_w_ta: ProxyArray | None = None + self._body_link_lin_vel_w_ta: ProxyArray | None = None + self._body_link_ang_vel_w_ta: ProxyArray | None = None + # Sliced properties (body com) + self._body_com_pos_w_ta: ProxyArray | None = None + self._body_com_quat_w_ta: ProxyArray | None = None + self._body_com_lin_vel_w_ta: ProxyArray | None = None + self._body_com_ang_vel_w_ta: ProxyArray | None = None + self._body_com_lin_acc_w_ta: ProxyArray | None = None + self._body_com_ang_acc_w_ta: ProxyArray | None = None + # Sliced properties (body com in body frame) + self._body_com_pos_b_ta: ProxyArray | None = None + self._body_com_quat_b_ta: ProxyArray | None = None + # Deprecated state-concat properties + self._default_root_state_ta: ProxyArray | None = None + self._root_state_w_ta: ProxyArray | None = None + self._root_link_state_w_ta: ProxyArray | None = None + self._root_com_state_w_ta: ProxyArray | None = None + self._body_state_w_ta: ProxyArray | None = None + self._body_link_state_w_ta: ProxyArray | None = None + self._body_com_state_w_ta: ProxyArray | None = None + """ Internal helpers. """ - def _get_pos_from_transform(self, transform: wp.array) -> wp.array: + def _get_pos_from_transform(self, transform: wp.array) -> ProxyArray: """Generates a position array from a transform array.""" return wp.array( ptr=transform.ptr, @@ -703,7 +888,7 @@ def _get_pos_from_transform(self, transform: wp.array) -> wp.array: device=self.device, ) - def _get_quat_from_transform(self, transform: wp.array) -> wp.array: + def _get_quat_from_transform(self, transform: wp.array) -> ProxyArray: """Generates a quaternion array from a transform array.""" return wp.array( ptr=transform.ptr + 3 * 4, @@ -713,7 +898,7 @@ def _get_quat_from_transform(self, transform: wp.array) -> wp.array: device=self.device, ) - def _get_lin_vel_from_spatial_vector(self, spatial_vector: wp.array) -> wp.array: + def _get_lin_vel_from_spatial_vector(self, spatial_vector: wp.array) -> ProxyArray: """Generates a linear velocity array from a spatial vector array.""" return wp.array( ptr=spatial_vector.ptr, @@ -723,7 +908,7 @@ def _get_lin_vel_from_spatial_vector(self, spatial_vector: wp.array) -> wp.array device=self.device, ) - def _get_ang_vel_from_spatial_vector(self, spatial_vector: wp.array) -> wp.array: + def _get_ang_vel_from_spatial_vector(self, spatial_vector: wp.array) -> ProxyArray: """Generates an angular velocity array from a spatial vector array.""" return wp.array( ptr=spatial_vector.ptr + 3 * 4, @@ -738,7 +923,7 @@ def _get_ang_vel_from_spatial_vector(self, spatial_vector: wp.array) -> wp.array """ @property - def default_root_state(self) -> wp.array: + def default_root_state(self) -> ProxyArray: """Default root state ``[pos, quat, lin_vel, ang_vel]`` in local environment frame. The position and quaternion are of the rigid body's actor frame. Meanwhile, the linear and angular velocities @@ -764,10 +949,12 @@ def default_root_state(self) -> wp.array: ], device=self.device, ) - return self._default_root_state + if self._default_root_state_ta is None: + self._default_root_state_ta = ProxyArray(self._default_root_state) + return self._default_root_state_ta @property - def root_state_w(self) -> wp.array: + def root_state_w(self) -> ProxyArray: """Deprecated, same as :attr:`root_link_pose_w` and :attr:`root_com_vel_w`.""" warnings.warn( "The `root_state_w` property will be deprecated in IsaacLab 4.0. Please use `root_link_pose_w` and " @@ -790,10 +977,12 @@ def root_state_w(self) -> wp.array: ) self._root_state_w.timestamp = self._sim_timestamp - return self._root_state_w.data + if self._root_state_w_ta is None: + self._root_state_w_ta = ProxyArray(self._root_state_w.data) + return self._root_state_w_ta @property - def root_link_state_w(self) -> wp.array: + def root_link_state_w(self) -> ProxyArray: """Deprecated, same as :attr:`root_link_pose_w` and :attr:`root_link_vel_w`.""" warnings.warn( "The `root_link_state_w` property will be deprecated in IsaacLab 4.0. Please use `root_link_pose_w` and " @@ -816,10 +1005,12 @@ def root_link_state_w(self) -> wp.array: ) self._root_link_state_w.timestamp = self._sim_timestamp - return self._root_link_state_w.data + if self._root_link_state_w_ta is None: + self._root_link_state_w_ta = ProxyArray(self._root_link_state_w.data) + return self._root_link_state_w_ta @property - def root_com_state_w(self) -> wp.array: + def root_com_state_w(self) -> ProxyArray: """Deprecated, same as :attr:`root_com_pose_w` and :attr:`root_com_vel_w`.""" warnings.warn( "The `root_com_state_w` property will be deprecated in IsaacLab 4.0. Please use `root_com_pose_w` and " @@ -842,10 +1033,12 @@ def root_com_state_w(self) -> wp.array: ) self._root_com_state_w.timestamp = self._sim_timestamp - return self._root_com_state_w.data + if self._root_com_state_w_ta is None: + self._root_com_state_w_ta = ProxyArray(self._root_com_state_w.data) + return self._root_com_state_w_ta @property - def body_state_w(self) -> wp.array: + def body_state_w(self) -> ProxyArray: """Deprecated, same as :attr:`body_link_pose_w` and :attr:`body_com_vel_w`.""" warnings.warn( "The `body_state_w` property will be deprecated in IsaacLab 4.0. Please use `body_link_pose_w` and " @@ -868,10 +1061,12 @@ def body_state_w(self) -> wp.array: device=self.device, ) self._root_state_w.timestamp = self._sim_timestamp - return self._root_state_w.data.reshape((self._num_instances, 1)) + if self._body_state_w_ta is None: + self._body_state_w_ta = ProxyArray(self._root_state_w.data.reshape((self._num_instances, 1))) + return self._body_state_w_ta @property - def body_link_state_w(self) -> wp.array: + def body_link_state_w(self) -> ProxyArray: """Deprecated, same as :attr:`body_link_pose_w` and :attr:`body_link_vel_w`.""" warnings.warn( "The `body_link_state_w` property will be deprecated in IsaacLab 4.0. Please use `body_link_pose_w` and " @@ -894,10 +1089,12 @@ def body_link_state_w(self) -> wp.array: device=self.device, ) self._root_link_state_w.timestamp = self._sim_timestamp - return self._root_link_state_w.data.reshape((self._num_instances, 1)) + if self._body_link_state_w_ta is None: + self._body_link_state_w_ta = ProxyArray(self._root_link_state_w.data.reshape((self._num_instances, 1))) + return self._body_link_state_w_ta @property - def body_com_state_w(self) -> wp.array: + def body_com_state_w(self) -> ProxyArray: """Deprecated, same as :attr:`body_com_pose_w` and :attr:`body_com_vel_w`.""" warnings.warn( "The `body_com_state_w` property will be deprecated in IsaacLab 4.0. Please use `body_com_pose_w` and " @@ -920,4 +1117,6 @@ def body_com_state_w(self) -> wp.array: device=self.device, ) self._root_com_state_w.timestamp = self._sim_timestamp - return self._root_com_state_w.data.reshape((self._num_instances, 1)) + if self._body_com_state_w_ta is None: + self._body_com_state_w_ta = ProxyArray(self._root_com_state_w.data.reshape((self._num_instances, 1))) + return self._body_com_state_w_ta diff --git a/source/isaaclab_physx/isaaclab_physx/assets/rigid_object_collection/rigid_object_collection.py b/source/isaaclab_physx/isaaclab_physx/assets/rigid_object_collection/rigid_object_collection.py index 877a44261293..6d07ddbf1bc1 100644 --- a/source/isaaclab_physx/isaaclab_physx/assets/rigid_object_collection/rigid_object_collection.py +++ b/source/isaaclab_physx/isaaclab_physx/assets/rigid_object_collection/rigid_object_collection.py @@ -15,7 +15,7 @@ import torch import warp as wp -import omni.physics.tensors.impl.api as physx +import omni.physics.tensors.api as physx from pxr import UsdPhysics import isaaclab.sim as sim_utils @@ -186,42 +186,22 @@ def write_data_to_sim(self) -> None: # write external wrench if self._instantaneous_wrench_composer.active or self._permanent_wrench_composer.active: if self._instantaneous_wrench_composer.active: - # Compose instantaneous wrench with permanent wrench - self._instantaneous_wrench_composer.add_forces_and_torques_index( - forces=self._permanent_wrench_composer.composed_force, - torques=self._permanent_wrench_composer.composed_torque, - body_ids=self._ALL_BODY_INDICES, - env_ids=self._ALL_ENV_INDICES, - ) - # Apply both instantaneous and permanent wrench to the simulation - self.root_view.apply_forces_and_torques_at_position( - force_data=self.reshape_data_to_view_2d( - self._instantaneous_wrench_composer.composed_force, device=self.device - ).view(wp.float32), - torque_data=self.reshape_data_to_view_2d( - self._instantaneous_wrench_composer.composed_torque, device=self.device - ).view(wp.float32), - position_data=None, - indices=self._env_body_ids_to_view_ids( - self._ALL_ENV_INDICES, self._ALL_BODY_INDICES, device=self.device - ), - is_global=False, - ) + composer = self._instantaneous_wrench_composer + composer.add_raw_buffers_from(self._permanent_wrench_composer) else: - # Apply permanent wrench to the simulation - self.root_view.apply_forces_and_torques_at_position( - force_data=self.reshape_data_to_view_2d( - self._permanent_wrench_composer.composed_force, device=self.device - ).view(wp.float32), - torque_data=self.reshape_data_to_view_2d( - self._permanent_wrench_composer.composed_torque, device=self.device - ).view(wp.float32), - position_data=None, - indices=self._env_body_ids_to_view_ids( - self._ALL_ENV_INDICES, self._ALL_BODY_INDICES, device=self.device - ), - is_global=False, - ) + composer = self._permanent_wrench_composer + composer.compose_to_body_frame() + self.root_view.apply_forces_and_torques_at_position( + force_data=self.reshape_data_to_view_2d(composer.out_force_b.warp, device=self.device).view(wp.float32), + torque_data=self.reshape_data_to_view_2d(composer.out_torque_b.warp, device=self.device).view( + wp.float32 + ), + position_data=None, + indices=self._env_body_ids_to_view_ids( + self._ALL_ENV_INDICES, self._ALL_BODY_INDICES, device=self.device + ), + is_global=False, + ) self._instantaneous_wrench_composer.reset() def update(self, dt: float) -> None: @@ -434,8 +414,6 @@ def write_body_link_pose_to_sim_index( ], outputs=[ self.data.body_link_pose_w, - None, # self.data._body_link_state_w.data, - None, # self.data._body_state_w.data, ], device=self.device, ) @@ -530,9 +508,6 @@ def write_body_com_pose_to_sim_index( outputs=[ self.data.body_com_pose_w, self.data.body_link_pose_w, - None, # self.data._body_com_state_w.data, - None, # self.data._body_link_state_w.data, - None, # self.data._body_state_w.data, ], device=self.device, ) @@ -630,8 +605,6 @@ def write_body_com_velocity_to_sim_index( outputs=[ self.data.body_com_vel_w, self.data.body_com_acc_w, - None, # self.data._body_state_w.data, - None, # self.data._body_com_state_w.data, ], device=self.device, ) @@ -739,9 +712,6 @@ def write_body_link_velocity_to_sim_index( self.data.body_link_vel_w, self.data.body_com_vel_w, self.data.body_com_acc_w, - None, # self.data._body_link_state_w.data, - None, # self.data._body_state_w.data, - None, # self.data._body_com_state_w.data, ], device=self.device, ) @@ -1188,26 +1158,30 @@ def reshape_data_to_view_3d(self, data: wp.array, data_dim: int, device: str = " def _resolve_env_ids(self, env_ids) -> wp.array: """Resolve environment indices to a warp array.""" - if isinstance(env_ids, list): - return wp.array(env_ids, dtype=wp.int32, device=self.device) if (env_ids is None) or (env_ids == slice(None)): return self._ALL_ENV_INDICES if isinstance(env_ids, torch.Tensor): - return wp.from_torch(env_ids.to(torch.int32), dtype=wp.int32) + if env_ids.dtype == torch.int64: + env_ids = env_ids.to(torch.int32) + return wp.from_torch(env_ids, dtype=wp.int32) + if isinstance(env_ids, list): + return wp.array(env_ids, dtype=wp.int32, device=self.device) return env_ids def _resolve_body_ids(self, body_ids) -> wp.array: """Resolve body indices to a warp array.""" + if isinstance(body_ids, list): + return wp.array(body_ids, dtype=wp.int32, device=self.device) if body_ids is None or (body_ids == slice(None)): return self._ALL_BODY_INDICES if isinstance(body_ids, slice): return wp.from_torch( torch.arange(self.num_bodies, dtype=torch.int32, device=self.device)[body_ids], dtype=wp.int32 ) - if isinstance(body_ids, list): - return wp.array(body_ids, dtype=wp.int32, device=self.device) if isinstance(body_ids, torch.Tensor): - return wp.from_torch(body_ids.to(torch.int32), dtype=wp.int32) + if body_ids.dtype == torch.int64: + body_ids = body_ids.to(torch.int32) + return wp.from_torch(body_ids, dtype=wp.int32) return body_ids def _resolve_env_mask(self, env_mask: wp.array | None) -> torch.Tensor | wp.array: diff --git a/source/isaaclab_physx/isaaclab_physx/assets/rigid_object_collection/rigid_object_collection_data.py b/source/isaaclab_physx/isaaclab_physx/assets/rigid_object_collection/rigid_object_collection_data.py index a0bdec5af8c9..cee0d4de01dd 100644 --- a/source/isaaclab_physx/isaaclab_physx/assets/rigid_object_collection/rigid_object_collection_data.py +++ b/source/isaaclab_physx/isaaclab_physx/assets/rigid_object_collection/rigid_object_collection_data.py @@ -15,12 +15,13 @@ from isaaclab.assets.rigid_object_collection.base_rigid_object_collection_data import BaseRigidObjectCollectionData from isaaclab.utils.buffers import TimestampedBufferWarp as TimestampedBuffer from isaaclab.utils.math import normalize +from isaaclab.utils.warp import ProxyArray from isaaclab_physx.assets import kernels as shared_kernels from isaaclab_physx.physics import PhysxManager as SimulationManager if TYPE_CHECKING: - import omni.physics.tensors.impl.api as physx + import omni.physics.tensors.api as physx # import logger logger = logging.getLogger(__name__) @@ -45,6 +46,16 @@ class RigidObjectCollectionData(BaseRigidObjectCollectionData): The data is lazily updated, meaning that the data is only updated when it is accessed. This is useful when the data is expensive to compute or retrieve. The data is updated when the timestamp of the buffer is older than the current simulation timestamp. The timestamp is updated whenever the data is updated. + + .. note:: + **Pull-to-refresh model.** Properties pull fresh data from the PhysX tensor API on first + access per timestamp and cache the result. This differs from Newton, where buffers are + refreshed automatically by the simulation. + + .. note:: + **ProxyArray pointer stability.** Each :class:`ProxyArray` wrapper is created once and + reused because the PhysX tensor API returns views into stable, pre-allocated GPU buffers + whose device pointer does not change across simulation steps. """ __backend_name__: str = "physx" @@ -78,10 +89,14 @@ def __init__(self, root_view: physx.RigidBodyView, num_bodies: int, device: str) gravity_dir = normalize(gravity_dir.unsqueeze(0)).squeeze(0) # Initialize constants - self.GRAVITY_VEC_W = wp.from_torch(gravity_dir.repeat(self.num_instances, self.num_bodies, 1), dtype=wp.vec3f) - self.FORWARD_VEC_B = wp.from_torch( - torch.tensor((1.0, 0.0, 0.0), device=self.device).repeat(self.num_instances, self.num_bodies, 1), - dtype=wp.vec3f, + self.GRAVITY_VEC_W = ProxyArray( + wp.from_torch(gravity_dir.repeat(self.num_instances, self.num_bodies, 1), dtype=wp.vec3f) + ) + self.FORWARD_VEC_B = ProxyArray( + wp.from_torch( + torch.tensor((1.0, 0.0, 0.0), device=self.device).repeat(self.num_instances, self.num_bodies, 1), + dtype=wp.vec3f, + ) ) self._create_buffers() @@ -129,14 +144,16 @@ def update(self, dt: float) -> None: """ @property - def default_body_pose(self) -> wp.array: + def default_body_pose(self) -> ProxyArray: """Default body pose ``[pos, quat]`` in local environment frame. The position and quaternion are of the rigid body's actor frame. Shape is (num_instances, num_bodies), dtype = wp.transformf. In torch this resolves to (num_instances, num_bodies, 7). """ - return self._default_body_pose + if self._default_body_pose_ta is None: + self._default_body_pose_ta = ProxyArray(self._default_body_pose) + return self._default_body_pose_ta @default_body_pose.setter def default_body_pose(self, value: wp.array) -> None: @@ -153,14 +170,16 @@ def default_body_pose(self, value: wp.array) -> None: self._default_body_pose.assign(value) @property - def default_body_vel(self) -> wp.array: + def default_body_vel(self) -> ProxyArray: """Default body velocity ``[lin_vel, ang_vel]`` in local environment frame. The linear and angular velocities are of the rigid body's center of mass frame. Shape is (num_instances, num_bodies), dtype = wp.spatial_vectorf. In torch this resolves to (num_instances, num_bodies, 6). """ - return self._default_body_vel + if self._default_body_vel_ta is None: + self._default_body_vel_ta = ProxyArray(self._default_body_vel) + return self._default_body_vel_ta @default_body_vel.setter def default_body_vel(self, value: wp.array) -> None: @@ -181,7 +200,7 @@ def default_body_vel(self, value: wp.array) -> None: """ @property - def body_link_pose_w(self) -> wp.array: + def body_link_pose_w(self) -> ProxyArray: """Body link pose ``[pos, quat]`` in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.transformf. In torch this resolves to @@ -195,11 +214,18 @@ def body_link_pose_w(self) -> wp.array: # set the buffer data and timestamp self._body_link_pose_w.data = pose self._body_link_pose_w.timestamp = self._sim_timestamp + # Rebind ProxyArray since reshape creates a new wp.array each time + if self._body_link_pose_w_ta is not None: + self._body_link_pose_w_ta = ProxyArray(pose) + self._body_link_pos_w_ta = None + self._body_link_quat_w_ta = None - return self._body_link_pose_w.data + if self._body_link_pose_w_ta is None: + self._body_link_pose_w_ta = ProxyArray(self._body_link_pose_w.data) + return self._body_link_pose_w_ta @property - def body_link_vel_w(self) -> wp.array: + def body_link_vel_w(self) -> ProxyArray: """Body link velocity ``[lin_vel, ang_vel]`` in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.spatial_vectorf. In torch this resolves to @@ -223,10 +249,12 @@ def body_link_vel_w(self) -> wp.array: ) self._body_link_vel_w.timestamp = self._sim_timestamp - return self._body_link_vel_w.data + if self._body_link_vel_w_ta is None: + self._body_link_vel_w_ta = ProxyArray(self._body_link_vel_w.data) + return self._body_link_vel_w_ta @property - def body_com_pose_w(self) -> wp.array: + def body_com_pose_w(self) -> ProxyArray: """Body center of mass pose ``[pos, quat]`` in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.transformf. In torch this resolves to @@ -249,10 +277,12 @@ def body_com_pose_w(self) -> wp.array: ) self._body_com_pose_w.timestamp = self._sim_timestamp - return self._body_com_pose_w.data + if self._body_com_pose_w_ta is None: + self._body_com_pose_w_ta = ProxyArray(self._body_com_pose_w.data) + return self._body_com_pose_w_ta @property - def body_com_vel_w(self) -> wp.array: + def body_com_vel_w(self) -> ProxyArray: """Body center of mass velocity ``[lin_vel, ang_vel]`` in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.spatial_vectorf. In torch this resolves to @@ -264,11 +294,18 @@ def body_com_vel_w(self) -> wp.array: vel = self._reshape_view_to_data_2d(self._root_view.get_velocities().view(wp.spatial_vectorf)) self._body_com_vel_w.data = vel self._body_com_vel_w.timestamp = self._sim_timestamp + # Rebind ProxyArray since reshape creates a new wp.array each time + if self._body_com_vel_w_ta is not None: + self._body_com_vel_w_ta = ProxyArray(vel) + self._body_com_lin_vel_w_ta = None + self._body_com_ang_vel_w_ta = None - return self._body_com_vel_w.data + if self._body_com_vel_w_ta is None: + self._body_com_vel_w_ta = ProxyArray(self._body_com_vel_w.data) + return self._body_com_vel_w_ta @property - def body_com_acc_w(self) -> wp.array: + def body_com_acc_w(self) -> ProxyArray: """Acceleration of all bodies ``[lin_acc, ang_acc]`` in the simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.spatial_vectorf. In torch this resolves to @@ -279,10 +316,17 @@ def body_com_acc_w(self) -> wp.array: acc = self._reshape_view_to_data_2d(self._root_view.get_accelerations().view(wp.spatial_vectorf)) self._body_com_acc_w.data = acc self._body_com_acc_w.timestamp = self._sim_timestamp - return self._body_com_acc_w.data + # Rebind ProxyArray since reshape creates a new wp.array each time + if self._body_com_acc_w_ta is not None: + self._body_com_acc_w_ta = ProxyArray(acc) + self._body_com_lin_acc_w_ta = None + self._body_com_ang_acc_w_ta = None + if self._body_com_acc_w_ta is None: + self._body_com_acc_w_ta = ProxyArray(self._body_com_acc_w.data) + return self._body_com_acc_w_ta @property - def body_com_pose_b(self) -> wp.array: + def body_com_pose_b(self) -> ProxyArray: """Center of mass pose ``[pos, quat]`` of all bodies in their respective body's link frames. Shape is (num_instances, num_bodies), dtype = wp.transformf. In torch this resolves to @@ -297,32 +341,38 @@ def body_com_pose_b(self) -> wp.array: self._body_com_pose_b.data.assign(poses) self._body_com_pose_b.timestamp = self._sim_timestamp - return self._body_com_pose_b.data + if self._body_com_pose_b_ta is None: + self._body_com_pose_b_ta = ProxyArray(self._body_com_pose_b.data) + return self._body_com_pose_b_ta @property - def body_mass(self) -> wp.array: + def body_mass(self) -> ProxyArray: """Mass of all bodies in the simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.float32. In torch this resolves to (num_instances, num_bodies). """ - return self._body_mass + if self._body_mass_ta is None: + self._body_mass_ta = ProxyArray(self._body_mass) + return self._body_mass_ta @property - def body_inertia(self) -> wp.array: + def body_inertia(self) -> ProxyArray: """Inertia of all bodies in the simulation world frame. Shape is (num_instances, num_bodies, 9), dtype = wp.float32. In torch this resolves to (num_instances, num_bodies, 9). """ - return self._body_inertia + if self._body_inertia_ta is None: + self._body_inertia_ta = ProxyArray(self._body_inertia) + return self._body_inertia_ta """ Derived Properties. """ @property - def projected_gravity_b(self) -> wp.array: + def projected_gravity_b(self) -> ProxyArray: """Projection of the gravity direction on base frame. Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to @@ -337,10 +387,12 @@ def projected_gravity_b(self) -> wp.array: device=self.device, ) self._projected_gravity_b.timestamp = self._sim_timestamp - return self._projected_gravity_b.data + if self._projected_gravity_b_ta is None: + self._projected_gravity_b_ta = ProxyArray(self._projected_gravity_b.data) + return self._projected_gravity_b_ta @property - def heading_w(self) -> wp.array: + def heading_w(self) -> ProxyArray: """Yaw heading of the base frame (in radians). Shape is (num_instances, num_bodies), dtype = wp.float32. In torch this resolves to (num_instances, num_bodies). @@ -358,10 +410,12 @@ def heading_w(self) -> wp.array: device=self.device, ) self._heading_w.timestamp = self._sim_timestamp - return self._heading_w.data + if self._heading_w_ta is None: + self._heading_w_ta = ProxyArray(self._heading_w.data) + return self._heading_w_ta @property - def body_link_lin_vel_b(self) -> wp.array: + def body_link_lin_vel_b(self) -> ProxyArray: """Root link linear velocity in base frame. Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to @@ -378,10 +432,12 @@ def body_link_lin_vel_b(self) -> wp.array: device=self.device, ) self._body_link_lin_vel_b.timestamp = self._sim_timestamp - return self._body_link_lin_vel_b.data + if self._body_link_lin_vel_b_ta is None: + self._body_link_lin_vel_b_ta = ProxyArray(self._body_link_lin_vel_b.data) + return self._body_link_lin_vel_b_ta @property - def body_link_ang_vel_b(self) -> wp.array: + def body_link_ang_vel_b(self) -> ProxyArray: """Root link angular velocity in base frame. Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to @@ -398,10 +454,12 @@ def body_link_ang_vel_b(self) -> wp.array: device=self.device, ) self._body_link_ang_vel_b.timestamp = self._sim_timestamp - return self._body_link_ang_vel_b.data + if self._body_link_ang_vel_b_ta is None: + self._body_link_ang_vel_b_ta = ProxyArray(self._body_link_ang_vel_b.data) + return self._body_link_ang_vel_b_ta @property - def body_com_lin_vel_b(self) -> wp.array: + def body_com_lin_vel_b(self) -> ProxyArray: """Root center of mass linear velocity in base frame. Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to @@ -418,10 +476,12 @@ def body_com_lin_vel_b(self) -> wp.array: device=self.device, ) self._body_com_lin_vel_b.timestamp = self._sim_timestamp - return self._body_com_lin_vel_b.data + if self._body_com_lin_vel_b_ta is None: + self._body_com_lin_vel_b_ta = ProxyArray(self._body_com_lin_vel_b.data) + return self._body_com_lin_vel_b_ta @property - def body_com_ang_vel_b(self) -> wp.array: + def body_com_ang_vel_b(self) -> ProxyArray: """Root center of mass angular velocity in base frame. Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to @@ -438,124 +498,159 @@ def body_com_ang_vel_b(self) -> wp.array: device=self.device, ) self._body_com_ang_vel_b.timestamp = self._sim_timestamp - return self._body_com_ang_vel_b.data + if self._body_com_ang_vel_b_ta is None: + self._body_com_ang_vel_b_ta = ProxyArray(self._body_com_ang_vel_b.data) + return self._body_com_ang_vel_b_ta """ Sliced properties. """ @property - def body_link_pos_w(self) -> wp.array: + def body_link_pos_w(self) -> ProxyArray: """Positions of all bodies in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to (num_instances, num_bodies, 3). This quantity is the position of the rigid bodies' actor frame relative to the world. """ - return self._get_pos_from_transform(self.body_link_pose_w) + parent = self.body_link_pose_w + if self._body_link_pos_w_ta is None: + self._body_link_pos_w_ta = ProxyArray(self._get_pos_from_transform(parent.warp)) + return self._body_link_pos_w_ta @property - def body_link_quat_w(self) -> wp.array: + def body_link_quat_w(self) -> ProxyArray: """Orientation (x, y, z, w) of all bodies in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.quatf. In torch this resolves to (num_instances, num_bodies, 4). This quantity is the orientation of the rigid bodies' actor frame relative to the world. """ - return self._get_quat_from_transform(self.body_link_pose_w) + parent = self.body_link_pose_w + if self._body_link_quat_w_ta is None: + self._body_link_quat_w_ta = ProxyArray(self._get_quat_from_transform(parent.warp)) + return self._body_link_quat_w_ta @property - def body_link_lin_vel_w(self) -> wp.array: + def body_link_lin_vel_w(self) -> ProxyArray: """Linear velocity of all bodies in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to (num_instances, num_bodies, 3). This quantity is the linear velocity of the rigid bodies' actor frame relative to the world. """ - return self._get_lin_vel_from_spatial_vector(self.body_link_vel_w) + parent = self.body_link_vel_w + if self._body_link_lin_vel_w_ta is None: + self._body_link_lin_vel_w_ta = ProxyArray(self._get_lin_vel_from_spatial_vector(parent.warp)) + return self._body_link_lin_vel_w_ta @property - def body_link_ang_vel_w(self) -> wp.array: + def body_link_ang_vel_w(self) -> ProxyArray: """Angular velocity of all bodies in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to (num_instances, num_bodies, 3). This quantity is the angular velocity of the rigid bodies' actor frame relative to the world. """ - return self._get_ang_vel_from_spatial_vector(self.body_link_vel_w) + parent = self.body_link_vel_w + if self._body_link_ang_vel_w_ta is None: + self._body_link_ang_vel_w_ta = ProxyArray(self._get_ang_vel_from_spatial_vector(parent.warp)) + return self._body_link_ang_vel_w_ta @property - def body_com_pos_w(self) -> wp.array: + def body_com_pos_w(self) -> ProxyArray: """Positions of all bodies' center of mass in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to (num_instances, num_bodies, 3). This quantity is the position of the rigid bodies' center of mass frame. """ - return self._get_pos_from_transform(self.body_com_pose_w) + parent = self.body_com_pose_w + if self._body_com_pos_w_ta is None: + self._body_com_pos_w_ta = ProxyArray(self._get_pos_from_transform(parent.warp)) + return self._body_com_pos_w_ta @property - def body_com_quat_w(self) -> wp.array: + def body_com_quat_w(self) -> ProxyArray: """Orientation (x, y, z, w) of the principal axes of inertia of all bodies in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.quatf. In torch this resolves to (num_instances, num_bodies, 4). This quantity is the orientation of the principal axes of inertia of the rigid bodies. """ - return self._get_quat_from_transform(self.body_com_pose_w) + parent = self.body_com_pose_w + if self._body_com_quat_w_ta is None: + self._body_com_quat_w_ta = ProxyArray(self._get_quat_from_transform(parent.warp)) + return self._body_com_quat_w_ta @property - def body_com_lin_vel_w(self) -> wp.array: + def body_com_lin_vel_w(self) -> ProxyArray: """Linear velocity of all bodies in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to (num_instances, num_bodies, 3). This quantity is the linear velocity of the rigid bodies' center of mass frame. """ - return self._get_lin_vel_from_spatial_vector(self.body_com_vel_w) + parent = self.body_com_vel_w + if self._body_com_lin_vel_w_ta is None: + self._body_com_lin_vel_w_ta = ProxyArray(self._get_lin_vel_from_spatial_vector(parent.warp)) + return self._body_com_lin_vel_w_ta @property - def body_com_ang_vel_w(self) -> wp.array: + def body_com_ang_vel_w(self) -> ProxyArray: """Angular velocity of all bodies in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to (num_instances, num_bodies, 3). This quantity is the angular velocity of the rigid bodies' center of mass frame. """ - return self._get_ang_vel_from_spatial_vector(self.body_com_vel_w) + parent = self.body_com_vel_w + if self._body_com_ang_vel_w_ta is None: + self._body_com_ang_vel_w_ta = ProxyArray(self._get_ang_vel_from_spatial_vector(parent.warp)) + return self._body_com_ang_vel_w_ta @property - def body_com_lin_acc_w(self) -> wp.array: + def body_com_lin_acc_w(self) -> ProxyArray: """Linear acceleration of all bodies in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to (num_instances, num_bodies, 3). This quantity is the linear acceleration of the rigid bodies' center of mass frame. """ - return self._get_lin_vel_from_spatial_vector(self.body_com_acc_w) + parent = self.body_com_acc_w + if self._body_com_lin_acc_w_ta is None: + self._body_com_lin_acc_w_ta = ProxyArray(self._get_lin_vel_from_spatial_vector(parent.warp)) + return self._body_com_lin_acc_w_ta @property - def body_com_ang_acc_w(self) -> wp.array: + def body_com_ang_acc_w(self) -> ProxyArray: """Angular acceleration of all bodies in simulation world frame. Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to (num_instances, num_bodies, 3). This quantity is the angular acceleration of the rigid bodies' center of mass frame. """ - return self._get_ang_vel_from_spatial_vector(self.body_com_acc_w) + parent = self.body_com_acc_w + if self._body_com_ang_acc_w_ta is None: + self._body_com_ang_acc_w_ta = ProxyArray(self._get_ang_vel_from_spatial_vector(parent.warp)) + return self._body_com_ang_acc_w_ta @property - def body_com_pos_b(self) -> wp.array: + def body_com_pos_b(self) -> ProxyArray: """Center of mass position of all of the bodies in their respective link frames. Shape is (num_instances, num_bodies), dtype = wp.vec3f. In torch this resolves to (num_instances, num_bodies, 3). This quantity is the center of mass location relative to its body's link frame. """ - return self._get_pos_from_transform(self.body_com_pose_b) + parent = self.body_com_pose_b + if self._body_com_pos_b_ta is None: + self._body_com_pos_b_ta = ProxyArray(self._get_pos_from_transform(parent.warp)) + return self._body_com_pos_b_ta @property - def body_com_quat_b(self) -> wp.array: + def body_com_quat_b(self) -> ProxyArray: """Orientation (x, y, z, w) of the principal axes of inertia of all of the bodies in their respective link frames. @@ -563,7 +658,10 @@ def body_com_quat_b(self) -> wp.array: (num_instances, num_bodies, 4). This quantity is the orientation of the principal axes of inertia relative to its body's link frame. """ - return self._get_quat_from_transform(self.body_com_pose_b) + parent = self.body_com_pose_b + if self._body_com_quat_b_ta is None: + self._body_com_quat_b_ta = ProxyArray(self._get_quat_from_transform(parent.warp)) + return self._body_com_quat_b_ta def _create_buffers(self) -> None: super()._create_buffers() @@ -616,6 +714,58 @@ def _create_buffers(self) -> None: # _reshape_view_to_data only handles single-element dtypes, so we use _reshape_view_to_data_3d. self._body_inertia = self._reshape_view_to_data_3d(self._root_view.get_inertias(), 9) + # Initialize ProxyArray wrappers + self._pin_proxy_arrays() + + def _pin_proxy_arrays(self) -> None: + """Create pinned ProxyArray wrappers for all data buffers. + + This is called once from :meth:`_create_buffers` during initialization. + PhysX tensor API buffers have stable GPU pointers across simulation steps, + so no rebinding is needed (unlike Newton). + """ + # -- Pinned ProxyArray cache (one per read property, lazily created on first access) + # Defaults + self._default_body_pose_ta: ProxyArray | None = None + self._default_body_vel_ta: ProxyArray | None = None + # Body state (timestamped) + self._body_link_pose_w_ta: ProxyArray | None = None + self._body_link_vel_w_ta: ProxyArray | None = None + self._body_com_pose_w_ta: ProxyArray | None = None + self._body_com_vel_w_ta: ProxyArray | None = None + self._body_com_acc_w_ta: ProxyArray | None = None + self._body_com_pose_b_ta: ProxyArray | None = None + # Body properties + self._body_mass_ta: ProxyArray | None = None + self._body_inertia_ta: ProxyArray | None = None + # Derived properties (timestamped) + self._projected_gravity_b_ta: ProxyArray | None = None + self._heading_w_ta: ProxyArray | None = None + self._body_link_lin_vel_b_ta: ProxyArray | None = None + self._body_link_ang_vel_b_ta: ProxyArray | None = None + self._body_com_lin_vel_b_ta: ProxyArray | None = None + self._body_com_ang_vel_b_ta: ProxyArray | None = None + # Sliced properties (body link) + self._body_link_pos_w_ta: ProxyArray | None = None + self._body_link_quat_w_ta: ProxyArray | None = None + self._body_link_lin_vel_w_ta: ProxyArray | None = None + self._body_link_ang_vel_w_ta: ProxyArray | None = None + # Sliced properties (body com) + self._body_com_pos_w_ta: ProxyArray | None = None + self._body_com_quat_w_ta: ProxyArray | None = None + self._body_com_lin_vel_w_ta: ProxyArray | None = None + self._body_com_ang_vel_w_ta: ProxyArray | None = None + self._body_com_lin_acc_w_ta: ProxyArray | None = None + self._body_com_ang_acc_w_ta: ProxyArray | None = None + # Sliced properties (body com in body frame) + self._body_com_pos_b_ta: ProxyArray | None = None + self._body_com_quat_b_ta: ProxyArray | None = None + # Deprecated state-concat properties + self._default_body_state_ta: ProxyArray | None = None + self._body_state_w_ta: ProxyArray | None = None + self._body_link_state_w_ta: ProxyArray | None = None + self._body_com_state_w_ta: ProxyArray | None = None + """ Helpers. """ @@ -669,7 +819,7 @@ def _reshape_view_to_data_3d(self, data: wp.array, data_dim: int) -> wp.array: ) return wp.clone(strided_view, self.device) - def _get_pos_from_transform(self, transform: wp.array) -> wp.array: + def _get_pos_from_transform(self, transform: wp.array) -> ProxyArray: """Generates a position array from a transform array.""" return wp.array( ptr=transform.ptr, @@ -679,7 +829,7 @@ def _get_pos_from_transform(self, transform: wp.array) -> wp.array: device=self.device, ) - def _get_quat_from_transform(self, transform: wp.array) -> wp.array: + def _get_quat_from_transform(self, transform: wp.array) -> ProxyArray: """Generates a quaternion array from a transform array.""" return wp.array( ptr=transform.ptr + 3 * 4, @@ -689,7 +839,7 @@ def _get_quat_from_transform(self, transform: wp.array) -> wp.array: device=self.device, ) - def _get_lin_vel_from_spatial_vector(self, spatial_vector: wp.array) -> wp.array: + def _get_lin_vel_from_spatial_vector(self, spatial_vector: wp.array) -> ProxyArray: """Generates a linear velocity array from a spatial vector array.""" return wp.array( ptr=spatial_vector.ptr, @@ -699,7 +849,7 @@ def _get_lin_vel_from_spatial_vector(self, spatial_vector: wp.array) -> wp.array device=self.device, ) - def _get_ang_vel_from_spatial_vector(self, spatial_vector: wp.array) -> wp.array: + def _get_ang_vel_from_spatial_vector(self, spatial_vector: wp.array) -> ProxyArray: """Generates an angular velocity array from a spatial vector array.""" return wp.array( ptr=spatial_vector.ptr + 3 * 4, @@ -714,7 +864,7 @@ def _get_ang_vel_from_spatial_vector(self, spatial_vector: wp.array) -> wp.array """ @property - def default_body_state(self) -> wp.array: + def default_body_state(self) -> ProxyArray: """Default root state ``[pos, quat, lin_vel, ang_vel]`` in local environment frame. The position and quaternion are of the rigid body's actor frame. Meanwhile, the linear and angular velocities @@ -742,10 +892,12 @@ def default_body_state(self) -> wp.array: ], device=self.device, ) - return self._default_body_state + if self._default_body_state_ta is None: + self._default_body_state_ta = ProxyArray(self._default_body_state) + return self._default_body_state_ta @property - def body_state_w(self) -> wp.array: + def body_state_w(self) -> ProxyArray: """Deprecated, same as :attr:`body_link_pose_w` and :attr:`body_com_vel_w`.""" warnings.warn( "The `body_state_w` property will be deprecated in IsaacLab 4.0. Please use `body_link_pose_w` and " @@ -768,10 +920,12 @@ def body_state_w(self) -> wp.array: ) self._body_state_w.timestamp = self._sim_timestamp - return self._body_state_w.data + if self._body_state_w_ta is None: + self._body_state_w_ta = ProxyArray(self._body_state_w.data) + return self._body_state_w_ta @property - def body_link_state_w(self) -> wp.array: + def body_link_state_w(self) -> ProxyArray: """Deprecated, same as :attr:`body_link_pose_w` and :attr:`body_link_vel_w`.""" warnings.warn( "The `body_link_state_w` property will be deprecated in IsaacLab 4.0. Please use `body_link_pose_w` and " @@ -794,10 +948,12 @@ def body_link_state_w(self) -> wp.array: ) self._body_link_state_w.timestamp = self._sim_timestamp - return self._body_link_state_w.data + if self._body_link_state_w_ta is None: + self._body_link_state_w_ta = ProxyArray(self._body_link_state_w.data) + return self._body_link_state_w_ta @property - def body_com_state_w(self) -> wp.array: + def body_com_state_w(self) -> ProxyArray: """Deprecated, same as :attr:`body_com_pose_w` and :attr:`body_com_vel_w`.""" warnings.warn( "The `body_com_state_w` property will be deprecated in IsaacLab 4.0. Please use `body_com_pose_w` and " @@ -820,4 +976,6 @@ def body_com_state_w(self) -> wp.array: ) self._body_com_state_w.timestamp = self._sim_timestamp - return self._body_com_state_w.data + if self._body_com_state_w_ta is None: + self._body_com_state_w_ta = ProxyArray(self._body_com_state_w.data) + return self._body_com_state_w_ta diff --git a/source/isaaclab_physx/isaaclab_physx/assets/surface_gripper/surface_gripper.py b/source/isaaclab_physx/isaaclab_physx/assets/surface_gripper/surface_gripper.py index cd1e4e0aaea9..590289feb659 100644 --- a/source/isaaclab_physx/isaaclab_physx/assets/surface_gripper/surface_gripper.py +++ b/source/isaaclab_physx/isaaclab_physx/assets/surface_gripper/surface_gripper.py @@ -13,7 +13,7 @@ import torch import warp as wp -from isaacsim.core.utils.extensions import enable_extension +from isaacsim.core.experimental.utils.app import enable_extension import isaaclab.sim as sim_utils from isaaclab.assets import AssetBase diff --git a/source/isaaclab_physx/isaaclab_physx/physics/physx_manager.py b/source/isaaclab_physx/isaaclab_physx/physics/physx_manager.py index 2298cbbb2d70..4fb55064f072 100644 --- a/source/isaaclab_physx/isaaclab_physx/physics/physx_manager.py +++ b/source/isaaclab_physx/isaaclab_physx/physics/physx_manager.py @@ -28,7 +28,7 @@ import omni.physx import omni.timeline import omni.usd -from pxr import Sdf +from pxr import Sdf, UsdUtils import isaaclab.sim as sim_utils from isaaclab.physics import CallbackHandle, PhysicsEvent, PhysicsManager @@ -290,6 +290,30 @@ def stop(cls) -> None: # Pump events so timeline callbacks fire synchronously omni.kit.app.get_app().update() + @classmethod + def wait_for_playing(cls) -> None: + """Block until the timeline is playing, keeping the GUI responsive. + + After resume, forces a fabric re-sync so articulation meshes unfreeze. + See: https://github.com/isaac-sim/IsaacLab/issues/4279 + """ + if cls._timeline.is_playing(): + return + app = omni.kit.app.get_app() + while not cls._timeline.is_playing(): + app.update() + if cls._timeline.is_stopped(): + break + # Force fabric to re-sync articulation transforms after resume. + # detach/attach resets the FabricManager, then we immediately push + # current poses so the first render after resume shows correct state. + if not cls._timeline.is_stopped(): + cls._re_sync_fabric() + if cls._view is not None: + cls._view.update_articulations_kinematic() + if cls._update_fabric is not None: + cls._update_fabric(0.0, 0.0) + @classmethod def close(cls) -> None: """Clean up physics resources.""" @@ -585,6 +609,42 @@ def _load_fabric(cls) -> None: sim.set_setting("/isaaclab/fabric_enabled", use_fabric) # type: ignore[union-attr] sim.set_setting("/physics/visualizationDisplaySimulationOutput", False) # type: ignore[union-attr] + @classmethod + def _re_sync_fabric(cls) -> None: + """Force the PhysX fabric extension to re-synchronize after a pause/resume transition. + + Starting with PhysX fabric 107.3.21 (Isaac Sim 5.1), the FabricManager skips writing + initial articulation poses to fabric on subsequent resumes, causing articulation meshes + to freeze visually while physics continues to run. + + The workaround detaches and re-attaches the USD stage on the fabric interface, forcing + the FabricManager to fully reinitialize and write transforms into fabric so that Hydra + picks them up. + """ + if cls._fabric is None: + return + sim = PhysicsManager._sim + if sim is None: + return + stage = sim.stage + if stage is None: + return + stage_id = UsdUtils.StageCache.Get().GetId(stage).ToLongInt() + if stage_id <= 0: + return + try: + cls._fabric.detach_stage() + except Exception: + logger.warning("Failed to detach fabric stage during re-sync. Articulation visuals may be stale.") + return + try: + cls._fabric.attach_stage(stage_id) + except Exception: + logger.error( + "Could not re-attach fabric stage. Articulation visuals will be broken until next reset.", + exc_info=True, + ) + @classmethod def _warmup_and_create_views(cls) -> None: """Warm-start physics and create simulation views.""" diff --git a/source/isaaclab_physx/isaaclab_physx/renderers/isaac_rtx_renderer.py b/source/isaaclab_physx/isaaclab_physx/renderers/isaac_rtx_renderer.py index 22b07f13def0..242ac3729d0b 100644 --- a/source/isaaclab_physx/isaaclab_physx/renderers/isaac_rtx_renderer.py +++ b/source/isaaclab_physx/isaaclab_physx/renderers/isaac_rtx_renderer.py @@ -8,34 +8,62 @@ from __future__ import annotations import json +import logging import math -import weakref -from dataclasses import dataclass +from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any import numpy as np import torch import warp as wp +from packaging import version + +from pxr import Sdf from isaaclab.app.settings_manager import get_settings_manager -from isaaclab.renderers import BaseRenderer +from isaaclab.renderers import BaseRenderer, RenderBufferKind, RenderBufferSpec +from isaaclab.renderers.camera_render_spec import CameraRenderSpec +from isaaclab.utils.version import get_isaac_sim_version from isaaclab.utils.warp.kernels import reshape_tiled_image -from .isaac_rtx_renderer_utils import ensure_isaac_rtx_render_update +from .isaac_rtx_renderer_utils import ensure_isaac_rtx_render_update, ensure_rtx_hydra_engine_attached + +logger = logging.getLogger(__name__) if TYPE_CHECKING: - from isaaclab.sensors import SensorBase + from isaaclab.sensors.camera.camera_data import CameraData - from .isaac_rtx_renderer_cfg import IsaacRtxRendererCfg +from .isaac_rtx_renderer_cfg import IsaacRtxRendererCfg -# Constants from Camera (SIMPLE_SHADING_MODES, etc.) - avoid circular import +# RTX simple-shading constants. +# +# Simple shading is driven by Kit's RTX "Minimal" render mode via the +# ``/rtx/minimal/mode`` carb setting (key ``omni:rtx:minimal:mode``), with +# integer values: +# 0 = No Rendering (black output; only other AOVs are produced) +# 1 = Constant Diffuse (single constant color for all surfaces) +# 2 = Texture Diffuse (diffuse shading using texture colors) +# 3 = Diffuse/Glossy/Emission (full material shading) +# +# The public data-type names we expose (``simple_shading_*``) are kept stable +# for backwards compatibility and map onto the Kit integer values below. SIMPLE_SHADING_AOV = "SimpleShadingSD" SIMPLE_SHADING_MODES = { - "simple_shading_constant_diffuse": 0, - "simple_shading_diffuse_mdl": 1, - "simple_shading_full_mdl": 2, + "simple_shading_constant_diffuse": 1, + "simple_shading_diffuse_mdl": 2, + "simple_shading_full_mdl": 3, } -SIMPLE_SHADING_MODE_SETTING = "/rtx/sdg/simpleShading/mode" +SIMPLE_SHADING_MODE_SETTING = "/rtx/minimal/mode" + + +def _camera_semantic_filter_predicate(semantic_filter: str | list[str]) -> str: + """Build the instance-mapping semantics predicate from :attr:`isaaclab.sensors.camera.CameraCfg.semantic_filter`. + + Replicator's semantic/instance segmentation annotators consume this via the synthetic-data pipeline. + """ + if isinstance(semantic_filter, list): + return ":*; ".join(semantic_filter) + ":*" + return semantic_filter @dataclass @@ -45,7 +73,8 @@ class IsaacRtxRenderData: annotators: dict[str, Any] render_product_paths: list[str] output_data: dict[str, torch.Tensor] | None = None - sensor: SensorBase | None = None + spec: CameraRenderSpec | None = None + renderer_info: dict[str, Any] = field(default_factory=dict) class IsaacRtxRenderer(BaseRenderer): @@ -56,48 +85,133 @@ class IsaacRtxRenderer(BaseRenderer): def __init__(self, cfg: IsaacRtxRendererCfg): self.cfg = cfg + # RTX rendering requires the app to be launched with ``--enable_cameras``. + if not get_settings_manager().get("/isaaclab/cameras_enabled"): + raise RuntimeError( + "A camera was spawned without the --enable_cameras flag. Please use --enable_cameras to enable" + " rendering." + ) + ensure_rtx_hydra_engine_attached() + # ``/isaaclab/render/rtx_sensors`` is owned by ``Camera.__init__`` (must be set pre-``sim.reset()``). + + def supported_output_types(self) -> dict[RenderBufferKind, RenderBufferSpec]: + """Publish the per-output Replicator layout this RTX backend writes. + + ``ALBEDO`` and the three ``SIMPLE_SHADING_*`` outputs require Isaac Sim 6.0+ + and are omitted on older versions. The three segmentation outputs report + ``RenderBufferSpec(4, uint8)`` when the matching ``self.cfg.colorize_*`` flag is + set, otherwise ``RenderBufferSpec(1, int32)``. + """ + sim_major = get_isaac_sim_version().major + + specs: dict[RenderBufferKind, RenderBufferSpec] = { + # Replicator's native layout for color output is rgba/uint8; + # ``Camera`` aliases ``rgb`` as a view into ``rgba`` storage. + RenderBufferKind.RGBA: RenderBufferSpec(4, torch.uint8), + RenderBufferKind.RGB: RenderBufferSpec(3, torch.uint8), + RenderBufferKind.DEPTH: RenderBufferSpec(1, torch.float32), + RenderBufferKind.DISTANCE_TO_IMAGE_PLANE: RenderBufferSpec(1, torch.float32), + RenderBufferKind.DISTANCE_TO_CAMERA: RenderBufferSpec(1, torch.float32), + RenderBufferKind.NORMALS: RenderBufferSpec(3, torch.float32), + RenderBufferKind.MOTION_VECTORS: RenderBufferSpec(2, torch.float32), + } + + if sim_major >= 6: + specs[RenderBufferKind.ALBEDO] = RenderBufferSpec(4, torch.uint8) + for shading_type in SIMPLE_SHADING_MODES: + specs[RenderBufferKind(shading_type)] = RenderBufferSpec(3, torch.uint8) + + seg_specs = ( + (RenderBufferKind.SEMANTIC_SEGMENTATION, self.cfg.colorize_semantic_segmentation), + (RenderBufferKind.INSTANCE_SEGMENTATION_FAST, self.cfg.colorize_instance_segmentation), + (RenderBufferKind.INSTANCE_ID_SEGMENTATION_FAST, self.cfg.colorize_instance_id_segmentation), + ) + for name, colorize in seg_specs: + specs[name] = RenderBufferSpec(4, torch.uint8) if colorize else RenderBufferSpec(1, torch.int32) + + return specs def prepare_stage(self, stage: Any, num_envs: int) -> None: """No-op for Isaac RTX - uses USD scene directly without export. See :meth:`~isaaclab.renderers.base_renderer.BaseRenderer.prepare_stage`.""" pass - def create_render_data(self, sensor: SensorBase) -> IsaacRtxRenderData: + def create_render_data(self, spec: CameraRenderSpec) -> IsaacRtxRenderData: """Create render product and annotators for the tiled camera. See :meth:`~isaaclab.renderers.base_renderer.BaseRenderer.create_render_data`.""" import omni.replicator.core as rep + from omni.syntheticdata import SyntheticData from pxr import UsdGeom + from isaaclab.sim.utils.stage import get_current_stage + + settings = get_settings_manager() + isaac_sim_version = get_isaac_sim_version() + + if isaac_sim_version.major >= 6: + needs_color_render = "rgb" in spec.cfg.data_types or "rgba" in spec.cfg.data_types + if not needs_color_render: + settings.set_bool("/rtx/sdg/force/disableColorRender", True) + if settings.get("/isaaclab/has_gui"): + settings.set_bool("/rtx/sdg/force/disableColorRender", False) + else: + if "albedo" in spec.cfg.data_types: + logger.warning( + "Albedo annotator is only supported in Isaac Sim 6.0+. The albedo data type will be ignored." + ) + if any(dt in SIMPLE_SHADING_MODES for dt in spec.cfg.data_types): + logger.warning( + "Simple shading annotators are only supported in Isaac Sim 6.0+." + " The simple shading data types will be ignored." + ) + + # HACK: Isaac Sim 4.5 has a bug in Camera that breaks segmentation + # outputs for instanceable assets. Disable instancing as a workaround. + stage = get_current_stage() + if isaac_sim_version == version.parse("4.5") and ( + "semantic_segmentation" in spec.cfg.data_types or "instance_segmentation_fast" in spec.cfg.data_types + ): + logger.warning( + "Isaac Sim 4.5 introduced a bug in Camera when outputting instance and semantic" + " segmentation outputs for instanceable assets. As a workaround, the instanceable flag on assets" + " will be disabled in the current workflow and may lead to longer load times and increased memory" + " usage." + ) + with Sdf.ChangeBlock(): + for prim in stage.Traverse(): + prim.SetInstanceable(False) + # Get camera prim paths from sensor view - view = sensor._view - cam_prim_paths = [] - for cam_prim in view.prims: - cam_prim_path = cam_prim.GetPath().pathString + cam_prim_paths = list(spec.camera_prim_paths) + for cam_prim_path in cam_prim_paths: + cam_prim = stage.GetPrimAtPath(cam_prim_path) if not cam_prim.IsA(UsdGeom.Camera): raise RuntimeError(f"Prim at path '{cam_prim_path}' is not a Camera.") - cam_prim_paths.append(cam_prim_path) # Create replicator tiled render product - rp = rep.create.render_product_tiled( - cameras=cam_prim_paths, tile_resolution=(sensor.cfg.width, sensor.cfg.height) - ) + rp = rep.create.render_product_tiled(cameras=cam_prim_paths, tile_resolution=(spec.cfg.width, spec.cfg.height)) render_product_paths = [rp.path] + # Synthetic-data instance mapping filter for segmentation; before annotator attach. + SyntheticData.Get().set_instance_mapping_semantic_filter( + _camera_semantic_filter_predicate(self.cfg.semantic_filter) + ) + # Register simple shading if needed - if any(data_type in SIMPLE_SHADING_MODES for data_type in sensor.cfg.data_types): + if any(data_type in SIMPLE_SHADING_MODES for data_type in spec.cfg.data_types): rep.AnnotatorRegistry.register_annotator_from_aov( aov=SIMPLE_SHADING_AOV, output_data_type=np.uint8, output_channels=4 ) # Set simple shading mode (if requested) before rendering - simple_shading_mode = self._resolve_simple_shading_mode(sensor) + simple_shading_mode = self._resolve_simple_shading_mode(spec) if simple_shading_mode is not None: get_settings_manager().set_int(SIMPLE_SHADING_MODE_SETTING, simple_shading_mode) # Define annotators based on requested data types annotators = {} - for annotator_type in sensor.cfg.data_types: + for annotator_type in spec.cfg.data_types: if annotator_type == "rgba" or annotator_type == "rgb": - annotator = rep.AnnotatorRegistry.get_annotator("rgb", device=sensor.device, do_array_copy=False) + annotator = rep.AnnotatorRegistry.get_annotator("rgb", device=spec.device, do_array_copy=False) annotators["rgba"] = annotator elif annotator_type == "albedo": # TODO: this is a temporary solution because replicator has not exposed the annotator yet @@ -106,18 +220,18 @@ def create_render_data(self, sensor: SensorBase) -> IsaacRtxRenderData: aov="DiffuseAlbedoSD", output_data_type=np.uint8, output_channels=4 ) annotator = rep.AnnotatorRegistry.get_annotator( - "DiffuseAlbedoSD", device=sensor.device, do_array_copy=False + "DiffuseAlbedoSD", device=spec.device, do_array_copy=False ) annotators["albedo"] = annotator elif annotator_type in SIMPLE_SHADING_MODES: annotator = rep.AnnotatorRegistry.get_annotator( - SIMPLE_SHADING_AOV, device=sensor.device, do_array_copy=False + SIMPLE_SHADING_AOV, device=spec.device, do_array_copy=False ) annotators[annotator_type] = annotator elif annotator_type == "depth" or annotator_type == "distance_to_image_plane": # keep depth for backwards compatibility annotator = rep.AnnotatorRegistry.get_annotator( - "distance_to_image_plane", device=sensor.device, do_array_copy=False + "distance_to_image_plane", device=spec.device, do_array_copy=False ) annotators[annotator_type] = annotator # note: we are verbose here to make it easier to understand the code. @@ -127,16 +241,16 @@ def create_render_data(self, sensor: SensorBase) -> IsaacRtxRenderData: init_params = None if annotator_type == "semantic_segmentation": init_params = { - "colorize": sensor.cfg.colorize_semantic_segmentation, - "mapping": json.dumps(sensor.cfg.semantic_segmentation_mapping), + "colorize": self.cfg.colorize_semantic_segmentation, + "mapping": json.dumps(self.cfg.semantic_segmentation_mapping), } elif annotator_type == "instance_segmentation_fast": - init_params = {"colorize": sensor.cfg.colorize_instance_segmentation} + init_params = {"colorize": self.cfg.colorize_instance_segmentation} elif annotator_type == "instance_id_segmentation_fast": - init_params = {"colorize": sensor.cfg.colorize_instance_id_segmentation} + init_params = {"colorize": self.cfg.colorize_instance_id_segmentation} annotator = rep.AnnotatorRegistry.get_annotator( - annotator_type, init_params, device=sensor.device, do_array_copy=False + annotator_type, init_params, device=spec.device, do_array_copy=False ) annotators[annotator_type] = annotator @@ -144,21 +258,23 @@ def create_render_data(self, sensor: SensorBase) -> IsaacRtxRenderData: for annotator in annotators.values(): annotator.attach(render_product_paths) - # Currently camera owns the renderer and render data. By holding full - # reference of the sensor, we create a circular reference between the - # sensor and the render data. Weak reference ensures proper garbage - # collection. return IsaacRtxRenderData( annotators=annotators, render_product_paths=render_product_paths, - sensor=weakref.ref(sensor), + spec=spec, ) - def _resolve_simple_shading_mode(self, sensor: SensorBase) -> int | None: + def _resolve_simple_shading_mode(self, spec: CameraRenderSpec) -> int | None: """Resolve the requested simple shading mode from data types.""" - requested = [dt for dt in sensor.cfg.data_types if dt in SIMPLE_SHADING_MODES] + requested = [dt for dt in spec.cfg.data_types if dt in SIMPLE_SHADING_MODES] if not requested: return None + if len(requested) > 1: + logger.warning( + "Multiple simple shading modes requested (%s). Using '%s' only.", + requested, + requested[0], + ) return SIMPLE_SHADING_MODES[requested[0]] def set_outputs(self, render_data: IsaacRtxRenderData, output_data: dict[str, torch.Tensor]): @@ -185,9 +301,9 @@ def update_camera( def render(self, render_data: IsaacRtxRenderData): """Extract data from annotators and write to output buffers. See :meth:`~isaaclab.renderers.base_renderer.BaseRenderer.render`.""" - sensor = render_data.sensor() if render_data.sensor else None + spec = render_data.spec output_data = render_data.output_data - if output_data is None or sensor is None: + if output_data is None or spec is None: return # Ensure the RTX renderer has been pumped so annotator buffers are fresh. @@ -195,8 +311,9 @@ def render(self, render_data: IsaacRtxRenderData): # for the current physics step, or if a visualizer already pumped it. ensure_isaac_rtx_render_update() - view_count = sensor._view.count - cfg = sensor.cfg + view_count = spec.view_count + cfg = spec.cfg + device = spec.device def tiling_grid_shape(): cols = math.ceil(math.sqrt(view_count)) @@ -211,8 +328,7 @@ def tiling_grid_shape(): output = annotator.get_data() if isinstance(output, dict): tiled_data_buffer = output["data"] - if hasattr(sensor, "_data") and sensor._data is not None: - sensor._data.info[data_type] = output["info"] + render_data.renderer_info[data_type] = output["info"] else: tiled_data_buffer = output @@ -220,20 +336,20 @@ def tiling_grid_shape(): if isinstance(tiled_data_buffer, np.ndarray): # Let warp infer the dtype from numpy array instead of hardcoding uint8 # Different annotators return different dtypes: RGB(uint8), depth(float32), segmentation(uint32) - tiled_data_buffer = wp.array(tiled_data_buffer, device=sensor.device) + tiled_data_buffer = wp.array(tiled_data_buffer, device=device) else: - tiled_data_buffer = tiled_data_buffer.to(device=sensor.device) + tiled_data_buffer = tiled_data_buffer.to(device=device) # process data for different segmentation types # Note: Replicator returns raw buffers of dtype uint32 for segmentation types # so we need to convert them to uint8 4 channel images for colorized types if ( - (data_type == "semantic_segmentation" and cfg.colorize_semantic_segmentation) - or (data_type == "instance_segmentation_fast" and cfg.colorize_instance_segmentation) - or (data_type == "instance_id_segmentation_fast" and cfg.colorize_instance_id_segmentation) + (data_type == "semantic_segmentation" and self.cfg.colorize_semantic_segmentation) + or (data_type == "instance_segmentation_fast" and self.cfg.colorize_instance_segmentation) + or (data_type == "instance_id_segmentation_fast" and self.cfg.colorize_instance_id_segmentation) ): tiled_data_buffer = wp.array( - ptr=tiled_data_buffer.ptr, shape=(*tiled_data_buffer.shape, 4), dtype=wp.uint8, device=sensor.device + ptr=tiled_data_buffer.ptr, shape=(*tiled_data_buffer.shape, 4), dtype=wp.uint8, device=device ) # For motion vectors, use specialized kernel that reads 4 channels but only writes 2 @@ -257,7 +373,7 @@ def tiling_grid_shape(): *list(output_data[data_type].shape[1:]), num_tiles_x, ], - device=sensor.device, + device=device, ) # alias rgb as first 3 channels of rgba @@ -274,16 +390,18 @@ def tiling_grid_shape(): # apply defined clipping behavior if ( data_type in ("distance_to_camera", "distance_to_image_plane", "depth") - and cfg.depth_clipping_behavior != "none" + and self.cfg.depth_clipping_behavior != "none" ): output_data[data_type][torch.isinf(output_data[data_type])] = ( - 0.0 if cfg.depth_clipping_behavior == "zero" else cfg.spawn.clipping_range[1] + 0.0 if self.cfg.depth_clipping_behavior == "zero" else cfg.spawn.clipping_range[1] ) - def write_output(self, render_data: IsaacRtxRenderData, output_name: str, output_data: torch.Tensor): - """No-op for Isaac RTX - all outputs written in render(). - See :meth:`~isaaclab.renderers.base_renderer.BaseRenderer.write_output`.""" - pass + def read_output(self, render_data: IsaacRtxRenderData, camera_data: CameraData) -> None: + """Populate per-output metadata collected during render(). Pixel data already written in render(). + See :meth:`~isaaclab.renderers.base_renderer.BaseRenderer.read_output`.""" + for output_name, info in render_data.renderer_info.items(): + if info is not None: + camera_data.info[output_name] = info def cleanup(self, render_data: IsaacRtxRenderData | None): """Detach annotators from render product. @@ -291,4 +409,4 @@ def cleanup(self, render_data: IsaacRtxRenderData | None): if render_data: for annotator in render_data.annotators.values(): annotator.detach(render_data.render_product_paths) - render_data.sensor = None + render_data.spec = None diff --git a/source/isaaclab_physx/isaaclab_physx/renderers/isaac_rtx_renderer_cfg.py b/source/isaaclab_physx/isaaclab_physx/renderers/isaac_rtx_renderer_cfg.py index e36cca4e53b8..de5d433e867f 100644 --- a/source/isaaclab_physx/isaaclab_physx/renderers/isaac_rtx_renderer_cfg.py +++ b/source/isaaclab_physx/isaaclab_physx/renderers/isaac_rtx_renderer_cfg.py @@ -5,13 +5,88 @@ """Configuration for Isaac RTX (Replicator) Renderer.""" +from typing import Literal + from isaaclab.renderers.renderer_cfg import RendererCfg from isaaclab.utils import configclass @configclass class IsaacRtxRendererCfg(RendererCfg): - """Configuration for Isaac RTX renderer using Omniverse Replicator.""" + """Configuration for Isaac RTX renderer using Omniverse Replicator. + + Holds the Replicator/RTX-specific knobs (semantic segmentation, instance + segmentation, semantic filtering, depth clipping) used by the RTX rendering + pipeline. + """ renderer_type: str = "isaac_rtx" """Type identifier for Isaac RTX renderer.""" + + semantic_filter: str | list[str] = "*:*" + """A string or a list specifying a semantic filter predicate. Defaults to ``"*:*"``. + + If a string, it should be a disjunctive normal form of (semantic type, labels). For examples: + + * ``"typeA : labelA & !labelB | labelC , typeB: labelA ; typeC: labelE"``: + All prims with semantic type "typeA" and label "labelA" but not "labelB" or with label "labelC". + Also, all prims with semantic type "typeB" and label "labelA", or with semantic type "typeC" and label "labelE". + * ``"typeA : * ; * : labelA"``: All prims with semantic type "typeA" or with label "labelA" + + If a list of strings, each string should be a semantic type. The segmentation for prims with + semantics of the specified types will be retrieved. For example, if the list is ["class"], only + the segmentation for prims with semantics of type "class" will be retrieved. + + .. seealso:: + + For more information on the semantics filter, see the documentation on `Replicator Semantics Schema Editor`_. + + .. _Replicator Semantics Schema Editor: https://docs.omniverse.nvidia.com/extensions/latest/ext_replicator/semantics_schema_editor.html#semantics-filtering + """ + + colorize_semantic_segmentation: bool = True + """Whether to colorize the semantic segmentation images. Defaults to True. + + If True, semantic segmentation is converted to an image where semantic IDs are mapped to colors + and returned as a ``uint8`` 4-channel array. If False, the output is returned as a ``int32`` array. + """ + + colorize_instance_id_segmentation: bool = True + """Whether to colorize the instance ID segmentation images. Defaults to True. + + If True, instance id segmentation is converted to an image where instance IDs are mapped to colors. + and returned as a ``uint8`` 4-channel array. If False, the output is returned as a ``int32`` array. + """ + + colorize_instance_segmentation: bool = True + """Whether to colorize the instance segmentation images. Defaults to True. + + If True, instance segmentation is converted to an image where instance IDs are mapped to colors. + and returned as a ``uint8`` 4-channel array. If False, the output is returned as a ``int32`` array. + """ + + semantic_segmentation_mapping: dict = {} + """Dictionary mapping semantics to specific colours + + Eg. + + .. code-block:: python + + { + "class:cube_1": (255, 36, 66, 255), + "class:cube_2": (255, 184, 48, 255), + "class:cube_3": (55, 255, 139, 255), + "class:table": (255, 237, 218, 255), + "class:ground": (100, 100, 100, 255), + "class:robot": (61, 178, 255, 255), + } + + """ + + depth_clipping_behavior: Literal["max", "zero", "none"] = "none" + """Clipping behavior for the camera for values exceed the maximum value. Defaults to "none". + + - ``"max"``: Values are clipped to the maximum value. + - ``"zero"``: Values are clipped to zero. + - ``"none"``: No clipping is applied. Values will be returned as ``inf``. + """ diff --git a/source/isaaclab_physx/isaaclab_physx/renderers/isaac_rtx_renderer_utils.py b/source/isaaclab_physx/isaaclab_physx/renderers/isaac_rtx_renderer_utils.py index 8e5b9abc8549..bdc5596b717f 100644 --- a/source/isaaclab_physx/isaaclab_physx/renderers/isaac_rtx_renderer_utils.py +++ b/source/isaaclab_physx/isaaclab_physx/renderers/isaac_rtx_renderer_utils.py @@ -9,61 +9,31 @@ import logging import time +from typing import Any + +import omni.usd import isaaclab.sim as sim_utils logger = logging.getLogger(__name__) -# Module-level dedup stamp: tracks the last (sim instance, physics step) at +# Module-level dedup stamp: tracks the last (sim instance, physics step, render generation) at # which Kit's ``app.update()`` was pumped. Keyed on ``id(sim)`` so that a # new ``SimulationContext`` (e.g. in a new test) automatically invalidates # any stale stamp from a previous instance. -_last_render_update_key: tuple[int, int] = (0, -1) - -# --------------------------------------------------------------------------- -# RTX streaming status tracking -# --------------------------------------------------------------------------- -_RTX_STREAMING_STATUS_EVENT: str = "omni.streamingstatus:streaming_status" - -_streaming_is_busy: bool = False -_streaming_subscription = None -_streaming_subscribed: bool = False +_last_render_update_key: tuple[int, int, int] = (0, -1, -1) _STREAMING_WAIT_TIMEOUT_S: float = 30.0 -def _on_streaming_status_event(event) -> None: - """Callback fired by the RTX renderer whenever streaming status changes.""" - global _streaming_is_busy - try: - is_busy = event["isBusy"] - if is_busy is not None: - _streaming_is_busy = bool(is_busy) - except (KeyError, TypeError): - pass - - -def _ensure_streaming_subscription() -> None: - """Subscribe to RTX streaming status events (idempotent).""" - global _streaming_subscription, _streaming_subscribed - if _streaming_subscribed: - return +def _get_stage_streaming_busy() -> bool: + """Synchronously query whether RTX stage streaming is still in progress.""" + import omni.usd - # Mark initialization as attempted even if dispatcher lookup fails. - # This flag enforces no-retry behavior after the first attempt. - _streaming_subscribed = True - - from carb.eventdispatcher import get_eventdispatcher - - dispatcher = get_eventdispatcher() - if dispatcher is None: - logger.warning("carb event dispatcher unavailable – RTX streaming wait will be inactive.") - else: - _streaming_subscription = dispatcher.observe_event( - observer_name="isaaclab_rtx_streaming_wait", - event_name=_RTX_STREAMING_STATUS_EVENT, - on_event=_on_streaming_status_event, - ) + usd_context = omni.usd.get_context() + if usd_context is None: + return False + return usd_context.get_stage_streaming_status() def _wait_for_streaming_complete() -> None: @@ -75,11 +45,11 @@ def _wait_for_streaming_complete() -> None: import omni.kit.app start = time.monotonic() - while _streaming_is_busy and (time.monotonic() - start) < _STREAMING_WAIT_TIMEOUT_S: + while _get_stage_streaming_busy() and (time.monotonic() - start) < _STREAMING_WAIT_TIMEOUT_S: omni.kit.app.get_app().update() elapsed = time.monotonic() - start - if _streaming_is_busy: + if _get_stage_streaming_busy(): logger.warning( "RTX streaming did not complete within %.1f s – proceeding anyway.", _STREAMING_WAIT_TIMEOUT_S, @@ -90,56 +60,84 @@ def _wait_for_streaming_complete() -> None: omni.kit.app.get_app().update() +def ensure_rtx_hydra_engine_attached() -> None: + """Attach the RTX Hydra engine to the USD context if not already attached. + + Headless app files such as ``isaaclab.python.headless.rendering.kit`` intentionally + omit ``omni.kit.viewport.window`` to avoid pulling in the ``omni.ui``-based viewport + stack. However, ``ViewportWindow`` is normally responsible for calling + :func:`omni.usd.create_hydra_engine` at startup; without it the RTX Hydra engine is + never bound to the :class:`omni.usd.UsdContext`, and the first Replicator tiled + render product runs against a cold pipeline. On some GPUs this manifests as + ``cudaErrorIllegalAddress`` inside ``omni.rtx`` (CUDA ``freeAsync``) and/or all + tiles rendering as black. + + This helper replicates only the activation step ``ViewportWindow`` performs, + without creating a UI or a window. It is idempotent: when the engine is already + attached (e.g. GUI runs that do load ``omni.kit.viewport.window``, or a previous + call already attached it) the function is a no-op. Failures are logged as errors + and do not propagate, so non-RTX contexts (e.g. unit tests importing this module + without a running Kit app) continue to work. + """ + try: + ctx = omni.usd.get_context() + if ctx is None: + return + if "rtx" in ctx.get_attached_hydra_engine_names(): + return + omni.usd.create_hydra_engine("rtx", ctx) + except Exception as e: # noqa: BLE001 + logger.error("RTX Hydra engine attach failed: %s", e) + + def ensure_isaac_rtx_render_update() -> None: - """Ensure the Isaac RTX renderer has been pumped for the current physics step. + """Ensure the Isaac RTX renderer has been pumped for the current sim step. This keeps the Kit-specific ``app.update()`` logic inside the renderers package rather than in the backend-agnostic ``SimulationContext``. - Safe to call from multiple ``Camera`` / ``TiledCamera`` instances per step — + Safe to call from multiple ``Camera`` instances per step — only the first call triggers ``app.update()``. Subsequent calls are no-ops because the module-level ``_last_render_update_key`` already matches the - current ``(id(sim), step_count)`` pair. + current ``(id(sim), step_count, render_generation)`` tuple. - The key is a ``(sim_instance_id, step_count)`` tuple so that creating a new - ``SimulationContext`` (e.g. in a subsequent test) automatically invalidates - any stale stamp left over from a previous instance. + The key is a ``(sim_instance_id, step_count, render_generation)`` tuple so that: + - creating a new ``SimulationContext`` invalidates stale stamps, and + - render/reset transitions that do not advance physics step count still force a fresh update. - If RTX texture/geometry streaming is in progress, additional - ``app.update()`` calls are pumped until the streaming subsystem reports - idle (or a timeout is reached). + After the initial ``app.update()`` the streaming subsystem is queried + synchronously via ``UsdContext.get_stage_streaming_status()``. If textures + are still loading, additional ``app.update()`` calls are pumped until the + subsystem reports idle (or a timeout is reached). No-op conditions: * Already called this step (dedup across camera instances). * A visualizer already pumps ``app.update()`` (e.g. KitVisualizer). * Rendering is not active. """ - global _last_render_update_key, _streaming_is_busy, _streaming_subscribed, _streaming_subscription + global _last_render_update_key sim = sim_utils.SimulationContext.instance() if sim is None: return - key = (id(sim), sim._physics_step_count) + render_generation = getattr(sim, "render_generation", getattr(sim, "_render_generation", 0)) + key = (id(sim), sim._physics_step_count, render_generation) if _last_render_update_key == key: return # Already pumped this step (by another camera or a visualizer) - # Reset stale streaming state when a new SimulationContext is detected. - if key[0] != _last_render_update_key[0]: - _streaming_is_busy = False - _streaming_subscribed = False - _streaming_subscription = None - # If a visualizer already pumps the Kit app loop, mark as done and skip. - if any(viz.pumps_app_update() for viz in sim.visualizers): + # However, on the very first call for a new SimulationContext, the visualizer + # has not had a chance to pump yet (sim.render() was never called), so we + # must perform the initial app.update() ourselves to populate annotator buffers. + first_call_for_sim = _last_render_update_key[0] != id(sim) + if not first_call_for_sim and any(viz.pumps_app_update() for viz in sim.visualizers): _last_render_update_key = key return if not sim.is_rendering: return - _ensure_streaming_subscription() - # Sync physics results → Fabric so RTX sees updated positions. # physics_manager.step() only runs simulate()/fetch_results() and does NOT # call _update_fabric(), so without this the render would lag one frame behind. @@ -150,9 +148,34 @@ def ensure_isaac_rtx_render_update() -> None: sim.set_setting("/app/player/playSimulations", False) omni.kit.app.get_app().update() - if _streaming_is_busy: + if _get_stage_streaming_busy(): _wait_for_streaming_complete() sim.set_setting("/app/player/playSimulations", True) _last_render_update_key = key + + +def pump_kit_app_for_headless_video_render_if_needed(sim: Any) -> None: + """Pump Kit app-loop for headless rgb-array rendering when needed. + + Isaac Sim / RTX specific; kept out of backend-agnostic :class:`~isaaclab.sim.SimulationContext`. + """ + if not bool(sim.get_setting("/isaaclab/video/enabled")): + return + + from isaaclab.utils.version import has_kit + + if not has_kit(): + return + if any(viz.pumps_app_update() for viz in sim.visualizers): + return + try: + ensure_isaac_rtx_render_update() + except (ImportError, AttributeError, ModuleNotFoundError) as exc: + logger.debug("[isaac_rtx] Skipping Kit app-loop pump in render() (non-Kit env): %s", exc) + except Exception as exc: + logger.warning( + "[isaac_rtx] Kit app-loop pump failed in render() — video frames may be stale or black: %s", + exc, + ) diff --git a/source/isaaclab_physx/isaaclab_physx/renderers/kit_viewport_utils.py b/source/isaaclab_physx/isaaclab_physx/renderers/kit_viewport_utils.py new file mode 100644 index 000000000000..f371aac7c603 --- /dev/null +++ b/source/isaaclab_physx/isaaclab_physx/renderers/kit_viewport_utils.py @@ -0,0 +1,39 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Kit / Omniverse viewport helpers (Isaac Sim specific). + +These live in :mod:`isaaclab_physx` so :class:`~isaaclab.sim.SimulationContext` stays +backend-agnostic. +""" + +from __future__ import annotations + +import logging + +logger = logging.getLogger(__name__) + + +def set_kit_renderer_camera_view( + eye: tuple[float, float, float] | list[float], + target: tuple[float, float, float] | list[float], + camera_prim_path: str = "/OmniverseKit_Persp", +) -> None: + """Set camera view for the renderer/viewport camera only. + + This does not broadcast to visualizers. + """ + try: + from isaacsim.core.rendering_manager import ViewportManager + + ViewportManager.set_camera_view( + str(camera_prim_path), + eye=list(eye), + target=list(target), + ) + except (ImportError, ModuleNotFoundError) as exc: + logger.debug("[kit_viewport] Renderer camera update skipped (no Kit): %s", exc) + except Exception as exc: + logger.warning("[kit_viewport] Renderer camera update failed: %s", exc) diff --git a/source/isaaclab_physx/isaaclab_physx/scene_data_providers/__init__.pyi b/source/isaaclab_physx/isaaclab_physx/scene_data_providers/__init__.pyi index d1612d1f3bbd..32c6f9c07335 100644 --- a/source/isaaclab_physx/isaaclab_physx/scene_data_providers/__init__.pyi +++ b/source/isaaclab_physx/isaaclab_physx/scene_data_providers/__init__.pyi @@ -4,9 +4,7 @@ # SPDX-License-Identifier: BSD-3-Clause __all__ = [ - "NewtonSceneDataProvider", "PhysxSceneDataProvider", ] -from .newton_scene_data_provider import NewtonSceneDataProvider from .physx_scene_data_provider import PhysxSceneDataProvider diff --git a/source/isaaclab_physx/isaaclab_physx/scene_data_providers/physx_scene_data_provider.py b/source/isaaclab_physx/isaaclab_physx/scene_data_providers/physx_scene_data_provider.py index 19aa1eb34986..9a88660da498 100644 --- a/source/isaaclab_physx/isaaclab_physx/scene_data_providers/physx_scene_data_provider.py +++ b/source/isaaclab_physx/isaaclab_physx/scene_data_providers/physx_scene_data_provider.py @@ -13,17 +13,16 @@ from collections import deque from typing import Any +import torch import warp as wp from pxr import UsdGeom, UsdPhysics from isaaclab.physics.base_scene_data_provider import BaseSceneDataProvider +from isaaclab.sim.utils.newton_model_utils import replace_newton_shape_colors logger = logging.getLogger(__name__) -# Path pattern for env prims: /World/envs/env_/... -_ENV_ID_RE = re.compile(r"/World/envs/env_(\d+)") - @wp.kernel(enable_backward=False) def _set_body_q_kernel( @@ -36,36 +35,19 @@ def _set_body_q_kernel( body_q[i] = wp.transformf(positions[i], orientations[i]) -@wp.kernel(enable_backward=False) -def _set_body_q_subset_kernel( - positions: wp.array(dtype=wp.vec3), - orientations: wp.array(dtype=wp.quatf), - body_indices: wp.array(dtype=wp.int32), - body_q: wp.array(dtype=wp.transformf), -): - """Write pose arrays into selected Newton ``body_q`` indices.""" - i = wp.tid() - bi = body_indices[i] - body_q[bi] = wp.transformf(positions[i], orientations[i]) - - class PhysxSceneDataProvider(BaseSceneDataProvider): """Scene data provider for Omni PhysX backend. Supports: - - body poses via PhysX tensor views, with XformPrimView fallback + - body poses via PhysX tensor views, with FrameView fallback - camera poses & intrinsics - USD stage handles - - Newton model/state handles + - Newton model/state (built locally from the scene's per-group :class:`ClonePlan` map + when required) """ # ---- Environment discovery / metadata ------------------------------------------------- - def _env_id_from_path(self, path: str) -> int | None: - """Extract env id from path (e.g. /World/envs/env_42/...). Used to map body paths to envs for sync.""" - m = _ENV_ID_RE.search(path) - return int(m.group(1)) if m else None - def get_num_envs(self) -> int: """Return env count from stage discovery, cached once available.""" if self._num_envs is not None and self._num_envs > 0: @@ -99,7 +81,7 @@ def __init__(self, stage, simulation_context) -> None: stage: USD stage handle. simulation_context: Active simulation context. """ - from isaacsim.core.simulation_manager import SimulationManager + from isaaclab_physx.physics import PhysxManager as SimulationManager self._simulation_context = simulation_context self._stage = stage @@ -117,10 +99,6 @@ def __init__(self, stage, simulation_context) -> None: requirements = self._simulation_context.get_scene_data_requirements() self._needs_newton_sync = bool(requirements.requires_newton_model) - # Benchmark/debug override: force USD traversal fallback even when prebuilt - # visualizer artifacts are available from the cloner path. - self._force_usd_fallback_for_newton_model_build = False - # Fixed metadata for visualizers. get_metadata() returns this plus num_envs so visualizers # can .get("num_envs", 0), .get("physics_backend", ...) etc. without the provider exposing many methods. self._metadata = {"physics_backend": "omni"} @@ -129,21 +107,14 @@ def __init__(self, stage, simulation_context) -> None: "[PhysxSceneDataProvider] USD stage is None and not available from simulation_context. " "Ensure the simulation context has a valid stage when using OV/Newton/Rerun/Viser visualizers." ) - self._up_axis = UsdGeom.GetStageUpAxis(self._stage) self._num_envs_at_last_newton_build: int | None = None # for _refresh_newton_model_if_needed self._device = getattr(self._simulation_context, "device", "cuda:0") self._newton_model = None self._newton_state = None - self._filtered_newton_model = None - self._filtered_newton_state = None - self._filtered_env_ids_key: tuple[int, ...] | None = None - self._filtered_body_indices: list[int] = [] self._rigid_body_paths: list[str] = [] # Paths used to create PhysX views. May include articulation roots for coverage. self._rigid_body_view_paths: list[str] = [] - # env_id -> list of body indices (in Newton body_key order) - self._env_id_to_body_indices: dict[int, list[int]] = {} # Reused pose buffers (MR perf): avoid per-call allocations in _read_poses_from_best_source. self._pose_buf_num_bodies = 0 @@ -153,14 +124,12 @@ def __init__(self, stage, simulation_context) -> None: self._xform_mask_buf = None # View index order as device tensors for vectorized scatter in _apply_view_poses. self._view_order_tensors: dict[str, Any] = {} - # Last full-model build source for tests/debugging ("prebuilt", "usd_fallback", "error"). + # Last load outcome (tests / debug): "built" | "missing" | "error". self._last_newton_model_build_source: str | None = None self._last_newton_model_build_elapsed_ms: float | None = None - # Initialize Newton pipeline only if needed for visualization if self._needs_newton_sync: - self._build_newton_model_from_usd() - self._build_env_id_to_body_indices() + self._build_newton_model_from_clone_plans() self._setup_rigid_body_view() # ---- Newton model + PhysX view setup -------------------------------------------------- @@ -173,7 +142,7 @@ def _wildcard_env_paths(self, paths: list[str]) -> list[str]: return list(dict.fromkeys(wildcard_paths)) if wildcard_paths else paths def _refresh_newton_model_if_needed(self) -> None: - """Rebuild Newton model/state and PhysX views if discovered env count changes.""" + """Reload Newton model/state and PhysX views when the discovered env count changes.""" num_envs = self.get_num_envs() if num_envs <= 0: return @@ -181,202 +150,113 @@ def _refresh_newton_model_if_needed(self) -> None: needs_rebuild = self._newton_model is None or self._newton_state is None needs_rebuild = needs_rebuild or (self._num_envs_at_last_newton_build != num_envs) if needs_rebuild: - self._build_newton_model_from_usd() - self._build_env_id_to_body_indices() + self._build_newton_model_from_clone_plans() self._setup_rigid_body_view() - def _model_body_paths(self, model) -> list[str]: - """Return body paths/keys from a Newton model. - - Args: - model: Newton model object. - - Returns: - Body paths/keys from the model, or an empty list when unavailable. - """ - if model is None: - return [] - return list(getattr(model, "body_label", None) or getattr(model, "body_key", [])) - - def _try_use_prebuilt_newton_artifact(self) -> bool: - """Use scene-time prebuilt Newton visualizer artifact when available. - - Returns: - ``True`` when a valid prebuilt artifact was consumed, otherwise ``False``. + def _build_newton_model_from_clone_plans(self) -> None: + """Build Newton model and state from the scene's per-group :class:`ClonePlan` map. + + Reads plans :meth:`InteractiveScene.clone_environments` publishes on + :class:`SimulationContext`, derives the flat ``(sources, destinations, mask)`` shape + :func:`isaaclab_newton.cloner.newton_visualizer_prebuild` expects, and caches the + resulting model/state. Per-prototype source paths recover as + ``dest_template.format()``; per-env positions are + read off ``xformOp:translate`` on the env-level prims derived from the same template. + Pre-condition violations raise :class:`RuntimeError` (logged as ``"missing"``); + ``isaaclab_newton`` being absent (optional dep) maps to ``"missing"`` via the + import's own exception types; unexpected failures fall through to ``"error"``. """ - if self._force_usd_fallback_for_newton_model_build: - return False - artifact = self._simulation_context.get_scene_data_visualizer_prebuilt_artifact() - if not artifact: - return False - - model = artifact.model - state = artifact.state - if model is None or state is None: - return False - - self._newton_model = model - self._newton_state = state - body_paths = list(artifact.rigid_body_paths) or self._model_body_paths(model) - # Keep one-to-one alignment between `body_paths` and Newton `state.body_q`. - # Articulation root prims are not body_q entries and must not be mixed here. - self._rigid_body_paths = body_paths - # Build the PhysX-view query set separately so articulation roots can still be - # included for view coverage without breaking body_q alignment. - view_paths = list(body_paths) - if artifact.articulation_paths: - seen = set(view_paths) - for path in artifact.articulation_paths: - if path not in seen: - view_paths.append(path) - seen.add(path) - self._rigid_body_view_paths = view_paths - self._xform_views.clear() - self._view_body_index_map = {} - self._view_order_tensors.clear() - self._pose_buf_num_bodies = 0 - self._positions_buf = None - self._orientations_buf = None - self._covered_buf = None - self._xform_mask_buf = None - self._env_id_to_body_indices = {} - self._num_envs_at_last_newton_build = int(artifact.num_envs) - self._filtered_newton_model = None - self._filtered_newton_state = None - self._filtered_env_ids_key = None - self._filtered_body_indices = [] - return True - - def _build_newton_model_from_usd(self) -> None: - """Build Newton model from USD and cache body paths.""" - # TODO: Deprecate this USD-traversal fallback once cloner/prebuilt coverage - # is complete for full and partial visualization model-build paths. start_t = time.perf_counter() + source = "missing" try: - if self._try_use_prebuilt_newton_artifact(): - self._last_newton_model_build_source = "prebuilt" - return - self._last_newton_model_build_source = ( - "usd_fallback_forced" if self._force_usd_fallback_for_newton_model_build else "usd_fallback" + plans = self._simulation_context.get_clone_plans() + if not plans: + raise RuntimeError("No clone plans on simulation context.") + from isaaclab_newton.cloner.newton_replicate import newton_visualizer_prebuild + + # Flatten per-group plans into one (sources, destinations, mask) bundle. Source + # paths recover via ``dest_template.format()``; + # all-False rows are dropped (possible when ``num_prototypes > num_envs``). + plan_list = list(plans.values()) + num_envs = plan_list[0].clone_mask.size(1) + if any(p.clone_mask.size(1) != num_envs for p in plan_list): + raise RuntimeError(f"Clone plans disagree on num_envs: {[p.clone_mask.size(1) for p in plan_list]}") + sources, destinations, mask_rows = [], [], [] + for p in plan_list: + for i in range(p.clone_mask.size(0)): + nz = p.clone_mask[i].nonzero(as_tuple=False) + if nz.numel() == 0: + continue + sources.append(p.dest_template.format(int(nz[0].item()))) + destinations.append(p.dest_template) + mask_rows.append(p.clone_mask[i : i + 1]) + if not sources: + raise RuntimeError("All clone-plan prototype rows are empty.") + mask = torch.cat(mask_rows, dim=0) + + # Env-level path template = dest_template up to the first ``{}``. Per-env world + # positions: xformOp:translate read off each env prim; missing prims fall through. + env_path_template = plan_list[0].dest_template.split("{}")[0] + "{}" + positions = torch.zeros((num_envs, 3), dtype=torch.float32, device=self._device) + for i in range(num_envs): + prim = self._stage.GetPrimAtPath(env_path_template.format(i)) + if prim.IsValid() and (v := prim.GetAttribute("xformOp:translate").Get()) is not None: + positions[i] = torch.tensor([v[0], v[1], v[2]], device=self._device) + + model, state = newton_visualizer_prebuild( + stage=self._stage, + sources=sources, + destinations=destinations, + env_ids=torch.arange(num_envs, dtype=torch.long, device=mask.device), + mapping=mask, + positions=positions, + device=self._device, + up_axis=UsdGeom.GetStageUpAxis(self._stage), ) - from newton import ModelBuilder - - builder = ModelBuilder(up_axis=self._up_axis) - builder.add_usd(self._stage, ignore_paths=[r"/World/envs/.*"]) - for env_id in range(self.get_num_envs()): - builder.begin_world() - builder.add_usd(self._stage, root_path=f"/World/envs/env_{env_id}") - builder.end_world() - self._newton_model = builder.finalize(device=self._device) - self._newton_state = self._newton_model.state() - - # Extract scene structure from Newton model (single source of truth) - self._rigid_body_paths = self._model_body_paths(self._newton_model) - self._rigid_body_view_paths = list(self._rigid_body_paths) - + if model is None or state is None: + raise RuntimeError("newton_visualizer_prebuild returned None.") + + self._newton_model, self._newton_state = model, state + replace_newton_shape_colors(self._newton_model, self._stage) + # Newton renamed ``*_key`` → ``*_label`` mid-development; fall back so we work either way. + # ``dict.fromkeys`` preserves order while deduping — articulation roots can overlap rigid bodies. + label_or_key = lambda kind: list(getattr(model, f"{kind}_label", None) or getattr(model, f"{kind}_key", [])) # noqa: E731 + self._rigid_body_paths = label_or_key("body") + self._rigid_body_view_paths = list(dict.fromkeys(self._rigid_body_paths + label_or_key("articulation"))) + # Reset cached views/buffers; rebuilt lazily by ``_setup_rigid_body_view``. self._xform_views.clear() - self._view_body_index_map = {} self._view_order_tensors.clear() + self._view_body_index_map = {} self._pose_buf_num_bodies = 0 - self._positions_buf = None - self._orientations_buf = None - self._covered_buf = None - self._xform_mask_buf = None - self._env_id_to_body_indices = {} - self._num_envs_at_last_newton_build = self.get_num_envs() - # Invalidate any filtered model when full model changes. - self._filtered_newton_model = None - self._filtered_newton_state = None - self._filtered_env_ids_key = None - self._filtered_body_indices = [] - except ModuleNotFoundError as exc: - self._last_newton_model_build_source = "error" - logger.error( - "[PhysxSceneDataProvider] Newton module not available. " - "Install the Newton backend to use newton/rerun/viser visualizers." - ) - logger.debug(f"[PhysxSceneDataProvider] Newton import error: {exc}") + self._positions_buf = self._orientations_buf = self._covered_buf = self._xform_mask_buf = None + self._num_envs_at_last_newton_build = num_envs + source = "built" + except (ImportError, ModuleNotFoundError) as exc: + logger.warning("[PhysxSceneDataProvider] isaaclab_newton not available: %s", exc) + self._clear_newton_model_state() + except RuntimeError as exc: + logger.error("[PhysxSceneDataProvider] %s", exc) + self._clear_newton_model_state() except Exception as exc: - self._last_newton_model_build_source = "error" - logger.error(f"[PhysxSceneDataProvider] Failed to build Newton model from USD: {exc}") - self._newton_model = None - self._newton_state = None - self._rigid_body_paths = [] - self._rigid_body_view_paths = [] - self._num_envs_at_last_newton_build = None + source = "error" + logger.error("[PhysxSceneDataProvider] Failed to build Newton model from clone plans: %s", exc) + self._clear_newton_model_state() finally: - elapsed_ms = (time.perf_counter() - start_t) * 1000.0 - self._last_newton_model_build_elapsed_ms = elapsed_ms - try: - num_envs = self.get_num_envs() - except Exception: - num_envs = -1 + self._last_newton_model_build_elapsed_ms = (time.perf_counter() - start_t) * 1000.0 + self._last_newton_model_build_source = source logger.debug( - "[PhysxSceneDataProvider] Newton model build source=%s num_envs=%d elapsed_ms=%.2f", - self._last_newton_model_build_source, - num_envs, - elapsed_ms, + "[PhysxSceneDataProvider] Newton model build source=%s elapsed_ms=%.2f", + source, + self._last_newton_model_build_elapsed_ms, ) - def _build_filtered_newton_model(self, env_ids: list[int]) -> None: - """Build Newton model/state for a subset of environments. - - Args: - env_ids: Environment ids to include in the subset model. - """ - # TODO: Deprecate this USD-traversal fallback once cloner/prebuilt coverage - # is complete for full and partial visualization model-build paths. - try: - from newton import ModelBuilder - - # Newton model building from USD with partial visualization does not currently use cloner, - # and falls back to slower USD-stage traversal. - builder = ModelBuilder(up_axis=self._up_axis) - builder.add_usd(self._stage, ignore_paths=[r"/World/envs/.*"]) - for env_id in env_ids: - builder.begin_world() - builder.add_usd(self._stage, root_path=f"/World/envs/env_{env_id}") - builder.end_world() - self._filtered_newton_model = builder.finalize(device=self._device) - self._filtered_newton_state = self._filtered_newton_model.state() - - full_index_by_path = {path: i for i, path in enumerate(self._rigid_body_paths)} - filtered_paths = self._model_body_paths(self._filtered_newton_model) - self._filtered_body_indices = [] - missing = [] - for path in filtered_paths: - idx = full_index_by_path.get(path) - if idx is None: - missing.append(path) - else: - self._filtered_body_indices.append(idx) - if missing: - logger.warning( - "[PhysxSceneDataProvider] Filtered model contains %d bodies not in full model.", - len(missing), - ) - except ModuleNotFoundError as exc: - logger.error( - "[PhysxSceneDataProvider] Newton module not available. " - "Install the Newton backend to use newton/rerun/viser visualizers." - ) - logger.debug(f"[PhysxSceneDataProvider] Newton import error: {exc}") - self._filtered_newton_model = None - self._filtered_newton_state = None - self._filtered_body_indices = [] - except Exception as exc: - logger.error(f"[PhysxSceneDataProvider] Failed to build filtered Newton model from USD: {exc}") - self._filtered_newton_model = None - self._filtered_newton_state = None - self._filtered_body_indices = [] - - def _build_env_id_to_body_indices(self) -> None: - """Build mapping env_id -> list of body indices from rigid_body_paths.""" - self._env_id_to_body_indices = {} - for body_idx, path in enumerate(self._rigid_body_paths): - eid = self._env_id_from_path(path) - if eid is not None: - self._env_id_to_body_indices.setdefault(eid, []).append(body_idx) + def _clear_newton_model_state(self) -> None: + """Clear cached Newton model, state, and rigid-body path lists.""" + self._newton_model = None + self._newton_state = None + self._rigid_body_paths = [] + self._rigid_body_view_paths = [] + self._num_envs_at_last_newton_build = None def _setup_rigid_body_view(self) -> None: """Create PhysX RigidBodyView from Newton's body paths. @@ -535,7 +415,7 @@ def _apply_view_poses(self, view: Any, view_key: str, positions: Any, orientatio return newton_indices.numel() return 0 - # Fallback: Python loop when view does not fully cover or cache missing. + # Per-index path when the view does not fully cover bodies or the order cache is missing. count = 0 for newton_idx, view_idx in enumerate(order): if view_idx is not None and not covered[newton_idx]: @@ -547,13 +427,10 @@ def _apply_view_poses(self, view: Any, view_key: str, positions: Any, orientatio return count def _apply_xform_poses(self, positions: Any, orientations: Any, covered: Any, xform_mask: Any) -> int: - """Fill remaining poses using XformPrimView (USD fallback). - - This is slower but more robust when PhysX views don't cover all bodies. - """ + """Fill remaining body poses using ``XformPrimView`` for prims not covered by the rigid-body view.""" import torch - from isaaclab.sim.views import XformPrimView + from isaaclab.sim.views import FrameView uncovered = torch.where(~covered)[0].cpu().tolist() if not uncovered: @@ -565,14 +442,14 @@ def _apply_xform_poses(self, positions: Any, orientations: Any, covered: Any, xf path = self._rigid_body_paths[idx] try: if path not in self._xform_views: - self._xform_views[path] = XformPrimView( + self._xform_views[path] = FrameView( path, device=self._device, stage=self._stage, validate_xform_ops=False ) - pos, quat = self._xform_views[path].get_world_poses() - if pos is not None and quat is not None: - positions[idx] = pos.to(device=self._device, dtype=torch.float32).squeeze() - orientations[idx] = quat.to(device=self._device, dtype=torch.float32).squeeze() + pos_w, quat_w = self._xform_views[path].get_world_poses() + if pos_w is not None and quat_w is not None: + positions[idx] = pos_w.torch.to(device=self._device, dtype=torch.float32).squeeze() + orientations[idx] = quat_w.torch.to(device=self._device, dtype=torch.float32).squeeze() covered[idx] = True xform_mask[idx] = True count += 1 @@ -583,7 +460,7 @@ def _apply_xform_poses(self, positions: Any, orientations: Any, covered: Any, xf if len(self._xform_view_failures) > 0: self._warn_once( "xform-fallback-failures", - "[PhysxSceneDataProvider] Xform fallback failed for %d body paths.", + "[PhysxSceneDataProvider] XformPrimView reads failed for %d body paths.", len(self._xform_view_failures), level=logging.DEBUG, ) @@ -592,7 +469,7 @@ def _apply_xform_poses(self, positions: Any, orientations: Any, covered: Any, xf def _convert_xform_quats(self, orientations: Any, xform_mask: Any) -> Any: """Return quaternions in xyzw convention. - PhysX views, XformPrimView, and resolve_prim_pose() in Isaac Lab all use xyzw. + PhysX views, FrameView, and resolve_prim_pose() in Isaac Lab all use xyzw. Keeping this helper as a no-op preserves a single conversion point if conventions ever diverge again. """ @@ -631,13 +508,15 @@ def _read_poses_from_best_source(self) -> tuple[Any, Any, str, Any] | None: covered = self._covered_buf xform_mask = self._xform_mask_buf - # Apply sources in preferred order: rigid bodies, then USD fallback. rigid_count = self._apply_view_poses(self._rigid_body_view, "rigid_body_view", positions, orientations, covered) xform_count = self._apply_xform_poses(positions, orientations, covered, xform_mask) if rigid_count == 0: self._warn_once( "rigid-source-unused", - "[PhysxSceneDataProvider] RigidBodyView did not provide any body transforms; using fallback sources.", + ( + "[PhysxSceneDataProvider] RigidBodyView returned no transforms; " + "filled from XformPrimView where needed." + ), level=logging.DEBUG, ) @@ -660,18 +539,10 @@ def _get_set_body_q_kernel(self): """Return module-level Warp kernel for writing transforms to Newton state.""" return _set_body_q_kernel - def _get_set_body_q_subset_kernel(self): - """Return module-level Warp kernel for subset writes.""" - return _set_body_q_subset_kernel - # ---- Newton state sync ---------------------------------------------------------------- - def update(self, env_ids: list[int] | None = None) -> None: - """Sync PhysX transforms to Newton state for visualization. - - When env_ids is not None, only body indices belonging to those envs are written - (partial sync). When None, all bodies are synced. - """ + def update(self) -> None: + """Sync PhysX transforms into the full Newton state (one kernel launch).""" if not self._needs_newton_sync or self._newton_state is None: return @@ -689,41 +560,15 @@ def update(self, env_ids: list[int] | None = None) -> None: positions_wp = wp.from_torch(positions.reshape(-1, 3), dtype=wp.vec3) orientations_wp = wp.from_torch(orientations_xyzw, dtype=wp.quatf) - if env_ids is None or not env_ids or not self._env_id_to_body_indices: - # Fast path: full state sync in one kernel launch. - set_body_q = self._get_set_body_q_kernel() - if set_body_q is None or positions_wp.shape[0] != self._newton_state.body_q.shape[0]: - return - wp.launch( - set_body_q, - dim=positions_wp.shape[0], - inputs=[positions_wp, orientations_wp, self._newton_state.body_q], - device=self._device, - ) - else: - body_indices = [] - for eid in env_ids: - body_indices.extend(self._env_id_to_body_indices.get(eid, [])) - if not body_indices: - return - # Subset path: write only env-selected body indices. - subset_kernel = self._get_set_body_q_subset_kernel() - if subset_kernel is None: - return - import torch - - indices_t = torch.tensor(body_indices, dtype=torch.int32, device=self._device) - pos_subset = positions.reshape(-1, 3)[body_indices] - ori_subset = orientations_xyzw[body_indices] - indices_wp = wp.from_torch(indices_t, dtype=wp.int32) - pos_wp = wp.from_torch(pos_subset.contiguous(), dtype=wp.vec3) - ori_wp = wp.from_torch(ori_subset.contiguous(), dtype=wp.quatf) - wp.launch( - subset_kernel, - dim=len(body_indices), - inputs=[pos_wp, ori_wp, indices_wp, self._newton_state.body_q], - device=self._device, - ) + set_body_q = self._get_set_body_q_kernel() + if set_body_q is None or positions_wp.shape[0] != self._newton_state.body_q.shape[0]: + return + wp.launch( + set_body_q, + dim=positions_wp.shape[0], + inputs=[positions_wp, orientations_wp, self._newton_state.body_q], + device=self._device, + ) except Exception as exc: self._warn_once( "newton-sync-update-failed", @@ -739,97 +584,11 @@ def get_newton_model(self) -> Any | None: """ return self._newton_model if self._needs_newton_sync else None - def get_newton_model_for_env_ids(self, env_ids: list[int] | None) -> Any | None: - """Return Newton model for selected environments. - - Args: - env_ids: Optional environment ids. ``None`` returns full model. - - Returns: - Full or filtered Newton model, or ``None`` when unavailable. - """ - if not self._needs_newton_sync: - return None - if env_ids is None: - return self._newton_model - env_ids_key = tuple(sorted(env_ids)) - if self._filtered_newton_model is None or self._filtered_env_ids_key != env_ids_key: - self._filtered_env_ids_key = env_ids_key - self._build_filtered_newton_model(list(env_ids_key)) - return self._filtered_newton_model - - def get_newton_state(self, env_ids: list[int] | None = None) -> Any | None: - """Return Newton state when sync is enabled. - - If env_ids is None, returns the full state. If env_ids is provided, returns a - state-like object whose body_q contains only the bodies for those envs (same order - as in the full model, for use with e.g. max_worlds=len(env_ids)). - """ + def get_newton_state(self) -> Any | None: + """Return full Newton state when sync is enabled.""" if not self._needs_newton_sync or self._newton_state is None: return None - if env_ids is None: - return self._newton_state - if not self._env_id_to_body_indices: - return self._create_empty_subset_state() - env_ids_key = tuple(sorted(env_ids)) - if self._filtered_newton_model is not None and self._filtered_env_ids_key == env_ids_key: - if not self._filtered_body_indices: - return self._create_empty_subset_state() - try: - import warp as wp - - body_q_t = wp.to_torch(self._newton_state.body_q) - subset = body_q_t[self._filtered_body_indices].clone() - self._filtered_newton_state.body_q = wp.from_torch(subset, dtype=wp.transformf) - return self._filtered_newton_state - except Exception: - return self._newton_state - body_indices = [] - for eid in env_ids: - body_indices.extend(self._env_id_to_body_indices.get(eid, [])) - if not body_indices: - return self._create_empty_subset_state() - - body_q = self._newton_state.body_q - try: - import warp as wp - - body_q_t = wp.to_torch(body_q) - body_q_subset = body_q_t[body_indices].clone() - except Exception: - return self._newton_state - return self._create_subset_state(body_q_subset) - - def _create_empty_subset_state(self): - """Return a minimal state-like object with empty body_q.""" - if self._newton_state is None: - return None - try: - import warp as wp - - body_q_t = wp.to_torch(self._newton_state.body_q) - empty = body_q_t[:0].clone() - return self._create_subset_state(empty) - except Exception: - return self._newton_state - - # ---- Newton subset helpers ------------------------------------------------------------- - - def _create_subset_state(self, body_q_subset): - """Return a minimal state-like object for subset rendering.""" - import warp as wp - - if hasattr(body_q_subset, "device") and not isinstance(body_q_subset, wp.array): - body_q_subset = wp.from_torch(body_q_subset, dtype=wp.transformf) - - class _SubsetState: - """Minimal state carrier with ``body_q`` field for subset rendering.""" - - pass - - s = _SubsetState() - s.body_q = body_q_subset - return s + return self._newton_state # ---- Public provider API --------------------------------------------------------------- diff --git a/source/isaaclab_physx/isaaclab_physx/sensors/__init__.pyi b/source/isaaclab_physx/isaaclab_physx/sensors/__init__.pyi index 12cb14529852..e536b281952b 100644 --- a/source/isaaclab_physx/isaaclab_physx/sensors/__init__.pyi +++ b/source/isaaclab_physx/isaaclab_physx/sensors/__init__.pyi @@ -11,8 +11,14 @@ __all__ = [ "FrameTransformerData", "Imu", "ImuData", + "JointWrenchSensor", + "JointWrenchSensorData", + "Pva", + "PvaData", ] from .contact_sensor import ContactSensor, ContactSensorData, ContactSensorCfg from .frame_transformer import FrameTransformer, FrameTransformerData from .imu import Imu, ImuData +from .joint_wrench import JointWrenchSensor, JointWrenchSensorData +from .pva import Pva, PvaData diff --git a/source/isaaclab_physx/isaaclab_physx/sensors/contact_sensor/contact_sensor.py b/source/isaaclab_physx/isaaclab_physx/sensors/contact_sensor/contact_sensor.py index e4cd2e97429f..c38a0fffe281 100644 --- a/source/isaaclab_physx/isaaclab_physx/sensors/contact_sensor/contact_sensor.py +++ b/source/isaaclab_physx/isaaclab_physx/sensors/contact_sensor/contact_sensor.py @@ -14,12 +14,13 @@ import torch import warp as wp -import omni.physics.tensors.impl.api as physx +import omni.physics.tensors.api as physx import isaaclab.sim as sim_utils from isaaclab.app.settings_manager import get_settings_manager from isaaclab.markers import VisualizationMarkers from isaaclab.sensors.contact_sensor import BaseContactSensor +from isaaclab.utils.warp import ProxyArray from isaaclab_physx.physics import PhysxManager as SimulationManager @@ -65,7 +66,7 @@ class ContactSensor(BaseContactSensor): it against the object. .. _PhysX ContactReporter: https://docs.omniverse.nvidia.com/kit/docs/omni_usd_schema_physics/104.2/class_physx_schema_physx_contact_report_a_p_i.html - .. _RigidContact: https://docs.isaacsim.omniverse.nvidia.com/latest/py/source/extensions/isaacsim.core.api/docs/index.html#isaacsim.core.api.sensors.RigidContactView + .. _RigidContact: https://docs.isaacsim.omniverse.nvidia.com/latest/py/source/extensions/isaacsim.core.experimental.prims/docs/index.html """ cfg: ContactSensorCfg @@ -189,7 +190,7 @@ def reset(self, env_ids: Sequence[int] | None = None, env_mask: wp.array | None device=self._device, ) - def compute_first_contact(self, dt: float, abs_tol: float = 1.0e-8) -> wp.array: + def compute_first_contact(self, dt: float, abs_tol: float = 1.0e-8) -> ProxyArray: """Checks if bodies that have established contact within the last :attr:`dt` seconds. This function checks if the bodies have established contact within the last :attr:`dt` seconds @@ -232,9 +233,9 @@ def compute_first_contact(self, dt: float, abs_tol: float = 1.0e-8) -> wp.array: outputs=[self._data._first_transition], device=self._device, ) - return self._data._first_transition + return self._data._first_transition_ta - def compute_first_air(self, dt: float, abs_tol: float = 1.0e-8) -> wp.array: + def compute_first_air(self, dt: float, abs_tol: float = 1.0e-8) -> ProxyArray: """Checks if bodies that have broken contact within the last :attr:`dt` seconds. This function checks if the bodies have broken contact within the last :attr:`dt` seconds @@ -277,7 +278,7 @@ def compute_first_air(self, dt: float, abs_tol: float = 1.0e-8) -> wp.array: outputs=[self._data._first_transition], device=self._device, ) - return self._data._first_transition + return self._data._first_transition_ta """ Implementation. @@ -478,13 +479,13 @@ def _debug_vis_callback(self, event): if self.body_physx_view is None: return # Convert warp data to torch at the boundary for visualization - net_forces_torch = wp.to_torch(self._data._net_forces_w) # (N, B, 3) + net_forces_torch = self._data.net_forces_w.torch # (N, B, 3) net_contact_force_w = torch.linalg.norm(net_forces_torch, dim=-1) # marker indices: 0 = contact, 1 = no contact marker_indices = torch.where(net_contact_force_w > self.cfg.force_threshold, 0, 1) # check if prim is visualized if self.cfg.track_pose: - frame_origins = wp.to_torch(self._data._pos_w) # (N, B, 3) + frame_origins = self._data.pos_w.torch # (N, B, 3) else: pose = self.body_physx_view.get_transforms() # (N*B, 7) float32 pose_torch = wp.to_torch(pose) diff --git a/source/isaaclab_physx/isaaclab_physx/sensors/contact_sensor/contact_sensor_data.py b/source/isaaclab_physx/isaaclab_physx/sensors/contact_sensor/contact_sensor_data.py index 93f12c33918b..5e50c42da7ef 100644 --- a/source/isaaclab_physx/isaaclab_physx/sensors/contact_sensor/contact_sensor_data.py +++ b/source/isaaclab_physx/isaaclab_physx/sensors/contact_sensor/contact_sensor_data.py @@ -11,6 +11,7 @@ import warp as wp from isaaclab.sensors.contact_sensor import BaseContactSensorData +from isaaclab.utils.warp import ProxyArray from isaaclab_physx.sensors.kernels import concat_pos_and_quat_to_pose_kernel @@ -21,11 +22,13 @@ class ContactSensorData(BaseContactSensorData): """Data container for the PhysX contact reporting sensor.""" @property - def pose_w(self) -> wp.array | None: + def pose_w(self) -> ProxyArray | None: """Pose of the sensor origin in world frame. None if :attr:`ContactSensorCfg.track_pose` is False. """ + if self._pose_w is None: + return None wp.launch( concat_pos_and_quat_to_pose_kernel, dim=(self._num_envs, self._num_sensors), @@ -33,10 +36,12 @@ def pose_w(self) -> wp.array | None: outputs=[self._pose_w], device=self._device, ) - return self._pose_w + if self._pose_w_ta is None: + self._pose_w_ta = ProxyArray(self._pose_w) + return self._pose_w_ta @property - def pos_w(self) -> wp.array | None: + def pos_w(self) -> ProxyArray | None: """Position of the sensor origin in world frame. Shape is (num_instances, num_sensors), dtype = wp.vec3f. In torch this resolves to @@ -44,10 +49,14 @@ def pos_w(self) -> wp.array | None: None if :attr:`ContactSensorCfg.track_pose` is False. """ - return self._pos_w + if self._pos_w is None: + return None + if self._pos_w_ta is None: + self._pos_w_ta = ProxyArray(self._pos_w) + return self._pos_w_ta @property - def quat_w(self) -> wp.array | None: + def quat_w(self) -> ProxyArray | None: """Orientation of the sensor origin in world frame. Shape is (num_instances, num_sensors), dtype = wp.quatf. In torch this resolves to @@ -55,28 +64,40 @@ def quat_w(self) -> wp.array | None: None if :attr:`ContactSensorCfg.track_pose` is False. """ - return self._quat_w + if self._quat_w is None: + return None + if self._quat_w_ta is None: + self._quat_w_ta = ProxyArray(self._quat_w) + return self._quat_w_ta @property - def net_forces_w(self) -> wp.array | None: + def net_forces_w(self) -> ProxyArray | None: """The net normal contact forces in world frame. Shape is (num_instances, num_sensors), dtype = wp.vec3f. In torch this resolves to (num_instances, num_sensors, 3). """ - return self._net_forces_w + if self._net_forces_w is None: + return None + if self._net_forces_w_ta is None: + self._net_forces_w_ta = ProxyArray(self._net_forces_w) + return self._net_forces_w_ta @property - def net_forces_w_history(self) -> wp.array | None: + def net_forces_w_history(self) -> ProxyArray | None: """History of net normal contact forces. Shape is (num_instances, history_length, num_sensors), dtype = wp.vec3f. In torch this resolves to (num_instances, history_length, num_sensors, 3). """ - return self._net_forces_w_history + if self._net_forces_w_history is None: + return None + if self._net_forces_w_history_ta is None: + self._net_forces_w_history_ta = ProxyArray(self._net_forces_w_history) + return self._net_forces_w_history_ta @property - def force_matrix_w(self) -> wp.array | None: + def force_matrix_w(self) -> ProxyArray | None: """Normal contact forces filtered between sensor and filtered bodies. Shape is (num_instances, num_sensors, num_filter_shapes), dtype = wp.vec3f. In torch this resolves to @@ -84,10 +105,14 @@ def force_matrix_w(self) -> wp.array | None: None if :attr:`ContactSensorCfg.filter_prim_paths_expr` is empty. """ - return self._force_matrix_w + if self._force_matrix_w is None: + return None + if self._force_matrix_w_ta is None: + self._force_matrix_w_ta = ProxyArray(self._force_matrix_w) + return self._force_matrix_w_ta @property - def force_matrix_w_history(self) -> wp.array | None: + def force_matrix_w_history(self) -> ProxyArray | None: """History of filtered contact forces. Shape is (num_instances, history_length, num_sensors, num_filter_shapes), dtype = wp.vec3f. @@ -95,10 +120,14 @@ def force_matrix_w_history(self) -> wp.array | None: None if :attr:`ContactSensorCfg.filter_prim_paths_expr` is empty. """ - return self._force_matrix_w_history + if self._force_matrix_w_history is None: + return None + if self._force_matrix_w_history_ta is None: + self._force_matrix_w_history_ta = ProxyArray(self._force_matrix_w_history) + return self._force_matrix_w_history_ta @property - def contact_pos_w(self) -> wp.array | None: + def contact_pos_w(self) -> ProxyArray | None: """Average position of contact points. Shape is (num_instances, num_sensors, num_filter_shapes), dtype = wp.vec3f. In torch this resolves to @@ -106,10 +135,14 @@ def contact_pos_w(self) -> wp.array | None: None if :attr:`ContactSensorCfg.track_contact_points` is False. """ - return self._contact_pos_w + if self._contact_pos_w is None: + return None + if self._contact_pos_w_ta is None: + self._contact_pos_w_ta = ProxyArray(self._contact_pos_w) + return self._contact_pos_w_ta @property - def friction_forces_w(self) -> wp.array | None: + def friction_forces_w(self) -> ProxyArray | None: """Sum of friction forces. Shape is (num_instances, num_sensors, num_filter_shapes), dtype = wp.vec3f. In torch this resolves to @@ -117,47 +150,67 @@ def friction_forces_w(self) -> wp.array | None: None if :attr:`ContactSensorCfg.track_friction_forces` is False. """ - return self._friction_forces_w + if self._friction_forces_w is None: + return None + if self._friction_forces_w_ta is None: + self._friction_forces_w_ta = ProxyArray(self._friction_forces_w) + return self._friction_forces_w_ta @property - def last_air_time(self) -> wp.array | None: + def last_air_time(self) -> ProxyArray | None: """Time spent in air before last contact. Shape is (num_instances, num_sensors), dtype = wp.float32. None if :attr:`ContactSensorCfg.track_air_time` is False. """ - return self._last_air_time + if self._last_air_time is None: + return None + if self._last_air_time_ta is None: + self._last_air_time_ta = ProxyArray(self._last_air_time) + return self._last_air_time_ta @property - def current_air_time(self) -> wp.array | None: + def current_air_time(self) -> ProxyArray | None: """Time spent in air since last detach. Shape is (num_instances, num_sensors), dtype = wp.float32. None if :attr:`ContactSensorCfg.track_air_time` is False. """ - return self._current_air_time + if self._current_air_time is None: + return None + if self._current_air_time_ta is None: + self._current_air_time_ta = ProxyArray(self._current_air_time) + return self._current_air_time_ta @property - def last_contact_time(self) -> wp.array | None: + def last_contact_time(self) -> ProxyArray | None: """Time spent in contact before last detach. Shape is (num_instances, num_sensors), dtype = wp.float32. None if :attr:`ContactSensorCfg.track_air_time` is False. """ - return self._last_contact_time + if self._last_contact_time is None: + return None + if self._last_contact_time_ta is None: + self._last_contact_time_ta = ProxyArray(self._last_contact_time) + return self._last_contact_time_ta @property - def current_contact_time(self) -> wp.array | None: + def current_contact_time(self) -> ProxyArray | None: """Time spent in contact since last contact. Shape is (num_instances, num_sensors), dtype = wp.float32. None if :attr:`ContactSensorCfg.track_air_time` is False. """ - return self._current_contact_time + if self._current_contact_time is None: + return None + if self._current_contact_time_ta is None: + self._current_contact_time_ta = ProxyArray(self._current_contact_time) + return self._current_contact_time_ta def create_buffers( self, @@ -221,12 +274,14 @@ def create_buffers( self._last_contact_time = wp.zeros((num_envs, num_sensors), dtype=wp.float32, device=device) self._current_contact_time = wp.zeros((num_envs, num_sensors), dtype=wp.float32, device=device) self._first_transition = wp.zeros((num_envs, num_sensors), dtype=wp.float32, device=device) + self._first_transition_ta = ProxyArray(self._first_transition) else: self._last_air_time = None self._current_air_time = None self._last_contact_time = None self._current_contact_time = None self._first_transition = None + self._first_transition_ta = None # Track contact points if requested - filled with NaN if track_contact_points: @@ -246,3 +301,18 @@ def create_buffers( ) else: self._friction_forces_w = None + + # -- Pinned ProxyArray cache (one per read property, lazily created on first access) + self._pose_w_ta: ProxyArray | None = None + self._pos_w_ta: ProxyArray | None = None + self._quat_w_ta: ProxyArray | None = None + self._net_forces_w_ta: ProxyArray | None = None + self._net_forces_w_history_ta: ProxyArray | None = None + self._force_matrix_w_ta: ProxyArray | None = None + self._force_matrix_w_history_ta: ProxyArray | None = None + self._contact_pos_w_ta: ProxyArray | None = None + self._friction_forces_w_ta: ProxyArray | None = None + self._last_air_time_ta: ProxyArray | None = None + self._current_air_time_ta: ProxyArray | None = None + self._last_contact_time_ta: ProxyArray | None = None + self._current_contact_time_ta: ProxyArray | None = None diff --git a/source/isaaclab_physx/isaaclab_physx/sensors/frame_transformer/frame_transformer_data.py b/source/isaaclab_physx/isaaclab_physx/sensors/frame_transformer/frame_transformer_data.py index f73c00bbfaf2..7f7c0a837b2f 100644 --- a/source/isaaclab_physx/isaaclab_physx/sensors/frame_transformer/frame_transformer_data.py +++ b/source/isaaclab_physx/isaaclab_physx/sensors/frame_transformer/frame_transformer_data.py @@ -8,6 +8,7 @@ import warp as wp from isaaclab.sensors.frame_transformer import BaseFrameTransformerData +from isaaclab.utils.warp import ProxyArray from isaaclab_physx.sensors.kernels import concat_pos_and_quat_to_pose_1d_kernel, concat_pos_and_quat_to_pose_kernel @@ -21,7 +22,7 @@ def target_frame_names(self) -> list[str]: return self._target_frame_names @property - def target_pose_source(self) -> wp.array: + def target_pose_source(self) -> ProxyArray: """Pose of target frame(s) relative to source frame. Shape is (num_instances, num_target_frames), dtype = wp.transformf. In torch this resolves to @@ -34,28 +35,34 @@ def target_pose_source(self) -> wp.array: outputs=[self._target_pose_source], device=self._device, ) - return self._target_pose_source + if self._target_pose_source_ta is None: + self._target_pose_source_ta = ProxyArray(self._target_pose_source) + return self._target_pose_source_ta @property - def target_pos_source(self) -> wp.array: + def target_pos_source(self) -> ProxyArray: """Position of target frame(s) relative to source frame. Shape is (num_instances, num_target_frames), dtype = wp.vec3f. In torch this resolves to (num_instances, num_target_frames, 3). """ - return self._target_pos_source + if self._target_pos_source_ta is None: + self._target_pos_source_ta = ProxyArray(self._target_pos_source) + return self._target_pos_source_ta @property - def target_quat_source(self) -> wp.array: + def target_quat_source(self) -> ProxyArray: """Orientation of target frame(s) relative to source frame. Shape is (num_instances, num_target_frames), dtype = wp.quatf. In torch this resolves to (num_instances, num_target_frames, 4). The orientation is provided in (x, y, z, w) format. """ - return self._target_quat_source + if self._target_quat_source_ta is None: + self._target_quat_source_ta = ProxyArray(self._target_quat_source) + return self._target_quat_source_ta @property - def target_pose_w(self) -> wp.array: + def target_pose_w(self) -> ProxyArray: """Pose of target frame(s) after offset in world frame. Shape is (num_instances, num_target_frames), dtype = wp.transformf. In torch this resolves to @@ -68,28 +75,34 @@ def target_pose_w(self) -> wp.array: outputs=[self._target_pose_w], device=self._device, ) - return self._target_pose_w + if self._target_pose_w_ta is None: + self._target_pose_w_ta = ProxyArray(self._target_pose_w) + return self._target_pose_w_ta @property - def target_pos_w(self) -> wp.array: + def target_pos_w(self) -> ProxyArray: """Position of target frame(s) after offset in world frame. Shape is (num_instances, num_target_frames), dtype = wp.vec3f. In torch this resolves to (num_instances, num_target_frames, 3). """ - return self._target_pos_w + if self._target_pos_w_ta is None: + self._target_pos_w_ta = ProxyArray(self._target_pos_w) + return self._target_pos_w_ta @property - def target_quat_w(self) -> wp.array: + def target_quat_w(self) -> ProxyArray: """Orientation of target frame(s) after offset in world frame. Shape is (num_instances, num_target_frames), dtype = wp.quatf. In torch this resolves to (num_instances, num_target_frames, 4). The orientation is provided in (x, y, z, w) format. """ - return self._target_quat_w + if self._target_quat_w_ta is None: + self._target_quat_w_ta = ProxyArray(self._target_quat_w) + return self._target_quat_w_ta @property - def source_pose_w(self) -> wp.array: + def source_pose_w(self) -> ProxyArray: """Pose of source frame after offset in world frame. Shape is (num_instances,), dtype = wp.transformf. In torch this resolves to (num_instances, 7). @@ -102,24 +115,30 @@ def source_pose_w(self) -> wp.array: outputs=[self._source_pose_w], device=self._device, ) - return self._source_pose_w + if self._source_pose_w_ta is None: + self._source_pose_w_ta = ProxyArray(self._source_pose_w) + return self._source_pose_w_ta @property - def source_pos_w(self) -> wp.array: + def source_pos_w(self) -> ProxyArray: """Position of source frame after offset in world frame. Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). """ - return self._source_pos_w + if self._source_pos_w_ta is None: + self._source_pos_w_ta = ProxyArray(self._source_pos_w) + return self._source_pos_w_ta @property - def source_quat_w(self) -> wp.array: + def source_quat_w(self) -> ProxyArray: """Orientation of source frame after offset in world frame. Shape is (num_instances,), dtype = wp.quatf. In torch this resolves to (num_instances, 4). The orientation is provided in (x, y, z, w) format. """ - return self._source_quat_w + if self._source_quat_w_ta is None: + self._source_quat_w_ta = ProxyArray(self._source_quat_w) + return self._source_quat_w_ta def create_buffers( self, @@ -155,3 +174,14 @@ def create_buffers( wp.to_torch(self._source_quat_w)[:, 3] = 1.0 wp.to_torch(self._target_quat_w)[:, :, 3] = 1.0 wp.to_torch(self._target_quat_source)[:, :, 3] = 1.0 + + # -- Pinned ProxyArray cache (one per read property, lazily created on first access) + self._target_pose_source_ta: ProxyArray | None = None + self._target_pos_source_ta: ProxyArray | None = None + self._target_quat_source_ta: ProxyArray | None = None + self._target_pose_w_ta: ProxyArray | None = None + self._target_pos_w_ta: ProxyArray | None = None + self._target_quat_w_ta: ProxyArray | None = None + self._source_pose_w_ta: ProxyArray | None = None + self._source_pos_w_ta: ProxyArray | None = None + self._source_quat_w_ta: ProxyArray | None = None diff --git a/source/isaaclab_physx/isaaclab_physx/sensors/imu/imu.py b/source/isaaclab_physx/isaaclab_physx/sensors/imu/imu.py index 11e2faba4df4..50c173103492 100644 --- a/source/isaaclab_physx/isaaclab_physx/sensors/imu/imu.py +++ b/source/isaaclab_physx/isaaclab_physx/sensors/imu/imu.py @@ -11,11 +11,10 @@ import torch import warp as wp -from pxr import UsdGeom, UsdPhysics +from pxr import UsdPhysics import isaaclab.sim as sim_utils import isaaclab.utils.math as math_utils -from isaaclab.markers import VisualizationMarkers from isaaclab.sensors.imu import BaseImu from isaaclab_physx.physics import PhysxManager as SimulationManager @@ -28,32 +27,27 @@ class Imu(BaseImu): - """The PhysX Inertia Measurement Unit (IMU) sensor. + """The PhysX Inertial Measurement Unit (IMU) sensor. - The sensor can be attached to any prim path with a rigid ancestor in its tree and produces body-frame - linear acceleration and angular velocity, along with world-frame pose and body-frame linear and angular - accelerations/velocities. + This sensor models a real IMU that measures angular velocity (gyroscope) and + linear acceleration (accelerometer) in the sensor's body frame. Unlike the PVA + sensor, it does not provide pose, linear velocity, angular acceleration, or + projected gravity. - If the provided path is not a rigid body, the closest rigid-body ancestor is used for simulation queries. - The fixed transform from that ancestor to the target prim is computed once during initialization and - composed with the configured sensor offset. + Like a real accelerometer, the linear acceleration readings always include the + contribution of gravity. The gravity vector is queried from the simulation at + initialization. - .. note:: - - We are computing the accelerations using numerical differentiation from the velocities. Consequently, the - IMU sensor accuracy depends on the chosen physx timestep. For a sufficient accuracy, we recommend to keep the - timestep at least as 200Hz. + The sensor can be attached to any prim path with a rigid ancestor in its tree. + If the provided path is not a rigid body, the closest rigid-body ancestor is used + for simulation queries. The fixed transform from that ancestor to the target prim + is computed once during initialization and composed with the configured sensor offset. .. note:: - The user can configure the sensor offset in the configuration file. The offset is applied relative to the - rigid source prim. If the target prim is not a rigid body, the offset is composed with the fixed transform - from the rigid ancestor to the target prim. The offset is applied in the body frame of the rigid source prim. - The offset is defined as a position vector and a quaternion rotation, which - are applied in the order: position, then rotation. The position is applied as a translation - in the body frame of the rigid source prim, and the rotation is applied as a rotation - in the body frame of the rigid source prim. - + Linear acceleration is computed using numerical differentiation from velocities. + Consequently, the IMU sensor accuracy depends on the chosen physics timestep. + For sufficient accuracy, we recommend keeping the timestep at least 200 Hz. """ cfg: ImuCfg @@ -63,17 +57,13 @@ class Imu(BaseImu): """The name of the backend for the IMU sensor.""" def __init__(self, cfg: ImuCfg): - """Initializes the Imu sensor. + """Initializes the IMU sensor. Args: cfg: The configuration parameters. """ - # initialize base class super().__init__(cfg) - # Create empty variables for storing output data self._data = ImuData() - - # Internal: expression used to build the rigid body view (may be different from cfg.prim_path) self._rigid_parent_expr: str | None = None def __str__(self) -> str: @@ -91,9 +81,7 @@ def __str__(self) -> str: @property def data(self) -> ImuData: - # update sensors if needed self._update_outdated_buffers() - # return the data return self._data @property @@ -105,9 +93,7 @@ def num_instances(self) -> int: """ def reset(self, env_ids: Sequence[int] | None = None, env_mask: wp.array | None = None): - # resolve indices and mask env_mask = self._resolve_indices_and_mask(env_ids, env_mask) - # reset the timestamps super().reset(None, env_mask) wp.launch( @@ -115,23 +101,15 @@ def reset(self, env_ids: Sequence[int] | None = None, env_mask: wp.array | None dim=self._num_envs, inputs=[ env_mask, - self._data._pos_w, - self._data._quat_w, - self._data._lin_vel_b, self._data._ang_vel_b, self._data._lin_acc_b, - self._data._ang_acc_b, - self._data._projected_gravity_b, self._prev_lin_vel_w, - self._prev_ang_vel_w, ], device=self._device, ) def update(self, dt: float, force_recompute: bool = False): - # save timestamp self._dt = dt - # execute updating super().update(dt, force_recompute) """ @@ -145,51 +123,38 @@ def _initialize_impl(self): - Otherwise find the closest rigid-body ancestor, cache the fixed transform from that ancestor to the target prim, and build the view on the ancestor expression. """ - # Initialize parent class super()._initialize_impl() - # obtain global simulation view self._physics_sim_view = SimulationManager.get_physics_sim_view() - # check if the prim at path is a rigid prim prim = sim_utils.find_first_matching_prim(self.cfg.prim_path) if prim is None: raise RuntimeError(f"Failed to find a prim at path expression: {self.cfg.prim_path}") - # Find the first matching ancestor prim that implements rigid body API ancestor_prim = sim_utils.get_first_matching_ancestor_prim( prim.GetPath(), predicate=lambda _prim: _prim.HasAPI(UsdPhysics.RigidBodyAPI) ) if ancestor_prim is None: raise RuntimeError(f"Failed to find a rigid body ancestor prim at path expression: {self.cfg.prim_path}") - # Convert ancestor prim path to expression + if ancestor_prim == prim: self._rigid_parent_expr = self.cfg.prim_path fixed_pos_b, fixed_quat_b = None, None else: - # Convert ancestor prim path to expression by stripping the relative - # suffix (including its leading '/') so no trailing '/' remains. relative_path = prim.GetPath().MakeRelativePath(ancestor_prim.GetPath()).pathString self._rigid_parent_expr = self.cfg.prim_path.replace("/" + relative_path, "") - # Resolve the relative pose between the target prim and the ancestor prim fixed_pos_b, fixed_quat_b = sim_utils.resolve_prim_pose(prim, ancestor_prim) - # Create the rigid body view on the ancestor self._view = self._physics_sim_view.create_rigid_body_view(self._rigid_parent_expr.replace(".*", "*")) - # Get world gravity + # Query world gravity and compute accelerometer bias (real IMUs always measure gravity) gravity = self._physics_sim_view.get_gravity() - gravity_dir = torch.tensor((gravity[0], gravity[1], gravity[2]), device=self.device) - gravity_dir = math_utils.normalize(gravity_dir.unsqueeze(0)).squeeze(0) - gravity_dir_repeated = gravity_dir.repeat(self.num_instances, 1) - self.GRAVITY_VEC_W = wp.from_torch(gravity_dir_repeated.contiguous(), dtype=wp.vec3f) + gravity_bias = torch.tensor((-gravity[0], -gravity[1], -gravity[2]), device=self._device) + gravity_bias_torch = gravity_bias.repeat(self._view.count, 1) + self._gravity_bias_w = wp.from_torch(gravity_bias_torch.contiguous(), dtype=wp.vec3f) - # Create internal buffers self._initialize_buffers_impl() # Compose the configured offset with the fixed ancestor->target transform (done once) - # new_offset = fixed * cfg.offset - # where composition is: p = p_fixed + R_fixed * p_cfg, q = q_fixed * q_cfg if fixed_pos_b is not None and fixed_quat_b is not None: - # Broadcast fixed transform across instances fixed_p = torch.tensor(fixed_pos_b, device=self._device).repeat(self._view.count, 1) fixed_q = torch.tensor(fixed_quat_b, device=self._device).repeat(self._view.count, 1) @@ -206,10 +171,8 @@ def _update_buffers_impl(self, env_mask: wp.array | None = None): """Fills the buffers of the sensor data.""" env_mask = self._resolve_indices_and_mask(None, env_mask) - # Fetch view data as warp typed arrays transforms = self._view.get_transforms().view(wp.transformf) velocities = self._view.get_velocities().view(wp.spatial_vectorf) - # get_coms() returns a CPU warp array; copy to pre-allocated GPU buffer wp.copy(self._coms_buffer, self._view.get_coms().view(wp.transformf)) wp.launch( @@ -223,85 +186,23 @@ def _update_buffers_impl(self, env_mask: wp.array | None = None): self._offset_pos_b, self._offset_quat_b, self._gravity_bias_w, - self.GRAVITY_VEC_W, self._prev_lin_vel_w, - self._prev_ang_vel_w, 1.0 / self._dt, - self._data._pos_w, - self._data._quat_w, - self._data._lin_vel_b, self._data._ang_vel_b, self._data._lin_acc_b, - self._data._ang_acc_b, - self._data._projected_gravity_b, ], device=self._device, ) def _initialize_buffers_impl(self): """Create buffers for storing data.""" - # Create data buffers via data class self._data.create_buffers(num_envs=self._view.count, device=self._device) - # Sensor-internal buffers for velocity tracking (not exposed via data) self._prev_lin_vel_w = wp.zeros(self._view.count, dtype=wp.vec3f, device=self._device) - self._prev_ang_vel_w = wp.zeros(self._view.count, dtype=wp.vec3f, device=self._device) - # Store sensor offset (applied relative to rigid source). - # This may be composed later with a fixed ancestor->target transform. offset_pos_torch = torch.tensor(list(self.cfg.offset.pos), device=self._device).repeat(self._view.count, 1) offset_quat_torch = torch.tensor(list(self.cfg.offset.rot), device=self._device).repeat(self._view.count, 1) self._offset_pos_b = wp.from_torch(offset_pos_torch.contiguous(), dtype=wp.vec3f) self._offset_quat_b = wp.from_torch(offset_quat_torch.contiguous(), dtype=wp.quatf) - # Set gravity bias - gravity_bias_torch = torch.tensor(list(self.cfg.gravity_bias), device=self._device).repeat(self._view.count, 1) - self._gravity_bias_w = wp.from_torch(gravity_bias_torch.contiguous(), dtype=wp.vec3f) - - # Pre-allocate GPU buffer for COMs (get_coms() returns CPU array) self._coms_buffer = wp.zeros(self._view.count, dtype=wp.transformf, device=self._device) - - def _set_debug_vis_impl(self, debug_vis: bool): - # set visibility of markers - # note: parent only deals with callbacks. not their visibility - if debug_vis: - # create markers if necessary for the first time - if not hasattr(self, "acceleration_visualizer"): - self.acceleration_visualizer = VisualizationMarkers(self.cfg.visualizer_cfg) - # set their visibility to true - self.acceleration_visualizer.set_visibility(True) - else: - if hasattr(self, "acceleration_visualizer"): - self.acceleration_visualizer.set_visibility(False) - - def _debug_vis_callback(self, event): - # safely return if view becomes invalid - # note: this invalidity happens because of isaac sim view callbacks - if self._view is None: - return - # get marker location - # -- base state (convert warp -> torch for visualization) - base_pos_w = wp.to_torch(self._data.pos_w).clone() - base_pos_w[:, 2] += 0.5 - # -- resolve the scales - default_scale = self.acceleration_visualizer.cfg.markers["arrow"].scale - arrow_scale = torch.tensor(default_scale, device=self.device).repeat( - wp.to_torch(self._data.lin_acc_b).shape[0], 1 - ) - # get up axis of current stage - up_axis = UsdGeom.GetStageUpAxis(self.stage) - # arrow-direction - pos_w_torch = wp.to_torch(self._data.pos_w) - quat_w_torch = wp.to_torch(self._data.quat_w) - lin_acc_b_torch = wp.to_torch(self._data.lin_acc_b) - quat_opengl = math_utils.quat_from_matrix( - math_utils.create_rotation_matrix_from_view( - pos_w_torch, - pos_w_torch + math_utils.quat_apply(quat_w_torch, lin_acc_b_torch), - up_axis=up_axis, - device=self._device, - ) - ) - quat_w = math_utils.convert_camera_frame_orientation_convention(quat_opengl, "opengl", "world") - # display markers - self.acceleration_visualizer.visualize(base_pos_w, quat_w, arrow_scale) diff --git a/source/isaaclab_physx/isaaclab_physx/sensors/imu/imu_data.py b/source/isaaclab_physx/isaaclab_physx/sensors/imu/imu_data.py index 449e37591e12..7251111c3eb5 100644 --- a/source/isaaclab_physx/isaaclab_physx/sensors/imu/imu_data.py +++ b/source/isaaclab_physx/isaaclab_physx/sensors/imu/imu_data.py @@ -5,92 +5,36 @@ from __future__ import annotations -import logging - import warp as wp from isaaclab.sensors.imu import BaseImuData - -from isaaclab_physx.sensors.kernels import concat_pos_and_quat_to_pose_1d_kernel - -logger = logging.getLogger(__name__) +from isaaclab.utils.warp import ProxyArray class ImuData(BaseImuData): - """Data container for the PhysX Imu sensor.""" - - @property - def pose_w(self) -> wp.array: - """Pose of the sensor origin in world frame. - - Shape is (num_instances,), dtype = wp.transformf. In torch this resolves to (num_instances, 7). - The pose is provided in (x, y, z, qx, qy, qz, qw) format. - """ - wp.launch( - concat_pos_and_quat_to_pose_1d_kernel, - dim=self._num_envs, - inputs=[self._pos_w, self._quat_w], - outputs=[self._pose_w], - device=self._device, - ) - return self._pose_w + """Data container for the PhysX IMU sensor.""" @property - def pos_w(self) -> wp.array: - """Position of the sensor origin in world frame. + def ang_vel_b(self) -> ProxyArray: + """IMU frame angular velocity relative to the world expressed in IMU frame [rad/s]. Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). """ - return self._pos_w - - @property - def quat_w(self) -> wp.array: - """Orientation of the sensor origin in world frame. - - Shape is (num_instances,), dtype = wp.quatf. In torch this resolves to (num_instances, 4). - The orientation is provided in (x, y, z, w) format. - """ - return self._quat_w + if self._ang_vel_b_ta is None: + self._ang_vel_b_ta = ProxyArray(self._ang_vel_b) + return self._ang_vel_b_ta @property - def projected_gravity_b(self) -> wp.array: - """Gravity direction unit vector projected on the IMU frame. - - Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). - """ - return self._projected_gravity_b + def lin_acc_b(self) -> ProxyArray: + """Linear acceleration (proper) in the IMU frame [m/s^2]. - @property - def lin_vel_b(self) -> wp.array: - """IMU frame linear velocity relative to the world expressed in IMU frame. + Zero in freefall, +g upward at rest. Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). """ - return self._lin_vel_b - - @property - def ang_vel_b(self) -> wp.array: - """IMU frame angular velocity relative to the world expressed in IMU frame. - - Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). - """ - return self._ang_vel_b - - @property - def lin_acc_b(self) -> wp.array: - """IMU frame linear acceleration relative to the world expressed in IMU frame. - - Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). - """ - return self._lin_acc_b - - @property - def ang_acc_b(self) -> wp.array: - """IMU frame angular acceleration relative to the world expressed in IMU frame. - - Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). - """ - return self._ang_acc_b + if self._lin_acc_b_ta is None: + self._lin_acc_b_ta = ProxyArray(self._lin_acc_b) + return self._lin_acc_b_ta def create_buffers(self, num_envs: int, device: str) -> None: """Create internal buffers for sensor data. @@ -101,18 +45,9 @@ def create_buffers(self, num_envs: int, device: str) -> None: """ self._num_envs = num_envs self._device = device - self._pose_w = wp.zeros(num_envs, dtype=wp.transformf, device=device) - self._pos_w = wp.zeros(num_envs, dtype=wp.vec3f, device=device) - self._quat_w = wp.zeros(num_envs, dtype=wp.quatf, device=device) - # Initialize quaternion to identity (w=1): warp quatf is (x,y,z,w) - # Use torch interop to set the w component - quat_torch = wp.to_torch(self._quat_w) - quat_torch[:, 3] = 1.0 - self._projected_gravity_b = wp.zeros(num_envs, dtype=wp.vec3f, device=device) - # Initialize projected gravity to (0, 0, -1) - pg_torch = wp.to_torch(self._projected_gravity_b) - pg_torch[:, 2] = -1.0 - self._lin_vel_b = wp.zeros(num_envs, dtype=wp.vec3f, device=device) self._ang_vel_b = wp.zeros(num_envs, dtype=wp.vec3f, device=device) self._lin_acc_b = wp.zeros(num_envs, dtype=wp.vec3f, device=device) - self._ang_acc_b = wp.zeros(num_envs, dtype=wp.vec3f, device=device) + + # -- Pinned ProxyArray cache (one per read property, lazily created on first access) + self._ang_vel_b_ta: ProxyArray | None = None + self._lin_acc_b_ta: ProxyArray | None = None diff --git a/source/isaaclab_physx/isaaclab_physx/sensors/imu/kernels.py b/source/isaaclab_physx/isaaclab_physx/sensors/imu/kernels.py index 8e0fd5c18996..b22912ec0faa 100644 --- a/source/isaaclab_physx/isaaclab_physx/sensors/imu/kernels.py +++ b/source/isaaclab_physx/isaaclab_physx/sensors/imu/kernels.py @@ -18,31 +18,22 @@ def imu_update_kernel( offset_pos_b: wp.array(dtype=wp.vec3f), offset_quat_b: wp.array(dtype=wp.quatf), gravity_bias_w: wp.array(dtype=wp.vec3f), - gravity_vec_w: wp.array(dtype=wp.vec3f), # previous velocities (read + write) prev_lin_vel_w: wp.array(dtype=wp.vec3f), - prev_ang_vel_w: wp.array(dtype=wp.vec3f), # scalar inv_dt: wp.float32, # outputs (written in-place) - out_pos_w: wp.array(dtype=wp.vec3f), - out_quat_w: wp.array(dtype=wp.quatf), - out_lin_vel_b: wp.array(dtype=wp.vec3f), out_ang_vel_b: wp.array(dtype=wp.vec3f), out_lin_acc_b: wp.array(dtype=wp.vec3f), - out_ang_acc_b: wp.array(dtype=wp.vec3f), - out_projected_gravity_b: wp.array(dtype=wp.vec3f), ): idx = wp.tid() if not env_mask[idx]: return - # 1. Extract body pose - body_pos = wp.transform_get_translation(transforms[idx]) + # 1. Extract body orientation body_quat = wp.transform_get_rotation(transforms[idx]) - # 2. Apply sensor offset - sensor_pos = body_pos + wp.quat_rotate(body_quat, offset_pos_b[idx]) + # 2. Apply sensor offset to get sensor orientation sensor_quat = body_quat * offset_quat_b[idx] # 3. Extract lin/ang velocity @@ -54,54 +45,32 @@ def imu_update_kernel( lever_arm = wp.quat_rotate(body_quat, offset_pos_b[idx] - com_pos_b) lin_vel_w = lin_vel_w + wp.cross(ang_vel_w, lever_arm) - # 5. Numerical differentiation (world frame) + # 5. Numerical differentiation for linear acceleration (world frame) lin_acc_w = (lin_vel_w - prev_lin_vel_w[idx]) * inv_dt + gravity_bias_w[idx] - ang_acc_w = (ang_vel_w - prev_ang_vel_w[idx]) * inv_dt # 6. Rotate world -> body using sensor orientation - lin_vel_b = wp.quat_rotate_inv(sensor_quat, lin_vel_w) ang_vel_b = wp.quat_rotate_inv(sensor_quat, ang_vel_w) lin_acc_b = wp.quat_rotate_inv(sensor_quat, lin_acc_w) - ang_acc_b = wp.quat_rotate_inv(sensor_quat, ang_acc_w) - projected_gravity_b = wp.quat_rotate_inv(sensor_quat, gravity_vec_w[idx]) # 7. Store results - out_pos_w[idx] = sensor_pos - out_quat_w[idx] = sensor_quat - out_lin_vel_b[idx] = lin_vel_b out_ang_vel_b[idx] = ang_vel_b out_lin_acc_b[idx] = lin_acc_b - out_ang_acc_b[idx] = ang_acc_b - out_projected_gravity_b[idx] = projected_gravity_b - # Update previous velocities + # Update previous velocity prev_lin_vel_w[idx] = lin_vel_w - prev_ang_vel_w[idx] = ang_vel_w @wp.kernel def imu_reset_kernel( env_mask: wp.array(dtype=wp.bool), - out_pos_w: wp.array(dtype=wp.vec3f), - out_quat_w: wp.array(dtype=wp.quatf), - out_lin_vel_b: wp.array(dtype=wp.vec3f), out_ang_vel_b: wp.array(dtype=wp.vec3f), out_lin_acc_b: wp.array(dtype=wp.vec3f), - out_ang_acc_b: wp.array(dtype=wp.vec3f), - out_projected_gravity_b: wp.array(dtype=wp.vec3f), prev_lin_vel_w: wp.array(dtype=wp.vec3f), - prev_ang_vel_w: wp.array(dtype=wp.vec3f), ): idx = wp.tid() if not env_mask[idx]: return - out_pos_w[idx] = wp.vec3f(0.0, 0.0, 0.0) - out_quat_w[idx] = wp.quatf(0.0, 0.0, 0.0, 1.0) - out_lin_vel_b[idx] = wp.vec3f(0.0, 0.0, 0.0) out_ang_vel_b[idx] = wp.vec3f(0.0, 0.0, 0.0) out_lin_acc_b[idx] = wp.vec3f(0.0, 0.0, 0.0) - out_ang_acc_b[idx] = wp.vec3f(0.0, 0.0, 0.0) - out_projected_gravity_b[idx] = wp.vec3f(0.0, 0.0, -1.0) prev_lin_vel_w[idx] = wp.vec3f(0.0, 0.0, 0.0) - prev_ang_vel_w[idx] = wp.vec3f(0.0, 0.0, 0.0) diff --git a/source/isaaclab_physx/isaaclab_physx/sensors/joint_wrench/__init__.py b/source/isaaclab_physx/isaaclab_physx/sensors/joint_wrench/__init__.py new file mode 100644 index 000000000000..539f0250a568 --- /dev/null +++ b/source/isaaclab_physx/isaaclab_physx/sensors/joint_wrench/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Sub-module for the PhysX joint-wrench sensor.""" + +from isaaclab.utils.module import lazy_export + +lazy_export() diff --git a/source/isaaclab_physx/isaaclab_physx/sensors/joint_wrench/__init__.pyi b/source/isaaclab_physx/isaaclab_physx/sensors/joint_wrench/__init__.pyi new file mode 100644 index 000000000000..b2bcd3582d44 --- /dev/null +++ b/source/isaaclab_physx/isaaclab_physx/sensors/joint_wrench/__init__.pyi @@ -0,0 +1,9 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +__all__ = ["JointWrenchSensor", "JointWrenchSensorData"] + +from .joint_wrench_sensor import JointWrenchSensor +from .joint_wrench_sensor_data import JointWrenchSensorData diff --git a/source/isaaclab_physx/isaaclab_physx/sensors/joint_wrench/joint_wrench_sensor.py b/source/isaaclab_physx/isaaclab_physx/sensors/joint_wrench/joint_wrench_sensor.py new file mode 100644 index 000000000000..9ae39c621240 --- /dev/null +++ b/source/isaaclab_physx/isaaclab_physx/sensors/joint_wrench/joint_wrench_sensor.py @@ -0,0 +1,253 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +# pyright: reportPrivateUsage=false + +from __future__ import annotations + +import logging +from collections.abc import Sequence +from typing import TYPE_CHECKING + +import numpy as np +import warp as wp + +from pxr import Usd, UsdPhysics + +from isaaclab.sensors.joint_wrench import BaseJointWrenchSensor +from isaaclab.sim.utils.queries import find_first_matching_prim, get_all_matching_child_prims + +from isaaclab_physx.physics import PhysxManager as SimulationManager + +from .joint_wrench_sensor_data import JointWrenchSensorData +from .kernels import joint_wrench_reset_kernel, joint_wrench_split_kernel + +if TYPE_CHECKING: + import omni.physics.tensors.api as physx + + from isaaclab.sensors.joint_wrench import JointWrenchSensorCfg + +logger = logging.getLogger(__name__) + + +class JointWrenchSensor(BaseJointWrenchSensor): + """PhysX joint reaction wrench sensor. + + The sensor reads PhysX's incoming joint wrench for every articulation link + and exposes the linear force [N] and angular torque [N·m] components in + the child-side joint frame, with torque referenced at the child-side joint + anchor. The root body's entry is included. + + :attr:`~isaaclab.sensors.SensorBaseCfg.prim_path` must point at either + the articulation root prim or a parent prim containing a single + articulation root in every environment. + """ + + cfg: JointWrenchSensorCfg + """The configuration parameters.""" + + __backend_name__: str = "physx" + """The name of the backend for the joint wrench sensor.""" + + def __init__(self, cfg: JointWrenchSensorCfg): + """Initialize the PhysX joint-wrench sensor. + + Args: + cfg: The configuration parameters. + """ + super().__init__(cfg) + + self._data = JointWrenchSensorData() + self._physics_sim_view = None + self._root_view: physx.ArticulationView | None = None + self._joint_pos_b: wp.array | None = None + self._joint_quat_b: wp.array | None = None + self._num_bodies: int = 0 + + def __str__(self) -> str: + """String representation of the sensor instance.""" + return ( + f"Joint wrench sensor @ '{self.cfg.prim_path}': \n" + f"\tbackend : physx\n" + f"\tupdate period (s) : {self.cfg.update_period}\n" + f"\tnumber of bodies : {self._num_bodies}\n" + f"\tbody names : {self.body_names}\n" + ) + + """ + Properties + """ + + @property + def body_names(self) -> list[str]: + """Ordered names of the bodies whose incoming joint wrench is reported.""" + return self._data._body_names + + @property + def data(self) -> JointWrenchSensorData: + """The joint-wrench sensor data.""" + self._update_outdated_buffers() + return self._data + + """ + Operations + """ + + def reset(self, env_ids: Sequence[int] | None = None, env_mask: wp.array | None = None) -> None: + """Reset the sensor buffers for the given environments. + + Args: + env_ids: The environment ids to reset. + env_mask: The mask used to reset the environments. Shape is ``(num_envs,)``. + """ + if self._data._force is None or self._data._torque is None: + return + env_mask = self._resolve_indices_and_mask(env_ids, env_mask) + super().reset(None, env_mask) + wp.launch( + joint_wrench_reset_kernel, + dim=(self._num_envs, self._num_bodies), + inputs=[env_mask, self._data._force, self._data._torque], + device=self._device, + ) + + """ + Implementation + """ + + def _initialize_impl(self) -> None: + """PHYSICS_READY callback: builds the articulation view and allocates buffers.""" + super()._initialize_impl() + + self._physics_sim_view = SimulationManager.get_physics_sim_view() + root_prim_path_expr = self._resolve_articulation_root_prim_path() + self._root_view = self._physics_sim_view.create_articulation_view(root_prim_path_expr.replace(".*", "*")) + if self._root_view._backend is None: + raise RuntimeError(f"Failed to create articulation view at: {root_prim_path_expr}. Check PhysX logs.") + + self._num_bodies = self._root_view.shared_metatype.link_count + if self._num_bodies == 0: + raise RuntimeError(f"Joint wrench sensor matched zero bodies at '{self.cfg.prim_path}'.") + + self._data._body_names = list(self._root_view.shared_metatype.link_names) + self._create_joint_frame_buffers() + self._data.create_buffers(num_envs=self._num_envs, num_bodies=self._num_bodies, device=self._device) + + logger.info(f"Joint wrench sensor initialized: {self._num_envs} envs, {self._num_bodies} bodies") + + def _resolve_articulation_root_prim_path(self) -> str: + """Resolve the articulation root prim path expression from the configured asset prim path.""" + first_env_matching_prim = find_first_matching_prim(self.cfg.prim_path) + if first_env_matching_prim is None: + raise RuntimeError(f"Failed to find prim for expression: '{self.cfg.prim_path}'.") + first_env_matching_prim_path = first_env_matching_prim.GetPath().pathString + + first_env_root_prims = get_all_matching_child_prims( + first_env_matching_prim_path, + predicate=lambda prim: prim.HasAPI(UsdPhysics.ArticulationRootAPI) + and prim.GetAttribute("physxArticulation:articulationEnabled").Get() is not False, + traverse_instance_prims=False, + ) + if len(first_env_root_prims) == 0: + raise RuntimeError( + f"Failed to find an articulation when resolving '{first_env_matching_prim_path}'." + " Please ensure that the prim has 'USD ArticulationRootAPI' applied." + ) + if len(first_env_root_prims) > 1: + raise RuntimeError( + f"Failed to find a single articulation when resolving '{first_env_matching_prim_path}'." + f" Found multiple '{first_env_root_prims}' under '{first_env_matching_prim_path}'." + " Please ensure that there is only one articulation in the prim path tree." + ) + + first_env_root_prim_path = first_env_root_prims[0].GetPath().pathString + root_prim_path_relative_to_prim_path = first_env_root_prim_path[len(first_env_matching_prim_path) :] + return self.cfg.prim_path + root_prim_path_relative_to_prim_path + + def _create_joint_frame_buffers(self) -> None: + """Create child-side joint frame transforms indexed by PhysX link order.""" + joint_pos_b = np.zeros((self._num_bodies, 3), dtype=np.float32) + joint_quat_b = np.zeros((self._num_bodies, 4), dtype=np.float32) + joint_quat_b[:, 3] = 1.0 + + first_env_matching_prim = find_first_matching_prim(self.cfg.prim_path) + if first_env_matching_prim is None: + raise RuntimeError(f"Failed to find prim for expression: '{self.cfg.prim_path}'.") + link_name_to_index = {name: index for index, name in enumerate(self._data._body_names)} + + for prim in Usd.PrimRange(first_env_matching_prim): + joint = UsdPhysics.Joint(prim) + if not joint or joint.GetJointEnabledAttr().Get() is False: + continue + body1_targets = joint.GetBody1Rel().GetTargets() + if len(body1_targets) == 0: + continue + body_index = link_name_to_index.get(body1_targets[0].name) + if body_index is None: + continue + + local_pos1 = joint.GetLocalPos1Attr().Get() + if local_pos1 is not None: + joint_pos_b[body_index] = (float(local_pos1[0]), float(local_pos1[1]), float(local_pos1[2])) + + local_rot1 = joint.GetLocalRot1Attr().Get() + if local_rot1 is not None: + local_rot1_imag = local_rot1.GetImaginary() + joint_quat_b[body_index] = ( + float(local_rot1_imag[0]), + float(local_rot1_imag[1]), + float(local_rot1_imag[2]), + float(local_rot1.GetReal()), + ) + + self._joint_pos_b = wp.array(joint_pos_b, dtype=wp.vec3f, device=self._device) + self._joint_quat_b = wp.array(joint_quat_b, dtype=wp.quatf, device=self._device) + + def _update_buffers_impl(self, env_mask: wp.array) -> None: + """Read PhysX incoming joint wrenches and split them into force / torque buffers. + + Args: + env_mask: A mask containing which environments need to be updated. Shape is ``(num_envs,)``. + """ + if self._root_view is None: + raise RuntimeError( + f"Joint wrench sensor '{self.cfg.prim_path}': not initialized." + " Access sensor data only after sim.reset() has been called." + ) + if self._joint_pos_b is None or self._joint_quat_b is None: + raise RuntimeError(f"Joint wrench sensor '{self.cfg.prim_path}': joint frame buffers are not initialized.") + + incoming_joint_wrench = self._root_view.get_link_incoming_joint_force().view(wp.spatial_vectorf) + wp.launch( + joint_wrench_split_kernel, + dim=(self._num_envs, self._num_bodies), + inputs=[ + env_mask, + incoming_joint_wrench, + self._joint_pos_b, + self._joint_quat_b, + self._data._force, + self._data._torque, + ], + device=self._device, + ) + + def _invalidate_initialize_callback(self, event) -> None: + """Drop view, cached sizes, and buffers when physics stops. + + Args: + event: An invalidate event. + """ + super()._invalidate_initialize_callback(event) + self._physics_sim_view = None + self._root_view = None + self._joint_pos_b = None + self._joint_quat_b = None + self._num_bodies = 0 + self._data._force = None + self._data._torque = None + self._data._body_names = [] + self._data._force_ta = None + self._data._torque_ta = None diff --git a/source/isaaclab_physx/isaaclab_physx/sensors/joint_wrench/joint_wrench_sensor_data.py b/source/isaaclab_physx/isaaclab_physx/sensors/joint_wrench/joint_wrench_sensor_data.py new file mode 100644 index 000000000000..80cea4c1a5ce --- /dev/null +++ b/source/isaaclab_physx/isaaclab_physx/sensors/joint_wrench/joint_wrench_sensor_data.py @@ -0,0 +1,67 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from __future__ import annotations + +import warp as wp + +from isaaclab.sensors.joint_wrench import BaseJointWrenchSensorData +from isaaclab.utils.warp import ProxyArray + + +class JointWrenchSensorData(BaseJointWrenchSensorData): + """Data container for the PhysX joint-wrench sensor.""" + + def __init__(self): + self._force: wp.array | None = None + self._torque: wp.array | None = None + self._body_names: list[str] = [] + self._force_ta: ProxyArray | None = None + self._torque_ta: ProxyArray | None = None + + @property + def force(self) -> ProxyArray | None: + """Linear component of the incoming joint wrench [N]. + + Expressed in the frame selected by + :attr:`~isaaclab.sensors.JointWrenchSensorCfg.convention`. Shape is + ``(num_envs, num_bodies)``, dtype ``wp.vec3f``. In torch this resolves + to ``(num_envs, num_bodies, 3)``. ``None`` before the simulation is + initialized. + """ + if self._force is None: + return None + if self._force_ta is None: + self._force_ta = ProxyArray(self._force) + return self._force_ta + + @property + def torque(self) -> ProxyArray | None: + """Angular component of the incoming joint wrench [N·m]. + + Expressed in the frame selected by + :attr:`~isaaclab.sensors.JointWrenchSensorCfg.convention`. Shape is + ``(num_envs, num_bodies)``, dtype ``wp.vec3f``. In torch this resolves + to ``(num_envs, num_bodies, 3)``. ``None`` before the simulation is + initialized. + """ + if self._torque is None: + return None + if self._torque_ta is None: + self._torque_ta = ProxyArray(self._torque) + return self._torque_ta + + def create_buffers(self, num_envs: int, num_bodies: int, device: str) -> None: + """Allocate internal buffers. + + Args: + num_envs: Number of environments. + num_bodies: Number of bodies with incoming joint wrench reports. + device: Device for array storage. + """ + self._force = wp.zeros((num_envs, num_bodies), dtype=wp.vec3f, device=device) + self._torque = wp.zeros((num_envs, num_bodies), dtype=wp.vec3f, device=device) + self._force_ta = None + self._torque_ta = None diff --git a/source/isaaclab_physx/isaaclab_physx/sensors/joint_wrench/kernels.py b/source/isaaclab_physx/isaaclab_physx/sensors/joint_wrench/kernels.py new file mode 100644 index 000000000000..bb3d0c7cf67c --- /dev/null +++ b/source/isaaclab_physx/isaaclab_physx/sensors/joint_wrench/kernels.py @@ -0,0 +1,47 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +import warp as wp + + +@wp.kernel +def joint_wrench_split_kernel( + env_mask: wp.array(dtype=wp.bool), + incoming_joint_wrench: wp.array(dtype=wp.spatial_vectorf, ndim=2), + joint_pos_b: wp.array(dtype=wp.vec3f), + joint_quat_b: wp.array(dtype=wp.quatf), + out_force: wp.array(dtype=wp.vec3f, ndim=2), + out_torque: wp.array(dtype=wp.vec3f, ndim=2), +): + """Convert PhysX incoming joint spatial wrenches into the child-side joint frame.""" + env, body = wp.tid() + if not env_mask[env]: + return + + wrench = incoming_joint_wrench[env, body] + force_b = wp.spatial_top(wrench) + torque_b = wp.spatial_bottom(wrench) + + # PhysX reports the wrench in body1's frame, referenced at body1's origin. + # Shift torque to the child-side joint anchor and rotate both components + # into the child-side joint frame. + torque_joint_anchor_b = torque_b - wp.cross(joint_pos_b[body], force_b) + out_force[env, body] = wp.quat_rotate_inv(joint_quat_b[body], force_b) + out_torque[env, body] = wp.quat_rotate_inv(joint_quat_b[body], torque_joint_anchor_b) + + +@wp.kernel +def joint_wrench_reset_kernel( + env_mask: wp.array(dtype=wp.bool), + out_force: wp.array(dtype=wp.vec3f, ndim=2), + out_torque: wp.array(dtype=wp.vec3f, ndim=2), +): + """Zero force and torque entries for the environments selected by ``env_mask``.""" + env, body = wp.tid() + if not env_mask[env]: + return + + out_force[env, body] = wp.vec3f(0.0, 0.0, 0.0) + out_torque[env, body] = wp.vec3f(0.0, 0.0, 0.0) diff --git a/source/isaaclab_physx/isaaclab_physx/sensors/pva/__init__.py b/source/isaaclab_physx/isaaclab_physx/sensors/pva/__init__.py new file mode 100644 index 000000000000..aba8c3b7af7f --- /dev/null +++ b/source/isaaclab_physx/isaaclab_physx/sensors/pva/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Sub-module for PhysX PVA sensor.""" + +from isaaclab.utils.module import lazy_export + +lazy_export() diff --git a/source/isaaclab_physx/isaaclab_physx/sensors/pva/__init__.pyi b/source/isaaclab_physx/isaaclab_physx/sensors/pva/__init__.pyi new file mode 100644 index 000000000000..3ad9f6fff741 --- /dev/null +++ b/source/isaaclab_physx/isaaclab_physx/sensors/pva/__init__.pyi @@ -0,0 +1,12 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +__all__ = [ + "Pva", + "PvaData", +] + +from .pva import Pva +from .pva_data import PvaData diff --git a/source/isaaclab_physx/isaaclab_physx/sensors/pva/kernels.py b/source/isaaclab_physx/isaaclab_physx/sensors/pva/kernels.py new file mode 100644 index 000000000000..a76c6dcf5fda --- /dev/null +++ b/source/isaaclab_physx/isaaclab_physx/sensors/pva/kernels.py @@ -0,0 +1,106 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +import warp as wp + + +@wp.kernel +def pva_update_kernel( + # indexing + env_mask: wp.array(dtype=wp.bool), + # PhysX view data + transforms: wp.array(dtype=wp.transformf), + velocities: wp.array(dtype=wp.spatial_vectorf), + coms: wp.array(dtype=wp.transformf), + # sensor config (per-env) + offset_pos_b: wp.array(dtype=wp.vec3f), + offset_quat_b: wp.array(dtype=wp.quatf), + gravity_vec_w: wp.array(dtype=wp.vec3f), + # previous velocities (read + write) + prev_lin_vel_w: wp.array(dtype=wp.vec3f), + prev_ang_vel_w: wp.array(dtype=wp.vec3f), + # scalar + inv_dt: wp.float32, + # outputs (written in-place) + out_pos_w: wp.array(dtype=wp.vec3f), + out_quat_w: wp.array(dtype=wp.quatf), + out_lin_vel_b: wp.array(dtype=wp.vec3f), + out_ang_vel_b: wp.array(dtype=wp.vec3f), + out_lin_acc_b: wp.array(dtype=wp.vec3f), + out_ang_acc_b: wp.array(dtype=wp.vec3f), + out_projected_gravity_b: wp.array(dtype=wp.vec3f), +): + idx = wp.tid() + if not env_mask[idx]: + return + + # 1. Extract body pose + body_pos = wp.transform_get_translation(transforms[idx]) + body_quat = wp.transform_get_rotation(transforms[idx]) + + # 2. Apply sensor offset + sensor_pos = body_pos + wp.quat_rotate(body_quat, offset_pos_b[idx]) + sensor_quat = body_quat * offset_quat_b[idx] + + # 3. Extract lin/ang velocity + lin_vel_w = wp.spatial_top(velocities[idx]) + ang_vel_w = wp.spatial_bottom(velocities[idx]) + + # 4. COM correction: lin_vel += cross(ang_vel, quat_rotate(body_quat, offset_pos - com_pos)) + com_pos_b = wp.transform_get_translation(coms[idx]) + lever_arm = wp.quat_rotate(body_quat, offset_pos_b[idx] - com_pos_b) + lin_vel_w = lin_vel_w + wp.cross(ang_vel_w, lever_arm) + + # 5. Numerical differentiation (world frame) + lin_acc_w = (lin_vel_w - prev_lin_vel_w[idx]) * inv_dt + ang_acc_w = (ang_vel_w - prev_ang_vel_w[idx]) * inv_dt + + # 6. Rotate world -> body using sensor orientation + lin_vel_b = wp.quat_rotate_inv(sensor_quat, lin_vel_w) + ang_vel_b = wp.quat_rotate_inv(sensor_quat, ang_vel_w) + lin_acc_b = wp.quat_rotate_inv(sensor_quat, lin_acc_w) + ang_acc_b = wp.quat_rotate_inv(sensor_quat, ang_acc_w) + projected_gravity_b = wp.quat_rotate_inv(sensor_quat, gravity_vec_w[idx]) + + # 7. Store results + out_pos_w[idx] = sensor_pos + out_quat_w[idx] = sensor_quat + out_lin_vel_b[idx] = lin_vel_b + out_ang_vel_b[idx] = ang_vel_b + out_lin_acc_b[idx] = lin_acc_b + out_ang_acc_b[idx] = ang_acc_b + out_projected_gravity_b[idx] = projected_gravity_b + + # Update previous velocities + prev_lin_vel_w[idx] = lin_vel_w + prev_ang_vel_w[idx] = ang_vel_w + + +@wp.kernel +def pva_reset_kernel( + env_mask: wp.array(dtype=wp.bool), + out_pos_w: wp.array(dtype=wp.vec3f), + out_quat_w: wp.array(dtype=wp.quatf), + out_lin_vel_b: wp.array(dtype=wp.vec3f), + out_ang_vel_b: wp.array(dtype=wp.vec3f), + out_lin_acc_b: wp.array(dtype=wp.vec3f), + out_ang_acc_b: wp.array(dtype=wp.vec3f), + out_projected_gravity_b: wp.array(dtype=wp.vec3f), + prev_lin_vel_w: wp.array(dtype=wp.vec3f), + prev_ang_vel_w: wp.array(dtype=wp.vec3f), +): + idx = wp.tid() + if not env_mask[idx]: + return + + out_pos_w[idx] = wp.vec3f(0.0, 0.0, 0.0) + out_quat_w[idx] = wp.quatf(0.0, 0.0, 0.0, 1.0) + out_lin_vel_b[idx] = wp.vec3f(0.0, 0.0, 0.0) + out_ang_vel_b[idx] = wp.vec3f(0.0, 0.0, 0.0) + out_lin_acc_b[idx] = wp.vec3f(0.0, 0.0, 0.0) + out_ang_acc_b[idx] = wp.vec3f(0.0, 0.0, 0.0) + out_projected_gravity_b[idx] = wp.vec3f(0.0, 0.0, -1.0) + prev_lin_vel_w[idx] = wp.vec3f(0.0, 0.0, 0.0) + prev_ang_vel_w[idx] = wp.vec3f(0.0, 0.0, 0.0) diff --git a/source/isaaclab_physx/isaaclab_physx/sensors/pva/pva.py b/source/isaaclab_physx/isaaclab_physx/sensors/pva/pva.py new file mode 100644 index 000000000000..32f4549e416d --- /dev/null +++ b/source/isaaclab_physx/isaaclab_physx/sensors/pva/pva.py @@ -0,0 +1,301 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from __future__ import annotations + +from collections.abc import Sequence +from typing import TYPE_CHECKING + +import torch +import warp as wp + +from pxr import UsdGeom, UsdPhysics + +import isaaclab.sim as sim_utils +import isaaclab.utils.math as math_utils +from isaaclab.markers import VisualizationMarkers +from isaaclab.sensors.pva import BasePva +from isaaclab.utils.warp import ProxyArray + +from isaaclab_physx.physics import PhysxManager as SimulationManager + +from .kernels import pva_reset_kernel, pva_update_kernel +from .pva_data import PvaData + +if TYPE_CHECKING: + from isaaclab.sensors.pva import PvaCfg + + +class Pva(BasePva): + """The PhysX Pose Velocity Acceleration (PVA) sensor. + + The sensor can be attached to any prim path with a rigid ancestor in its tree and produces body-frame + linear acceleration and angular velocity, along with world-frame pose and body-frame linear and angular + accelerations/velocities. + + If the provided path is not a rigid body, the closest rigid-body ancestor is used for simulation queries. + The fixed transform from that ancestor to the target prim is computed once during initialization and + composed with the configured sensor offset. + + .. note:: + + We are computing the accelerations using numerical differentiation from the velocities. Consequently, the + PVA sensor accuracy depends on the chosen physx timestep. For a sufficient accuracy, we recommend to keep the + timestep at least as 200Hz. + + .. note:: + + The user can configure the sensor offset in the configuration file. The offset is applied relative to the + rigid source prim. If the target prim is not a rigid body, the offset is composed with the fixed transform + from the rigid ancestor to the target prim. The offset is applied in the body frame of the rigid source prim. + The offset is defined as a position vector and a quaternion rotation, which + are applied in the order: position, then rotation. The position is applied as a translation + in the body frame of the rigid source prim, and the rotation is applied as a rotation + in the body frame of the rigid source prim. + + """ + + cfg: PvaCfg + """The configuration parameters.""" + + __backend_name__: str = "physx" + """The name of the backend for the PVA sensor.""" + + def __init__(self, cfg: PvaCfg): + """Initializes the PVA sensor. + + Args: + cfg: The configuration parameters. + """ + # initialize base class + super().__init__(cfg) + # Create empty variables for storing output data + self._data = PvaData() + + # Internal: expression used to build the rigid body view (may be different from cfg.prim_path) + self._rigid_parent_expr: str | None = None + + def __str__(self) -> str: + """Returns: A string containing information about the instance.""" + return ( + f"PVA sensor @ '{self.cfg.prim_path}': \n" + f"\tview type : {self._view.__class__}\n" + f"\tupdate period (s) : {self.cfg.update_period}\n" + f"\tnumber of sensors : {self._view.count}\n" + ) + + """ + Properties + """ + + @property + def data(self) -> PvaData: + # update sensors if needed + self._update_outdated_buffers() + # return the data + return self._data + + @property + def num_instances(self) -> int: + return self._view.count + + """ + Operations + """ + + def reset(self, env_ids: Sequence[int] | None = None, env_mask: wp.array | None = None): + # resolve indices and mask + env_mask = self._resolve_indices_and_mask(env_ids, env_mask) + # reset the timestamps + super().reset(None, env_mask) + + wp.launch( + pva_reset_kernel, + dim=self._num_envs, + inputs=[ + env_mask, + self._data._pos_w, + self._data._quat_w, + self._data._lin_vel_b, + self._data._ang_vel_b, + self._data._lin_acc_b, + self._data._ang_acc_b, + self._data._projected_gravity_b, + self._prev_lin_vel_w, + self._prev_ang_vel_w, + ], + device=self._device, + ) + + def update(self, dt: float, force_recompute: bool = False): + # save timestamp + self._dt = dt + # execute updating + super().update(dt, force_recompute) + + """ + Implementation. + """ + + def _initialize_impl(self): + """Initializes the sensor handles and internal buffers. + + - If the target prim path is a rigid body, build the view directly on it. + - Otherwise find the closest rigid-body ancestor, cache the fixed transform from that ancestor + to the target prim, and build the view on the ancestor expression. + """ + # Initialize parent class + super()._initialize_impl() + # obtain global simulation view + self._physics_sim_view = SimulationManager.get_physics_sim_view() + # check if the prim at path is a rigid prim + prim = sim_utils.find_first_matching_prim(self.cfg.prim_path) + if prim is None: + raise RuntimeError(f"Failed to find a prim at path expression: {self.cfg.prim_path}") + + # Find the first matching ancestor prim that implements rigid body API + ancestor_prim = sim_utils.get_first_matching_ancestor_prim( + prim.GetPath(), predicate=lambda _prim: _prim.HasAPI(UsdPhysics.RigidBodyAPI) + ) + if ancestor_prim is None: + raise RuntimeError(f"Failed to find a rigid body ancestor prim at path expression: {self.cfg.prim_path}") + # Convert ancestor prim path to expression + if ancestor_prim == prim: + self._rigid_parent_expr = self.cfg.prim_path + fixed_pos_b, fixed_quat_b = None, None + else: + # Convert ancestor prim path to expression by stripping the relative + # suffix (including its leading '/') so no trailing '/' remains. + relative_path = prim.GetPath().MakeRelativePath(ancestor_prim.GetPath()).pathString + self._rigid_parent_expr = self.cfg.prim_path.replace("/" + relative_path, "") + # Resolve the relative pose between the target prim and the ancestor prim + fixed_pos_b, fixed_quat_b = sim_utils.resolve_prim_pose(prim, ancestor_prim) + + # Create the rigid body view on the ancestor + self._view = self._physics_sim_view.create_rigid_body_view(self._rigid_parent_expr.replace(".*", "*")) + + # Get world gravity + gravity = self._physics_sim_view.get_gravity() + gravity_dir = torch.tensor((gravity[0], gravity[1], gravity[2]), device=self.device) + gravity_dir = math_utils.normalize(gravity_dir.unsqueeze(0)).squeeze(0) + gravity_dir_repeated = gravity_dir.repeat(self.num_instances, 1) + self.GRAVITY_VEC_W = ProxyArray(wp.from_torch(gravity_dir_repeated.contiguous(), dtype=wp.vec3f)) + + # Create internal buffers + self._initialize_buffers_impl() + + # Compose the configured offset with the fixed ancestor->target transform (done once) + # new_offset = fixed * cfg.offset + # where composition is: p = p_fixed + R_fixed * p_cfg, q = q_fixed * q_cfg + if fixed_pos_b is not None and fixed_quat_b is not None: + # Broadcast fixed transform across instances + fixed_p = torch.tensor(fixed_pos_b, device=self._device).repeat(self._view.count, 1) + fixed_q = torch.tensor(fixed_quat_b, device=self._device).repeat(self._view.count, 1) + + cfg_p = wp.to_torch(self._offset_pos_b).clone() + cfg_q = wp.to_torch(self._offset_quat_b).clone() + + composed_p = fixed_p + math_utils.quat_apply(fixed_q, cfg_p) + composed_q = math_utils.quat_mul(fixed_q, cfg_q) + + self._offset_pos_b = wp.from_torch(composed_p.contiguous(), dtype=wp.vec3f) + self._offset_quat_b = wp.from_torch(composed_q.contiguous(), dtype=wp.quatf) + + def _update_buffers_impl(self, env_mask: wp.array | None = None): + """Fills the buffers of the sensor data.""" + env_mask = self._resolve_indices_and_mask(None, env_mask) + + # Fetch view data as warp typed arrays + transforms = self._view.get_transforms().view(wp.transformf) + velocities = self._view.get_velocities().view(wp.spatial_vectorf) + # get_coms() returns a CPU warp array; copy to pre-allocated GPU buffer + wp.copy(self._coms_buffer, self._view.get_coms().view(wp.transformf)) + + wp.launch( + pva_update_kernel, + dim=self._num_envs, + inputs=[ + env_mask, + transforms, + velocities, + self._coms_buffer, + self._offset_pos_b, + self._offset_quat_b, + self.GRAVITY_VEC_W, + self._prev_lin_vel_w, + self._prev_ang_vel_w, + 1.0 / self._dt, + self._data._pos_w, + self._data._quat_w, + self._data._lin_vel_b, + self._data._ang_vel_b, + self._data._lin_acc_b, + self._data._ang_acc_b, + self._data._projected_gravity_b, + ], + device=self._device, + ) + + def _initialize_buffers_impl(self): + """Create buffers for storing data.""" + # Create data buffers via data class + self._data.create_buffers(num_envs=self._view.count, device=self._device) + + # Sensor-internal buffers for velocity tracking (not exposed via data) + self._prev_lin_vel_w = wp.zeros(self._view.count, dtype=wp.vec3f, device=self._device) + self._prev_ang_vel_w = wp.zeros(self._view.count, dtype=wp.vec3f, device=self._device) + + # Store sensor offset (applied relative to rigid source). + # This may be composed later with a fixed ancestor->target transform. + offset_pos_torch = torch.tensor(list(self.cfg.offset.pos), device=self._device).repeat(self._view.count, 1) + offset_quat_torch = torch.tensor(list(self.cfg.offset.rot), device=self._device).repeat(self._view.count, 1) + self._offset_pos_b = wp.from_torch(offset_pos_torch.contiguous(), dtype=wp.vec3f) + self._offset_quat_b = wp.from_torch(offset_quat_torch.contiguous(), dtype=wp.quatf) + + # Pre-allocate GPU buffer for COMs (get_coms() returns CPU array) + self._coms_buffer = wp.zeros(self._view.count, dtype=wp.transformf, device=self._device) + + def _set_debug_vis_impl(self, debug_vis: bool): + # set visibility of markers + # note: parent only deals with callbacks. not their visibility + if debug_vis: + # create markers if necessary for the first time + if not hasattr(self, "acceleration_visualizer"): + self.acceleration_visualizer = VisualizationMarkers(self.cfg.visualizer_cfg) + # set their visibility to true + self.acceleration_visualizer.set_visibility(True) + else: + if hasattr(self, "acceleration_visualizer"): + self.acceleration_visualizer.set_visibility(False) + + def _debug_vis_callback(self, event): + # safely return if view becomes invalid + # note: this invalidity happens because of isaac sim view callbacks + if self._view is None: + return + # get marker location + # -- base state (convert warp -> torch for visualization) + base_pos_w = self._data.pos_w.torch.clone() + base_pos_w[:, 2] += 0.5 + # -- resolve the scales + default_scale = self.acceleration_visualizer.cfg.markers["arrow"].scale + arrow_scale = torch.tensor(default_scale, device=self.device).repeat(self._data.lin_acc_b.torch.shape[0], 1) + # get up axis of current stage + up_axis = UsdGeom.GetStageUpAxis(self.stage) + # arrow-direction + pos_w_torch = self._data.pos_w.torch + quat_w_torch = self._data.quat_w.torch + lin_acc_b_torch = self._data.lin_acc_b.torch + quat_opengl = math_utils.quat_from_matrix( + math_utils.create_rotation_matrix_from_view( + pos_w_torch, + pos_w_torch + math_utils.quat_apply(quat_w_torch, lin_acc_b_torch), + up_axis=up_axis, + device=self._device, + ) + ) + quat_w = math_utils.convert_camera_frame_orientation_convention(quat_opengl, "opengl", "world") + # display markers + self.acceleration_visualizer.visualize(base_pos_w, quat_w, arrow_scale) diff --git a/source/isaaclab_physx/isaaclab_physx/sensors/pva/pva_data.py b/source/isaaclab_physx/isaaclab_physx/sensors/pva/pva_data.py new file mode 100644 index 000000000000..3128551c3273 --- /dev/null +++ b/source/isaaclab_physx/isaaclab_physx/sensors/pva/pva_data.py @@ -0,0 +1,147 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from __future__ import annotations + +import logging + +import warp as wp + +from isaaclab.sensors.pva import BasePvaData +from isaaclab.utils.warp import ProxyArray + +from isaaclab_physx.sensors.kernels import concat_pos_and_quat_to_pose_1d_kernel + +logger = logging.getLogger(__name__) + + +class PvaData(BasePvaData): + """Data container for the PhysX PVA sensor.""" + + @property + def pose_w(self) -> ProxyArray: + """Pose of the sensor origin in world frame. + + Shape is (num_instances,), dtype = wp.transformf. In torch this resolves to (num_instances, 7). + The pose is provided in (x, y, z, qx, qy, qz, qw) format. + """ + wp.launch( + concat_pos_and_quat_to_pose_1d_kernel, + dim=self._num_envs, + inputs=[self._pos_w, self._quat_w], + outputs=[self._pose_w], + device=self._device, + ) + if self._pose_w_ta is None: + self._pose_w_ta = ProxyArray(self._pose_w) + return self._pose_w_ta + + @property + def pos_w(self) -> ProxyArray: + """Position of the sensor origin in world frame. + + Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). + """ + if self._pos_w_ta is None: + self._pos_w_ta = ProxyArray(self._pos_w) + return self._pos_w_ta + + @property + def quat_w(self) -> ProxyArray: + """Orientation of the sensor origin in world frame. + + Shape is (num_instances,), dtype = wp.quatf. In torch this resolves to (num_instances, 4). + The orientation is provided in (x, y, z, w) format. + """ + if self._quat_w_ta is None: + self._quat_w_ta = ProxyArray(self._quat_w) + return self._quat_w_ta + + @property + def projected_gravity_b(self) -> ProxyArray: + """Gravity direction unit vector projected on the PVA frame. + + Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). + """ + if self._projected_gravity_b_ta is None: + self._projected_gravity_b_ta = ProxyArray(self._projected_gravity_b) + return self._projected_gravity_b_ta + + @property + def lin_vel_b(self) -> ProxyArray: + """PVA frame linear velocity relative to the world expressed in PVA frame. + + Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). + """ + if self._lin_vel_b_ta is None: + self._lin_vel_b_ta = ProxyArray(self._lin_vel_b) + return self._lin_vel_b_ta + + @property + def ang_vel_b(self) -> ProxyArray: + """PVA frame angular velocity relative to the world expressed in PVA frame. + + Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). + """ + if self._ang_vel_b_ta is None: + self._ang_vel_b_ta = ProxyArray(self._ang_vel_b) + return self._ang_vel_b_ta + + @property + def lin_acc_b(self) -> ProxyArray: + """Linear acceleration (coordinate) in the PVA frame [m/s^2]. + + Equal to -g in freefall, zero at rest. + + Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). + """ + if self._lin_acc_b_ta is None: + self._lin_acc_b_ta = ProxyArray(self._lin_acc_b) + return self._lin_acc_b_ta + + @property + def ang_acc_b(self) -> ProxyArray: + """PVA frame angular acceleration relative to the world expressed in PVA frame. + + Shape is (num_instances,), dtype = wp.vec3f. In torch this resolves to (num_instances, 3). + """ + if self._ang_acc_b_ta is None: + self._ang_acc_b_ta = ProxyArray(self._ang_acc_b) + return self._ang_acc_b_ta + + def create_buffers(self, num_envs: int, device: str) -> None: + """Create internal buffers for sensor data. + + Args: + num_envs: Number of environments. + device: Device for tensor storage. + """ + self._num_envs = num_envs + self._device = device + self._pose_w = wp.zeros(num_envs, dtype=wp.transformf, device=device) + self._pos_w = wp.zeros(num_envs, dtype=wp.vec3f, device=device) + self._quat_w = wp.zeros(num_envs, dtype=wp.quatf, device=device) + # Initialize quaternion to identity (w=1): warp quatf is (x,y,z,w) + # Use torch interop to set the w component + quat_torch = wp.to_torch(self._quat_w) + quat_torch[:, 3] = 1.0 + self._projected_gravity_b = wp.zeros(num_envs, dtype=wp.vec3f, device=device) + # Initialize projected gravity to (0, 0, -1) + pg_torch = wp.to_torch(self._projected_gravity_b) + pg_torch[:, 2] = -1.0 + self._lin_vel_b = wp.zeros(num_envs, dtype=wp.vec3f, device=device) + self._ang_vel_b = wp.zeros(num_envs, dtype=wp.vec3f, device=device) + self._lin_acc_b = wp.zeros(num_envs, dtype=wp.vec3f, device=device) + self._ang_acc_b = wp.zeros(num_envs, dtype=wp.vec3f, device=device) + + # -- Pinned ProxyArray cache (one per read property, lazily created on first access) + self._pose_w_ta: ProxyArray | None = None + self._pos_w_ta: ProxyArray | None = None + self._quat_w_ta: ProxyArray | None = None + self._projected_gravity_b_ta: ProxyArray | None = None + self._lin_vel_b_ta: ProxyArray | None = None + self._ang_vel_b_ta: ProxyArray | None = None + self._lin_acc_b_ta: ProxyArray | None = None + self._ang_acc_b_ta: ProxyArray | None = None diff --git a/source/isaaclab_physx/isaaclab_physx/sim/__init__.py b/source/isaaclab_physx/isaaclab_physx/sim/__init__.py new file mode 100644 index 000000000000..c315db7b9b3e --- /dev/null +++ b/source/isaaclab_physx/isaaclab_physx/sim/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Sub-package containing simulation-specific functionalities for PhysX backend.""" + +from isaaclab.utils.module import lazy_export + +lazy_export() diff --git a/source/isaaclab_physx/isaaclab_physx/sim/__init__.pyi b/source/isaaclab_physx/isaaclab_physx/sim/__init__.pyi new file mode 100644 index 000000000000..abc8d0087afd --- /dev/null +++ b/source/isaaclab_physx/isaaclab_physx/sim/__init__.pyi @@ -0,0 +1,28 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +__all__ = [ + "define_deformable_body_properties", + "modify_deformable_body_properties", + "DeformableBodyPropertiesCfg", + "DeformableObjectSpawnerCfg", + "spawn_deformable_body_material", + "DeformableBodyMaterialCfg", + "SurfaceDeformableBodyMaterialCfg", + "views", +] + +from .schemas import ( + define_deformable_body_properties, + modify_deformable_body_properties, + DeformableBodyPropertiesCfg +) +from .spawners import ( + DeformableObjectSpawnerCfg, + spawn_deformable_body_material, + DeformableBodyMaterialCfg, + SurfaceDeformableBodyMaterialCfg, +) +from . import views diff --git a/source/isaaclab_physx/isaaclab_physx/sim/schemas/__init__.py b/source/isaaclab_physx/isaaclab_physx/sim/schemas/__init__.py new file mode 100644 index 000000000000..b0d1477483d6 --- /dev/null +++ b/source/isaaclab_physx/isaaclab_physx/sim/schemas/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Sub-module containing utilities for schemas used in Omniverse for PhysX backend.""" + +from isaaclab.utils.module import lazy_export + +lazy_export() diff --git a/source/isaaclab_physx/isaaclab_physx/sim/schemas/__init__.pyi b/source/isaaclab_physx/isaaclab_physx/sim/schemas/__init__.pyi new file mode 100644 index 000000000000..bb0e51a19b4b --- /dev/null +++ b/source/isaaclab_physx/isaaclab_physx/sim/schemas/__init__.pyi @@ -0,0 +1,16 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +__all__ = [ + "define_deformable_body_properties", + "modify_deformable_body_properties", + "DeformableBodyPropertiesCfg", +] + +from .schemas import ( + define_deformable_body_properties, + modify_deformable_body_properties, +) +from .schemas_cfg import DeformableBodyPropertiesCfg diff --git a/source/isaaclab_physx/isaaclab_physx/sim/schemas/schemas.py b/source/isaaclab_physx/isaaclab_physx/sim/schemas/schemas.py new file mode 100644 index 000000000000..5b57b93d7ff4 --- /dev/null +++ b/source/isaaclab_physx/isaaclab_physx/sim/schemas/schemas.py @@ -0,0 +1,208 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +# needed to import for allowing type-hinting: Usd.Stage | None +from __future__ import annotations + +import logging + +from omni.physx.scripts import deformableUtils +from pxr import Usd + +from isaaclab.sim.utils import ( + apply_nested, + get_all_matching_child_prims, + safe_set_attribute_on_usd_prim, +) +from isaaclab.sim.utils.stage import get_current_stage +from isaaclab.utils.string import to_camel_case + +from isaaclab_physx.sim.schemas.schemas_cfg import DeformableBodyPropertiesCfg + +# import logger +logger = logging.getLogger(__name__) + + +""" +Deformable body properties. +""" + + +def define_deformable_body_properties( + prim_path: str, + cfg: DeformableBodyPropertiesCfg, + stage: Usd.Stage | None = None, + deformable_type: str = "volume", + sim_mesh_prim_path: str | None = None, +): + """Apply the deformable body schema on the input prim and set its properties. + + See :func:`modify_deformable_body_properties` for more details on how the properties are set. + + .. note:: + If the input prim is not a mesh, this function will traverse the prim and find the first mesh + under it. If no mesh or multiple meshes are found, an error is raised. This is because the deformable + body schema can only be applied to a single mesh. + + Args: + prim_path: The prim path where to apply the deformable body schema. + cfg: The configuration for the deformable body. + stage: The stage where to find the prim. Defaults to None, in which case the + current stage is used. + deformable_type: The type of the deformable body (surface or volume). + This is used to determine which PhysX API to use for the deformable body. Defaults to "volume". + sim_mesh_prim_path: Optional override for the simulation mesh prim path. + If None, it is set to ``{prim_path}/sim_mesh`` for surface deformables + and ``{prim_path}/sim_tetmesh`` for volume deformables. + + Raises: + ValueError: When the prim path is not valid. + ValueError: When the prim has no mesh or multiple meshes. + RuntimeError: When setting the deformable body properties fails. + """ + # get stage handle + if stage is None: + stage = get_current_stage() + + # get USD prim + prim = stage.GetPrimAtPath(prim_path) + # check if prim path is valid + if not prim.IsValid(): + raise ValueError(f"Prim path '{prim_path}' is not valid.") + + # traverse the prim and get the mesh. If none or multiple meshes are found, raise error. + matching_prims = get_all_matching_child_prims(prim_path, lambda p: p.GetTypeName() == "Mesh") + # check if the volume deformable mesh is valid + if len(matching_prims) == 0: + raise ValueError(f"Could not find any mesh in '{prim_path}'. Please check asset.") + if len(matching_prims) > 1: + # get list of all meshes found + mesh_paths = [p.GetPrimPath() for p in matching_prims] + raise ValueError( + f"Found multiple meshes in '{prim_path}': {mesh_paths}." + " Deformable body schema can only be applied to one mesh." + ) + mesh_prim = matching_prims[0] + mesh_prim_path = mesh_prim.GetPrimPath() + + # check if the prim is valid + if not mesh_prim.IsValid(): + raise ValueError(f"Mesh prim path '{mesh_prim_path}' is not valid.") + + # set root prim properties based on the type of the deformable mesh (surface vs volume) + if deformable_type == "surface": + sim_mesh_prim_path = prim_path + "/sim_mesh" if sim_mesh_prim_path is None else sim_mesh_prim_path + success = deformableUtils.create_auto_surface_deformable_hierarchy( + stage=stage, + root_prim_path=prim_path, + simulation_mesh_path=sim_mesh_prim_path, + cooking_src_mesh_path=mesh_prim_path, + cooking_src_simplification_enabled=False, + set_visibility_with_guide_purpose=True, + ) + elif deformable_type == "volume": + sim_mesh_prim_path = prim_path + "/sim_tetmesh" if sim_mesh_prim_path is None else sim_mesh_prim_path + success = deformableUtils.create_auto_volume_deformable_hierarchy( + stage=stage, + root_prim_path=prim_path, + simulation_tetmesh_path=sim_mesh_prim_path, + collision_tetmesh_path=sim_mesh_prim_path, + cooking_src_mesh_path=mesh_prim_path, + simulation_hex_mesh_enabled=False, + cooking_src_simplification_enabled=False, + set_visibility_with_guide_purpose=True, + ) + else: + raise ValueError( + f"""Unsupported deformable type: '{deformable_type}'. + Only surface and volume deformables are supported.""" + ) + + # api failure + if not success: + raise RuntimeError(f"Failed to set deformable body properties on prim '{mesh_prim_path}'.") + + # set deformable body properties + modify_deformable_body_properties(prim_path, cfg, stage) + + +@apply_nested +def modify_deformable_body_properties(prim_path: str, cfg: DeformableBodyPropertiesCfg, stage: Usd.Stage | None = None): + """Modify PhysX parameters for a deformable body prim. + + A `deformable body`_ is a single body (either surface or volume deformable) that can be simulated by PhysX. + Unlike rigid bodies, deformable bodies support relative motion of the nodes in the mesh. + Consequently, they can be used to simulate deformations under applied forces. + + PhysX deformable body simulation employs Finite Element Analysis (FEA) to simulate the deformations of the mesh. + It uses two meshes to represent the deformable body: + + 1. **Simulation mesh**: This mesh is used for the simulation and is the one that is deformed by the solver. + 2. **Collision mesh**: This mesh only needs to match the surface of the simulation mesh and is used for + collision detection. + + For most applications, we assume that the above two meshes are computed from the "render mesh" of the deformable + body. The render mesh is the mesh that is visible in the scene and is used for rendering purposes. It is composed + of triangles, while the simulation mesh is composed of tetrahedrons for volume deformables, + and triangles for surface deformables. + + .. caution:: + The deformable body schema is still under development by the Omniverse team. The current implementation + works with the PhysX schemas shipped with Isaac Sim 6.0.0 onwards. It may change in future releases. + + .. note:: + This function is decorated with :func:`apply_nested` that sets the properties to all the prims + (that have the schema applied on them) under the input prim path. + + .. _deformable body: https://nvidia-omniverse.github.io/PhysX/physx/5.6.1/docs/DeformableVolume.html + .. _PhysxDeformableBodyAPI: https://docs.omniverse.nvidia.com/kit/docs/omni_usd_schema_physics/latest/physxschema/annotated.html + + Args: + prim_path: The prim path to the deformable body. + cfg: The configuration for the deformable body. + stage: The stage where to find the prim. Defaults to None, in which case the + current stage is used. + + Returns: + True if the properties were successfully set, False otherwise. + """ + # get stage handle + if stage is None: + stage = get_current_stage() + + # get deformable-body USD prim + deformable_body_prim = stage.GetPrimAtPath(prim_path) + # check if the prim is valid + if not deformable_body_prim.IsValid(): + return False + # check if deformable body API is applied + if "OmniPhysicsDeformableBodyAPI" not in deformable_body_prim.GetAppliedSchemas(): + return False + + # apply customization to deformable API + if "PhysxBaseDeformableBodyAPI" not in deformable_body_prim.GetAppliedSchemas(): + deformable_body_prim.AddAppliedSchema("PhysxBaseDeformableBodyAPI") + + # ensure PhysX collision API is applied on the collision mesh + if "PhysxCollisionAPI" not in deformable_body_prim.GetAppliedSchemas(): + deformable_body_prim.AddAppliedSchema("PhysxCollisionAPI") + + # convert to dict + cfg = cfg.to_dict() + # set into PhysX API + if cfg["kinematic_enabled"]: + logger.warning( + "Kinematic deformable bodies are not fully supported in the current version of Omni Physics. " + "Setting kinematic_enabled to True may lead to unexpected behavior." + ) + # prefixes for each attribute (collision attributes: physxCollision:*, and physxDeformable:* for rest) + property_prefixes = cfg["_property_prefix"] + for prefix, attr_list in property_prefixes.items(): + for attr_name in attr_list: + safe_set_attribute_on_usd_prim( + deformable_body_prim, f"{prefix}:{to_camel_case(attr_name, 'cC')}", cfg[attr_name], camel_case=False + ) + # success + return True diff --git a/source/isaaclab_physx/isaaclab_physx/sim/schemas/schemas_cfg.py b/source/isaaclab_physx/isaaclab_physx/sim/schemas/schemas_cfg.py new file mode 100644 index 000000000000..6579fee6356a --- /dev/null +++ b/source/isaaclab_physx/isaaclab_physx/sim/schemas/schemas_cfg.py @@ -0,0 +1,163 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from __future__ import annotations + +import dataclasses + +from isaaclab.utils import configclass + + +@configclass +class OmniPhysicsPropertiesCfg: + """OmniPhysics properties for a deformable body. + + These properties are set with the prefix ``omniphysics:``. For example, to set the mass of the + deformable body, you would set the property ``omniphysics:mass``. + + See the OmniPhysics documentation for more information on the available properties. + """ + + deformable_body_enabled: bool | None = None + """Enables deformable body.""" + + kinematic_enabled: bool = False + """Enables kinematic body. Defaults to False, which means that the body is not kinematic.""" + + mass: float | None = None + """The material mass in [kg]. Defaults to None, in which case the material density is used to compute the mass.""" + + +@configclass +class PhysXDeformableBodyPropertiesCfg: + """PhysX-specific properties for a deformable body. + + These properties are set with the prefix ``physxDeformableBody:`` + + For more information on the available properties, please refer to the `documentation `_. + """ + + solver_position_iteration_count: int = 16 + """Number of the solver positional iterations per step. Range is [1,255], default to 16.""" + + linear_damping: float | None = None + """Linear damping coefficient, in units of [1/s] and constrained to the range [0, inf).""" + + max_linear_velocity: float | None = None + """Maximum allowable linear velocity for the deformable body, in units of distance/second and constrained to the + range [0, inf). A negative value allows the simulation to choose suitable a per vertex value dynamically, + currently only supported for surface deformables. This can help prevent surface-surface intersections.""" + + settling_damping: float | None = None + """Additional damping applied when a vertex's velocity falls below :attr:`settling_threshold`. + Specified in units of [1/s] and constrained to the range [0, inf).""" + + settling_threshold: float | None = None + """Velocity threshold below which :attr:`settling_damping` is applied in addition to standard damping. + Specified in units of distance/second and constrained to the range [0, inf).""" + + sleep_threshold: float | None = None + """Velocity threshold below which a vertex becomes a candidate for sleeping. + Specified in units of distance/seconds and constrained to the range [0, inf).""" + + max_depenetration_velocity: float | None = None + """Maximum velocity that the solver may apply to resolve intersections. + Specified in units of distance/seconds and constrained to the range [0, inf).""" + + self_collision: bool | None = None + """Enables self-collisions for the deformable body, preventing self-intersections.""" + + self_collision_filter_distance: float | None = None + r"""Distance below which self-collision is disabled [m]. + + The default value of -inf indicates that the simulation selects a suitable value. + Constrained to range [:attr:`rest_offset` \* 2, inf]. + """ + + enable_speculative_c_c_d: bool | None = None + """Enables dynamic adjustment of contact offset based on velocity (speculative continuous collision detection).""" + + disable_gravity: bool | None = None + """Disables gravity for the deformable body.""" + + # specific to surface deformables + collision_pair_update_frequency: int | None = None + """Determines how often surface-to-surface collision pairs are updated during each time step. + Increasing this value results in more frequent updates to the contact pairs, which provides better contact points. + + For example, a value of 2 means collision pairs are updated twice per time step: + once at the beginning and once in the middle of the time step (i.e., during the middle solver iteration). + If set to 0, the solver adaptively determines when to update the surface-to-surface contact pairs, + instead of using a fixed frequency. + + Valid range: [1, :attr:`solver_position_iteration_count`]. + """ + + collision_iteration_multiplier: float | None = None + """Determines how many collision subiterations are used in each solver iteration. + By default, collision constraints are applied once per solver iteration. + Increasing this value applies collision constraints more frequently within each solver iteration. + + For example, a value of 2 means collision constraints are applied twice per solver iteration + (i.e., collision constraints are applied 2 x :attr:`solver_position_iteration_count` times per time step). + Increasing this value does not update collision pairs more frequently; + refer to :attr:`collision_pair_update_frequency` for that. + + Valid range: [1, :attr:`solver_position_iteration_count` / 2]. + """ + + +@configclass +class PhysXCollisionPropertiesCfg: + """PhysX-specific collision properties for a deformable body. + + These properties are set with the prefix ``physxCollision:``. + + See the PhysX documentation for more information on the available properties. + """ + + contact_offset: float | None = None + """Contact offset for the collision shape [m]. + + The collision detector generates contact points as soon as two shapes get closer than the sum of their + contact offsets. This quantity should be non-negative which means that contact generation can potentially start + before the shapes actually penetrate. + """ + + rest_offset: float | None = None + """Rest offset for the collision shape [m]. + + The rest offset quantifies how close a shape gets to others at rest, At rest, the distance between two + vertically stacked objects is the sum of their rest offsets. If a pair of shapes have a positive rest + offset, the shapes will be separated at rest by an air gap. + """ + + +@configclass +class DeformableBodyPropertiesCfg( + OmniPhysicsPropertiesCfg, PhysXDeformableBodyPropertiesCfg, PhysXCollisionPropertiesCfg +): + """Properties to apply to a deformable body. + + A deformable body is a body that can deform under forces, both surface and volume deformables. + The configuration allows users to specify the properties of the deformable body, + such as the solver iteration counts, damping, and self-collision. + + An FEM-based deformable body is created by providing a collision mesh and simulation mesh. The collision mesh + is used for collision detection and the simulation mesh is used for simulation. + + See :meth:`modify_deformable_body_properties` for more information. + + .. note:: + If the values are :obj:`None`, they are not modified. This is useful when you want to set only a subset of + the properties and leave the rest as-is. + """ + + _property_prefix: dict[str, list[str]] = { + "omniphysics": [field.name for field in dataclasses.fields(OmniPhysicsPropertiesCfg)], + "physxDeformableBody": [field.name for field in dataclasses.fields(PhysXDeformableBodyPropertiesCfg)], + "physxCollision": [field.name for field in dataclasses.fields(PhysXCollisionPropertiesCfg)], + } + """Mapping between the property prefixes and the properties that fall under each prefix.""" diff --git a/source/isaaclab_physx/isaaclab_physx/sim/spawners/__init__.py b/source/isaaclab_physx/isaaclab_physx/sim/spawners/__init__.py new file mode 100644 index 000000000000..82b931452f4f --- /dev/null +++ b/source/isaaclab_physx/isaaclab_physx/sim/spawners/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Sub-module containing utilities for creating prims in Omniverse for the PhysX backend.""" + +from isaaclab.utils.module import lazy_export + +lazy_export() diff --git a/source/isaaclab_physx/isaaclab_physx/sim/spawners/__init__.pyi b/source/isaaclab_physx/isaaclab_physx/sim/spawners/__init__.pyi new file mode 100644 index 000000000000..805a9f79fd52 --- /dev/null +++ b/source/isaaclab_physx/isaaclab_physx/sim/spawners/__init__.pyi @@ -0,0 +1,18 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +__all__ = [ + "DeformableObjectSpawnerCfg", + "spawn_deformable_body_material", + "DeformableBodyMaterialCfg", + "SurfaceDeformableBodyMaterialCfg", +] + +from .spawner_cfg import DeformableObjectSpawnerCfg +from .materials import ( + spawn_deformable_body_material, + DeformableBodyMaterialCfg, + SurfaceDeformableBodyMaterialCfg, +) diff --git a/source/isaaclab_physx/isaaclab_physx/sim/spawners/materials/__init__.py b/source/isaaclab_physx/isaaclab_physx/sim/spawners/materials/__init__.py new file mode 100644 index 000000000000..4877bb0c1470 --- /dev/null +++ b/source/isaaclab_physx/isaaclab_physx/sim/spawners/materials/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Sub-module for spawners that spawn PhysX-based materials.""" + +from isaaclab.utils.module import lazy_export + +lazy_export() diff --git a/source/isaaclab_physx/isaaclab_physx/sim/spawners/materials/__init__.pyi b/source/isaaclab_physx/isaaclab_physx/sim/spawners/materials/__init__.pyi new file mode 100644 index 000000000000..6e8a48b2f118 --- /dev/null +++ b/source/isaaclab_physx/isaaclab_physx/sim/spawners/materials/__init__.pyi @@ -0,0 +1,16 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +__all__ = [ + "spawn_deformable_body_material", + "DeformableBodyMaterialCfg", + "SurfaceDeformableBodyMaterialCfg", +] + +from .physics_materials import spawn_deformable_body_material +from .physics_materials_cfg import ( + DeformableBodyMaterialCfg, + SurfaceDeformableBodyMaterialCfg, +) diff --git a/source/isaaclab_physx/isaaclab_physx/sim/spawners/materials/physics_materials.py b/source/isaaclab_physx/isaaclab_physx/sim/spawners/materials/physics_materials.py new file mode 100644 index 000000000000..78920cca9f8d --- /dev/null +++ b/source/isaaclab_physx/isaaclab_physx/sim/spawners/materials/physics_materials.py @@ -0,0 +1,80 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from __future__ import annotations + +from pxr import Usd, UsdShade + +from isaaclab.sim.utils import clone, safe_set_attribute_on_usd_prim +from isaaclab.sim.utils.stage import get_current_stage +from isaaclab.utils.string import to_camel_case + +from . import physics_materials_cfg + + +@clone +def spawn_deformable_body_material(prim_path: str, cfg: physics_materials_cfg.DeformableBodyMaterialCfg) -> Usd.Prim: + """Create material with deformable-body physics properties. + + Deformable body materials are used to define the physical properties to meshes of a deformable body. These + include the friction and deformable body properties. For more information on deformable body material, + please refer to the documentation on `PxFEMSoftBodyMaterial`_. + + .. note:: + This function is decorated with :func:`clone` that resolves prim path into list of paths + if the input prim path is a regex pattern. This is done to support spawning multiple assets + from a single and cloning the USD prim at the given path expression. + + Args: + prim_path: The prim path or pattern to spawn the asset at. If the prim path is a regex pattern, + then the asset is spawned at all the matching prim paths. + cfg: The configuration for the physics material. + + Returns: + The spawned deformable body material prim. + + Raises: + ValueError: When a prim already exists at the specified prim path and is not a material. + + .. _PxFEMSoftBodyMaterial: https://nvidia-omniverse.github.io/PhysX/physx/5.4.1/_api_build/structPxFEMSoftBodyMaterialModel.html + """ + # get stage handle + stage = get_current_stage() + + # create material prim if no prim exists + if not stage.GetPrimAtPath(prim_path).IsValid(): + _ = UsdShade.Material.Define(stage, prim_path) + + # obtain prim + prim = stage.GetPrimAtPath(prim_path) + # check if prim is a material + if not prim.IsA(UsdShade.Material): + raise ValueError(f"A prim already exists at path: '{prim_path}' but is not a material.") + # ensure PhysX deformable body material API is applied + applied = prim.GetAppliedSchemas() + if "OmniPhysicsDeformableMaterialAPI" not in applied: + prim.AddAppliedSchema("OmniPhysicsDeformableMaterialAPI") + if "PhysxDeformableMaterialAPI" not in applied: + prim.AddAppliedSchema("PhysxDeformableMaterialAPI") + # surface deformable material API + is_surface_deformable = isinstance(cfg, physics_materials_cfg.SurfaceDeformableBodyMaterialCfg) + if is_surface_deformable: + if "OmniPhysicsSurfaceDeformableMaterialAPI" not in applied: + prim.AddAppliedSchema("OmniPhysicsSurfaceDeformableMaterialAPI") + if "PhysxSurfaceDeformableMaterialAPI" not in applied: + prim.AddAppliedSchema("PhysxSurfaceDeformableMaterialAPI") + + # convert to dict + cfg = cfg.to_dict() + del cfg["func"] + # set into PhysX API, gather prefixes for each attribute + property_prefixes = cfg["_property_prefix"] + for prefix, attr_list in property_prefixes.items(): + for attr_name in attr_list: + safe_set_attribute_on_usd_prim( + prim, f"{prefix}:{to_camel_case(attr_name, 'cC')}", cfg[attr_name], camel_case=False + ) + # return the prim + return prim diff --git a/source/isaaclab_physx/isaaclab_physx/sim/spawners/materials/physics_materials_cfg.py b/source/isaaclab_physx/isaaclab_physx/sim/spawners/materials/physics_materials_cfg.py new file mode 100644 index 000000000000..35b066fa8736 --- /dev/null +++ b/source/isaaclab_physx/isaaclab_physx/sim/spawners/materials/physics_materials_cfg.py @@ -0,0 +1,122 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from __future__ import annotations + +import dataclasses +from collections.abc import Callable + +from isaaclab.sim.spawners.materials import PhysicsMaterialCfg +from isaaclab.utils import configclass + + +@configclass +class OmniPhysicsDeformableMaterialCfg: + """OmniPhysics material properties for a deformable body. + + These properties are set with the prefix ``omniphysics:``. For example, to set the density of the + deformable body, you would set the property ``omniphysics:density``. + + See the OmniPhysics documentation for more information on the available properties. + """ + + density: float | None = None + """The material density in [kg/m^3]. Defaults to None, in which case the simulation decides the default density.""" + + static_friction: float = 0.25 + """The static friction. Defaults to 0.25.""" + + dynamic_friction: float = 0.25 + """The dynamic friction. Defaults to 0.25.""" + + youngs_modulus: float = 1000000.0 + """The Young's modulus, which defines the body's stiffness. Defaults to 1[MPa]. + + The Young's modulus is a measure of the material's ability to deform under stress. It is measured in Pascals ([Pa]). + """ + + poissons_ratio: float = 0.45 + """The Poisson's ratio which defines the body's volume preservation. Defaults to 0.45. + + The Poisson's ratio is a measure of the material's ability to expand in the lateral direction when compressed + in the axial direction. It is a dimensionless number between 0 and 0.5. Using a value of 0.5 will make the + material incompressible. + """ + + +@configclass +class OmniPhysicsSurfaceDeformableMaterialCfg(OmniPhysicsDeformableMaterialCfg): + """OmniPhysics material properties for a surface deformable body, + extending on :class:`OmniPhysicsDeformableMaterialCfg` with additional parameters for surface deformable bodies. + + These properties are set with the prefix ``omniphysics:``. + For example, to set the surface thickness of the surface deformable body, + you would set the property ``omniphysics:surfaceThickness``. + + See the OmniPhysics documentation for more information on the available properties. + """ + + surface_thickness: float = 0.01 + """The thickness of the deformable body's surface. Defaults to 0.01 meters ([m]).""" + + surface_stretch_stiffness: float = 0.0 + """The stretch stiffness of the deformable body's surface. Defaults to 0.0.""" + + surface_shear_stiffness: float = 0.0 + """The shear stiffness of the deformable body's surface. Defaults to 0.0.""" + + surface_bend_stiffness: float = 0.0 + """The bend stiffness of the deformable body's surface. Defaults to 0.0.""" + + bend_damping: float = 0.0 + """The bend damping for the deformable body's surface. Defaults to 0.0.""" + + +@configclass +class PhysXDeformableMaterialCfg: + """PhysX-specific material properties for a deformable body. + + These properties are set with the prefix ``physxDeformableBody:``. + For example, to set the elasticity damping of the deformable body, + you would set the property ``physxDeformableBody:elasticityDamping``. + + See the PhysX documentation for more information on the available properties. + """ + + elasticity_damping: float = 0.005 + """The elasticity damping for the deformable material. Defaults to 0.005.""" + + +@configclass +class DeformableBodyMaterialCfg(PhysicsMaterialCfg, OmniPhysicsDeformableMaterialCfg, PhysXDeformableMaterialCfg): + """Physics material parameters for deformable bodies. + + See :meth:`spawn_deformable_body_material` for more information. + """ + + func: Callable | str = "{DIR}.physics_materials:spawn_deformable_body_material" + + _property_prefix: dict[str, list[str]] = { + "omniphysics": [field.name for field in dataclasses.fields(OmniPhysicsDeformableMaterialCfg)], + "physxDeformableBody": [field.name for field in dataclasses.fields(PhysXDeformableMaterialCfg)], + } + """Mapping between the property prefixes and the properties that fall under each prefix.""" + + +@configclass +class SurfaceDeformableBodyMaterialCfg(DeformableBodyMaterialCfg, OmniPhysicsSurfaceDeformableMaterialCfg): + """Physics material parameters for surface deformable bodies, + extending on :class:`DeformableBodyMaterialCfg` with additional parameters for surface deformable bodies. + + See :meth:`spawn_deformable_body_material` for more information. + """ + + func: Callable | str = "{DIR}.physics_materials:spawn_deformable_body_material" + + _property_prefix: dict[str, list[str]] = { + "omniphysics": [field.name for field in dataclasses.fields(OmniPhysicsSurfaceDeformableMaterialCfg)], + "physxDeformableBody": [field.name for field in dataclasses.fields(PhysXDeformableMaterialCfg)], + } + """Extend DeformableBodyMaterialCfg properties under each prefix.""" diff --git a/source/isaaclab_physx/isaaclab_physx/sim/spawners/spawner_cfg.py b/source/isaaclab_physx/isaaclab_physx/sim/spawners/spawner_cfg.py new file mode 100644 index 000000000000..dda028508762 --- /dev/null +++ b/source/isaaclab_physx/isaaclab_physx/sim/spawners/spawner_cfg.py @@ -0,0 +1,39 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from isaaclab.sim.spawners.spawner_cfg import SpawnerCfg +from isaaclab.utils import configclass + +if TYPE_CHECKING: + from isaaclab.sim import schemas + + # deformables only supported on PhysX backend + from isaaclab_physx.sim.schemas.schemas_cfg import DeformableBodyPropertiesCfg + + +@configclass +class DeformableObjectSpawnerCfg(SpawnerCfg): + """Configuration parameters for spawning a deformable asset. + + Unlike rigid objects, deformable objects are affected by forces and can deform when subjected to + external forces. This class is used to configure the properties of the deformable object. + + Deformable bodies don't have a separate collision mesh. The collision mesh is the same as the visual mesh. + The collision properties such as rest and collision offsets are specified in the :attr:`deformable_props`. + + Note: + By default, all properties are set to None. This means that no properties will be added or modified + to the prim outside of the properties available by default when spawning the prim. + """ + + mass_props: schemas.MassPropertiesCfg | None = None + """Mass properties.""" + + deformable_props: DeformableBodyPropertiesCfg | None = None + """Deformable body properties. Only supported on PhysX backend for now.""" diff --git a/source/isaaclab_physx/isaaclab_physx/sim/views/__init__.py b/source/isaaclab_physx/isaaclab_physx/sim/views/__init__.py new file mode 100644 index 000000000000..85c69b44a24f --- /dev/null +++ b/source/isaaclab_physx/isaaclab_physx/sim/views/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""PhysX simulation views.""" + +from isaaclab.utils.module import lazy_export + +lazy_export() diff --git a/source/isaaclab_physx/isaaclab_physx/sim/views/__init__.pyi b/source/isaaclab_physx/isaaclab_physx/sim/views/__init__.pyi new file mode 100644 index 000000000000..789d62af9d14 --- /dev/null +++ b/source/isaaclab_physx/isaaclab_physx/sim/views/__init__.pyi @@ -0,0 +1,10 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +__all__ = [ + "FabricFrameView", +] + +from .fabric_frame_view import FabricFrameView diff --git a/source/isaaclab_physx/isaaclab_physx/sim/views/fabric_frame_view.py b/source/isaaclab_physx/isaaclab_physx/sim/views/fabric_frame_view.py new file mode 100644 index 000000000000..de65e8501793 --- /dev/null +++ b/source/isaaclab_physx/isaaclab_physx/sim/views/fabric_frame_view.py @@ -0,0 +1,410 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""PhysX FrameView with Fabric GPU acceleration.""" + +from __future__ import annotations + +import logging + +import torch +import warp as wp + +from pxr import Usd + +import isaaclab.sim as sim_utils +from isaaclab.app.settings_manager import SettingsManager +from isaaclab.sim.views.base_frame_view import BaseFrameView +from isaaclab.sim.views.usd_frame_view import UsdFrameView +from isaaclab.utils.warp import ProxyArray +from isaaclab.utils.warp import fabric as fabric_utils + +logger = logging.getLogger(__name__) + + +def _to_float32_2d(a: wp.array | torch.Tensor) -> wp.array | torch.Tensor: + """Ensure array is compatible with Fabric kernels (2-D float32). + + For ``wp.array`` with vec dtypes (``vec3f``, ``vec4f``), uses + :meth:`wp.array.view` for zero-copy reinterpretation. + ``torch.Tensor`` and already-correct 2-D float32 arrays pass through. + """ + if not isinstance(a, wp.array): + return a + if a.shape[0] == 0: + return a + if a.ndim == 2 and a.dtype == wp.float32: + return a + return a.view(dtype=wp.float32) + + +class FabricFrameView(BaseFrameView): + """FrameView with Fabric GPU acceleration for the PhysX backend. + + Uses composition: holds a :class:`UsdFrameView` internally for USD + fallback and non-accelerated operations (local poses, visibility, scales + when Fabric is disabled). + + When Fabric is enabled, world-pose and scale operations use GPU-accelerated + Warp kernels operating on ``omni:fabric:worldMatrix``. All other operations + delegate to the internal USD view. + + Pose getters return :class:`~isaaclab.utils.warp.ProxyArray`. Setters accept ``wp.array``. + """ + + def __init__( + self, + prim_path: str, + device: str = "cpu", + validate_xform_ops: bool = True, + sync_usd_on_fabric_write: bool = False, + stage: Usd.Stage | None = None, + ): + self._usd_view = UsdFrameView(prim_path, device=device, validate_xform_ops=validate_xform_ops, stage=stage) + self._device = device + self._sync_usd_on_fabric_write = sync_usd_on_fabric_write + + settings = SettingsManager.instance() + self._use_fabric = bool(settings.get("/physics/fabricEnabled", False)) + + if self._use_fabric and self._device == "cpu": + logger.warning( + "Fabric mode with Warp fabric-array operations is not supported on CPU devices. " + "Falling back to standard USD operations on the CPU. This may impact performance." + ) + self._use_fabric = False + + if self._use_fabric and self._device not in ("cuda", "cuda:0"): + logger.warning( + f"Fabric mode is not supported on device '{self._device}'. " + "USDRT SelectPrims and Warp fabric arrays only support cuda:0. " + "Falling back to standard USD operations. This may impact performance." + ) + self._use_fabric = False + + self._fabric_initialized = False + self._fabric_usd_sync_done = False + self._fabric_selection = None + self._fabric_to_view: wp.array | None = None + self._view_to_fabric: wp.array | None = None + self._default_view_indices: wp.array | None = None + self._fabric_hierarchy = None + self._view_index_attr = f"isaaclab:view_index:{abs(hash(self))}" + + # ------------------------------------------------------------------ + # Delegated properties + # ------------------------------------------------------------------ + + @property + def count(self) -> int: + return self._usd_view.count + + @property + def device(self) -> str: + """Device where arrays are allocated (cpu or cuda).""" + return self._device + + @property + def prims(self) -> list: + return self._usd_view.prims + + @property + def prim_paths(self) -> list[str]: + return self._usd_view.prim_paths + + # ------------------------------------------------------------------ + # Delegated operations (USD-only) + # ------------------------------------------------------------------ + + def get_visibility(self, indices=None): + return self._usd_view.get_visibility(indices) + + def set_visibility(self, visibility, indices=None): + self._usd_view.set_visibility(visibility, indices) + + # ------------------------------------------------------------------ + # World poses — Fabric-accelerated or USD fallback + # ------------------------------------------------------------------ + + def set_world_poses(self, positions=None, orientations=None, indices=None): + if not self._use_fabric: + self._usd_view.set_world_poses(positions, orientations, indices) + return + + if not self._fabric_initialized: + self._initialize_fabric() + + indices_wp = self._resolve_indices_wp(indices) + count = indices_wp.shape[0] + + dummy = wp.zeros((0, 3), dtype=wp.float32, device=self._device) + positions_wp = _to_float32_2d(positions) if positions is not None else dummy + orientations_wp = ( + _to_float32_2d(orientations) + if orientations is not None + else wp.zeros((0, 4), dtype=wp.float32, device=self._device) + ) + + wp.launch( + kernel=fabric_utils.compose_fabric_transformation_matrix_from_warp_arrays, + dim=count, + inputs=[ + self._fabric_world_matrices, + positions_wp, + orientations_wp, + dummy, + False, + False, + False, + indices_wp, + self._view_to_fabric, + ], + device=self._fabric_device, + ) + wp.synchronize() + + self._fabric_hierarchy.update_world_xforms() + self._fabric_usd_sync_done = True + if self._sync_usd_on_fabric_write: + self._usd_view.set_world_poses(positions, orientations, indices) + + def get_world_poses(self, indices: wp.array | None = None) -> tuple[ProxyArray, ProxyArray]: + if not self._use_fabric: + return self._usd_view.get_world_poses(indices) + + if not self._fabric_initialized: + self._initialize_fabric() + if not self._fabric_usd_sync_done: + self._sync_fabric_from_usd_once() + + indices_wp = self._resolve_indices_wp(indices) + count = indices_wp.shape[0] + + use_cached = indices is None or indices == slice(None) + if use_cached: + positions_wp = self._fabric_positions_buf + orientations_wp = self._fabric_orientations_buf + else: + positions_wp = wp.zeros((count, 3), dtype=wp.float32, device=self._device) + orientations_wp = wp.zeros((count, 4), dtype=wp.float32, device=self._device) + + wp.launch( + kernel=fabric_utils.decompose_fabric_transformation_matrix_to_warp_arrays, + dim=count, + inputs=[ + self._fabric_world_matrices, + positions_wp, + orientations_wp, + self._fabric_dummy_buffer, + indices_wp, + self._view_to_fabric, + ], + device=self._fabric_device, + ) + + if use_cached: + wp.synchronize() + return self._fabric_positions_ta, self._fabric_orientations_ta + return ProxyArray(positions_wp), ProxyArray(orientations_wp) + + # ------------------------------------------------------------------ + # Local poses — USD fallback (Fabric only accelerates world poses) + # ------------------------------------------------------------------ + + def set_local_poses(self, translations=None, orientations=None, indices=None): + self._usd_view.set_local_poses(translations, orientations, indices) + + def get_local_poses(self, indices: wp.array | None = None) -> tuple[ProxyArray, ProxyArray]: + return self._usd_view.get_local_poses(indices) + + # ------------------------------------------------------------------ + # Scales — Fabric-accelerated or USD fallback + # ------------------------------------------------------------------ + + def set_scales(self, scales, indices=None): + if not self._use_fabric: + self._usd_view.set_scales(scales, indices) + return + + if not self._fabric_initialized: + self._initialize_fabric() + + indices_wp = self._resolve_indices_wp(indices) + count = indices_wp.shape[0] + + dummy3 = wp.zeros((0, 3), dtype=wp.float32, device=self._device) + dummy4 = wp.zeros((0, 4), dtype=wp.float32, device=self._device) + scales_wp = _to_float32_2d(scales) + + wp.launch( + kernel=fabric_utils.compose_fabric_transformation_matrix_from_warp_arrays, + dim=count, + inputs=[ + self._fabric_world_matrices, + dummy3, + dummy4, + scales_wp, + False, + False, + False, + indices_wp, + self._view_to_fabric, + ], + device=self._fabric_device, + ) + wp.synchronize() + + self._fabric_hierarchy.update_world_xforms() + self._fabric_usd_sync_done = True + if self._sync_usd_on_fabric_write: + self._usd_view.set_scales(scales, indices) + + def get_scales(self, indices=None): + if not self._use_fabric: + return self._usd_view.get_scales(indices) + + if not self._fabric_initialized: + self._initialize_fabric() + if not self._fabric_usd_sync_done: + self._sync_fabric_from_usd_once() + + indices_wp = self._resolve_indices_wp(indices) + count = indices_wp.shape[0] + + use_cached = indices is None or indices == slice(None) + if use_cached: + scales_wp = self._fabric_scales_buf + else: + scales_wp = wp.zeros((count, 3), dtype=wp.float32, device=self._device) + + wp.launch( + kernel=fabric_utils.decompose_fabric_transformation_matrix_to_warp_arrays, + dim=count, + inputs=[ + self._fabric_world_matrices, + self._fabric_dummy_buffer, + self._fabric_dummy_buffer, + scales_wp, + indices_wp, + self._view_to_fabric, + ], + device=self._fabric_device, + ) + + if use_cached: + wp.synchronize() + return scales_wp + + # ------------------------------------------------------------------ + # Internal — Fabric initialization + # ------------------------------------------------------------------ + + def _initialize_fabric(self) -> None: + """Initialize Fabric batch infrastructure for GPU-accelerated pose queries.""" + import usdrt # noqa: PLC0415 + from usdrt import Rt # noqa: PLC0415 + + stage_id = sim_utils.get_current_stage_id() + fabric_stage = usdrt.Usd.Stage.Attach(stage_id) + + for i in range(self.count): + rt_prim = fabric_stage.GetPrimAtPath(self.prim_paths[i]) + rt_xformable = Rt.Xformable(rt_prim) + + has_attr = ( + rt_xformable.HasFabricHierarchyWorldMatrixAttr() + if hasattr(rt_xformable, "HasFabricHierarchyWorldMatrixAttr") + else False + ) + if not has_attr: + rt_xformable.CreateFabricHierarchyWorldMatrixAttr() + + rt_xformable.SetWorldXformFromUsd() + + rt_prim.CreateAttribute(self._view_index_attr, usdrt.Sdf.ValueTypeNames.UInt, custom=True) + rt_prim.GetAttribute(self._view_index_attr).Set(i) + + self._fabric_hierarchy = usdrt.hierarchy.IFabricHierarchy().get_fabric_hierarchy( + fabric_stage.GetFabricId(), fabric_stage.GetStageIdAsStageId() + ) + self._fabric_hierarchy.update_world_xforms() + + self._default_view_indices = wp.zeros((self.count,), dtype=wp.uint32, device=self._device) + wp.launch( + kernel=fabric_utils.arange_k, dim=self.count, inputs=[self._default_view_indices], device=self._device + ) + wp.synchronize() + + fabric_device = self._device + if self._device == "cuda": + logger.warning("Fabric device is not specified, defaulting to 'cuda:0'.") + fabric_device = "cuda:0" + elif self._device.startswith("cuda:"): + if self._device != "cuda:0": + logger.debug( + f"SelectPrims only supports cuda:0. Using cuda:0 for SelectPrims " + f"even though simulation device is {self._device}." + ) + fabric_device = "cuda:0" + + self._fabric_selection = fabric_stage.SelectPrims( + require_attrs=[ + (usdrt.Sdf.ValueTypeNames.UInt, self._view_index_attr, usdrt.Usd.Access.Read), + (usdrt.Sdf.ValueTypeNames.Matrix4d, "omni:fabric:worldMatrix", usdrt.Usd.Access.ReadWrite), + ], + device=fabric_device, + ) + + self._view_to_fabric = wp.zeros((self.count,), dtype=wp.uint32, device=fabric_device) + self._fabric_to_view = wp.fabricarray(self._fabric_selection, self._view_index_attr) + + wp.launch( + kernel=fabric_utils.set_view_to_fabric_array, + dim=self._fabric_to_view.shape[0], + inputs=[self._fabric_to_view, self._view_to_fabric], + device=fabric_device, + ) + wp.synchronize() + + self._fabric_positions_buf = wp.zeros((self.count, 3), dtype=wp.float32, device=self._device) + self._fabric_orientations_buf = wp.zeros((self.count, 4), dtype=wp.float32, device=self._device) + self._fabric_positions_ta = ProxyArray(self._fabric_positions_buf) + self._fabric_orientations_ta = ProxyArray(self._fabric_orientations_buf) + self._fabric_scales_buf = wp.zeros((self.count, 3), dtype=wp.float32, device=self._device) + self._fabric_dummy_buffer = wp.zeros((0, 3), dtype=wp.float32, device=self._device) + self._fabric_world_matrices = wp.fabricarray(self._fabric_selection, "omni:fabric:worldMatrix") + self._fabric_stage = fabric_stage + self._fabric_device = fabric_device + + self._fabric_initialized = True + self._fabric_usd_sync_done = False + + def _sync_fabric_from_usd_once(self) -> None: + """Sync Fabric world matrices from USD once, on the first read.""" + if not self._fabric_initialized: + self._initialize_fabric() + + positions_usd_ta, orientations_usd_ta = self._usd_view.get_world_poses() + positions_usd = positions_usd_ta.warp + orientations_usd = orientations_usd_ta.warp + scales_usd = self._usd_view.get_scales() + + prev_sync = self._sync_usd_on_fabric_write + self._sync_usd_on_fabric_write = False + self.set_world_poses(positions_usd, orientations_usd) + self.set_scales(scales_usd) + self._sync_usd_on_fabric_write = prev_sync + + self._fabric_usd_sync_done = True + + def _resolve_indices_wp(self, indices: wp.array | None) -> wp.array: + """Resolve view indices as a Warp uint32 array.""" + if indices is None or indices == slice(None): + if self._default_view_indices is None: + raise RuntimeError("Fabric indices are not initialized.") + return self._default_view_indices + if indices.dtype != wp.uint32: + return wp.array(indices.numpy().astype("uint32"), dtype=wp.uint32, device=self._device) + return indices diff --git a/source/isaaclab_physx/isaaclab_physx/video_recording/__init__.py b/source/isaaclab_physx/isaaclab_physx/video_recording/__init__.py new file mode 100644 index 000000000000..8deb00ddc466 --- /dev/null +++ b/source/isaaclab_physx/isaaclab_physx/video_recording/__init__.py @@ -0,0 +1,6 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Isaac Sim Kit perspective video recording.""" diff --git a/source/isaaclab_physx/isaaclab_physx/video_recording/isaacsim_kit_perspective_video.py b/source/isaaclab_physx/isaaclab_physx/video_recording/isaacsim_kit_perspective_video.py new file mode 100644 index 000000000000..4796340f2724 --- /dev/null +++ b/source/isaaclab_physx/isaaclab_physx/video_recording/isaacsim_kit_perspective_video.py @@ -0,0 +1,65 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Isaac Sim Kit perspective RGB capture via ``/OmniverseKit_Persp`` and omni.replicator.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +import numpy as np + +if TYPE_CHECKING: + from .isaacsim_kit_perspective_video_cfg import IsaacsimKitPerspectiveVideoCfg + + +class IsaacsimKitPerspectiveVideo: + """Stateful capture of one RGB frame per call from the Kit perspective camera.""" + + def __init__(self, cfg: IsaacsimKitPerspectiveVideoCfg): + self.cfg = cfg + self._rgb_annotator = None + self._render_product = None + + def render_rgb_array(self) -> np.ndarray: + """Return one RGB frame. Blank frame during warmup; raises on other failures.""" + import omni.kit.app + import omni.replicator.core as rep + + omni.kit.app.get_app().update() + + h, w = self.cfg.window_height, self.cfg.window_width + if self._rgb_annotator is None: + from isaacsim.core.rendering_manager import ViewportManager + + ViewportManager.set_camera_view( + self.cfg.camera_prim_path, + eye=list(self.cfg.eye), + target=list(self.cfg.lookat), + ) + self._render_product = rep.create.render_product(self.cfg.camera_prim_path, (w, h)) + self._rgb_annotator = rep.AnnotatorRegistry.get_annotator("rgb", device="cpu") + self._rgb_annotator.attach([self._render_product]) + + rgb_data = self._rgb_annotator.get_data() + if isinstance(rgb_data, dict): + rgb_data = rgb_data.get("data", np.array([], dtype=np.uint8)) + rgb_data = np.asarray(rgb_data, dtype=np.uint8) + if rgb_data.size == 0: + return np.zeros((h, w, 3), dtype=np.uint8) + if rgb_data.ndim == 1: + rgb_data = rgb_data.reshape(h, w, -1) + return rgb_data[:, :, :3] + + +def create_isaacsim_kit_perspective_video(cfg: IsaacsimKitPerspectiveVideoCfg) -> IsaacsimKitPerspectiveVideo: + """Instantiate the perspective video capture implementation from ``cfg.class_type``.""" + ct = cfg.class_type + if isinstance(ct, type): + return ct(cfg) + from isaaclab.utils.string import string_to_callable + + cls = string_to_callable(str(ct)) + return cls(cfg) diff --git a/source/isaaclab_physx/isaaclab_physx/video_recording/isaacsim_kit_perspective_video_cfg.py b/source/isaaclab_physx/isaaclab_physx/video_recording/isaacsim_kit_perspective_video_cfg.py new file mode 100644 index 000000000000..c3f9280976aa --- /dev/null +++ b/source/isaaclab_physx/isaaclab_physx/video_recording/isaacsim_kit_perspective_video_cfg.py @@ -0,0 +1,41 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Configuration for Isaac Sim Kit perspective RGB capture (OmniverseKit_Persp + Replicator).""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +from isaaclab.utils import configclass + +if TYPE_CHECKING: + pass + + +@configclass +class IsaacsimKitPerspectiveVideoCfg: + """Settings for capturing a perspective RGB frame from the Kit viewport camera.""" + + class_type: type[Any] | str = ( + "isaaclab_physx.video_recording.isaacsim_kit_perspective_video:IsaacsimKitPerspectiveVideo" + ) + """Implementation class; default is + :class:`~isaaclab_physx.video_recording.isaacsim_kit_perspective_video.IsaacsimKitPerspectiveVideo`.""" + + camera_prim_path: str = "/OmniverseKit_Persp" + """Viewport camera prim used for the render product.""" + + eye: tuple[float, float, float] = (7.5, 7.5, 7.5) + """Camera position in world space (metres).""" + + lookat: tuple[float, float, float] = (0.0, 0.0, 0.0) + """Camera look-at target in world space (metres).""" + + window_width: int = 1280 + """Output width in pixels.""" + + window_height: int = 720 + """Output height in pixels.""" diff --git a/source/isaaclab_physx/setup.py b/source/isaaclab_physx/setup.py index d8e1b731b4b3..1e917e938c2b 100644 --- a/source/isaaclab_physx/setup.py +++ b/source/isaaclab_physx/setup.py @@ -16,11 +16,13 @@ EXTENSION_TOML_DATA = toml.load(os.path.join(EXTENSION_PATH, "config", "extension.toml")) # Minimum dependencies required prior to installation -INSTALL_REQUIRES = [ - # INTENTIONALLY disabled to avoid circular dependency with isaaclab_physx, which also depends on isaaclab_newton. - # This will be re-enabled once we move to UV and pyproject.toml-based packaging. - # f"isaaclab_newton @ file://{os.path.join(os.path.dirname(EXTENSION_PATH), 'isaaclab_newton')}", -] +INSTALL_REQUIRES = [] + +EXTRAS_REQUIRE = { + "newton": [ + "newton @ git+https://github.com/newton-physics/newton.git@2684d75bfa4bb8b058a93b81c458a74b7701c997", + ], +} # Installation operation setup( @@ -34,8 +36,9 @@ license="BSD-3-Clause", include_package_data=True, package_data={"": ["*.pyi"]}, - python_requires=">=3.11", + python_requires=">=3.12", install_requires=INSTALL_REQUIRES, + extras_require=EXTRAS_REQUIRE, packages=[ "isaaclab_physx", "isaaclab_physx.assets", @@ -52,6 +55,10 @@ "isaaclab_physx.sensors.contact_sensor", "isaaclab_physx.sensors.frame_transformer", "isaaclab_physx.sensors.imu", + "isaaclab_physx.sim", + "isaaclab_physx.sim.schemas", + "isaaclab_physx.sim.spawners", + "isaaclab_physx.sim.spawners.materials", "isaaclab_physx.test", "isaaclab_physx.test.benchmark", "isaaclab_physx.test.mock_interfaces", @@ -60,10 +67,7 @@ ], classifiers=[ "Natural Language :: English", - "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", - "Isaac Sim :: 5.0.0", - "Isaac Sim :: 5.1.0", "Isaac Sim :: 6.0.0", ], zip_safe=False, diff --git a/source/isaaclab_physx/test/assets/test_articulation.py b/source/isaaclab_physx/test/assets/test_articulation.py index f1e31795c130..3687dae5961d 100644 --- a/source/isaaclab_physx/test/assets/test_articulation.py +++ b/source/isaaclab_physx/test/assets/test_articulation.py @@ -233,9 +233,9 @@ def test_initialization_floating_base_non_root(sim, num_articulations, device, a # Check that is fixed base assert not articulation.is_fixed_base # Check buffers that exists and have correct shapes - assert wp.to_torch(articulation.data.root_pos_w).shape == (num_articulations, 3) - assert wp.to_torch(articulation.data.root_quat_w).shape == (num_articulations, 4) - assert wp.to_torch(articulation.data.joint_pos).shape == (num_articulations, 21) + assert articulation.data.root_pos_w.torch.shape == (num_articulations, 3) + assert articulation.data.root_quat_w.torch.shape == (num_articulations, 4) + assert articulation.data.joint_pos.torch.shape == (num_articulations, 21) # Check some internal physx data for debugging # -- joint related @@ -289,11 +289,11 @@ def test_initialization_floating_base(sim, num_articulations, device, add_ground # Check that floating base assert not articulation.is_fixed_base # Check buffers that exists and have correct shapes - assert wp.to_torch(articulation.data.root_pos_w).shape == (num_articulations, 3) - assert wp.to_torch(articulation.data.root_quat_w).shape == (num_articulations, 4) - assert wp.to_torch(articulation.data.joint_pos).shape == (num_articulations, 12) - assert wp.to_torch(articulation.data.body_mass).shape == (num_articulations, articulation.num_bodies) - assert wp.to_torch(articulation.data.body_inertia).shape == (num_articulations, articulation.num_bodies, 9) + assert articulation.data.root_pos_w.torch.shape == (num_articulations, 3) + assert articulation.data.root_quat_w.torch.shape == (num_articulations, 4) + assert articulation.data.joint_pos.torch.shape == (num_articulations, 12) + assert articulation.data.body_mass.torch.shape == (num_articulations, articulation.num_bodies) + assert articulation.data.body_inertia.torch.shape == (num_articulations, articulation.num_bodies, 9) # Check some internal physx data for debugging # -- joint related @@ -346,11 +346,11 @@ def test_initialization_fixed_base(sim, num_articulations, device): # Check that fixed base assert articulation.is_fixed_base # Check buffers that exists and have correct shapes - assert wp.to_torch(articulation.data.root_pos_w).shape == (num_articulations, 3) - assert wp.to_torch(articulation.data.root_quat_w).shape == (num_articulations, 4) - assert wp.to_torch(articulation.data.joint_pos).shape == (num_articulations, 9) - assert wp.to_torch(articulation.data.body_mass).shape == (num_articulations, articulation.num_bodies) - assert wp.to_torch(articulation.data.body_inertia).shape == (num_articulations, articulation.num_bodies, 9) + assert articulation.data.root_pos_w.torch.shape == (num_articulations, 3) + assert articulation.data.root_quat_w.torch.shape == (num_articulations, 4) + assert articulation.data.joint_pos.torch.shape == (num_articulations, 9) + assert articulation.data.body_mass.torch.shape == (num_articulations, articulation.num_bodies) + assert articulation.data.body_inertia.torch.shape == (num_articulations, articulation.num_bodies, 9) # Check some internal physx data for debugging # -- joint related @@ -373,12 +373,12 @@ def test_initialization_fixed_base(sim, num_articulations, device): articulation.update(sim.cfg.dt) # check that the root is at the correct state - its default state as it is fixed base - default_root_pose = wp.to_torch(articulation.data.default_root_pose).clone() - default_root_vel = wp.to_torch(articulation.data.default_root_vel).clone() + default_root_pose = articulation.data.default_root_pose.torch.clone() + default_root_vel = articulation.data.default_root_vel.torch.clone() default_root_pose[:, :3] = default_root_pose[:, :3] + translations - torch.testing.assert_close(wp.to_torch(articulation.data.root_link_pose_w), default_root_pose) - torch.testing.assert_close(wp.to_torch(articulation.data.root_com_vel_w), default_root_vel) + torch.testing.assert_close(articulation.data.root_link_pose_w.torch, default_root_pose) + torch.testing.assert_close(articulation.data.root_com_vel_w.torch, default_root_vel) @pytest.mark.parametrize("num_articulations", [1, 2]) @@ -412,11 +412,11 @@ def test_initialization_fixed_base_single_joint(sim, num_articulations, device, # Check that fixed base assert articulation.is_fixed_base # Check buffers that exists and have correct shapes - assert wp.to_torch(articulation.data.root_pos_w).shape == (num_articulations, 3) - assert wp.to_torch(articulation.data.root_quat_w).shape == (num_articulations, 4) - assert wp.to_torch(articulation.data.joint_pos).shape == (num_articulations, 1) - assert wp.to_torch(articulation.data.body_mass).shape == (num_articulations, articulation.num_bodies) - assert wp.to_torch(articulation.data.body_inertia).shape == (num_articulations, articulation.num_bodies, 9) + assert articulation.data.root_pos_w.torch.shape == (num_articulations, 3) + assert articulation.data.root_quat_w.torch.shape == (num_articulations, 4) + assert articulation.data.joint_pos.torch.shape == (num_articulations, 1) + assert articulation.data.body_mass.torch.shape == (num_articulations, articulation.num_bodies) + assert articulation.data.body_inertia.torch.shape == (num_articulations, articulation.num_bodies, 9) # Check some internal physx data for debugging # -- joint related @@ -439,12 +439,12 @@ def test_initialization_fixed_base_single_joint(sim, num_articulations, device, articulation.update(sim.cfg.dt) # check that the root is at the correct state - its default state as it is fixed base - default_root_pose = wp.to_torch(articulation.data.default_root_pose).clone() - default_root_vel = wp.to_torch(articulation.data.default_root_vel).clone() + default_root_pose = articulation.data.default_root_pose.torch.clone() + default_root_vel = articulation.data.default_root_vel.torch.clone() default_root_pose[:, :3] = default_root_pose[:, :3] + translations - torch.testing.assert_close(wp.to_torch(articulation.data.root_link_pose_w), default_root_pose) - torch.testing.assert_close(wp.to_torch(articulation.data.root_com_vel_w), default_root_vel) + torch.testing.assert_close(articulation.data.root_link_pose_w.torch, default_root_pose) + torch.testing.assert_close(articulation.data.root_com_vel_w.torch, default_root_vel) @pytest.mark.parametrize("num_articulations", [1, 2]) @@ -477,11 +477,11 @@ def test_initialization_hand_with_tendons(sim, num_articulations, device): # Check that fixed base assert articulation.is_fixed_base # Check buffers that exists and have correct shapes - assert wp.to_torch(articulation.data.root_pos_w).shape == (num_articulations, 3) - assert wp.to_torch(articulation.data.root_quat_w).shape == (num_articulations, 4) - assert wp.to_torch(articulation.data.joint_pos).shape == (num_articulations, 24) - assert wp.to_torch(articulation.data.body_mass).shape == (num_articulations, articulation.num_bodies) - assert wp.to_torch(articulation.data.body_inertia).shape == (num_articulations, articulation.num_bodies, 9) + assert articulation.data.root_pos_w.torch.shape == (num_articulations, 3) + assert articulation.data.root_quat_w.torch.shape == (num_articulations, 4) + assert articulation.data.joint_pos.torch.shape == (num_articulations, 24) + assert articulation.data.body_mass.torch.shape == (num_articulations, articulation.num_bodies) + assert articulation.data.body_inertia.torch.shape == (num_articulations, articulation.num_bodies, 9) # Check some internal physx data for debugging # -- joint related @@ -533,9 +533,9 @@ def test_initialization_floating_base_made_fixed_base(sim, num_articulations, de # Check that is fixed base assert articulation.is_fixed_base # Check buffers that exists and have correct shapes - assert wp.to_torch(articulation.data.root_pos_w).shape == (num_articulations, 3) - assert wp.to_torch(articulation.data.root_quat_w).shape == (num_articulations, 4) - assert wp.to_torch(articulation.data.joint_pos).shape == (num_articulations, 12) + assert articulation.data.root_pos_w.torch.shape == (num_articulations, 3) + assert articulation.data.root_quat_w.torch.shape == (num_articulations, 4) + assert articulation.data.joint_pos.torch.shape == (num_articulations, 12) # Check some internal physx data for debugging # -- joint related @@ -554,12 +554,12 @@ def test_initialization_floating_base_made_fixed_base(sim, num_articulations, de articulation.update(sim.cfg.dt) # check that the root is at the correct state - its default state as it is fixed base - default_root_pose = wp.to_torch(articulation.data.default_root_pose).clone() - default_root_vel = wp.to_torch(articulation.data.default_root_vel).clone() + default_root_pose = articulation.data.default_root_pose.torch.clone() + default_root_vel = articulation.data.default_root_vel.torch.clone() default_root_pose[:, :3] = default_root_pose[:, :3] + translations - torch.testing.assert_close(wp.to_torch(articulation.data.root_link_pose_w), default_root_pose) - torch.testing.assert_close(wp.to_torch(articulation.data.root_com_vel_w), default_root_vel) + torch.testing.assert_close(articulation.data.root_link_pose_w.torch, default_root_pose) + torch.testing.assert_close(articulation.data.root_com_vel_w.torch, default_root_vel) @pytest.mark.parametrize("num_articulations", [1, 2]) @@ -594,9 +594,9 @@ def test_initialization_fixed_base_made_floating_base(sim, num_articulations, de # Check that is floating base assert not articulation.is_fixed_base # Check buffers that exists and have correct shapes - assert wp.to_torch(articulation.data.root_pos_w).shape == (num_articulations, 3) - assert wp.to_torch(articulation.data.root_quat_w).shape == (num_articulations, 4) - assert wp.to_torch(articulation.data.joint_pos).shape == (num_articulations, 9) + assert articulation.data.root_pos_w.torch.shape == (num_articulations, 3) + assert articulation.data.root_quat_w.torch.shape == (num_articulations, 4) + assert articulation.data.joint_pos.torch.shape == (num_articulations, 9) # Check some internal physx data for debugging # -- joint related @@ -698,7 +698,7 @@ def test_joint_pos_limits(sim, num_articulations, device, add_ground_plane): assert articulation.is_initialized # Get current default joint pos - default_joint_pos = wp.to_torch(articulation._data.default_joint_pos).clone() + default_joint_pos = articulation._data.default_joint_pos.torch.clone() # Set new joint limits limits = torch.zeros(num_articulations, articulation.num_joints, 2, device=device) @@ -707,8 +707,8 @@ def test_joint_pos_limits(sim, num_articulations, device, add_ground_plane): articulation.write_joint_position_limit_to_sim_index(limits=limits) # Check new limits are in place - torch.testing.assert_close(wp.to_torch(articulation._data.joint_pos_limits), limits) - torch.testing.assert_close(wp.to_torch(articulation._data.default_joint_pos), default_joint_pos) + torch.testing.assert_close(articulation._data.joint_pos_limits.torch, limits) + torch.testing.assert_close(articulation._data.default_joint_pos.torch, default_joint_pos) # Set new joint limits with indexing env_ids = torch.arange(1, device=device, dtype=torch.int32) @@ -719,8 +719,8 @@ def test_joint_pos_limits(sim, num_articulations, device, add_ground_plane): articulation.write_joint_position_limit_to_sim_index(limits=limits, env_ids=env_ids, joint_ids=joint_ids) # Check new limits are in place - torch.testing.assert_close(wp.to_torch(articulation._data.joint_pos_limits)[env_ids][:, joint_ids], limits) - torch.testing.assert_close(wp.to_torch(articulation._data.default_joint_pos), default_joint_pos) + torch.testing.assert_close(articulation._data.joint_pos_limits.torch[env_ids][:, joint_ids], limits) + torch.testing.assert_close(articulation._data.default_joint_pos.torch, default_joint_pos) # Set new joint limits that invalidate default joint pos limits = torch.zeros(num_articulations, articulation.num_joints, 2, device=device) @@ -729,7 +729,7 @@ def test_joint_pos_limits(sim, num_articulations, device, add_ground_plane): articulation.write_joint_position_limit_to_sim_index(limits=limits) # Check if all values are within the bounds - default_joint_pos_torch = wp.to_torch(articulation._data.default_joint_pos) + default_joint_pos_torch = articulation._data.default_joint_pos.torch within_bounds = (default_joint_pos_torch >= limits[..., 0]) & (default_joint_pos_torch <= limits[..., 1]) assert torch.all(within_bounds) @@ -740,7 +740,7 @@ def test_joint_pos_limits(sim, num_articulations, device, add_ground_plane): articulation.write_joint_position_limit_to_sim_index(limits=limits, env_ids=env_ids, joint_ids=joint_ids) # Check if all values are within the bounds - default_joint_pos_torch = wp.to_torch(articulation._data.default_joint_pos) + default_joint_pos_torch = articulation._data.default_joint_pos.torch within_bounds = (default_joint_pos_torch[env_ids][:, joint_ids] >= limits[..., 0]) & ( default_joint_pos_torch[env_ids][:, joint_ids] <= limits[..., 1] ) @@ -768,14 +768,14 @@ def __init__(self, art): assert articulation.is_initialized # Case A: no clipping → should NOT terminate - wp.to_torch(articulation._data.computed_torque).zero_() - wp.to_torch(articulation._data.applied_torque).zero_() + articulation._data.computed_torque.torch.zero_() + articulation._data.applied_torque.torch.zero_() out = joint_effort_out_of_limit(env, robot_all) # [N] assert torch.all(~out) # Case B: simulate clipping → should terminate - wp.to_torch(articulation._data.computed_torque).fill_(100.0) # pretend controller commanded 100 - wp.to_torch(articulation._data.applied_torque).fill_(50.0) # pretend actuator clipped to 50 + articulation._data.computed_torque.torch.fill_(100.0) # pretend controller commanded 100 + articulation._data.applied_torque.torch.fill_(50.0) # pretend actuator clipped to 50 out = joint_effort_out_of_limit(env, robot_all) # [N] assert torch.all(out) @@ -805,13 +805,13 @@ def test_external_force_buffer(sim, num_articulations, device): body_ids, _ = articulation.find_bodies("base") # reset root state - articulation.write_root_pose_to_sim_index(root_pose=wp.to_torch(articulation.data.default_root_pose).clone()) - articulation.write_root_velocity_to_sim_index(root_velocity=wp.to_torch(articulation.data.default_root_vel).clone()) + articulation.write_root_pose_to_sim_index(root_pose=articulation.data.default_root_pose.torch.clone()) + articulation.write_root_velocity_to_sim_index(root_velocity=articulation.data.default_root_vel.torch.clone()) # reset dof state joint_pos, joint_vel = ( - wp.to_torch(articulation.data.default_joint_pos), - wp.to_torch(articulation.data.default_joint_vel), + articulation.data.default_joint_pos.torch, + articulation.data.default_joint_vel.torch, ) articulation.write_joint_position_to_sim_index(position=joint_pos) articulation.write_joint_velocity_to_sim_index(velocity=joint_vel) @@ -844,8 +844,8 @@ def test_external_force_buffer(sim, num_articulations, device): # check if the articulation's force and torque buffers are correctly updated for i in range(num_articulations): - assert wp.to_torch(articulation.permanent_wrench_composer.composed_force)[i, 0, 0].item() == force - assert wp.to_torch(articulation.permanent_wrench_composer.composed_torque)[i, 0, 0].item() == force + assert articulation.permanent_wrench_composer.composed_force.torch[i, 0, 0].item() == force + assert articulation.permanent_wrench_composer.composed_torque.torch[i, 0, 0].item() == force # Check if the instantaneous wrench is correctly added to the permanent wrench articulation.instantaneous_wrench_composer.add_forces_and_torques_index( @@ -855,7 +855,7 @@ def test_external_force_buffer(sim, num_articulations, device): ) # apply action to the articulation - articulation.set_joint_position_target_index(target=wp.to_torch(articulation.data.default_joint_pos).clone()) + articulation.set_joint_position_target_index(target=articulation.data.default_joint_pos.torch.clone()) articulation.write_data_to_sim() # perform step @@ -894,14 +894,12 @@ def test_external_force_on_single_body(sim, num_articulations, device): # Now we are ready! for _ in range(5): # reset root state - articulation.write_root_pose_to_sim_index(root_pose=wp.to_torch(articulation.data.default_root_pose).clone()) - articulation.write_root_velocity_to_sim_index( - root_velocity=wp.to_torch(articulation.data.default_root_vel).clone() - ) + articulation.write_root_pose_to_sim_index(root_pose=articulation.data.default_root_pose.torch.clone()) + articulation.write_root_velocity_to_sim_index(root_velocity=articulation.data.default_root_vel.torch.clone()) # reset dof state joint_pos, joint_vel = ( - wp.to_torch(articulation.data.default_joint_pos), - wp.to_torch(articulation.data.default_joint_vel), + articulation.data.default_joint_pos.torch, + articulation.data.default_joint_vel.torch, ) articulation.write_joint_position_to_sim_index(position=joint_pos) articulation.write_joint_velocity_to_sim_index(velocity=joint_vel) @@ -914,9 +912,7 @@ def test_external_force_on_single_body(sim, num_articulations, device): # perform simulation for _ in range(100): # apply action to the articulation - articulation.set_joint_position_target_index( - target=wp.to_torch(articulation.data.default_joint_pos).clone() - ) + articulation.set_joint_position_target_index(target=articulation.data.default_joint_pos.torch.clone()) articulation.write_data_to_sim() # perform step sim.step() @@ -924,7 +920,7 @@ def test_external_force_on_single_body(sim, num_articulations, device): articulation.update(sim.cfg.dt) # check condition that the articulations have fallen down for i in range(num_articulations): - assert wp.to_torch(articulation.data.root_pos_w)[i, 2].item() < 0.2 + assert articulation.data.root_pos_w.torch[i, 2].item() < 0.2 @pytest.mark.parametrize("num_articulations", [1, 2]) @@ -965,17 +961,15 @@ def test_external_force_on_single_body_at_position(sim, num_articulations, devic # Now we are ready! for i in range(5): # reset root state - root_pose = wp.to_torch(articulation.data.default_root_pose).clone() + root_pose = articulation.data.default_root_pose.torch.clone() root_pose[0, 0] = 2.5 # space them apart by 2.5m articulation.write_root_pose_to_sim_index(root_pose=root_pose) - articulation.write_root_velocity_to_sim_index( - root_velocity=wp.to_torch(articulation.data.default_root_vel).clone() - ) + articulation.write_root_velocity_to_sim_index(root_velocity=articulation.data.default_root_vel.torch.clone()) # reset dof state joint_pos, joint_vel = ( - wp.to_torch(articulation.data.default_joint_pos), - wp.to_torch(articulation.data.default_joint_vel), + articulation.data.default_joint_pos.torch, + articulation.data.default_joint_vel.torch, ) articulation.write_joint_position_to_sim_index(position=joint_pos) articulation.write_joint_velocity_to_sim_index(velocity=joint_vel) @@ -985,7 +979,7 @@ def test_external_force_on_single_body_at_position(sim, num_articulations, devic is_global = False if i % 2 == 0: - body_com_pos_w = wp.to_torch(articulation.data.body_com_pos_w)[:, body_ids, :3] + body_com_pos_w = articulation.data.body_com_pos_w.torch[:, body_ids, :3] # is_global = True external_wrench_positions_b[..., 0] = 0.0 external_wrench_positions_b[..., 1] = 1.0 @@ -1013,9 +1007,7 @@ def test_external_force_on_single_body_at_position(sim, num_articulations, devic # perform simulation for _ in range(100): # apply action to the articulation - articulation.set_joint_position_target_index( - target=wp.to_torch(articulation.data.default_joint_pos).clone() - ) + articulation.set_joint_position_target_index(target=articulation.data.default_joint_pos.torch.clone()) articulation.write_data_to_sim() # perform step sim.step() @@ -1023,7 +1015,7 @@ def test_external_force_on_single_body_at_position(sim, num_articulations, devic articulation.update(sim.cfg.dt) # check condition that the articulations have fallen down for i in range(num_articulations): - assert wp.to_torch(articulation.data.root_pos_w)[i, 2].item() < 0.2 + assert articulation.data.root_pos_w.torch[i, 2].item() < 0.2 @pytest.mark.parametrize("num_articulations", [1, 2]) @@ -1056,14 +1048,12 @@ def test_external_force_on_multiple_bodies(sim, num_articulations, device): # Now we are ready! for _ in range(5): # reset root state - articulation.write_root_pose_to_sim_index(root_pose=wp.to_torch(articulation.data.default_root_pose).clone()) - articulation.write_root_velocity_to_sim_index( - root_velocity=wp.to_torch(articulation.data.default_root_vel).clone() - ) + articulation.write_root_pose_to_sim_index(root_pose=articulation.data.default_root_pose.torch.clone()) + articulation.write_root_velocity_to_sim_index(root_velocity=articulation.data.default_root_vel.torch.clone()) # reset dof state joint_pos, joint_vel = ( - wp.to_torch(articulation.data.default_joint_pos), - wp.to_torch(articulation.data.default_joint_vel), + articulation.data.default_joint_pos.torch, + articulation.data.default_joint_vel.torch, ) articulation.write_joint_position_to_sim_index(position=joint_pos) articulation.write_joint_velocity_to_sim_index(velocity=joint_vel) @@ -1076,9 +1066,7 @@ def test_external_force_on_multiple_bodies(sim, num_articulations, device): # perform simulation for _ in range(100): # apply action to the articulation - articulation.set_joint_position_target_index( - target=wp.to_torch(articulation.data.default_joint_pos).clone() - ) + articulation.set_joint_position_target_index(target=articulation.data.default_joint_pos.torch.clone()) articulation.write_data_to_sim() # perform step sim.step() @@ -1087,7 +1075,7 @@ def test_external_force_on_multiple_bodies(sim, num_articulations, device): # check condition for i in range(num_articulations): # since there is a moment applied on the articulation, the articulation should rotate - assert wp.to_torch(articulation.data.root_ang_vel_w)[i, 2].item() > 0.1 + assert articulation.data.root_ang_vel_w.torch[i, 2].item() > 0.1 @pytest.mark.parametrize("num_articulations", [1, 2]) @@ -1129,14 +1117,12 @@ def test_external_force_on_multiple_bodies_at_position(sim, num_articulations, d # Now we are ready! for i in range(5): # reset root state - articulation.write_root_pose_to_sim_index(root_pose=wp.to_torch(articulation.data.default_root_pose).clone()) - articulation.write_root_velocity_to_sim_index( - root_velocity=wp.to_torch(articulation.data.default_root_vel).clone() - ) + articulation.write_root_pose_to_sim_index(root_pose=articulation.data.default_root_pose.torch.clone()) + articulation.write_root_velocity_to_sim_index(root_velocity=articulation.data.default_root_vel.torch.clone()) # reset dof state joint_pos, joint_vel = ( - wp.to_torch(articulation.data.default_joint_pos), - wp.to_torch(articulation.data.default_joint_vel), + articulation.data.default_joint_pos.torch, + articulation.data.default_joint_vel.torch, ) articulation.write_joint_position_to_sim_index(position=joint_pos) articulation.write_joint_velocity_to_sim_index(velocity=joint_vel) @@ -1145,7 +1131,7 @@ def test_external_force_on_multiple_bodies_at_position(sim, num_articulations, d is_global = False if i % 2 == 0: - body_com_pos_w = wp.to_torch(articulation.data.body_com_pos_w)[:, body_ids, :3] + body_com_pos_w = articulation.data.body_com_pos_w.torch[:, body_ids, :3] is_global = True external_wrench_positions_b[..., 0] = 0.0 external_wrench_positions_b[..., 1] = 1.0 @@ -1174,9 +1160,7 @@ def test_external_force_on_multiple_bodies_at_position(sim, num_articulations, d # perform simulation for _ in range(100): # apply action to the articulation - articulation.set_joint_position_target_index( - target=wp.to_torch(articulation.data.default_joint_pos).clone() - ) + articulation.set_joint_position_target_index(target=articulation.data.default_joint_pos.torch.clone()) articulation.write_data_to_sim() # perform step sim.step() @@ -1185,7 +1169,7 @@ def test_external_force_on_multiple_bodies_at_position(sim, num_articulations, d # check condition for i in range(num_articulations): # since there is a moment applied on the articulation, the articulation should rotate - assert torch.abs(wp.to_torch(articulation.data.root_ang_vel_w)[i, 2]).item() > 0.1 + assert torch.abs(articulation.data.root_ang_vel_w.torch[i, 2]).item() > 0.1 @pytest.mark.parametrize("num_articulations", [1, 2]) @@ -1360,7 +1344,7 @@ def test_setting_velocity_limit_implicit(sim, num_articulations, device, vel_lim # read the values set into the simulation physx_vel_limit = wp.to_torch(articulation.root_view.get_dof_max_velocities()).to(device) # check data buffer - torch.testing.assert_close(wp.to_torch(articulation.data.joint_velocity_limits), physx_vel_limit) + torch.testing.assert_close(articulation.data.joint_velocity_limits.torch, physx_vel_limit) # check actuator has simulation velocity limit torch.testing.assert_close(articulation.actuators["joint"].velocity_limit_sim, physx_vel_limit) # check that both values match for velocity limit @@ -1412,7 +1396,7 @@ def test_setting_velocity_limit_explicit(sim, num_articulations, device, vel_lim actuator_vel_limit_sim = articulation.actuators["joint"].velocity_limit_sim # check data buffer for joint_velocity_limits_sim - torch.testing.assert_close(wp.to_torch(articulation.data.joint_velocity_limits), physx_vel_limit) + torch.testing.assert_close(articulation.data.joint_velocity_limits.torch, physx_vel_limit) # check actuator velocity_limit_sim is set to physx torch.testing.assert_close(actuator_vel_limit_sim, physx_vel_limit) @@ -1575,10 +1559,10 @@ def test_reset(sim, num_articulations, device): # Reset should zero external forces and torques assert not articulation._instantaneous_wrench_composer.active assert not articulation._permanent_wrench_composer.active - assert torch.count_nonzero(wp.to_torch(articulation._instantaneous_wrench_composer.composed_force)) == 0 - assert torch.count_nonzero(wp.to_torch(articulation._instantaneous_wrench_composer.composed_torque)) == 0 - assert torch.count_nonzero(wp.to_torch(articulation._permanent_wrench_composer.composed_force)) == 0 - assert torch.count_nonzero(wp.to_torch(articulation._permanent_wrench_composer.composed_torque)) == 0 + assert torch.count_nonzero(articulation._instantaneous_wrench_composer.composed_force.torch) == 0 + assert torch.count_nonzero(articulation._instantaneous_wrench_composer.composed_torque.torch) == 0 + assert torch.count_nonzero(articulation._permanent_wrench_composer.composed_force.torch) == 0 + assert torch.count_nonzero(articulation._permanent_wrench_composer.composed_torque.torch) == 0 if num_articulations > 1: num_bodies = articulation.num_bodies @@ -1593,20 +1577,10 @@ def test_reset(sim, num_articulations, device): articulation.reset(env_ids=torch.tensor([0], device=device)) assert articulation._instantaneous_wrench_composer.active assert articulation._permanent_wrench_composer.active - assert ( - torch.count_nonzero(wp.to_torch(articulation._instantaneous_wrench_composer.composed_force)) - == num_bodies * 3 - ) - assert ( - torch.count_nonzero(wp.to_torch(articulation._instantaneous_wrench_composer.composed_torque)) - == num_bodies * 3 - ) - assert ( - torch.count_nonzero(wp.to_torch(articulation._permanent_wrench_composer.composed_force)) == num_bodies * 3 - ) - assert ( - torch.count_nonzero(wp.to_torch(articulation._permanent_wrench_composer.composed_torque)) == num_bodies * 3 - ) + assert torch.count_nonzero(articulation._instantaneous_wrench_composer.composed_force.torch) == num_bodies * 3 + assert torch.count_nonzero(articulation._instantaneous_wrench_composer.composed_torque.torch) == num_bodies * 3 + assert torch.count_nonzero(articulation._permanent_wrench_composer.composed_force.torch) == num_bodies * 3 + assert torch.count_nonzero(articulation._permanent_wrench_composer.composed_torque.torch) == num_bodies * 3 @pytest.mark.parametrize("num_articulations", [1, 2]) @@ -1630,7 +1604,7 @@ def test_apply_joint_command(sim, num_articulations, device, add_ground_plane): articulation.update(sim.cfg.dt) # reset dof state - joint_pos = wp.to_torch(articulation.data.default_joint_pos).clone() + joint_pos = articulation.data.default_joint_pos.torch.clone() joint_pos[:, 3] = 0.0 # apply action to the articulation @@ -1646,7 +1620,7 @@ def test_apply_joint_command(sim, num_articulations, device, add_ground_plane): # Check that current joint position is not the same as default joint position, meaning # the articulation moved. We can't check that it reached its desired joint position as the gains # are not properly tuned - assert not torch.allclose(wp.to_torch(articulation.data.joint_pos), joint_pos) + assert not torch.allclose(articulation.data.joint_pos.torch, joint_pos) @pytest.mark.parametrize("num_articulations", [1, 2]) @@ -1710,19 +1684,19 @@ def test_body_root_state(sim, num_articulations, device, with_offset): articulation.update(sim.cfg.dt) # get state properties - root_link_pose_w = wp.to_torch(articulation.data.root_link_pose_w) - root_link_vel_w = wp.to_torch(articulation.data.root_link_vel_w) - root_com_pose_w = wp.to_torch(articulation.data.root_com_pose_w) - root_com_vel_w = wp.to_torch(articulation.data.root_com_vel_w) - body_link_pose_w = wp.to_torch(articulation.data.body_link_pose_w) - body_link_vel_w = wp.to_torch(articulation.data.body_link_vel_w) - body_com_pose_w = wp.to_torch(articulation.data.body_com_pose_w) - body_com_vel_w = wp.to_torch(articulation.data.body_com_vel_w) + root_link_pose_w = articulation.data.root_link_pose_w.torch + root_link_vel_w = articulation.data.root_link_vel_w.torch + root_com_pose_w = articulation.data.root_com_pose_w.torch + root_com_vel_w = articulation.data.root_com_vel_w.torch + body_link_pose_w = articulation.data.body_link_pose_w.torch + body_link_vel_w = articulation.data.body_link_vel_w.torch + body_com_pose_w = articulation.data.body_com_pose_w.torch + body_com_vel_w = articulation.data.body_com_vel_w.torch if with_offset: # get joint state - joint_pos = wp.to_torch(articulation.data.joint_pos).unsqueeze(-1) - joint_vel = wp.to_torch(articulation.data.joint_vel).unsqueeze(-1) + joint_pos = articulation.data.joint_pos.torch.unsqueeze(-1) + joint_vel = articulation.data.joint_vel.torch.unsqueeze(-1) # LINK state # angular velocity should be the same for both COM and link frames @@ -1757,7 +1731,7 @@ def test_body_root_state(sim, num_articulations, device, with_offset): torch.testing.assert_close(pos_gt, body_com_pose_w[..., :3], atol=1e-3, rtol=1e-1) # orientation - com_quat_b = wp.to_torch(articulation.data.body_com_quat_b) + com_quat_b = articulation.data.body_com_quat_b.torch com_quat_w = math_utils.quat_mul(body_link_pose_w[..., 3:], com_quat_b) torch.testing.assert_close(com_quat_w, body_com_pose_w[..., 3:]) torch.testing.assert_close(com_quat_w[:, root_idx, :], root_com_pose_w[..., 3:]) @@ -1821,7 +1795,7 @@ def test_write_root_state(sim, num_articulations, device, with_offset, state_loc torch.testing.assert_close(wp.to_torch(articulation.root_view.get_coms()), com) rand_state = torch.zeros(num_articulations, 13, device=device) - rand_state[..., :7] = wp.to_torch(articulation.data.default_root_pose) + rand_state[..., :7] = articulation.data.default_root_pose.torch rand_state[..., :3] += env_pos # make quaternion a unit vector rand_state[..., 3:7] = torch.nn.functional.normalize(rand_state[..., 3:7], dim=-1) @@ -1849,113 +1823,11 @@ def test_write_root_state(sim, num_articulations, device, with_offset, state_loc articulation.write_root_link_velocity_to_sim_index(root_velocity=rand_state[..., 7:], env_ids=env_idx) if state_location == "com": - torch.testing.assert_close(rand_state[..., :7], wp.to_torch(articulation.data.root_com_pose_w)) - torch.testing.assert_close(rand_state[..., 7:], wp.to_torch(articulation.data.root_com_vel_w)) + torch.testing.assert_close(rand_state[..., :7], articulation.data.root_com_pose_w.torch) + torch.testing.assert_close(rand_state[..., 7:], articulation.data.root_com_vel_w.torch) elif state_location == "link": - torch.testing.assert_close(rand_state[..., :7], wp.to_torch(articulation.data.root_link_pose_w)) - torch.testing.assert_close(rand_state[..., 7:], wp.to_torch(articulation.data.root_link_vel_w)) - - -@pytest.mark.parametrize("num_articulations", [1, 2]) -@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) -@pytest.mark.isaacsim_ci -def test_body_incoming_joint_wrench_b_single_joint(sim, num_articulations, device): - """Test the data.body_incoming_joint_wrench_b buffer is populated correctly and statically correct for single joint. - - This test verifies that: - 1. The body incoming joint wrench buffer has correct shape - 2. The wrench values are statically correct for a single joint - 3. The wrench values match expected values from gravity and external forces - - Args: - sim: The simulation fixture - num_articulations: Number of articulations to test - device: The device to run the simulation on - """ - articulation_cfg = generate_articulation_cfg(articulation_type="single_joint_implicit") - articulation, _ = generate_articulation( - articulation_cfg=articulation_cfg, num_articulations=num_articulations, device=device - ) - - # Play the simulator - sim.reset() - - # Resolve body indices by name (ordering may differ across physics backends) - arm_idx = articulation.body_names.index("Arm") - root_idx = articulation.body_names.index("CenterPivot") - # apply external force - external_force_vector_b = torch.zeros((num_articulations, articulation.num_bodies, 3), device=device) - external_force_vector_b[:, arm_idx, 1] = 10.0 # 10 N in Y direction - external_torque_vector_b = torch.zeros((num_articulations, articulation.num_bodies, 3), device=device) - external_torque_vector_b[:, arm_idx, 2] = 10.0 # 10 Nm in z direction - - # apply action to the articulation - joint_pos = torch.ones_like(wp.to_torch(articulation.data.joint_pos)) * 1.5708 / 2.0 - articulation.write_joint_position_to_sim_index( - position=torch.ones_like(wp.to_torch(articulation.data.joint_pos)), - ) - articulation.write_joint_velocity_to_sim_index( - velocity=torch.zeros_like(wp.to_torch(articulation.data.joint_vel)), - ) - articulation.set_joint_position_target_index(target=joint_pos) - articulation.write_data_to_sim() - for _ in range(50): - articulation.permanent_wrench_composer.set_forces_and_torques_index( - forces=external_force_vector_b, torques=external_torque_vector_b - ) - articulation.write_data_to_sim() - # perform step - sim.step() - # update buffers - articulation.update(sim.cfg.dt) - - # check shape - assert wp.to_torch(articulation.data.body_incoming_joint_wrench_b).shape == ( - num_articulations, - articulation.num_bodies, - 6, - ) - - # calculate expected static - mass = wp.to_torch(articulation.data.body_mass).to("cpu") - pos_w = wp.to_torch(articulation.data.body_pos_w) - quat_w = wp.to_torch(articulation.data.body_quat_w) - - mass_link2 = mass[:, arm_idx].view(num_articulations, -1) - gravity = torch.tensor(sim.cfg.gravity, device="cpu").repeat(num_articulations, 1).view((num_articulations, 3)) - - # NOTE: the com and link pose for single joint are colocated - weight_vector_w = mass_link2 * gravity - # expected wrench from link mass and external wrench - # PhysX reports the incoming joint wrench as the force FROM body0 ONTO body1 (body1's frame). - # The USD asset defines body0=CenterPivot, body1=Arm, so the wrench is the constraint/support - # force from CenterPivot onto Arm, expressed in Arm's frame. - # In static equilibrium this equals -(gravity + external forces on Arm). - total_force_w = weight_vector_w.to(device) + math_utils.quat_apply( - quat_w[:, arm_idx, :], external_force_vector_b[:, arm_idx, :] - ) - total_torque_w = torch.cross( - pos_w[:, arm_idx, :].to(device) - pos_w[:, root_idx, :].to(device), - total_force_w, - dim=-1, - ) + math_utils.quat_apply(quat_w[:, arm_idx, :], external_torque_vector_b[:, arm_idx, :]) - expected_wrench = torch.zeros((num_articulations, 6), device=device) - expected_wrench[:, :3] = math_utils.quat_apply( - math_utils.quat_conjugate(quat_w[:, arm_idx, :]), - -total_force_w, - ) - expected_wrench[:, 3:] = math_utils.quat_apply( - math_utils.quat_conjugate(quat_w[:, arm_idx, :]), - -total_torque_w, - ) - - # check value of last joint wrench - torch.testing.assert_close( - expected_wrench, - wp.to_torch(articulation.data.body_incoming_joint_wrench_b)[:, arm_idx, :].squeeze(1), - atol=1e-2, - rtol=1e-3, - ) + torch.testing.assert_close(rand_state[..., :7], articulation.data.root_link_pose_w.torch) + torch.testing.assert_close(rand_state[..., 7:], articulation.data.root_link_vel_w.torch) @pytest.mark.parametrize("device", ["cuda:0", "cpu"]) @@ -2025,13 +1897,13 @@ def test_write_joint_state_data_consistency(sim, num_articulations, device, grav from torch.distributions import Uniform - joint_pos_limits = wp.to_torch(articulation.data.joint_pos_limits) - joint_vel_limits = wp.to_torch(articulation.data.joint_vel_limits) + joint_pos_limits = articulation.data.joint_pos_limits.torch + joint_vel_limits = articulation.data.joint_vel_limits.torch pos_dist = Uniform(joint_pos_limits[..., 0], joint_pos_limits[..., 1]) vel_dist = Uniform(-joint_vel_limits, joint_vel_limits) - original_body_link_pose_w = wp.to_torch(articulation.data.body_link_pose_w).clone() - original_body_com_vel_w = wp.to_torch(articulation.data.body_com_vel_w).clone() + original_body_link_pose_w = articulation.data.body_link_pose_w.torch.clone() + original_body_com_vel_w = articulation.data.body_com_vel_w.torch.clone() rand_joint_pos = pos_dist.sample() rand_joint_vel = vel_dist.sample() @@ -2039,65 +1911,65 @@ def test_write_joint_state_data_consistency(sim, num_articulations, device, grav articulation.write_joint_position_to_sim_index(position=rand_joint_pos) articulation.write_joint_velocity_to_sim_index(velocity=rand_joint_vel) # make sure valued updated - body_link_pose_w = wp.to_torch(articulation.data.body_link_pose_w) - body_com_vel_w = wp.to_torch(articulation.data.body_com_vel_w) + body_link_pose_w = articulation.data.body_link_pose_w.torch + body_com_vel_w = articulation.data.body_com_vel_w.torch original_body_states = torch.cat([original_body_link_pose_w, original_body_com_vel_w], dim=-1) body_state_w = torch.cat([body_link_pose_w, body_com_vel_w], dim=-1) assert torch.count_nonzero(original_body_states[:, 1:] != body_state_w[:, 1:]) > ( len(original_body_states[:, 1:]) / 2 ) # validate body - link consistency - body_link_vel_w = wp.to_torch(articulation.data.body_link_vel_w) - torch.testing.assert_close(body_link_pose_w, wp.to_torch(articulation.data.body_link_pose_w)) + body_link_vel_w = articulation.data.body_link_vel_w.torch + torch.testing.assert_close(body_link_pose_w, articulation.data.body_link_pose_w.torch) # skip lin_vel because it differs from link frame, this should be fine because we are only checking # if velocity update is triggered, which can be determined by comparing angular velocity torch.testing.assert_close(body_com_vel_w[..., 3:], body_link_vel_w[..., 3:]) # validate link - com conistency - body_com_pos_b = wp.to_torch(articulation.data.body_com_pos_b) - body_com_quat_b = wp.to_torch(articulation.data.body_com_quat_b) + body_com_pos_b = articulation.data.body_com_pos_b.torch + body_com_quat_b = articulation.data.body_com_quat_b.torch expected_com_pos, expected_com_quat = math_utils.combine_frame_transforms( body_link_pose_w[..., :3].view(-1, 3), body_link_pose_w[..., 3:].view(-1, 4), body_com_pos_b.view(-1, 3), body_com_quat_b.view(-1, 4), ) - body_com_pos_w = wp.to_torch(articulation.data.body_com_pos_w) - body_com_quat_w = wp.to_torch(articulation.data.body_com_quat_w) + body_com_pos_w = articulation.data.body_com_pos_w.torch + body_com_quat_w = articulation.data.body_com_quat_w.torch torch.testing.assert_close(expected_com_pos.view(len(env_idx), -1, 3), body_com_pos_w) torch.testing.assert_close(expected_com_quat.view(len(env_idx), -1, 4), body_com_quat_w) # validate body - com consistency - body_com_lin_vel_w = wp.to_torch(articulation.data.body_com_lin_vel_w) - body_com_ang_vel_w = wp.to_torch(articulation.data.body_com_ang_vel_w) + body_com_lin_vel_w = articulation.data.body_com_lin_vel_w.torch + body_com_ang_vel_w = articulation.data.body_com_ang_vel_w.torch torch.testing.assert_close(body_com_vel_w[..., :3], body_com_lin_vel_w) torch.testing.assert_close(body_com_vel_w[..., 3:], body_com_ang_vel_w) # validate pos_w, quat_w, pos_b, quat_b is consistent with pose_w and pose_b expected_com_pose_w = torch.cat((body_com_pos_w, body_com_quat_w), dim=2) expected_com_pose_b = torch.cat((body_com_pos_b, body_com_quat_b), dim=2) - body_pos_w = wp.to_torch(articulation.data.body_pos_w) - body_quat_w = wp.to_torch(articulation.data.body_quat_w) + body_pos_w = articulation.data.body_pos_w.torch + body_quat_w = articulation.data.body_quat_w.torch expected_body_pose_w = torch.cat((body_pos_w, body_quat_w), dim=2) - body_link_pos_w = wp.to_torch(articulation.data.body_link_pos_w) - body_link_quat_w = wp.to_torch(articulation.data.body_link_quat_w) + body_link_pos_w = articulation.data.body_link_pos_w.torch + body_link_quat_w = articulation.data.body_link_quat_w.torch expected_body_link_pose_w = torch.cat((body_link_pos_w, body_link_quat_w), dim=2) - body_com_pose_w = wp.to_torch(articulation.data.body_com_pose_w) - body_com_pose_b = wp.to_torch(articulation.data.body_com_pose_b) - body_pose_w = wp.to_torch(articulation.data.body_pose_w) - body_link_pose_w_fresh = wp.to_torch(articulation.data.body_link_pose_w) + body_com_pose_w = articulation.data.body_com_pose_w.torch + body_com_pose_b = articulation.data.body_com_pose_b.torch + body_pose_w = articulation.data.body_pose_w.torch + body_link_pose_w_fresh = articulation.data.body_link_pose_w.torch torch.testing.assert_close(body_com_pose_w, expected_com_pose_w) torch.testing.assert_close(body_com_pose_b, expected_com_pose_b) torch.testing.assert_close(body_pose_w, expected_body_pose_w) torch.testing.assert_close(body_link_pose_w_fresh, expected_body_link_pose_w) # validate pose_w is consistent with individual properties - body_vel_w = wp.to_torch(articulation.data.body_vel_w) - body_com_vel_w_fresh = wp.to_torch(articulation.data.body_com_vel_w) + body_vel_w = articulation.data.body_vel_w.torch + body_com_vel_w_fresh = articulation.data.body_com_vel_w.torch torch.testing.assert_close(body_pose_w, body_link_pose_w) torch.testing.assert_close(body_vel_w, body_com_vel_w) torch.testing.assert_close(body_link_pose_w_fresh, body_link_pose_w) - torch.testing.assert_close(body_com_pose_w, wp.to_torch(articulation.data.body_com_pose_w)) + torch.testing.assert_close(body_com_pose_w, articulation.data.body_com_pose_w.torch) torch.testing.assert_close(body_vel_w, body_com_vel_w_fresh) @@ -2132,11 +2004,11 @@ def test_spatial_tendons(sim, num_articulations, device): # Check that fixed base assert articulation.is_fixed_base # Check buffers that exists and have correct shapes - assert wp.to_torch(articulation.data.root_pos_w).shape == (num_articulations, 3) - assert wp.to_torch(articulation.data.root_quat_w).shape == (num_articulations, 4) - assert wp.to_torch(articulation.data.joint_pos).shape == (num_articulations, 3) - assert wp.to_torch(articulation.data.body_mass).shape == (num_articulations, articulation.num_bodies) - assert wp.to_torch(articulation.data.body_inertia).shape == (num_articulations, articulation.num_bodies, 9) + assert articulation.data.root_pos_w.torch.shape == (num_articulations, 3) + assert articulation.data.root_quat_w.torch.shape == (num_articulations, 4) + assert articulation.data.joint_pos.torch.shape == (num_articulations, 3) + assert articulation.data.body_mass.torch.shape == (num_articulations, articulation.num_bodies) + assert articulation.data.body_inertia.torch.shape == (num_articulations, articulation.num_bodies, 9) assert articulation.num_spatial_tendons == 1 articulation.set_spatial_tendon_stiffness_index(stiffness=10.0) @@ -2245,5 +2117,45 @@ def test_write_joint_frictions_to_sim(sim, num_articulations, device, add_ground assert torch.allclose(joint_friction_coeff_sim_2, friction_2.cpu()) +@pytest.mark.parametrize("add_ground_plane", [True]) +@pytest.mark.parametrize("num_articulations", [1, 2]) +@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) +@pytest.mark.parametrize("articulation_type", ["panda"]) +@pytest.mark.isaacsim_ci +def test_set_material_properties(sim, num_articulations, device, add_ground_plane, articulation_type): + """Test getting and setting material properties (friction/restitution) of articulation shapes.""" + articulation_cfg = generate_articulation_cfg(articulation_type=articulation_type) + articulation, _ = generate_articulation( + articulation_cfg=articulation_cfg, num_articulations=num_articulations, device=device + ) + + # Play the simulator + sim.reset() + + # Get number of shapes from the articulation + max_shapes = articulation.root_view.max_shapes + + # Generate random material properties: (static_friction, dynamic_friction, restitution) + materials = torch.empty(num_articulations, max_shapes, 3, device="cpu").uniform_(0.0, 1.0) + # Ensure dynamic friction <= static friction + materials[..., 1] = torch.min(materials[..., 0], materials[..., 1]) + + # Set material properties via the PhysX view-level API + env_ids = torch.arange(num_articulations, dtype=torch.int32) + articulation.root_view.set_material_properties( + wp.from_torch(materials, dtype=wp.float32), wp.from_torch(env_ids, dtype=wp.int32) + ) + + # Simulate physics + sim.step() + articulation.update(sim.cfg.dt) + + # Get material properties from simulation + materials_check = wp.to_torch(articulation.root_view.get_material_properties()) + + # Check if material properties are set correctly + torch.testing.assert_close(materials_check, materials) + + if __name__ == "__main__": pytest.main([__file__, "-v", "--maxfail=1"]) diff --git a/source/isaaclab_physx/test/assets/test_deformable_object.py b/source/isaaclab_physx/test/assets/test_deformable_object.py index a0dcd199b1ee..31a199938c94 100644 --- a/source/isaaclab_physx/test/assets/test_deformable_object.py +++ b/source/isaaclab_physx/test/assets/test_deformable_object.py @@ -23,6 +23,7 @@ import warp as wp from flaky import flaky from isaaclab_physx.assets import DeformableObject, DeformableObjectCfg +from isaaclab_physx.sim import DeformableBodyMaterialCfg, DeformableBodyPropertiesCfg, SurfaceDeformableBodyMaterialCfg import carb @@ -30,6 +31,10 @@ import isaaclab.utils.math as math_utils from isaaclab.sim import build_simulation_context +# Temporarily disabled: this suite intermittently aborts with SIGABRT on CI. +# Re-enable once the underlying crash is fixed. +pytestmark = pytest.mark.skip(reason="Temporarily disabled due to intermittent crash on CI.") + def generate_cubes_scene( num_cubes: int = 1, @@ -38,6 +43,7 @@ def generate_cubes_scene( has_api: bool = True, material_path: str | None = "material", kinematic_enabled: bool = False, + deformable_type: str = "volume", device: str = "cuda:0", ) -> DeformableObject: """Generate a scene with the provided number of cubes. @@ -50,6 +56,7 @@ def generate_cubes_scene( material_path: Path to the material file. If None, no material is added. Default is "material", which is path relative to the spawned object prim path. kinematic_enabled: Whether the cubes are kinematic. + deformable_type: The type of deformable body to spawn. Supported values are "volume" and "surface". device: Device to use for the simulation. Returns: @@ -65,11 +72,14 @@ def generate_cubes_scene( if has_api: spawn_cfg = sim_utils.MeshCuboidCfg( size=(0.2, 0.2, 0.2), - deformable_props=sim_utils.DeformableBodyPropertiesCfg(kinematic_enabled=kinematic_enabled), + deformable_props=DeformableBodyPropertiesCfg(kinematic_enabled=kinematic_enabled), ) # Add physics material if provided if material_path is not None: - spawn_cfg.physics_material = sim_utils.DeformableBodyMaterialCfg() + if deformable_type == "surface": + spawn_cfg.physics_material = SurfaceDeformableBodyMaterialCfg() + else: + spawn_cfg.physics_material = DeformableBodyMaterialCfg() spawn_cfg.physics_material_path = material_path else: spawn_cfg.physics_material = None @@ -131,52 +141,51 @@ def test_initialization(sim, num_cubes, material_path): # Check buffers that exist and have correct shapes # nodal_state_w is (N, V) vec6f -> wp.to_torch gives (N, V, 6) - assert wp.to_torch(cube_object.data.nodal_state_w).shape == (num_cubes, cube_object.max_sim_vertices_per_body, 6) - # nodal_kinematic_target is (N, V) vec4f -> wp.to_torch gives (N, V, 4) - assert wp.to_torch(cube_object.data.nodal_kinematic_target).shape == ( + assert cube_object.data.nodal_state_w.torch.shape == (num_cubes, cube_object.max_sim_vertices_per_body, 6) + # nodal_kinematic_target is (N, V) vec4f -> .torch gives (N, V, 4) + assert cube_object.data.nodal_kinematic_target.torch.shape == ( num_cubes, cube_object.max_sim_vertices_per_body, 4, ) # root_pos_w is (N,) vec3f -> wp.to_torch gives (N, 3) - assert wp.to_torch(cube_object.data.root_pos_w).shape == (num_cubes, 3) - assert wp.to_torch(cube_object.data.root_vel_w).shape == (num_cubes, 3) + assert cube_object.data.root_pos_w.torch.shape == (num_cubes, 3) + assert cube_object.data.root_vel_w.torch.shape == (num_cubes, 3) - # Simulate physics - for _ in range(2): - sim.step() - cube_object.update(sim.cfg.dt) - # Check sim data - assert wp.to_torch(cube_object.data.sim_element_quat_w).shape == ( - num_cubes, - cube_object.max_sim_elements_per_body, - 4, - ) - assert cube_object.data.sim_element_deform_gradient_w.shape == ( - num_cubes, - cube_object.max_sim_elements_per_body, - 3, - 3, - ) - assert cube_object.data.sim_element_stress_w.shape == (num_cubes, cube_object.max_sim_elements_per_body, 3, 3) - assert wp.to_torch(cube_object.data.collision_element_quat_w).shape == ( - num_cubes, - cube_object.max_collision_elements_per_body, - 4, - ) - assert cube_object.data.collision_element_deform_gradient_w.shape == ( - num_cubes, - cube_object.max_collision_elements_per_body, - 3, - 3, - ) - assert cube_object.data.collision_element_stress_w.shape == ( - num_cubes, - cube_object.max_collision_elements_per_body, - 3, - 3, - ) +@pytest.mark.parametrize("num_cubes", [1, 2]) +@pytest.mark.isaacsim_ci +def test_initialization_surface_deformable(sim, num_cubes): + """Test initialization of a surface deformable body.""" + cube_object = generate_cubes_scene(num_cubes=num_cubes, deformable_type="surface") + + # Play sim + sim.reset() + + # Check if object is initialized + assert cube_object.is_initialized + assert cube_object._deformable_type == "surface" + + # Check correct number of instances + assert cube_object.num_instances == num_cubes + assert cube_object.root_view.count == num_cubes + + # Check material view is created + assert cube_object.material_physx_view is not None + assert cube_object.material_physx_view.count == num_cubes + + # Check nodal state buffers have correct shapes + assert cube_object.data.nodal_state_w.torch.shape == (num_cubes, cube_object.max_sim_vertices_per_body, 6) + assert cube_object.data.root_pos_w.torch.shape == (num_cubes, 3) + assert cube_object.data.root_vel_w.torch.shape == (num_cubes, 3) + + # Kinematic targets are not allocated for surface deformables + assert cube_object.data.nodal_kinematic_target is None + + # Writing kinematic targets should raise ValueError + dummy_targets = torch.zeros(num_cubes, cube_object.max_sim_vertices_per_body, 4, device=sim.device) + with pytest.raises(ValueError, match="Kinematic targets can only be set for volume deformable bodies"): + cube_object.write_nodal_kinematic_target_to_sim_index(dummy_targets) @pytest.mark.isaacsim_ci @@ -194,33 +203,6 @@ def test_initialization_on_device_cpu(): sim.reset() -@pytest.mark.parametrize("num_cubes", [1, 2]) -@pytest.mark.isaacsim_ci -def test_initialization_with_kinematic_enabled(sim, num_cubes): - """Test that initialization for prim with kinematic flag enabled.""" - cube_object = generate_cubes_scene(num_cubes=num_cubes, kinematic_enabled=True) - - # Check that the framework doesn't hold excessive strong references. - assert sys.getrefcount(cube_object) < 10 - - # Play sim - sim.reset() - - # Check if object is initialized - assert cube_object.is_initialized - - # Check buffers that exist and have correct shapes - assert wp.to_torch(cube_object.data.root_pos_w).shape == (num_cubes, 3) - assert wp.to_torch(cube_object.data.root_vel_w).shape == (num_cubes, 3) - - # Simulate physics - for _ in range(2): - sim.step() - cube_object.update(sim.cfg.dt) - default_nodal_state_w = wp.to_torch(cube_object.data.default_nodal_state_w).clone() - torch.testing.assert_close(wp.to_torch(cube_object.data.nodal_state_w), default_nodal_state_w) - - @pytest.mark.parametrize("num_cubes", [1, 2]) @pytest.mark.isaacsim_ci def test_set_nodal_state(sim, num_cubes): @@ -232,8 +214,8 @@ def test_set_nodal_state(sim, num_cubes): for state_type_to_randomize in ["nodal_pos_w", "nodal_vel_w"]: state_dict = { - "nodal_pos_w": torch.zeros_like(wp.to_torch(cube_object.data.nodal_pos_w)), - "nodal_vel_w": torch.zeros_like(wp.to_torch(cube_object.data.nodal_vel_w)), + "nodal_pos_w": torch.zeros_like(cube_object.data.nodal_pos_w.torch), + "nodal_vel_w": torch.zeros_like(cube_object.data.nodal_vel_w.torch), } for _ in range(5): @@ -251,11 +233,9 @@ def test_set_nodal_state(sim, num_cubes): ], dim=-1, ) - cube_object.write_nodal_state_to_sim(nodal_state) + cube_object.write_nodal_state_to_sim_index(nodal_state) - torch.testing.assert_close( - wp.to_torch(cube_object.data.nodal_state_w), nodal_state, rtol=1e-5, atol=1e-5 - ) + torch.testing.assert_close(cube_object.data.nodal_state_w.torch, nodal_state, rtol=1e-5, atol=1e-5) sim.step() cube_object.update(sim.cfg.dt) @@ -278,11 +258,11 @@ def test_set_nodal_state_with_applied_transform(num_cubes, randomize_pos, random sim.reset() for _ in range(5): - nodal_state = wp.to_torch(cube_object.data.default_nodal_state_w).clone() + nodal_state = cube_object.data.default_nodal_state_w.torch.clone() mean_nodal_pos_default = nodal_state[..., :3].mean(dim=1) if randomize_pos: - pos_w = torch.rand(cube_object.num_instances, 3, device=sim.device) + pos_w = 0.5 * torch.rand(cube_object.num_instances, 3, device=sim.device) pos_w[:, 2] += 0.5 else: pos_w = None @@ -299,16 +279,14 @@ def test_set_nodal_state_with_applied_transform(num_cubes, randomize_pos, random else: torch.testing.assert_close(mean_nodal_pos_init, mean_nodal_pos_default + pos_w, rtol=1e-5, atol=1e-5) - cube_object.write_nodal_state_to_sim(nodal_state) + cube_object.write_nodal_state_to_sim_index(nodal_state) cube_object.reset() for _ in range(50): sim.step() cube_object.update(sim.cfg.dt) - torch.testing.assert_close( - wp.to_torch(cube_object.data.root_pos_w), mean_nodal_pos_init, rtol=1e-4, atol=1e-4 - ) + torch.testing.assert_close(cube_object.data.root_pos_w.torch, mean_nodal_pos_init, rtol=1e-4, atol=1e-4) @pytest.mark.parametrize("num_cubes", [2, 4]) @@ -319,19 +297,19 @@ def test_set_kinematic_targets(sim, num_cubes): sim.reset() - nodal_kinematic_targets = wp.to_torch(cube_object.root_view.get_sim_kinematic_targets()).clone() + nodal_kinematic_targets = wp.to_torch(cube_object.root_view.get_simulation_nodal_kinematic_targets()).clone() for _ in range(5): - cube_object.write_nodal_state_to_sim(wp.to_torch(cube_object.data.default_nodal_state_w)) + cube_object.write_nodal_state_to_sim_index(cube_object.data.default_nodal_state_w.torch) - default_root_pos = wp.to_torch(cube_object.data.default_nodal_state_w).mean(dim=1) + default_root_pos = cube_object.data.default_nodal_state_w.torch.mean(dim=1) cube_object.reset() nodal_kinematic_targets[1:, :, 3] = 1.0 nodal_kinematic_targets[0, :, 3] = 0.0 - nodal_kinematic_targets[0, :, :3] = wp.to_torch(cube_object.data.default_nodal_state_w)[0, :, :3] - cube_object.write_nodal_kinematic_target_to_sim( + nodal_kinematic_targets[0, :, :3] = cube_object.data.default_nodal_state_w.torch[0, :, :3] + cube_object.write_nodal_kinematic_target_to_sim_index( nodal_kinematic_targets[0:1], env_ids=torch.tensor([0], device=sim.device) ) @@ -340,10 +318,10 @@ def test_set_kinematic_targets(sim, num_cubes): cube_object.update(sim.cfg.dt) torch.testing.assert_close( - wp.to_torch(cube_object.data.nodal_pos_w)[0], + cube_object.data.nodal_pos_w.torch[0], nodal_kinematic_targets[0, :, :3], rtol=1e-5, atol=1e-5, ) - root_pos_w = wp.to_torch(cube_object.data.root_pos_w) + root_pos_w = cube_object.data.root_pos_w.torch assert torch.all(root_pos_w[1:, 2] < default_root_pos[1:, 2]) diff --git a/source/isaaclab_physx/test/assets/test_rigid_object.py b/source/isaaclab_physx/test/assets/test_rigid_object.py index 6cea115105e1..6a2211787e19 100644 --- a/source/isaaclab_physx/test/assets/test_rigid_object.py +++ b/source/isaaclab_physx/test/assets/test_rigid_object.py @@ -118,10 +118,10 @@ def test_initialization(num_cubes, device): assert len(cube_object.body_names) == 1 # Check buffers that exists and have correct shapes - assert wp.to_torch(cube_object.data.root_pos_w).shape == (num_cubes, 3) - assert wp.to_torch(cube_object.data.root_quat_w).shape == (num_cubes, 4) - assert wp.to_torch(cube_object.data.body_mass).shape == (num_cubes, 1) - assert wp.to_torch(cube_object.data.body_inertia).shape == (num_cubes, 1, 9) + assert cube_object.data.root_pos_w.torch.shape == (num_cubes, 3) + assert cube_object.data.root_quat_w.torch.shape == (num_cubes, 4) + assert cube_object.data.body_mass.torch.shape == (num_cubes, 1) + assert cube_object.data.body_inertia.torch.shape == (num_cubes, 1, 9) # Simulate physics for _ in range(2): @@ -152,8 +152,8 @@ def test_initialization_with_kinematic_enabled(num_cubes, device): assert len(cube_object.body_names) == 1 # Check buffers that exists and have correct shapes - assert wp.to_torch(cube_object.data.root_pos_w).shape == (num_cubes, 3) - assert wp.to_torch(cube_object.data.root_quat_w).shape == (num_cubes, 4) + assert cube_object.data.root_pos_w.torch.shape == (num_cubes, 3) + assert cube_object.data.root_quat_w.torch.shape == (num_cubes, 4) # Simulate physics for _ in range(2): @@ -162,11 +162,11 @@ def test_initialization_with_kinematic_enabled(num_cubes, device): # update object cube_object.update(sim.cfg.dt) # check that the object is kinematic - default_root_pose = wp.to_torch(cube_object.data.default_root_pose).clone() - default_root_vel = wp.to_torch(cube_object.data.default_root_vel).clone() + default_root_pose = cube_object.data.default_root_pose.torch.clone() + default_root_vel = cube_object.data.default_root_vel.torch.clone() default_root_pose[:, :3] += origins - torch.testing.assert_close(wp.to_torch(cube_object.data.root_link_pose_w), default_root_pose) - torch.testing.assert_close(wp.to_torch(cube_object.data.root_com_vel_w), default_root_vel) + torch.testing.assert_close(cube_object.data.root_link_pose_w.torch, default_root_pose) + torch.testing.assert_close(cube_object.data.root_com_vel_w.torch, default_root_vel) @pytest.mark.parametrize("num_cubes", [1, 2]) @@ -253,8 +253,8 @@ def test_external_force_buffer(device): # check if the cube's force and torque buffers are correctly updated for i in range(cube_object.num_instances): - assert wp.to_torch(cube_object._permanent_wrench_composer.composed_force)[i, 0, 0].item() == force - assert wp.to_torch(cube_object._permanent_wrench_composer.composed_torque)[i, 0, 0].item() == force + assert cube_object._permanent_wrench_composer.composed_force.torch[i, 0, 0].item() == force + assert cube_object._permanent_wrench_composer.composed_torque.torch[i, 0, 0].item() == force # Check if the instantaneous wrench is correctly added to the permanent wrench cube_object.permanent_wrench_composer.add_forces_and_torques_index( @@ -304,8 +304,8 @@ def test_external_force_on_single_body(num_cubes, device): # Now we are ready! for i in range(5): # reset root state - root_pose = wp.to_torch(cube_object.data.default_root_pose).clone() - root_vel = wp.to_torch(cube_object.data.default_root_vel).clone() + root_pose = cube_object.data.default_root_pose.torch.clone() + root_vel = cube_object.data.default_root_vel.torch.clone() # need to shift the position of the cubes otherwise they will be on top of each other root_pose[:, :3] = origins @@ -318,7 +318,7 @@ def test_external_force_on_single_body(num_cubes, device): is_global = False if i % 2 == 0: is_global = True - positions = wp.to_torch(cube_object.data.body_com_pos_w)[:, body_ids, :3] + positions = cube_object.data.body_com_pos_w.torch[:, body_ids, :3] else: positions = None @@ -343,10 +343,10 @@ def test_external_force_on_single_body(num_cubes, device): # First object should still be at the same Z position (1.0) torch.testing.assert_close( - wp.to_torch(cube_object.data.root_pos_w)[0::2, 2], torch.ones(num_cubes // 2, device=sim.device) + cube_object.data.root_pos_w.torch[0::2, 2], torch.ones(num_cubes // 2, device=sim.device) ) # Second object should have fallen, so it's Z height should be less than initial height of 1.0 - assert torch.all(wp.to_torch(cube_object.data.root_pos_w)[1::2, 2] < 1.0) + assert torch.all(cube_object.data.root_pos_w.torch[1::2, 2] < 1.0) @pytest.mark.parametrize("num_cubes", [2, 4]) @@ -386,8 +386,8 @@ def test_external_force_on_single_body_at_position(num_cubes, device): # Now we are ready! for i in range(5): # reset root state - root_pose = wp.to_torch(cube_object.data.default_root_pose).clone() - root_vel = wp.to_torch(cube_object.data.default_root_vel).clone() + root_pose = cube_object.data.default_root_pose.torch.clone() + root_vel = cube_object.data.default_root_vel.torch.clone() # need to shift the position of the cubes otherwise they will be on top of each other root_pose[:, :3] = origins @@ -400,7 +400,7 @@ def test_external_force_on_single_body_at_position(num_cubes, device): is_global = False if i % 2 == 0: is_global = True - body_com_pos_w = wp.to_torch(cube_object.data.body_com_pos_w)[:, body_ids, :3] + body_com_pos_w = cube_object.data.body_com_pos_w.torch[:, body_ids, :3] external_wrench_positions_b[..., 0] = 0.0 external_wrench_positions_b[..., 1] = 1.0 external_wrench_positions_b[..., 2] = 0.0 @@ -426,13 +426,13 @@ def test_external_force_on_single_body_at_position(num_cubes, device): is_global=is_global, ) torch.testing.assert_close( - wp.to_torch(cube_object._permanent_wrench_composer.composed_force)[:, 0, :], + cube_object._permanent_wrench_composer.composed_force.torch[:, 0, :], desired_force[:, 0, :], rtol=1e-6, atol=1e-7, ) torch.testing.assert_close( - wp.to_torch(cube_object._permanent_wrench_composer.composed_torque)[:, 0, :], + cube_object._permanent_wrench_composer.composed_torque.torch[:, 0, :], desired_torque[:, 0, :], rtol=1e-6, atol=1e-7, @@ -449,9 +449,9 @@ def test_external_force_on_single_body_at_position(num_cubes, device): cube_object.update(sim.cfg.dt) # The first object should be rotating around it's X axis - assert torch.all(torch.abs(wp.to_torch(cube_object.data.root_ang_vel_b)[0::2, 0]) > 0.1) + assert torch.all(torch.abs(cube_object.data.root_ang_vel_b.torch[0::2, 0]) > 0.1) # Second object should have fallen, so it's Z height should be less than initial height of 1.0 - assert torch.all(wp.to_torch(cube_object.data.root_pos_w)[1::2, 2] < 1.0) + assert torch.all(cube_object.data.root_pos_w.torch[1::2, 2] < 1.0) @pytest.mark.parametrize("num_cubes", [1, 2]) @@ -479,10 +479,10 @@ def test_set_rigid_object_state(num_cubes, device): # Set each state type individually as they are dependent on each other for state_type_to_randomize in state_types: state_dict = { - "root_pos_w": torch.zeros_like(wp.to_torch(cube_object.data.root_pos_w), device=sim.device), + "root_pos_w": torch.zeros_like(cube_object.data.root_pos_w.torch, device=sim.device), "root_quat_w": default_orientation(num=num_cubes, device=sim.device), - "root_lin_vel_w": torch.zeros_like(wp.to_torch(cube_object.data.root_lin_vel_w), device=sim.device), - "root_ang_vel_w": torch.zeros_like(wp.to_torch(cube_object.data.root_ang_vel_w), device=sim.device), + "root_lin_vel_w": torch.zeros_like(cube_object.data.root_lin_vel_w.torch, device=sim.device), + "root_ang_vel_w": torch.zeros_like(cube_object.data.root_ang_vel_w.torch, device=sim.device), } # Now we are ready! @@ -514,7 +514,7 @@ def test_set_rigid_object_state(num_cubes, device): # assert that set root quantities are equal to the ones set in the state_dict for key, expected_value in state_dict.items(): - value = wp.to_torch(getattr(cube_object.data, key)) + value = getattr(cube_object.data, key).torch torch.testing.assert_close(value, expected_value, rtol=1e-3, atol=1e-3) cube_object.update(sim.cfg.dt) @@ -541,13 +541,13 @@ def test_reset_rigid_object(num_cubes, device): cube_object.update(sim.cfg.dt) # Move the object to a random position - root_pose = wp.to_torch(cube_object.data.default_root_pose).clone() + root_pose = cube_object.data.default_root_pose.torch.clone() root_pose[:, :3] = torch.randn(num_cubes, 3, device=sim.device) # Random orientation root_pose[:, 3:7] = random_orientation(num=num_cubes, device=sim.device) cube_object.write_root_pose_to_sim_index(root_pose=root_pose) - root_vel = wp.to_torch(cube_object.data.default_root_vel).clone() + root_vel = cube_object.data.default_root_vel.torch.clone() cube_object.write_root_velocity_to_sim_index(root_velocity=root_vel) if i % 2 == 0: @@ -557,10 +557,10 @@ def test_reset_rigid_object(num_cubes, device): # Reset should zero external forces and torques assert not cube_object._instantaneous_wrench_composer.active assert not cube_object._permanent_wrench_composer.active - assert torch.count_nonzero(wp.to_torch(cube_object._instantaneous_wrench_composer.composed_force)) == 0 - assert torch.count_nonzero(wp.to_torch(cube_object._instantaneous_wrench_composer.composed_torque)) == 0 - assert torch.count_nonzero(wp.to_torch(cube_object._permanent_wrench_composer.composed_force)) == 0 - assert torch.count_nonzero(wp.to_torch(cube_object._permanent_wrench_composer.composed_torque)) == 0 + assert torch.count_nonzero(cube_object._instantaneous_wrench_composer.composed_force.torch) == 0 + assert torch.count_nonzero(cube_object._instantaneous_wrench_composer.composed_torque.torch) == 0 + assert torch.count_nonzero(cube_object._permanent_wrench_composer.composed_force.torch) == 0 + assert torch.count_nonzero(cube_object._permanent_wrench_composer.composed_torque.torch) == 0 @pytest.mark.parametrize("num_cubes", [1, 2]) @@ -604,6 +604,46 @@ def test_rigid_body_set_material_properties(num_cubes, device): torch.testing.assert_close(materials_to_check.reshape(num_cubes, 3), materials) +@pytest.mark.parametrize("num_cubes", [1, 2]) +@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) +@pytest.mark.isaacsim_ci +def test_set_material_properties_via_view(num_cubes, device): + """Test setting material properties via the PhysX view-level API.""" + with build_simulation_context( + device=device, gravity_enabled=True, add_ground_plane=True, auto_add_lighting=True + ) as sim: + sim._app_control_on_stop_handle = None + # Generate cubes scene + cube_object, _ = generate_cubes_scene(num_cubes=num_cubes, device=device) + + # Play sim + sim.reset() + + # Get number of shapes + max_shapes = cube_object.root_view.max_shapes + + # Generate random material properties: (static_friction, dynamic_friction, restitution) + materials = torch.empty(num_cubes, max_shapes, 3, device="cpu").uniform_(0.0, 1.0) + # Ensure dynamic friction <= static friction + materials[..., 1] = torch.min(materials[..., 0], materials[..., 1]) + + # Set material properties via the PhysX view-level API + env_ids = torch.arange(num_cubes, dtype=torch.int32) + cube_object.root_view.set_material_properties( + wp.from_torch(materials, dtype=wp.float32), wp.from_torch(env_ids, dtype=wp.int32) + ) + + # Simulate physics + sim.step() + cube_object.update(sim.cfg.dt) + + # Get material properties from simulation + materials_check = wp.to_torch(cube_object.root_view.get_material_properties()) + + # Check if material properties are set correctly + torch.testing.assert_close(materials_check, materials) + + @pytest.mark.parametrize("num_cubes", [1, 2]) @pytest.mark.parametrize("device", ["cuda:0", "cpu"]) @pytest.mark.isaacsim_ci @@ -660,7 +700,7 @@ def test_rigid_body_no_friction(num_cubes, device): tolerance = 1e-5 torch.testing.assert_close( - wp.to_torch(cube_object.data.root_lin_vel_w), initial_velocity[:, :3], rtol=1e-5, atol=tolerance + cube_object.data.root_lin_vel_w.torch, initial_velocity[:, :3], rtol=1e-5, atol=tolerance ) @@ -733,7 +773,7 @@ def test_rigid_body_with_static_friction(num_cubes, device): ) # Get root state - initial_root_pos = wp.to_torch(cube_object.data.root_pos_w).clone() + initial_root_pos = cube_object.data.root_pos_w.torch.clone() # Simulate physics for _ in range(200): # apply the wrench @@ -744,10 +784,10 @@ def test_rigid_body_with_static_friction(num_cubes, device): if force == "below_mu": # Assert that the block has not moved torch.testing.assert_close( - wp.to_torch(cube_object.data.root_pos_w), initial_root_pos, rtol=2e-3, atol=2e-3 + cube_object.data.root_pos_w.torch, initial_root_pos, rtol=2e-3, atol=2e-3 ) if force == "above_mu": - assert (wp.to_torch(cube_object.data.root_pos_w)[..., 0] - initial_root_pos[..., 0] > 0.02).all() + assert (cube_object.data.root_pos_w.torch[..., 0] - initial_root_pos[..., 0] > 0.02).all() @pytest.mark.parametrize("num_cubes", [1, 2]) @@ -807,14 +847,14 @@ def test_rigid_body_with_restitution(num_cubes, device): wp.from_torch(cube_object_materials, dtype=wp.float32), wp.from_torch(indices, dtype=wp.int32) ) - curr_z_velocity = wp.to_torch(cube_object.data.root_lin_vel_w)[:, 2].clone() + curr_z_velocity = cube_object.data.root_lin_vel_w.torch[:, 2].clone() for _ in range(100): sim.step() # update object cube_object.update(sim.cfg.dt) - curr_z_velocity = wp.to_torch(cube_object.data.root_lin_vel_w)[:, 2].clone() + curr_z_velocity = cube_object.data.root_lin_vel_w.torch[:, 2].clone() if expected_collision_type == "inelastic": # assert that the block has not bounced by checking that the z velocity is less than or equal to 0 @@ -898,9 +938,9 @@ def test_gravity_vec_w(num_cubes, device, gravity_enabled): sim.reset() # Check that gravity is set correctly - assert wp.to_torch(cube_object.data.GRAVITY_VEC_W)[0, 0] == gravity_dir[0] - assert wp.to_torch(cube_object.data.GRAVITY_VEC_W)[0, 1] == gravity_dir[1] - assert wp.to_torch(cube_object.data.GRAVITY_VEC_W)[0, 2] == gravity_dir[2] + assert cube_object.data.GRAVITY_VEC_W.torch[0, 0] == gravity_dir[0] + assert cube_object.data.GRAVITY_VEC_W.torch[0, 1] == gravity_dir[1] + assert cube_object.data.GRAVITY_VEC_W.torch[0, 2] == gravity_dir[2] # Simulate physics for _ in range(2): @@ -914,7 +954,7 @@ def test_gravity_vec_w(num_cubes, device, gravity_enabled): if gravity_enabled: gravity[:, :, 2] = -9.81 # Check the body accelerations are correct - torch.testing.assert_close(wp.to_torch(cube_object.data.body_acc_w), gravity) + torch.testing.assert_close(cube_object.data.body_acc_w.torch, gravity) @pytest.mark.parametrize("num_cubes", [1, 2]) @@ -963,14 +1003,14 @@ def test_body_root_state_properties(num_cubes, device, with_offset): cube_object.update(sim.cfg.dt) # get state properties - root_link_pose_w = wp.to_torch(cube_object.data.root_link_pose_w) - root_link_vel_w = wp.to_torch(cube_object.data.root_link_vel_w) - root_com_pose_w = wp.to_torch(cube_object.data.root_com_pose_w) - root_com_vel_w = wp.to_torch(cube_object.data.root_com_vel_w) - body_link_pose_w = wp.to_torch(cube_object.data.body_link_pose_w) - body_link_vel_w = wp.to_torch(cube_object.data.body_link_vel_w) - body_com_pose_w = wp.to_torch(cube_object.data.body_com_pose_w) - body_com_vel_w = wp.to_torch(cube_object.data.body_com_vel_w) + root_link_pose_w = cube_object.data.root_link_pose_w.torch + root_link_vel_w = cube_object.data.root_link_vel_w.torch + root_com_pose_w = cube_object.data.root_com_pose_w.torch + root_com_vel_w = cube_object.data.root_com_vel_w.torch + body_link_pose_w = cube_object.data.body_link_pose_w.torch + body_link_vel_w = cube_object.data.body_link_vel_w.torch + body_com_pose_w = cube_object.data.body_com_pose_w.torch + body_com_vel_w = cube_object.data.body_com_vel_w.torch # if offset is [0,0,0] all root_state_%_w will match and all body_%_w will match if not with_offset: @@ -1001,7 +1041,7 @@ def test_body_root_state_properties(num_cubes, device, with_offset): torch.testing.assert_close(-offset, body_link_state_pos_rel_com.squeeze(-2)) # orientation of com will be a constant rotation from link orientation - com_quat_b = wp.to_torch(cube_object.data.body_com_quat_b) + com_quat_b = cube_object.data.body_com_quat_b.torch com_quat_w = quat_mul(body_link_pose_w[..., 3:], com_quat_b) torch.testing.assert_close(com_quat_w, body_com_pose_w[..., 3:]) torch.testing.assert_close(com_quat_w.squeeze(-2), root_com_pose_w[..., 3:]) @@ -1061,7 +1101,7 @@ def test_write_root_state(num_cubes, device, with_offset, state_location): torch.testing.assert_close(wp.to_torch(cube_object.root_view.get_coms()), com) rand_state = torch.zeros(num_cubes, 13, device=device) - rand_state[..., :7] = wp.to_torch(cube_object.data.default_root_pose) + rand_state[..., :7] = cube_object.data.default_root_pose.torch rand_state[..., :3] += env_pos # make quaternion a unit vector rand_state[..., 3:7] = torch.nn.functional.normalize(rand_state[..., 3:7], dim=-1) @@ -1091,11 +1131,11 @@ def test_write_root_state(num_cubes, device, with_offset, state_location): ) if state_location == "com": - torch.testing.assert_close(rand_state[..., :7], wp.to_torch(cube_object.data.root_com_pose_w)) - torch.testing.assert_close(rand_state[..., 7:], wp.to_torch(cube_object.data.root_com_vel_w)) + torch.testing.assert_close(rand_state[..., :7], cube_object.data.root_com_pose_w.torch) + torch.testing.assert_close(rand_state[..., 7:], cube_object.data.root_com_vel_w.torch) elif state_location == "link": - torch.testing.assert_close(rand_state[..., :7], wp.to_torch(cube_object.data.root_link_pose_w)) - torch.testing.assert_close(rand_state[..., 7:], wp.to_torch(cube_object.data.root_link_vel_w)) + torch.testing.assert_close(rand_state[..., :7], cube_object.data.root_link_pose_w.torch) + torch.testing.assert_close(rand_state[..., 7:], cube_object.data.root_link_vel_w.torch) @pytest.mark.parametrize("num_cubes", [1, 2]) @@ -1153,9 +1193,9 @@ def test_write_state_functions_data_consistency(num_cubes, device, with_offset, cube_object.write_root_velocity_to_sim_index(root_velocity=rand_state[..., 7:]) if state_location == "com": - root_com_pose_w = wp.to_torch(cube_object.data.root_com_pose_w) - root_com_vel_w = wp.to_torch(cube_object.data.root_com_vel_w) - body_com_pose_b = wp.to_torch(cube_object.data.body_com_pose_b) + root_com_pose_w = cube_object.data.root_com_pose_w.torch + root_com_vel_w = cube_object.data.root_com_vel_w.torch + body_com_pose_b = cube_object.data.body_com_pose_b.torch expected_root_link_pos, expected_root_link_quat = combine_frame_transforms( root_com_pose_w[:, :3], root_com_pose_w[:, 3:], @@ -1163,19 +1203,19 @@ def test_write_state_functions_data_consistency(num_cubes, device, with_offset, quat_inv(body_com_pose_b[:, 0, 3:7]), ) expected_root_link_pose = torch.cat((expected_root_link_pos, expected_root_link_quat), dim=1) - root_link_pose_w = wp.to_torch(cube_object.data.root_link_pose_w) - root_link_vel_w = wp.to_torch(cube_object.data.root_link_vel_w) + root_link_pose_w = cube_object.data.root_link_pose_w.torch + root_link_vel_w = cube_object.data.root_link_vel_w.torch # test both root_pose and root_link successfully updated when root_com updates torch.testing.assert_close(expected_root_link_pose, root_link_pose_w) # skip lin_vel because it differs from link frame, this should be fine because we are only checking # if velocity update is triggered, which can be determined by comparing angular velocity torch.testing.assert_close(root_com_vel_w[:, 3:], root_link_vel_w[:, 3:]) torch.testing.assert_close(expected_root_link_pose, root_link_pose_w) - torch.testing.assert_close(root_com_vel_w[:, 3:], wp.to_torch(cube_object.data.root_com_vel_w)[:, 3:]) + torch.testing.assert_close(root_com_vel_w[:, 3:], cube_object.data.root_com_vel_w.torch[:, 3:]) elif state_location == "link": - root_link_pose_w = wp.to_torch(cube_object.data.root_link_pose_w) - root_link_vel_w = wp.to_torch(cube_object.data.root_link_vel_w) - body_com_pose_b = wp.to_torch(cube_object.data.body_com_pose_b) + root_link_pose_w = cube_object.data.root_link_pose_w.torch + root_link_vel_w = cube_object.data.root_link_vel_w.torch + body_com_pose_b = cube_object.data.body_com_pose_b.torch expected_com_pos, expected_com_quat = combine_frame_transforms( root_link_pose_w[:, :3], root_link_pose_w[:, 3:], @@ -1183,19 +1223,19 @@ def test_write_state_functions_data_consistency(num_cubes, device, with_offset, body_com_pose_b[:, 0, 3:7], ) expected_com_pose = torch.cat((expected_com_pos, expected_com_quat), dim=1) - root_com_pose_w = wp.to_torch(cube_object.data.root_com_pose_w) - root_com_vel_w = wp.to_torch(cube_object.data.root_com_vel_w) + root_com_pose_w = cube_object.data.root_com_pose_w.torch + root_com_vel_w = cube_object.data.root_com_vel_w.torch # test both root_pose and root_com successfully updated when root_link updates torch.testing.assert_close(expected_com_pose, root_com_pose_w) # skip lin_vel because it differs from link frame, this should be fine because we are only checking # if velocity update is triggered, which can be determined by comparing angular velocity torch.testing.assert_close(root_link_vel_w[:, 3:], root_com_vel_w[:, 3:]) - torch.testing.assert_close(root_link_pose_w, wp.to_torch(cube_object.data.root_link_pose_w)) - torch.testing.assert_close(root_link_vel_w[:, 3:], wp.to_torch(cube_object.data.root_com_vel_w)[:, 3:]) + torch.testing.assert_close(root_link_pose_w, cube_object.data.root_link_pose_w.torch) + torch.testing.assert_close(root_link_vel_w[:, 3:], cube_object.data.root_com_vel_w.torch[:, 3:]) elif state_location == "root": - root_link_pose_w = wp.to_torch(cube_object.data.root_link_pose_w) - root_com_vel_w = wp.to_torch(cube_object.data.root_com_vel_w) - body_com_pose_b = wp.to_torch(cube_object.data.body_com_pose_b) + root_link_pose_w = cube_object.data.root_link_pose_w.torch + root_com_vel_w = cube_object.data.root_com_vel_w.torch + body_com_pose_b = cube_object.data.body_com_pose_b.torch expected_com_pos, expected_com_quat = combine_frame_transforms( root_link_pose_w[:, :3], root_link_pose_w[:, 3:], @@ -1203,12 +1243,12 @@ def test_write_state_functions_data_consistency(num_cubes, device, with_offset, body_com_pose_b[:, 0, 3:7], ) expected_com_pose = torch.cat((expected_com_pos, expected_com_quat), dim=1) - root_com_pose_w = wp.to_torch(cube_object.data.root_com_pose_w) - root_link_vel_w = wp.to_torch(cube_object.data.root_link_vel_w) + root_com_pose_w = cube_object.data.root_com_pose_w.torch + root_link_vel_w = cube_object.data.root_link_vel_w.torch # test both root_com and root_link successfully updated when root_pose updates torch.testing.assert_close(expected_com_pose, root_com_pose_w) - torch.testing.assert_close(root_com_vel_w, wp.to_torch(cube_object.data.root_com_vel_w)) - torch.testing.assert_close(root_link_pose_w, wp.to_torch(cube_object.data.root_link_pose_w)) + torch.testing.assert_close(root_com_vel_w, cube_object.data.root_com_vel_w.torch) + torch.testing.assert_close(root_link_pose_w, cube_object.data.root_link_pose_w.torch) torch.testing.assert_close(root_com_vel_w[:, 3:], root_link_vel_w[:, 3:]) diff --git a/source/isaaclab_physx/test/assets/test_rigid_object_collection.py b/source/isaaclab_physx/test/assets/test_rigid_object_collection.py index 03689d73f48a..8401cc395a0c 100644 --- a/source/isaaclab_physx/test/assets/test_rigid_object_collection.py +++ b/source/isaaclab_physx/test/assets/test_rigid_object_collection.py @@ -126,10 +126,10 @@ def test_initialization(sim, num_envs, num_cubes, device): assert len(object_collection.body_names) == num_cubes # Check buffers that exist and have correct shapes - assert wp.to_torch(object_collection.data.body_link_pos_w).shape == (num_envs, num_cubes, 3) - assert wp.to_torch(object_collection.data.body_link_quat_w).shape == (num_envs, num_cubes, 4) - assert wp.to_torch(object_collection.data.body_mass).shape == (num_envs, num_cubes) - assert wp.to_torch(object_collection.data.body_inertia).shape == (num_envs, num_cubes, 9) + assert object_collection.data.body_link_pos_w.torch.shape == (num_envs, num_cubes, 3) + assert object_collection.data.body_link_quat_w.torch.shape == (num_envs, num_cubes, 4) + assert object_collection.data.body_mass.torch.shape == (num_envs, num_cubes) + assert object_collection.data.body_inertia.torch.shape == (num_envs, num_cubes, 9) # Simulate physics for _ in range(2): @@ -193,19 +193,19 @@ def test_initialization_with_kinematic_enabled(sim, num_envs, num_cubes, device) assert len(object_collection.body_names) == num_cubes # Check buffers that exist and have correct shapes - assert wp.to_torch(object_collection.data.body_link_pos_w).shape == (num_envs, num_cubes, 3) - assert wp.to_torch(object_collection.data.body_link_quat_w).shape == (num_envs, num_cubes, 4) + assert object_collection.data.body_link_pos_w.torch.shape == (num_envs, num_cubes, 3) + assert object_collection.data.body_link_quat_w.torch.shape == (num_envs, num_cubes, 4) # Simulate physics for _ in range(2): sim.step() object_collection.update(sim.cfg.dt) # check that the object is kinematic - default_body_pose = wp.to_torch(object_collection.data.default_body_pose).clone() - default_body_vel = wp.to_torch(object_collection.data.default_body_vel).clone() + default_body_pose = object_collection.data.default_body_pose.torch.clone() + default_body_vel = object_collection.data.default_body_vel.torch.clone() default_body_pose[..., :3] += origins.unsqueeze(1) - torch.testing.assert_close(wp.to_torch(object_collection.data.body_link_pose_w), default_body_pose) - torch.testing.assert_close(wp.to_torch(object_collection.data.body_link_vel_w), default_body_vel) + torch.testing.assert_close(object_collection.data.body_link_pose_w.torch, default_body_pose) + torch.testing.assert_close(object_collection.data.body_link_vel_w.torch, default_body_vel) @pytest.mark.parametrize("num_cubes", [1, 2]) @@ -259,8 +259,8 @@ def test_external_force_buffer(sim, device): # check if the object collection's force and torque buffers are correctly updated for i in range(num_envs): - assert wp.to_torch(object_collection._permanent_wrench_composer.composed_force)[i, 0, 0].item() == force - assert wp.to_torch(object_collection._permanent_wrench_composer.composed_torque)[i, 0, 0].item() == force + assert object_collection._permanent_wrench_composer.composed_force.torch[i, 0, 0].item() == force + assert object_collection._permanent_wrench_composer.composed_torque.torch[i, 0, 0].item() == force object_collection.instantaneous_wrench_composer.add_forces_and_torques_index( body_ids=object_ids, @@ -288,12 +288,12 @@ def test_external_force_on_single_body(sim, num_envs, num_cubes, device): # Sample a force equal to the weight of the object external_wrench_b = torch.zeros(object_collection.num_instances, len(object_ids), 6, device=sim.device) # Every 2nd cube should have a force applied to it - external_wrench_b[:, 0::2, 2] = 9.81 * wp.to_torch(object_collection.data.body_mass)[:, 0::2] + external_wrench_b[:, 0::2, 2] = 9.81 * object_collection.data.body_mass.torch[:, 0::2] for i in range(5): # reset object state - body_pose = wp.to_torch(object_collection.data.default_body_pose).clone() - body_vel = wp.to_torch(object_collection.data.default_body_vel).clone() + body_pose = object_collection.data.default_body_pose.torch.clone() + body_vel = object_collection.data.default_body_vel.torch.clone() # need to shift the position of the cubes otherwise they will be on top of each other body_pose[..., :2] += origins.unsqueeze(1)[..., :2] object_collection.write_body_link_pose_to_sim_index(body_poses=body_pose) @@ -303,7 +303,7 @@ def test_external_force_on_single_body(sim, num_envs, num_cubes, device): is_global = False if i % 2 == 0: - positions = wp.to_torch(object_collection.data.body_link_pos_w)[:, object_ids, :3] + positions = object_collection.data.body_link_pos_w.torch[:, object_ids, :3] is_global = True else: positions = None @@ -327,11 +327,11 @@ def test_external_force_on_single_body(sim, num_envs, num_cubes, device): # First object should still be at the same Z position (1.0) torch.testing.assert_close( - wp.to_torch(object_collection.data.body_link_pos_w)[:, 0::2, 2], - torch.ones_like(wp.to_torch(object_collection.data.body_link_pos_w)[:, 0::2, 2]), + object_collection.data.body_link_pos_w.torch[:, 0::2, 2], + torch.ones_like(object_collection.data.body_link_pos_w.torch[:, 0::2, 2]), ) # Second object should have fallen, so it's Z height should be less than initial height of 1.0 - assert torch.all(wp.to_torch(object_collection.data.body_link_pos_w)[:, 1::2, 2] < 1.0) + assert torch.all(object_collection.data.body_link_pos_w.torch[:, 1::2, 2] < 1.0) @pytest.mark.parametrize("num_envs", [1, 2]) @@ -360,8 +360,8 @@ def test_external_force_on_single_body_at_position(sim, num_envs, num_cubes, dev # Desired force and torque for i in range(5): # reset object state - body_pose = wp.to_torch(object_collection.data.default_body_pose).clone() - body_vel = wp.to_torch(object_collection.data.default_body_vel).clone() + body_pose = object_collection.data.default_body_pose.torch.clone() + body_vel = object_collection.data.default_body_vel.torch.clone() # need to shift the position of the cubes otherwise they will be on top of each other body_pose[..., :2] += origins.unsqueeze(1)[..., :2] object_collection.write_body_link_pose_to_sim_index(body_poses=body_pose) @@ -371,7 +371,7 @@ def test_external_force_on_single_body_at_position(sim, num_envs, num_cubes, dev is_global = False if i % 2 == 0: - body_com_pos_w = wp.to_torch(object_collection.data.body_link_pos_w)[:, object_ids, :3] + body_com_pos_w = object_collection.data.body_link_pos_w.torch[:, object_ids, :3] external_wrench_positions_b[..., 0] = 0.0 external_wrench_positions_b[..., 1] = 1.0 external_wrench_positions_b[..., 2] = 0.0 @@ -408,9 +408,9 @@ def test_external_force_on_single_body_at_position(sim, num_envs, num_cubes, dev object_collection.update(sim.cfg.dt) # First object should be rotating around it's X axis - assert torch.all(wp.to_torch(object_collection.data.body_com_ang_vel_b)[:, 0::2, 0] > 0.1) + assert torch.all(object_collection.data.body_com_ang_vel_b.torch[:, 0::2, 0] > 0.1) # Second object should have fallen, so it's Z height should be less than initial height of 1.0 - assert torch.all(wp.to_torch(object_collection.data.body_link_pos_w)[:, 1::2, 2] < 1.0) + assert torch.all(object_collection.data.body_link_pos_w.torch[:, 1::2, 2] < 1.0) @pytest.mark.parametrize("num_envs", [1, 3]) @@ -432,16 +432,12 @@ def test_set_object_state(sim, num_envs, num_cubes, device, gravity_enabled): # Set each state type individually as they are dependent on each other for state_type_to_randomize in state_types: state_dict = { - "body_link_pos_w": torch.zeros_like(wp.to_torch(object_collection.data.body_link_pos_w), device=sim.device), + "body_link_pos_w": torch.zeros_like(object_collection.data.body_link_pos_w.torch, device=sim.device), "body_link_quat_w": default_orientation(num=num_cubes * num_envs, device=sim.device).view( num_envs, num_cubes, 4 ), - "body_com_lin_vel_w": torch.zeros_like( - wp.to_torch(object_collection.data.body_com_lin_vel_w), device=sim.device - ), - "body_com_ang_vel_w": torch.zeros_like( - wp.to_torch(object_collection.data.body_com_ang_vel_w), device=sim.device - ), + "body_com_lin_vel_w": torch.zeros_like(object_collection.data.body_com_lin_vel_w.torch, device=sim.device), + "body_com_ang_vel_w": torch.zeros_like(object_collection.data.body_com_ang_vel_w.torch, device=sim.device), } for _ in range(5): @@ -476,7 +472,7 @@ def test_set_object_state(sim, num_envs, num_cubes, device, gravity_enabled): # assert that set object quantities are equal to the ones set in the state_dict for key, expected_value in state_dict.items(): - value = wp.to_torch(getattr(object_collection.data, key)) + value = getattr(object_collection.data, key).torch torch.testing.assert_close(value, expected_value, rtol=1e-5, atol=1e-5) object_collection.update(sim.cfg.dt) @@ -521,7 +517,7 @@ def test_object_state_properties(sim, num_envs, num_cubes, device, with_offset, spin_twist[5] = torch.randn(1, device=device) # initial spawn point - init_com = wp.to_torch(cube_object.data.body_com_pose_w)[..., :3] + init_com = cube_object.data.body_com_pose_w.torch[..., :3] for i in range(10): # spin the object around Z axis (com) @@ -530,10 +526,10 @@ def test_object_state_properties(sim, num_envs, num_cubes, device, with_offset, cube_object.update(sim.cfg.dt) # get state properties - object_link_pose_w = wp.to_torch(cube_object.data.body_link_pose_w) - object_link_vel_w = wp.to_torch(cube_object.data.body_link_vel_w) - object_com_pose_w = wp.to_torch(cube_object.data.body_com_pose_w) - object_com_vel_w = wp.to_torch(cube_object.data.body_com_vel_w) + object_link_pose_w = cube_object.data.body_link_pose_w.torch + object_link_vel_w = cube_object.data.body_link_vel_w.torch + object_com_pose_w = cube_object.data.body_com_pose_w.torch + object_com_vel_w = cube_object.data.body_com_vel_w.torch # if offset is [0,0,0] all object_state_%_w will match and all body_%_w will match if not with_offset: @@ -554,7 +550,7 @@ def test_object_state_properties(sim, num_envs, num_cubes, device, with_offset, torch.testing.assert_close(-offset, object_link_state_pos_rel_com) # orientation of com will be a constant rotation from link orientation - com_quat_b = wp.to_torch(cube_object.data.body_com_quat_b) + com_quat_b = cube_object.data.body_com_quat_b.torch com_quat_w = quat_mul(object_link_pose_w[..., 3:], com_quat_b) torch.testing.assert_close(com_quat_w, object_com_pose_w[..., 3:]) @@ -616,8 +612,8 @@ def test_write_object_state(sim, num_envs, num_cubes, device, with_offset, state ) rand_state = torch.zeros(num_envs, num_cubes, 13, device=device) - rand_state[..., :7] = wp.to_torch(cube_object.data.default_body_pose) - rand_state[..., :3] += wp.to_torch(cube_object.data.body_link_pos_w) + rand_state[..., :7] = cube_object.data.default_body_pose.torch + rand_state[..., :3] += cube_object.data.body_link_pos_w.torch # make quaternion a unit vector rand_state[..., 3:7] = torch.nn.functional.normalize(rand_state[..., 3:7], dim=-1) @@ -651,11 +647,11 @@ def test_write_object_state(sim, num_envs, num_cubes, device, with_offset, state ) if state_location == "com": - torch.testing.assert_close(rand_state[..., :7], wp.to_torch(cube_object.data.body_com_pose_w)) - torch.testing.assert_close(rand_state[..., 7:], wp.to_torch(cube_object.data.body_com_vel_w)) + torch.testing.assert_close(rand_state[..., :7], cube_object.data.body_com_pose_w.torch) + torch.testing.assert_close(rand_state[..., 7:], cube_object.data.body_com_vel_w.torch) elif state_location == "link": - torch.testing.assert_close(rand_state[..., :7], wp.to_torch(cube_object.data.body_link_pose_w)) - torch.testing.assert_close(rand_state[..., 7:], wp.to_torch(cube_object.data.body_link_vel_w)) + torch.testing.assert_close(rand_state[..., :7], cube_object.data.body_link_pose_w.torch) + torch.testing.assert_close(rand_state[..., 7:], cube_object.data.body_link_vel_w.torch) @pytest.mark.parametrize("num_envs", [1, 3]) @@ -671,12 +667,12 @@ def test_reset_object_collection(sim, num_envs, num_cubes, device): object_collection.update(sim.cfg.dt) # Move the object to a random position - body_pose = wp.to_torch(object_collection.data.default_body_pose).clone() + body_pose = object_collection.data.default_body_pose.torch.clone() body_pose[..., :3] = torch.randn(num_envs, num_cubes, 3, device=sim.device) # Random orientation body_pose[..., 3:7] = random_orientation(num=num_cubes, device=sim.device) object_collection.write_body_link_pose_to_sim_index(body_poses=body_pose) - body_vel = wp.to_torch(object_collection.data.default_body_vel).clone() + body_vel = object_collection.data.default_body_vel.torch.clone() object_collection.write_body_com_velocity_to_sim_index(body_velocities=body_vel) if i % 2 == 0: @@ -685,14 +681,10 @@ def test_reset_object_collection(sim, num_envs, num_cubes, device): # Reset should zero external forces and torques assert not object_collection._instantaneous_wrench_composer.active assert not object_collection._permanent_wrench_composer.active - assert ( - torch.count_nonzero(wp.to_torch(object_collection._instantaneous_wrench_composer.composed_force)) == 0 - ) - assert ( - torch.count_nonzero(wp.to_torch(object_collection._instantaneous_wrench_composer.composed_torque)) == 0 - ) - assert torch.count_nonzero(wp.to_torch(object_collection._permanent_wrench_composer.composed_force)) == 0 - assert torch.count_nonzero(wp.to_torch(object_collection._permanent_wrench_composer.composed_torque)) == 0 + assert torch.count_nonzero(object_collection._instantaneous_wrench_composer.composed_force.torch) == 0 + assert torch.count_nonzero(object_collection._instantaneous_wrench_composer.composed_torque.torch) == 0 + assert torch.count_nonzero(object_collection._permanent_wrench_composer.composed_force.torch) == 0 + assert torch.count_nonzero(object_collection._permanent_wrench_composer.composed_torque.torch) == 0 @pytest.mark.parametrize("num_envs", [1, 3]) @@ -744,7 +736,7 @@ def test_gravity_vec_w(sim, num_envs, num_cubes, device, gravity_enabled): sim.reset() # Check if gravity vector is set correctly - gravity_vec = wp.to_torch(object_collection.data.GRAVITY_VEC_W) + gravity_vec = object_collection.data.GRAVITY_VEC_W.torch assert gravity_vec[0, 0, 0] == gravity_dir[0] assert gravity_vec[0, 0, 1] == gravity_dir[1] assert gravity_vec[0, 0, 2] == gravity_dir[2] @@ -760,7 +752,7 @@ def test_gravity_vec_w(sim, num_envs, num_cubes, device, gravity_enabled): gravity[..., 2] = -9.81 # Check the body accelerations are correct - torch.testing.assert_close(wp.to_torch(object_collection.data.body_com_acc_w), gravity) + torch.testing.assert_close(object_collection.data.body_com_acc_w.torch, gravity) @pytest.mark.parametrize("num_envs", [1, 3]) @@ -804,7 +796,7 @@ def test_write_object_state_functions_data_consistency( ) rand_state = torch.rand(num_envs, num_cubes, 13, device=device) - rand_state[..., :3] += wp.to_torch(cube_object.data.body_link_pos_w) + rand_state[..., :3] += cube_object.data.body_link_pos_w.torch # make quaternion a unit vector rand_state[..., 3:7] = torch.nn.functional.normalize(rand_state[..., 3:7], dim=-1) @@ -813,8 +805,8 @@ def test_write_object_state_functions_data_consistency( sim.step() cube_object.update(sim.cfg.dt) - body_link_pose_w = wp.to_torch(cube_object.data.body_link_pose_w) - body_com_pose_w = wp.to_torch(cube_object.data.body_com_pose_w) + body_link_pose_w = cube_object.data.body_link_pose_w.torch + body_com_pose_w = cube_object.data.body_com_pose_w.torch object_link_to_com_pos, object_link_to_com_quat = subtract_frame_transforms( body_link_pose_w[..., :3].view(-1, 3), body_link_pose_w[..., 3:7].view(-1, 4), @@ -845,8 +837,8 @@ def test_write_object_state_functions_data_consistency( ) if state_location == "com": - com_pose_w = wp.to_torch(cube_object.data.body_com_pose_w) - com_vel_w = wp.to_torch(cube_object.data.body_com_vel_w) + com_pose_w = cube_object.data.body_com_pose_w.torch + com_vel_w = cube_object.data.body_com_vel_w.torch expected_root_link_pos, expected_root_link_quat = combine_frame_transforms( com_pose_w[..., :3].view(-1, 3), com_pose_w[..., 3:].view(-1, 4), @@ -856,18 +848,18 @@ def test_write_object_state_functions_data_consistency( expected_object_link_pose = torch.cat((expected_root_link_pos, expected_root_link_quat), dim=1).view( num_envs, -1, 7 ) - link_pose_w = wp.to_torch(cube_object.data.body_link_pose_w) - link_vel_w = wp.to_torch(cube_object.data.body_link_vel_w) + link_pose_w = cube_object.data.body_link_pose_w.torch + link_vel_w = cube_object.data.body_link_vel_w.torch # test both root_pose and root_link successfully updated when root_com updates torch.testing.assert_close(expected_object_link_pose, link_pose_w) # skip lin_vel because it differs from link frame, this should be fine because we are only checking # if velocity update is triggered, which can be determined by comparing angular velocity torch.testing.assert_close(com_vel_w[..., 3:], link_vel_w[..., 3:]) torch.testing.assert_close(expected_object_link_pose, link_pose_w) - torch.testing.assert_close(com_vel_w[..., 3:], wp.to_torch(cube_object.data.body_com_vel_w)[..., 3:]) + torch.testing.assert_close(com_vel_w[..., 3:], cube_object.data.body_com_vel_w.torch[..., 3:]) elif state_location == "link": - link_pose_w = wp.to_torch(cube_object.data.body_link_pose_w) - link_vel_w = wp.to_torch(cube_object.data.body_link_vel_w) + link_pose_w = cube_object.data.body_link_pose_w.torch + link_vel_w = cube_object.data.body_link_vel_w.torch expected_com_pos, expected_com_quat = combine_frame_transforms( link_pose_w[..., :3].view(-1, 3), link_pose_w[..., 3:].view(-1, 4), @@ -875,18 +867,18 @@ def test_write_object_state_functions_data_consistency( object_link_to_com_quat, ) expected_object_com_pose = torch.cat((expected_com_pos, expected_com_quat), dim=1).view(num_envs, -1, 7) - com_pose_w = wp.to_torch(cube_object.data.body_com_pose_w) - com_vel_w = wp.to_torch(cube_object.data.body_com_vel_w) + com_pose_w = cube_object.data.body_com_pose_w.torch + com_vel_w = cube_object.data.body_com_vel_w.torch # test both root_pose and root_com successfully updated when root_link updates torch.testing.assert_close(expected_object_com_pose, com_pose_w) # skip lin_vel because it differs from link frame, this should be fine because we are only checking # if velocity update is triggered, which can be determined by comparing angular velocity torch.testing.assert_close(link_vel_w[..., 3:], com_vel_w[..., 3:]) - torch.testing.assert_close(link_pose_w, wp.to_torch(cube_object.data.body_link_pose_w)) - torch.testing.assert_close(link_vel_w[..., 3:], wp.to_torch(cube_object.data.body_com_vel_w)[..., 3:]) + torch.testing.assert_close(link_pose_w, cube_object.data.body_link_pose_w.torch) + torch.testing.assert_close(link_vel_w[..., 3:], cube_object.data.body_com_vel_w.torch[..., 3:]) elif state_location == "root": - body_link_pose_w = wp.to_torch(cube_object.data.body_link_pose_w) - body_com_vel_w = wp.to_torch(cube_object.data.body_com_vel_w) + body_link_pose_w = cube_object.data.body_link_pose_w.torch + body_com_vel_w = cube_object.data.body_com_vel_w.torch expected_object_com_pos, expected_object_com_quat = combine_frame_transforms( body_link_pose_w[..., :3].view(-1, 3), body_link_pose_w[..., 3:].view(-1, 4), @@ -896,10 +888,10 @@ def test_write_object_state_functions_data_consistency( expected_object_com_pose = torch.cat((expected_object_com_pos, expected_object_com_quat), dim=1).view( num_envs, -1, 7 ) - com_pose_w = wp.to_torch(cube_object.data.body_com_pose_w) - com_vel_w = wp.to_torch(cube_object.data.body_com_vel_w) - link_pose_w = wp.to_torch(cube_object.data.body_link_pose_w) - link_vel_w = wp.to_torch(cube_object.data.body_link_vel_w) + com_pose_w = cube_object.data.body_com_pose_w.torch + com_vel_w = cube_object.data.body_com_vel_w.torch + link_pose_w = cube_object.data.body_link_pose_w.torch + link_vel_w = cube_object.data.body_link_vel_w.torch # test both root_com and root_link successfully updated when root_pose updates torch.testing.assert_close(expected_object_com_pose, com_pose_w) torch.testing.assert_close(body_com_vel_w, com_vel_w) diff --git a/source/isaaclab_physx/test/renderers/test_isaac_rtx_renderer_utils.py b/source/isaaclab_physx/test/renderers/test_isaac_rtx_renderer_utils.py index d3fce4d95b5e..068b6df87b38 100644 --- a/source/isaaclab_physx/test/renderers/test_isaac_rtx_renderer_utils.py +++ b/source/isaaclab_physx/test/renderers/test_isaac_rtx_renderer_utils.py @@ -11,11 +11,26 @@ from __future__ import annotations +import sys import time +import types from unittest.mock import MagicMock, patch -import isaaclab_physx.renderers.isaac_rtx_renderer_utils as rtx_utils -import pytest +# Stub ``omni`` / ``omni.usd`` in ``sys.modules`` before importing the module +# under test so its top-level ``import omni.usd`` succeeds outside a running +# Kit runtime. Per-test fixtures below still patch these with fresh mocks, so +# each test remains isolated. +if "omni" not in sys.modules: + sys.modules["omni"] = types.ModuleType("omni") +if "omni.usd" not in sys.modules: + _omni_usd_stub = MagicMock() + sys.modules["omni.usd"] = _omni_usd_stub + setattr(sys.modules["omni"], "usd", _omni_usd_stub) + +import isaaclab_physx.renderers.isaac_rtx_renderer_utils as rtx_utils # noqa: E402 +import pytest # noqa: E402 + +pytestmark = pytest.mark.isaacsim_ci # test-specific timeout overrides for _STREAMING_WAIT_TIMEOUT_S STREAMING_TIMEOUT_S = 0.1 @@ -29,90 +44,67 @@ @pytest.fixture(autouse=True) -def _reset_streaming_globals(monkeypatch): - """Restore module-level streaming state so tests are isolated.""" - monkeypatch.setattr(rtx_utils, "_streaming_is_busy", False) - monkeypatch.setattr(rtx_utils, "_streaming_subscription", None) - monkeypatch.setattr(rtx_utils, "_streaming_subscribed", False) +def _reset_globals(monkeypatch): + """Restore module-level state so tests are isolated.""" + monkeypatch.setattr(rtx_utils, "_last_render_update_key", (0, -1, -1)) -# --------------------------------------------------------------------------- -# _on_streaming_status_event -# --------------------------------------------------------------------------- +@pytest.fixture() +def mock_omni_usd(): + """Make ``omni.usd`` importable outside the Isaac Sim runtime. + Both ``sys.modules`` and the ``omni`` namespace attribute must be set, + because ``import omni.usd`` resolves the parent package first and then + looks up ``.usd`` as an attribute. + """ + import omni -class TestOnStreamingStatusEvent: - """Callback correctly translates RTX streaming events into the busy flag.""" + mock_module = MagicMock() + with ( + patch.dict(sys.modules, {"omni.usd": mock_module}), + patch.object(omni, "usd", mock_module, create=True), + ): + yield mock_module - def test_sets_busy_true(self): - """Sets busy flag to true when event reports busy.""" - rtx_utils._on_streaming_status_event({"isBusy": True}) - assert rtx_utils._streaming_is_busy is True - def test_sets_busy_false(self): - """Sets busy flag to false when event reports idle.""" - rtx_utils._streaming_is_busy = True - rtx_utils._on_streaming_status_event({"isBusy": False}) - assert rtx_utils._streaming_is_busy is False +@pytest.fixture() +def mock_omni_kit_app(): + """Make ``omni.kit.app`` importable outside the Isaac Sim runtime.""" + import omni - def test_ignores_missing_key(self): - """Leaves busy state unchanged when key is absent.""" - rtx_utils._streaming_is_busy = True - rtx_utils._on_streaming_status_event({"otherField": 42}) - assert rtx_utils._streaming_is_busy is True - - def test_ignores_none_value(self): - """Leaves busy state unchanged when value is None.""" - rtx_utils._streaming_is_busy = True - rtx_utils._on_streaming_status_event({"isBusy": None}) - assert rtx_utils._streaming_is_busy is True - - def test_handles_non_subscriptable_event(self): - """Ignores malformed events that are not subscriptable.""" - rtx_utils._on_streaming_status_event(None) - assert rtx_utils._streaming_is_busy is False + mock_kit = MagicMock() + mock_module = MagicMock() + mock_kit.app = mock_module + with ( + patch.dict(sys.modules, {"omni.kit": mock_kit, "omni.kit.app": mock_module}), + patch.object(omni, "kit", mock_kit, create=True), + ): + yield mock_module # --------------------------------------------------------------------------- -# _ensure_streaming_subscription +# _get_stage_streaming_busy # --------------------------------------------------------------------------- -class TestEnsureStreamingSubscription: - """Subscription helper registers once and does not retry on first failure.""" - - def test_subscribes_to_correct_event(self): - """Subscribes to the expected event and stores its handle.""" - mock_dispatcher = MagicMock() - mock_dispatcher.observe_event.return_value = "sub_handle" +class TestGetStageStreamingBusy: + """Synchronous streaming status query delegates to UsdContext.""" - with patch("carb.eventdispatcher.get_eventdispatcher", return_value=mock_dispatcher): - rtx_utils._ensure_streaming_subscription() + def test_returns_true_when_busy(self, mock_omni_usd): + mock_ctx = MagicMock() + mock_ctx.get_stage_streaming_status.return_value = True + mock_omni_usd.get_context.return_value = mock_ctx + assert rtx_utils._get_stage_streaming_busy() is True - mock_dispatcher.observe_event.assert_called_once_with( - observer_name="isaaclab_rtx_streaming_wait", - event_name=rtx_utils._RTX_STREAMING_STATUS_EVENT, - on_event=rtx_utils._on_streaming_status_event, - ) - assert rtx_utils._streaming_subscribed is True - assert rtx_utils._streaming_subscription == "sub_handle" + def test_returns_false_when_idle(self, mock_omni_usd): + mock_ctx = MagicMock() + mock_ctx.get_stage_streaming_status.return_value = False + mock_omni_usd.get_context.return_value = mock_ctx + assert rtx_utils._get_stage_streaming_busy() is False - def test_idempotent_after_first_call(self): - """Performs subscription at most once across repeated calls.""" - mock_dispatcher = MagicMock() - with patch("carb.eventdispatcher.get_eventdispatcher", return_value=mock_dispatcher): - rtx_utils._ensure_streaming_subscription() - rtx_utils._ensure_streaming_subscription() - - assert mock_dispatcher.observe_event.call_count == 1 - - def test_handles_missing_dispatcher(self): - """Marks subscription as attempted even when dispatcher is unavailable.""" - with patch("carb.eventdispatcher.get_eventdispatcher", return_value=None): - rtx_utils._ensure_streaming_subscription() - - assert rtx_utils._streaming_subscribed is True - assert rtx_utils._streaming_subscription is None + def test_returns_false_when_no_context(self, mock_omni_usd): + mock_omni_usd.get_context.return_value = None + assert rtx_utils._get_stage_streaming_busy() is False # --------------------------------------------------------------------------- @@ -121,59 +113,63 @@ def test_handles_missing_dispatcher(self): class TestWaitForStreamingComplete: - """Blocking wait pumps app.update() while busy and respects timeout.""" + """Blocking wait pumps app.update() while busy and respects timeout. - def test_returns_immediately_when_not_busy(self): + These tests patch ``_get_stage_streaming_busy`` at the module level so + they don't depend on ``omni.usd`` being importable. + """ + + def test_returns_immediately_when_not_busy(self, mock_omni_kit_app): """Skips loop and issues only the final update when idle.""" mock_app = MagicMock() - with patch("omni.kit.app.get_app", return_value=mock_app): + mock_omni_kit_app.get_app.return_value = mock_app + + with patch.object(rtx_utils, "_get_stage_streaming_busy", return_value=False): rtx_utils._wait_for_streaming_complete() - # Only the final update call, no streaming loop iterations. mock_app.update.assert_called_once() - def test_pumps_updates_until_idle(self): - """Pumps updates until busy flips to false.""" - rtx_utils._streaming_is_busy = True + def test_pumps_updates_until_idle(self, mock_omni_kit_app): + """Pumps updates until streaming reports idle.""" mock_app = MagicMock() + mock_omni_kit_app.get_app.return_value = mock_app loop_calls = 0 - def _simulate_streaming_done(): + def _streaming_status(): + return loop_calls < MOCK_ITERATIONS_BEFORE_IDLE + + def _count_update(): nonlocal loop_calls loop_calls += 1 - if loop_calls >= MOCK_ITERATIONS_BEFORE_IDLE: - rtx_utils._streaming_is_busy = False - mock_app.update.side_effect = _simulate_streaming_done + mock_app.update.side_effect = _count_update - with patch("omni.kit.app.get_app", return_value=mock_app): + with patch.object(rtx_utils, "_get_stage_streaming_busy", side_effect=_streaming_status): rtx_utils._wait_for_streaming_complete() assert mock_app.update.call_count == MOCK_ITERATIONS_BEFORE_IDLE + 1 - assert rtx_utils._streaming_is_busy is False - def test_respects_timeout(self, monkeypatch): + def test_respects_timeout(self, monkeypatch, mock_omni_kit_app): """Exits wait loop on timeout if busy never clears.""" monkeypatch.setattr(rtx_utils, "_STREAMING_WAIT_TIMEOUT_S", STREAMING_TIMEOUT_S) - rtx_utils._streaming_is_busy = True mock_app = MagicMock() mock_app.update.side_effect = lambda: time.sleep(MOCK_UPDATE_SLEEP_S) + mock_omni_kit_app.get_app.return_value = mock_app - with patch("omni.kit.app.get_app", return_value=mock_app): + with patch.object(rtx_utils, "_get_stage_streaming_busy", return_value=True): rtx_utils._wait_for_streaming_complete() - assert rtx_utils._streaming_is_busy is True assert mock_app.update.call_count > 0 - def test_timeout_logs_warning(self, monkeypatch): + def test_timeout_logs_warning(self, monkeypatch, mock_omni_kit_app): """Logs warning when timeout is reached while still busy.""" monkeypatch.setattr(rtx_utils, "_STREAMING_WAIT_TIMEOUT_S", STREAMING_TIMEOUT_SHORT_S) - rtx_utils._streaming_is_busy = True mock_app = MagicMock() + mock_omni_kit_app.get_app.return_value = mock_app mock_logger = MagicMock() with ( - patch("omni.kit.app.get_app", return_value=mock_app), + patch.object(rtx_utils, "_get_stage_streaming_busy", return_value=True), patch.object(rtx_utils, "logger", mock_logger), ): rtx_utils._wait_for_streaming_complete() @@ -181,23 +177,157 @@ def test_timeout_logs_warning(self, monkeypatch): mock_logger.warning.assert_called_once() assert "RTX streaming did not complete within" in mock_logger.warning.call_args[0][0] - def test_logs_info_on_non_trivial_completion(self): + def test_logs_info_on_non_trivial_completion(self, mock_omni_kit_app): """Logs completion info when streaming finishes after delay.""" - rtx_utils._streaming_is_busy = True mock_app = MagicMock() + mock_omni_kit_app.get_app.return_value = mock_app mock_logger = MagicMock() + call_count = 0 + + def _streaming_status(): + return call_count < 1 def _become_idle_after_delay(): + nonlocal call_count time.sleep(MOCK_UPDATE_SLEEP_S) - rtx_utils._streaming_is_busy = False + call_count += 1 mock_app.update.side_effect = _become_idle_after_delay with ( - patch("omni.kit.app.get_app", return_value=mock_app), + patch.object(rtx_utils, "_get_stage_streaming_busy", side_effect=_streaming_status), patch.object(rtx_utils, "logger", mock_logger), ): rtx_utils._wait_for_streaming_complete() mock_logger.info.assert_called_once() assert "RTX streaming completed in" in mock_logger.info.call_args[0][0] + + +# --------------------------------------------------------------------------- +# ensure_isaac_rtx_render_update +# --------------------------------------------------------------------------- + + +class TestEnsureIsaacRtxRenderUpdate: + """Tests for :func:`ensure_isaac_rtx_render_update`. + + Covers dedup logic, visualizer-skip behaviour, and the first-call-for-sim + guard that prevents annotator buffers from never being populated. + """ + + @pytest.fixture() + def mock_sim(self): + """A minimal mock of :class:`SimulationContext`.""" + sim = MagicMock() + sim._physics_step_count = 0 + sim._render_generation = 0 + sim.render_generation = 0 + sim.is_rendering = True + sim.visualizers = [] + return sim + + @pytest.fixture() + def pumping_visualizer(self): + """A visualizer that claims to pump ``app.update()``.""" + viz = MagicMock() + viz.pumps_app_update.return_value = True + return viz + + def test_first_call_with_visualizer_still_pumps(self, mock_sim, pumping_visualizer, mock_omni_kit_app): + """Regression: first call for a new sim must pump even with a visualizer. + + Without the fix (commit 2e8ace7), a visualizer returning + ``pumps_app_update() == True`` caused the function to skip + ``app.update()`` on the very first call. The visualizer had not + pumped yet (``sim.render()`` was never called), so annotator + buffers were never populated and cameras hung waiting for data. + """ + mock_sim.visualizers = [pumping_visualizer] + mock_app = MagicMock() + mock_omni_kit_app.get_app.return_value = mock_app + + with ( + patch.object( + rtx_utils.sim_utils.SimulationContext, + "instance", + return_value=mock_sim, + ), + patch.object(rtx_utils, "_get_stage_streaming_busy", return_value=False), + ): + rtx_utils.ensure_isaac_rtx_render_update() + + mock_app.update.assert_called_once() + + def test_second_call_with_visualizer_skips_pump(self, mock_sim, pumping_visualizer, mock_omni_kit_app): + """After the first call, a visualizer that pumps causes the skip.""" + mock_sim.visualizers = [pumping_visualizer] + mock_app = MagicMock() + mock_omni_kit_app.get_app.return_value = mock_app + + with ( + patch.object( + rtx_utils.sim_utils.SimulationContext, + "instance", + return_value=mock_sim, + ), + patch.object(rtx_utils, "_get_stage_streaming_busy", return_value=False), + ): + rtx_utils.ensure_isaac_rtx_render_update() + mock_app.update.assert_called_once() + mock_app.update.reset_mock() + + mock_sim._physics_step_count = 1 + rtx_utils.ensure_isaac_rtx_render_update() + + mock_app.update.assert_not_called() + + def test_no_sim_is_noop(self, mock_omni_kit_app): + """No-op when SimulationContext.instance() returns None.""" + mock_app = MagicMock() + mock_omni_kit_app.get_app.return_value = mock_app + + with patch.object( + rtx_utils.sim_utils.SimulationContext, + "instance", + return_value=None, + ): + rtx_utils.ensure_isaac_rtx_render_update() + + mock_app.update.assert_not_called() + + def test_dedup_same_step(self, mock_sim, mock_omni_kit_app): + """Second call in the same physics step is a no-op (dedup).""" + mock_app = MagicMock() + mock_omni_kit_app.get_app.return_value = mock_app + + with ( + patch.object( + rtx_utils.sim_utils.SimulationContext, + "instance", + return_value=mock_sim, + ), + patch.object(rtx_utils, "_get_stage_streaming_busy", return_value=False), + ): + rtx_utils.ensure_isaac_rtx_render_update() + mock_app.update.assert_called_once() + mock_app.update.reset_mock() + + rtx_utils.ensure_isaac_rtx_render_update() + + mock_app.update.assert_not_called() + + def test_not_rendering_skips(self, mock_sim, mock_omni_kit_app): + """No ``app.update()`` when rendering is disabled.""" + mock_sim.is_rendering = False + mock_app = MagicMock() + mock_omni_kit_app.get_app.return_value = mock_app + + with patch.object( + rtx_utils.sim_utils.SimulationContext, + "instance", + return_value=mock_sim, + ): + rtx_utils.ensure_isaac_rtx_render_update() + + mock_app.update.assert_not_called() diff --git a/source/isaaclab_physx/test/sensors/check_contact_sensor.py b/source/isaaclab_physx/test/sensors/check_contact_sensor.py index 035518fdf4d3..e840f00f1d34 100644 --- a/source/isaaclab_physx/test/sensors/check_contact_sensor.py +++ b/source/isaaclab_physx/test/sensors/check_contact_sensor.py @@ -36,9 +36,8 @@ import torch -from isaacsim.core.cloner import GridCloner - import isaaclab.sim as sim_utils +from isaaclab import cloner as lab_cloner from isaaclab.assets import Articulation from isaaclab.sensors.contact_sensor import ContactSensor, ContactSensorCfg from isaaclab.sim import SimulationCfg, SimulationContext @@ -82,16 +81,16 @@ def main(): # this is needed to visualize the scene when flatcache is enabled sim._settings.set_bool("/persistent/omnihydra/useSceneGraphInstancing", True) - # Create interface to clone the scene - cloner = GridCloner(spacing=2.0, stage=sim.stage) - cloner.define_base_env("/World/envs") + # Create environment clones using Lab's cloner utilities + num_envs = args_cli.num_robots + env_fmt = "/World/envs/env_{}" + env_ids = torch.arange(num_envs, dtype=torch.long, device=sim.device) + env_origins, _ = lab_cloner.grid_transforms(num_envs, spacing=2.0, device=sim.device) # Everything under the namespace "/World/envs/env_0" will be cloned sim.stage.DefinePrim("/World/envs/env_0", "Xform") # Clone the scene - num_envs = args_cli.num_robots - cloner.define_base_env("/World/envs") - envs_prim_paths = cloner.generate_paths("/World/envs/env", num_paths=num_envs) - _ = cloner.clone(source_prim_path="/World/envs/env_0", prim_paths=envs_prim_paths, replicate_physics=True) + envs_prim_paths = [f"/World/envs/env_{i}" for i in range(num_envs)] + lab_cloner.usd_replicate(sim.stage, [env_fmt.format(0)], [env_fmt], env_ids, positions=env_origins) # Design props design_scene() # Spawn things into the scene @@ -110,8 +109,8 @@ def main(): contact_sensor = ContactSensor(cfg=contact_sensor_cfg) # filter collisions within each environment instance physics_scene_path = sim.get_physics_context().prim_path - cloner.filter_collisions( - physics_scene_path, "/World/collisions", envs_prim_paths, global_paths=["/World/defaultGroundPlane"] + lab_cloner.filter_collisions( + sim.stage, physics_scene_path, "/World/collisions", envs_prim_paths, global_paths=["/World/defaultGroundPlane"] ) # Play the simulator diff --git a/source/isaaclab_physx/test/sensors/check_imu_sensor.py b/source/isaaclab_physx/test/sensors/check_pva_sensor.py similarity index 78% rename from source/isaaclab_physx/test/sensors/check_imu_sensor.py rename to source/isaaclab_physx/test/sensors/check_pva_sensor.py index 85f20881fe27..41476babf542 100644 --- a/source/isaaclab_physx/test/sensors/check_imu_sensor.py +++ b/source/isaaclab_physx/test/sensors/check_pva_sensor.py @@ -4,7 +4,7 @@ # SPDX-License-Identifier: BSD-3-Clause """ -Visual test script for the imu sensor from the Orbit framework. +Visual test script for the pva sensor from the Orbit framework. """ from __future__ import annotations @@ -16,7 +16,7 @@ from isaacsim import SimulationApp # add argparse arguments -parser = argparse.ArgumentParser(description="Imu Test Script") +parser = argparse.ArgumentParser(description="Pva Test Script") parser.add_argument("--headless", action="store_true", default=False, help="Force display off at all times.") parser.add_argument("--num_envs", type=int, default=128, help="Number of environments to clone.") parser.add_argument( @@ -40,13 +40,13 @@ import torch -from isaacsim.core.cloner import GridCloner -from isaacsim.core.utils.viewports import set_camera_view +from isaacsim.core.rendering_manager import ViewportManager import isaaclab.sim as sim_utils import isaaclab.terrains as terrain_gen +from isaaclab import cloner as lab_cloner from isaaclab.assets import RigidObject, RigidObjectCfg -from isaaclab.sensors.imu import Imu, ImuCfg +from isaaclab.sensors.pva import Pva, PvaCfg from isaaclab.sim import SimulationCfg, SimulationContext from isaaclab.terrains.config.rough import ROUGH_TERRAINS_CFG from isaaclab.terrains.terrain_importer import TerrainImporter @@ -72,13 +72,15 @@ def design_scene(sim: SimulationContext, num_envs: int = 2048) -> RigidObject: # obtain the current stage stage = sim_utils.get_current_stage() # Create interface to clone the scene - cloner = GridCloner(spacing=2.0, stage=stage) - cloner.define_base_env("/World/envs") - envs_prim_paths = cloner.generate_paths("/World/envs/env", num_paths=num_envs) + # Create environment clones using Lab's cloner utilities + env_fmt = "/World/envs/env_{}" + env_ids = torch.arange(num_envs, dtype=torch.long, device=sim.device) + env_origins, _ = lab_cloner.grid_transforms(num_envs, spacing=2.0, device=sim.device) + envs_prim_paths = [f"/World/envs/env_{i}" for i in range(num_envs)] # create source prim stage.DefinePrim(envs_prim_paths[0], "Xform") # clone the env xform - cloner.clone(source_prim_path="/World/envs/env_0", prim_paths=envs_prim_paths, replicate_physics=True) + lab_cloner.usd_replicate(stage, [env_fmt.format(0)], [env_fmt], env_ids, positions=env_origins) # Define the scene # -- Light cfg = sim_utils.DistantLightCfg(intensity=2000) @@ -105,7 +107,8 @@ def design_scene(sim: SimulationContext, num_envs: int = 2048) -> RigidObject: logging.info(f"Physics scene prim path: {physics_scene_prim_path}") break # filter collisions within each environment instance - cloner.filter_collisions( + lab_cloner.filter_collisions( + stage, physics_scene_prim_path, "/World/collisions", envs_prim_paths, @@ -119,33 +122,33 @@ def main(): # Load kit helper sim = SimulationContext(SimulationCfg()) # Set main camera - set_camera_view([0.0, 30.0, 25.0], [0.0, 0.0, -2.5]) + ViewportManager.set_camera_view("/OmniverseKit_Persp", eye=[0.0, 30.0, 25.0], target=[0.0, 0.0, -2.5]) # Parameters num_envs = args_cli.num_envs # Design the scene balls = design_scene(sim=sim, num_envs=num_envs) - # Create a ray-caster sensor - imu_cfg = ImuCfg( + # Create a pva sensor + pva_cfg = PvaCfg( prim_path="/World/envs/env_.*/ball", debug_vis=not args_cli.headless, ) # increase scale of the arrows for better visualization - imu_cfg.visualizer_cfg.markers["arrow"].scale = (1.0, 0.2, 0.2) - imu = Imu(cfg=imu_cfg) + pva_cfg.visualizer_cfg.markers["arrow"].scale = (1.0, 0.2, 0.2) + pva = Pva(cfg=pva_cfg) - # Play simulator and init the Imu + # Play simulator and init the Pva sim.reset() # Print the sensor information - print(imu) + print(pva) # Get the ball initial positions sim.step(render=not args_cli.headless) balls.update(sim.get_physics_dt()) - ball_initial_positions = balls.data.root_pos_w.clone() - ball_initial_orientations = balls.data.root_quat_w.clone() + ball_initial_positions = balls.data.root_pos_w.torch.clone() + ball_initial_orientations = balls.data.root_quat_w.torch.clone() # Create a counter for resetting the scene step_count = 0 @@ -164,14 +167,14 @@ def main(): balls.write_root_pose_to_sim(torch.cat([ball_initial_positions, ball_initial_orientations], dim=-1)) balls.reset() # reset the sensor - imu.reset() + pva.reset() # reset the counter step_count = 0 # Step simulation sim.step() - # Update the imu sensor - with Timer(f"Imu sensor update with {num_envs}"): - imu.update(dt=sim.get_physics_dt(), force_recompute=True) + # Update the pva sensor + with Timer(f"Pva sensor update with {num_envs}"): + pva.update(dt=sim.get_physics_dt(), force_recompute=True) # Update counter step_count += 1 diff --git a/source/isaaclab_physx/test/sensors/test_contact_sensor.py b/source/isaaclab_physx/test/sensors/test_contact_sensor.py index 0d7ea255006e..00772e6cb0d3 100644 --- a/source/isaaclab_physx/test/sensors/test_contact_sensor.py +++ b/source/isaaclab_physx/test/sensors/test_contact_sensor.py @@ -300,17 +300,17 @@ def test_cube_stack_contact_filtering(setup_simulation, device, num_envs): # Check values for cube 2 --> cube 1 is the only collision for cube 2 torch.testing.assert_close( - wp.to_torch(contact_sensor_2.data.force_matrix_w)[:, :, 0], - wp.to_torch(contact_sensor_2.data.net_forces_w), + contact_sensor_2.data.force_matrix_w.torch[:, :, 0], + contact_sensor_2.data.net_forces_w.torch, ) # Check that forces are opposite and equal torch.testing.assert_close( - wp.to_torch(contact_sensor_2.data.force_matrix_w)[:, :, 0], - -wp.to_torch(contact_sensor.data.force_matrix_w)[:, :, 0], + contact_sensor_2.data.force_matrix_w.torch[:, :, 0], + -contact_sensor.data.force_matrix_w.torch[:, :, 0], ) # Check values are non-zero (contacts are happening and are getting reported) - assert wp.to_torch(contact_sensor_2.data.net_forces_w).sum().item() > 0.0 - assert wp.to_torch(contact_sensor.data.net_forces_w).sum().item() > 0.0 + assert contact_sensor_2.data.net_forces_w.torch.sum().item() > 0.0 + assert contact_sensor.data.net_forces_w.torch.sum().item() > 0.0 def test_no_contact_reporting(setup_simulation): @@ -370,10 +370,10 @@ def test_no_contact_reporting(setup_simulation): _perform_sim_step(sim, scene, sim_dt) # check values are zero (contacts are happening but not reported) - assert wp.to_torch(contact_sensor.data.net_forces_w).sum().item() == 0.0 - assert wp.to_torch(contact_sensor.data.force_matrix_w).sum().item() == 0.0 - assert wp.to_torch(contact_sensor_2.data.net_forces_w).sum().item() == 0.0 - assert wp.to_torch(contact_sensor_2.data.force_matrix_w).sum().item() == 0.0 + assert contact_sensor.data.net_forces_w.torch.sum().item() == 0.0 + assert contact_sensor.data.force_matrix_w.torch.sum().item() == 0.0 + assert contact_sensor_2.data.net_forces_w.torch.sum().item() == 0.0 + assert contact_sensor_2.data.force_matrix_w.torch.sum().item() == 0.0 @pytest.mark.isaacsim_ci @@ -490,7 +490,7 @@ def test_friction_reporting(setup_simulation, grav_dir): # check that forces are being reported match expected friction forces expected_friction, _, _, _ = scene["contact_sensor"].contact_view.get_friction_data(dt=sim_dt) expected_friction_torch = wp.to_torch(expected_friction) - reported_friction = wp.to_torch(scene["contact_sensor"].data.friction_forces_w)[0, 0, :] + reported_friction = scene["contact_sensor"].data.friction_forces_w.torch[0, 0, :] torch.testing.assert_close(expected_friction_torch.sum(dim=0), reported_friction[0], atol=1e-6, rtol=1e-5) @@ -751,7 +751,7 @@ def _test_friction_forces(shape: RigidObject, sensor: ContactSensor, mode: Conta # check shape of the friction_forces_w tensor (wp.to_torch expands vec3f -> float32 trailing dim) num_bodies = sensor.num_bodies - friction_torch = wp.to_torch(sensor._data.friction_forces_w) + friction_torch = sensor._data.friction_forces_w.torch assert friction_torch.shape == (sensor.num_instances // num_bodies, num_bodies, 1, 3) # compare friction forces if mode == ContactTestMode.IN_CONTACT: @@ -789,11 +789,11 @@ def _test_contact_position(shape: RigidObject, sensor: ContactSensor, mode: Cont # check shape of the contact_pos_w tensor (wp.to_torch expands vec3f -> float32 trailing dim) num_bodies = sensor.num_bodies - contact_pos_torch = wp.to_torch(sensor._data.contact_pos_w) + contact_pos_torch = sensor._data.contact_pos_w.torch assert contact_pos_torch.shape == (sensor.num_instances // num_bodies, num_bodies, 1, 3) # check contact positions if mode == ContactTestMode.IN_CONTACT: - pos_w_torch = wp.to_torch(sensor._data.pos_w) + pos_w_torch = sensor._data.pos_w.torch contact_position = pos_w_torch + torch.tensor([[0.0, 0.0, -shape.cfg.spawn.radius]], device=pos_w_torch.device) assert torch.all( torch.abs(torch.linalg.norm(contact_pos_torch - contact_position.unsqueeze(1), ord=2, dim=-1)) < 1e-2 @@ -828,10 +828,10 @@ def _check_prim_contact_state_times( in_air = True if expected_contact_time > 0.0: in_contact = True - measured_contact_time = wp.to_torch(sensor.data.current_contact_time) - measured_air_time = wp.to_torch(sensor.data.current_air_time) - measured_last_contact_time = wp.to_torch(sensor.data.last_contact_time) - measured_last_air_time = wp.to_torch(sensor.data.last_air_time) + measured_contact_time = sensor.data.current_contact_time.torch + measured_air_time = sensor.data.current_air_time.torch + measured_last_contact_time = sensor.data.last_contact_time.torch + measured_last_air_time = sensor.data.last_air_time.torch # check current contact state assert pytest.approx(measured_contact_time.item(), 0.01) == expected_contact_time assert pytest.approx(measured_air_time.item(), 0.01) == expected_air_time @@ -839,8 +839,8 @@ def _check_prim_contact_state_times( assert pytest.approx(measured_last_contact_time.item(), 0.01) == expected_last_contact_time assert pytest.approx(measured_last_air_time.item(), 0.01) == expected_last_air_time # check current contact mode - assert wp.to_torch(sensor.compute_first_contact(dt=dt)).item() == in_contact - assert wp.to_torch(sensor.compute_first_air(dt=dt)).item() == in_air + assert sensor.compute_first_contact(dt=dt).torch.item() == in_contact + assert sensor.compute_first_air(dt=dt).torch.item() == in_air def _perform_sim_step(sim, scene, sim_dt): diff --git a/source/isaaclab_physx/test/sensors/test_frame_transformer.py b/source/isaaclab_physx/test/sensors/test_frame_transformer.py index 96c9eabec2c2..631e9ba118dd 100644 --- a/source/isaaclab_physx/test/sensors/test_frame_transformer.py +++ b/source/isaaclab_physx/test/sensors/test_frame_transformer.py @@ -17,7 +17,6 @@ import pytest import scipy.spatial.transform as tf import torch -import warp as wp import isaaclab.sim as sim_utils import isaaclab.utils.math as math_utils @@ -146,7 +145,7 @@ def test_frame_transformer_feet_wrt_base(sim): feet_indices = [feet_indices[i] for i in reordering_indices] # default joint targets - default_actions = wp.to_torch(scene.articulations["robot"].data.default_joint_pos).clone() + default_actions = scene.articulations["robot"].data.default_joint_pos.torch.clone() # Define simulation stepping sim_dt = sim.get_physics_dt() # Simulate physics @@ -154,10 +153,10 @@ def test_frame_transformer_feet_wrt_base(sim): # # reset if count % 25 == 0: # reset root state - root_state = wp.to_torch(scene.articulations["robot"].data.default_root_state).clone() + root_state = scene.articulations["robot"].data.default_root_state.torch.clone() root_state[:, :3] += scene.env_origins - joint_pos = scene.articulations["robot"].data.default_joint_pos - joint_vel = scene.articulations["robot"].data.default_joint_vel + joint_pos = scene.articulations["robot"].data.default_joint_pos.torch + joint_vel = scene.articulations["robot"].data.default_joint_vel.torch # -- set root state # -- robot scene.articulations["robot"].write_root_pose_to_sim(root_state[:, :7]) @@ -178,14 +177,14 @@ def test_frame_transformer_feet_wrt_base(sim): # check absolute frame transforms in world frame # -- ground-truth - root_pose_w = wp.to_torch(scene.articulations["robot"].data.root_pose_w) - feet_pos_w_gt = wp.to_torch(scene.articulations["robot"].data.body_pos_w)[:, feet_indices] - feet_quat_w_gt = wp.to_torch(scene.articulations["robot"].data.body_quat_w)[:, feet_indices] + root_pose_w = scene.articulations["robot"].data.root_pose_w.torch + feet_pos_w_gt = scene.articulations["robot"].data.body_pos_w.torch[:, feet_indices] + feet_quat_w_gt = scene.articulations["robot"].data.body_quat_w.torch[:, feet_indices] # -- frame transformer - source_pos_w_tf = wp.to_torch(scene.sensors["frame_transformer"].data.source_pos_w) - source_quat_w_tf = wp.to_torch(scene.sensors["frame_transformer"].data.source_quat_w) - feet_pos_w_tf = wp.to_torch(scene.sensors["frame_transformer"].data.target_pos_w) - feet_quat_w_tf = wp.to_torch(scene.sensors["frame_transformer"].data.target_quat_w) + source_pos_w_tf = scene.sensors["frame_transformer"].data.source_pos_w.torch + source_quat_w_tf = scene.sensors["frame_transformer"].data.source_quat_w.torch + feet_pos_w_tf = scene.sensors["frame_transformer"].data.target_pos_w.torch + feet_quat_w_tf = scene.sensors["frame_transformer"].data.target_quat_w.torch # check if they are same torch.testing.assert_close(root_pose_w[:, :3], source_pos_w_tf) @@ -194,8 +193,8 @@ def test_frame_transformer_feet_wrt_base(sim): torch.testing.assert_close(feet_quat_w_gt, feet_quat_w_tf) # check if relative transforms are same - feet_pos_source_tf = wp.to_torch(scene.sensors["frame_transformer"].data.target_pos_source) - feet_quat_source_tf = wp.to_torch(scene.sensors["frame_transformer"].data.target_quat_source) + feet_pos_source_tf = scene.sensors["frame_transformer"].data.target_pos_source.torch + feet_quat_source_tf = scene.sensors["frame_transformer"].data.target_quat_source.torch for index in range(len(feet_indices)): # ground-truth foot_pos_b, foot_quat_b = math_utils.subtract_frame_transforms( @@ -244,7 +243,7 @@ def test_frame_transformer_feet_wrt_thigh(sim): assert scene.sensors["frame_transformer"].data.target_frame_names == user_feet_names # default joint targets - default_actions = wp.to_torch(scene.articulations["robot"].data.default_joint_pos).clone() + default_actions = scene.articulations["robot"].data.default_joint_pos.torch.clone() # Define simulation stepping sim_dt = sim.get_physics_dt() # Simulate physics @@ -252,10 +251,10 @@ def test_frame_transformer_feet_wrt_thigh(sim): # # reset if count % 25 == 0: # reset root state - root_state = wp.to_torch(scene.articulations["robot"].data.default_root_state).clone() + root_state = scene.articulations["robot"].data.default_root_state.torch.clone() root_state[:, :3] += scene.env_origins - joint_pos = scene.articulations["robot"].data.default_joint_pos - joint_vel = scene.articulations["robot"].data.default_joint_vel + joint_pos = scene.articulations["robot"].data.default_joint_pos.torch + joint_vel = scene.articulations["robot"].data.default_joint_vel.torch # -- set root state # -- robot scene.articulations["robot"].write_root_pose_to_sim(root_state[:, :7]) @@ -276,14 +275,14 @@ def test_frame_transformer_feet_wrt_thigh(sim): # check absolute frame transforms in world frame # -- ground-truth - source_pose_w_gt = wp.to_torch(scene.articulations["robot"].data.body_state_w)[:, source_frame_index, :7] - feet_pos_w_gt = wp.to_torch(scene.articulations["robot"].data.body_pos_w)[:, feet_indices] - feet_quat_w_gt = wp.to_torch(scene.articulations["robot"].data.body_quat_w)[:, feet_indices] + source_pose_w_gt = scene.articulations["robot"].data.body_state_w.torch[:, source_frame_index, :7] + feet_pos_w_gt = scene.articulations["robot"].data.body_pos_w.torch[:, feet_indices] + feet_quat_w_gt = scene.articulations["robot"].data.body_quat_w.torch[:, feet_indices] # -- frame transformer - source_pos_w_tf = wp.to_torch(scene.sensors["frame_transformer"].data.source_pos_w) - source_quat_w_tf = wp.to_torch(scene.sensors["frame_transformer"].data.source_quat_w) - feet_pos_w_tf = wp.to_torch(scene.sensors["frame_transformer"].data.target_pos_w) - feet_quat_w_tf = wp.to_torch(scene.sensors["frame_transformer"].data.target_quat_w) + source_pos_w_tf = scene.sensors["frame_transformer"].data.source_pos_w.torch + source_quat_w_tf = scene.sensors["frame_transformer"].data.source_quat_w.torch + feet_pos_w_tf = scene.sensors["frame_transformer"].data.target_pos_w.torch + feet_quat_w_tf = scene.sensors["frame_transformer"].data.target_quat_w.torch # check if they are same torch.testing.assert_close(source_pose_w_gt[:, :3], source_pos_w_tf) torch.testing.assert_close(source_pose_w_gt[:, 3:], source_quat_w_tf) @@ -291,8 +290,8 @@ def test_frame_transformer_feet_wrt_thigh(sim): torch.testing.assert_close(feet_quat_w_gt, feet_quat_w_tf) # check if relative transforms are same - feet_pos_source_tf = wp.to_torch(scene.sensors["frame_transformer"].data.target_pos_source) - feet_quat_source_tf = wp.to_torch(scene.sensors["frame_transformer"].data.target_quat_source) + feet_pos_source_tf = scene.sensors["frame_transformer"].data.target_pos_source.torch + feet_quat_source_tf = scene.sensors["frame_transformer"].data.target_quat_source.torch for index in range(len(feet_indices)): # ground-truth foot_pos_b, foot_quat_b = math_utils.subtract_frame_transforms( @@ -322,7 +321,7 @@ def test_frame_transformer_robot_body_to_external_cube(sim): sim.reset() # default joint targets - default_actions = wp.to_torch(scene.articulations["robot"].data.default_joint_pos).clone() + default_actions = scene.articulations["robot"].data.default_joint_pos.torch.clone() # Define simulation stepping sim_dt = sim.get_physics_dt() # Simulate physics @@ -330,10 +329,10 @@ def test_frame_transformer_robot_body_to_external_cube(sim): # # reset if count % 25 == 0: # reset root state - root_state = wp.to_torch(scene.articulations["robot"].data.default_root_state).clone() + root_state = scene.articulations["robot"].data.default_root_state.torch.clone() root_state[:, :3] += scene.env_origins - joint_pos = scene.articulations["robot"].data.default_joint_pos - joint_vel = scene.articulations["robot"].data.default_joint_vel + joint_pos = scene.articulations["robot"].data.default_joint_pos.torch + joint_vel = scene.articulations["robot"].data.default_joint_vel.torch # -- set root state # -- robot scene.articulations["robot"].write_root_pose_to_sim(root_state[:, :7]) @@ -354,14 +353,14 @@ def test_frame_transformer_robot_body_to_external_cube(sim): # check absolute frame transforms in world frame # -- ground-truth - root_pose_w = wp.to_torch(scene.articulations["robot"].data.root_pose_w) - cube_pos_w_gt = wp.to_torch(scene.rigid_objects["cube"].data.root_pos_w) - cube_quat_w_gt = wp.to_torch(scene.rigid_objects["cube"].data.root_quat_w) + root_pose_w = scene.articulations["robot"].data.root_pose_w.torch + cube_pos_w_gt = scene.rigid_objects["cube"].data.root_pos_w.torch + cube_quat_w_gt = scene.rigid_objects["cube"].data.root_quat_w.torch # -- frame transformer - source_pos_w_tf = wp.to_torch(scene.sensors["frame_transformer"].data.source_pos_w) - source_quat_w_tf = wp.to_torch(scene.sensors["frame_transformer"].data.source_quat_w) - cube_pos_w_tf = wp.to_torch(scene.sensors["frame_transformer"].data.target_pos_w).squeeze() - cube_quat_w_tf = wp.to_torch(scene.sensors["frame_transformer"].data.target_quat_w).squeeze() + source_pos_w_tf = scene.sensors["frame_transformer"].data.source_pos_w.torch + source_quat_w_tf = scene.sensors["frame_transformer"].data.source_quat_w.torch + cube_pos_w_tf = scene.sensors["frame_transformer"].data.target_pos_w.torch.squeeze() + cube_quat_w_tf = scene.sensors["frame_transformer"].data.target_quat_w.torch.squeeze() # check if they are same torch.testing.assert_close(root_pose_w[:, :3], source_pos_w_tf) @@ -370,8 +369,8 @@ def test_frame_transformer_robot_body_to_external_cube(sim): torch.testing.assert_close(cube_quat_w_gt, cube_quat_w_tf) # check if relative transforms are same - cube_pos_source_tf = wp.to_torch(scene.sensors["frame_transformer"].data.target_pos_source) - cube_quat_source_tf = wp.to_torch(scene.sensors["frame_transformer"].data.target_quat_source) + cube_pos_source_tf = scene.sensors["frame_transformer"].data.target_pos_source.torch + cube_quat_source_tf = scene.sensors["frame_transformer"].data.target_quat_source.torch # ground-truth cube_pos_b, cube_quat_b = math_utils.subtract_frame_transforms( root_pose_w[:, :3], root_pose_w[:, 3:], cube_pos_w_tf, cube_quat_w_tf @@ -426,7 +425,7 @@ def test_frame_transformer_offset_frames(sim): # # reset if count % 25 == 0: # reset root state - root_state = wp.to_torch(scene["cube"].data.default_root_state).clone() + root_state = scene["cube"].data.default_root_state.torch.clone() root_state[:, :3] += scene.env_origins # -- set root state # -- cube @@ -444,13 +443,13 @@ def test_frame_transformer_offset_frames(sim): # check absolute frame transforms in world frame # -- ground-truth - cube_pos_w_gt = wp.to_torch(scene["cube"].data.root_pos_w) - cube_quat_w_gt = wp.to_torch(scene["cube"].data.root_quat_w) + cube_pos_w_gt = scene["cube"].data.root_pos_w.torch + cube_quat_w_gt = scene["cube"].data.root_quat_w.torch # -- frame transformer - source_pos_w_tf = wp.to_torch(scene.sensors["frame_transformer"].data.source_pos_w) - source_quat_w_tf = wp.to_torch(scene.sensors["frame_transformer"].data.source_quat_w) - target_pos_w_tf = wp.to_torch(scene.sensors["frame_transformer"].data.target_pos_w).squeeze() - target_quat_w_tf = wp.to_torch(scene.sensors["frame_transformer"].data.target_quat_w).squeeze() + source_pos_w_tf = scene.sensors["frame_transformer"].data.source_pos_w.torch + source_quat_w_tf = scene.sensors["frame_transformer"].data.source_quat_w.torch + target_pos_w_tf = scene.sensors["frame_transformer"].data.target_pos_w.torch.squeeze() + target_quat_w_tf = scene.sensors["frame_transformer"].data.target_quat_w.torch.squeeze() target_frame_names = scene.sensors["frame_transformer"].data.target_frame_names cube_center_idx = target_frame_names.index("CUBE_CENTER") @@ -506,7 +505,7 @@ def test_frame_transformer_all_bodies(sim): reordering_indices = [target_frame_names.index(name) for name in articulation_body_names] # default joint targets - default_actions = wp.to_torch(scene.articulations["robot"].data.default_joint_pos).clone() + default_actions = scene.articulations["robot"].data.default_joint_pos.torch.clone() # Define simulation stepping sim_dt = sim.get_physics_dt() # Simulate physics @@ -514,10 +513,10 @@ def test_frame_transformer_all_bodies(sim): # # reset if count % 25 == 0: # reset root state - root_state = wp.to_torch(scene.articulations["robot"].data.default_root_state).clone() + root_state = scene.articulations["robot"].data.default_root_state.torch.clone() root_state[:, :3] += scene.env_origins - joint_pos = scene.articulations["robot"].data.default_joint_pos - joint_vel = scene.articulations["robot"].data.default_joint_vel + joint_pos = scene.articulations["robot"].data.default_joint_pos.torch + joint_vel = scene.articulations["robot"].data.default_joint_vel.torch # -- set root state # -- robot scene.articulations["robot"].write_root_pose_to_sim(root_state[:, :7]) @@ -538,15 +537,15 @@ def test_frame_transformer_all_bodies(sim): # check absolute frame transforms in world frame # -- ground-truth - root_pose_w = wp.to_torch(scene.articulations["robot"].data.root_pose_w) - bodies_pos_w_gt = wp.to_torch(scene.articulations["robot"].data.body_pos_w) - bodies_quat_w_gt = wp.to_torch(scene.articulations["robot"].data.body_quat_w) + root_pose_w = scene.articulations["robot"].data.root_pose_w.torch + bodies_pos_w_gt = scene.articulations["robot"].data.body_pos_w.torch + bodies_quat_w_gt = scene.articulations["robot"].data.body_quat_w.torch # -- frame transformer - source_pos_w_tf = wp.to_torch(scene.sensors["frame_transformer"].data.source_pos_w) - source_quat_w_tf = wp.to_torch(scene.sensors["frame_transformer"].data.source_quat_w) - bodies_pos_w_tf = wp.to_torch(scene.sensors["frame_transformer"].data.target_pos_w) - bodies_quat_w_tf = wp.to_torch(scene.sensors["frame_transformer"].data.target_quat_w) + source_pos_w_tf = scene.sensors["frame_transformer"].data.source_pos_w.torch + source_quat_w_tf = scene.sensors["frame_transformer"].data.source_quat_w.torch + bodies_pos_w_tf = scene.sensors["frame_transformer"].data.target_pos_w.torch + bodies_quat_w_tf = scene.sensors["frame_transformer"].data.target_quat_w.torch # check if they are same torch.testing.assert_close(root_pose_w[:, :3], source_pos_w_tf) @@ -554,8 +553,8 @@ def test_frame_transformer_all_bodies(sim): torch.testing.assert_close(bodies_pos_w_gt, bodies_pos_w_tf[:, reordering_indices]) torch.testing.assert_close(bodies_quat_w_gt, bodies_quat_w_tf[:, reordering_indices]) - bodies_pos_source_tf = wp.to_torch(scene.sensors["frame_transformer"].data.target_pos_source) - bodies_quat_source_tf = wp.to_torch(scene.sensors["frame_transformer"].data.target_quat_source) + bodies_pos_source_tf = scene.sensors["frame_transformer"].data.target_pos_source.torch + bodies_quat_source_tf = scene.sensors["frame_transformer"].data.target_quat_source.torch # Go through each body and check if relative transforms are same for index in range(len(articulation_body_names)): @@ -709,22 +708,22 @@ class MultiRobotSceneCfg(InteractiveSceneCfg): # Reset periodically if count % 10 == 0: # Reset robot - root_state = wp.to_torch(scene.articulations["robot"].data.default_root_state).clone() + root_state = scene.articulations["robot"].data.default_root_state.torch.clone() root_state[:, :3] += scene.env_origins scene.articulations["robot"].write_root_pose_to_sim(root_state[:, :7]) scene.articulations["robot"].write_root_velocity_to_sim(root_state[:, 7:]) scene.articulations["robot"].write_joint_state_to_sim( - scene.articulations["robot"].data.default_joint_pos, - scene.articulations["robot"].data.default_joint_vel, + scene.articulations["robot"].data.default_joint_pos.torch, + scene.articulations["robot"].data.default_joint_vel.torch, ) # Reset robot_1 - root_state_1 = wp.to_torch(scene.articulations["robot_1"].data.default_root_state).clone() + root_state_1 = scene.articulations["robot_1"].data.default_root_state.torch.clone() root_state_1[:, :3] += scene.env_origins scene.articulations["robot_1"].write_root_pose_to_sim(root_state_1[:, :7]) scene.articulations["robot_1"].write_root_velocity_to_sim(root_state_1[:, 7:]) scene.articulations["robot_1"].write_joint_state_to_sim( - scene.articulations["robot_1"].data.default_joint_pos, - scene.articulations["robot_1"].data.default_joint_vel, + scene.articulations["robot_1"].data.default_joint_pos.torch, + scene.articulations["robot_1"].data.default_joint_vel.torch, ) scene.reset() @@ -737,21 +736,21 @@ class MultiRobotSceneCfg(InteractiveSceneCfg): # Get frame transformer data frame_transformer_data = scene.sensors["frame_transformer"].data - source_pos_w = wp.to_torch(frame_transformer_data.source_pos_w) - source_quat_w = wp.to_torch(frame_transformer_data.source_quat_w) - target_pos_w = wp.to_torch(frame_transformer_data.target_pos_w) + source_pos_w = frame_transformer_data.source_pos_w.torch + source_quat_w = frame_transformer_data.source_quat_w.torch + target_pos_w = frame_transformer_data.target_pos_w.torch # Get ground truth positions and orientations (after scene.update() so they're current) - robot_lf_pos_w = wp.to_torch(scene.articulations["robot"].data.body_pos_w)[:, robot_lf_shank_body_idx] - robot_1_lf_pos_w = wp.to_torch(scene.articulations["robot_1"].data.body_pos_w)[:, robot_1_lf_shank_body_idx] - robot_rf_pos_w = wp.to_torch(scene.articulations["robot"].data.body_pos_w)[:, robot_rf_shank_body_idx] - robot_1_rf_pos_w = wp.to_torch(scene.articulations["robot_1"].data.body_pos_w)[:, robot_1_rf_shank_body_idx] + robot_lf_pos_w = scene.articulations["robot"].data.body_pos_w.torch[:, robot_lf_shank_body_idx] + robot_1_lf_pos_w = scene.articulations["robot_1"].data.body_pos_w.torch[:, robot_1_lf_shank_body_idx] + robot_rf_pos_w = scene.articulations["robot"].data.body_pos_w.torch[:, robot_rf_shank_body_idx] + robot_1_rf_pos_w = scene.articulations["robot_1"].data.body_pos_w.torch[:, robot_1_rf_shank_body_idx] # Get expected source frame positions and orientations (after scene.update() so they're current) - expected_source_base_pos_w = wp.to_torch(scene.articulations[expected_source_robot].data.body_pos_w)[ + expected_source_base_pos_w = scene.articulations[expected_source_robot].data.body_pos_w.torch[ :, expected_source_base_body_idx ] - expected_source_base_quat_w = wp.to_torch(scene.articulations[expected_source_robot].data.body_quat_w)[ + expected_source_base_quat_w = scene.articulations[expected_source_robot].data.body_quat_w.torch[ :, expected_source_base_body_idx ] diff --git a/source/isaaclab_physx/test/sensors/test_imu.py b/source/isaaclab_physx/test/sensors/test_imu.py index 69d5d0ebf828..641c72a8d4ba 100644 --- a/source/isaaclab_physx/test/sensors/test_imu.py +++ b/source/isaaclab_physx/test/sensors/test_imu.py @@ -24,7 +24,6 @@ import isaaclab.utils.math as math_utils from isaaclab.actuators import ImplicitActuatorCfg from isaaclab.assets import ArticulationCfg, RigidObjectCfg -from isaaclab.markers.config import GREEN_ARROW_X_MARKER_CFG, RED_ARROW_X_MARKER_CFG from isaaclab.scene import InteractiveScene, InteractiveSceneCfg from isaaclab.sensors.imu import Imu, ImuCfg from isaaclab.terrains import TerrainImporterCfg @@ -131,25 +130,15 @@ class MySceneCfg(InteractiveSceneCfg): ) # sensors - imu (filled inside unit test) - imu_ball: ImuCfg = ImuCfg( - prim_path="{ENV_REGEX_NS}/ball", - gravity_bias=(0.0, 0.0, 0.0), - ) - imu_cube: ImuCfg = ImuCfg( - prim_path="{ENV_REGEX_NS}/cube", - gravity_bias=(0.0, 0.0, 0.0), - ) - imu_robot_imu_link: ImuCfg = ImuCfg( - prim_path="{ENV_REGEX_NS}/robot/imu_link", - gravity_bias=(0.0, 0.0, 0.0), - ) + imu_ball: ImuCfg = ImuCfg(prim_path="{ENV_REGEX_NS}/ball") + imu_cube: ImuCfg = ImuCfg(prim_path="{ENV_REGEX_NS}/cube") + imu_robot_imu_link: ImuCfg = ImuCfg(prim_path="{ENV_REGEX_NS}/robot/imu_link") imu_robot_base: ImuCfg = ImuCfg( prim_path="{ENV_REGEX_NS}/robot/base", offset=ImuCfg.OffsetCfg( pos=POS_OFFSET, rot=ROT_OFFSET, ), - gravity_bias=(0.0, 0.0, 0.0), ) imu_robot_norb: ImuCfg = ImuCfg( prim_path="{ENV_REGEX_NS}/robot/LF_HIP/LF_hip_fixed", @@ -157,7 +146,6 @@ class MySceneCfg(InteractiveSceneCfg): pos=POS_OFFSET, rot=ROT_OFFSET, ), - gravity_bias=(0.0, 0.0, 0.0), ) # The new URDF converter (urdf-usd-converter) places links under Geometry/ in a nested # kinematic tree. With merge_fixed_joints=True the hierarchy for simple_2_link.urdf is: @@ -165,9 +153,6 @@ class MySceneCfg(InteractiveSceneCfg): # A non-physics imu_link Xform is recreated in the test fixture (see setup_sim). imu_indirect_pendulum_link: ImuCfg = ImuCfg( prim_path="{ENV_REGEX_NS}/pendulum2/Geometry/world/link_1/imu_link", - debug_vis=not app_launcher._headless, - visualizer_cfg=RED_ARROW_X_MARKER_CFG.replace(prim_path="/Visuals/Acceleration/imu_link"), - gravity_bias=(0.0, 0.0, 9.81), ) imu_indirect_pendulum_base: ImuCfg = ImuCfg( prim_path="{ENV_REGEX_NS}/pendulum2/Geometry/world/link_1", @@ -175,15 +160,9 @@ class MySceneCfg(InteractiveSceneCfg): pos=PEND_POS_OFFSET, rot=PEND_ROT_OFFSET, ), - debug_vis=not app_launcher._headless, - visualizer_cfg=GREEN_ARROW_X_MARKER_CFG.replace(prim_path="/Visuals/Acceleration/base"), - gravity_bias=(0.0, 0.0, 9.81), ) imu_pendulum_imu_link: ImuCfg = ImuCfg( prim_path="{ENV_REGEX_NS}/pendulum/Geometry/world/link_1/imu_link", - debug_vis=not app_launcher._headless, - visualizer_cfg=RED_ARROW_X_MARKER_CFG.replace(prim_path="/Visuals/Acceleration/imu_link"), - gravity_bias=(0.0, 0.0, 9.81), ) imu_pendulum_base: ImuCfg = ImuCfg( prim_path="{ENV_REGEX_NS}/pendulum/Geometry/world/link_1", @@ -191,9 +170,6 @@ class MySceneCfg(InteractiveSceneCfg): pos=PEND_POS_OFFSET, rot=PEND_ROT_OFFSET, ), - debug_vis=not app_launcher._headless, - visualizer_cfg=GREEN_ARROW_X_MARKER_CFG.replace(prim_path="/Visuals/Acceleration/base"), - gravity_bias=(0.0, 0.0, 9.81), ) def __post_init__(self): @@ -225,7 +201,7 @@ def setup_sim(): # fixed-joint child link imu_link is removed from the URDF before USD # conversion. Recreate it as a plain Xform (no RigidBodyAPI) under each # pendulum's link_1 for every environment. The IMU sensor must then - # resolve the rigid-body ancestor (link_1) and cache the fixed offset — + # resolve the rigid-body ancestor (link_1) and cache the fixed offset -- # exercising the "indirect attachment" code path. for i in range(scene_cfg.num_envs): for art_name in ("pendulum", "pendulum2"): @@ -241,14 +217,12 @@ def setup_sim(): def test_constant_velocity(setup_sim): """Test the Imu sensor with a constant velocity. - Expected behavior is that the linear and angular are approx the same at every time step as in each step we set + Expected behavior is that the linear acceleration is approx the same at every time step as in each step we set the same velocity and therefore reset the physx buffers. """ sim, scene = setup_sim prev_lin_acc_ball = torch.zeros((scene.num_envs, 3), dtype=torch.float32, device=scene.device) - prev_ang_acc_ball = torch.zeros((scene.num_envs, 3), dtype=torch.float32, device=scene.device) prev_lin_acc_cube = torch.zeros((scene.num_envs, 3), dtype=torch.float32, device=scene.device) - prev_ang_acc_cube = torch.zeros((scene.num_envs, 3), dtype=torch.float32, device=scene.device) for idx in range(200): # set velocity @@ -273,57 +247,22 @@ def test_constant_velocity(setup_sim): if idx > 1: # check the imu accelerations torch.testing.assert_close( - wp.to_torch(scene.sensors["imu_ball"].data.lin_acc_b), + scene.sensors["imu_ball"].data.lin_acc_b.torch, prev_lin_acc_ball, rtol=1e-3, atol=1e-3, ) - torch.testing.assert_close( - wp.to_torch(scene.sensors["imu_ball"].data.ang_acc_b), - prev_ang_acc_ball, - rtol=1e-3, - atol=1e-3, - ) torch.testing.assert_close( - wp.to_torch(scene.sensors["imu_cube"].data.lin_acc_b), + scene.sensors["imu_cube"].data.lin_acc_b.torch, prev_lin_acc_cube, rtol=1e-3, atol=1e-3, ) - torch.testing.assert_close( - wp.to_torch(scene.sensors["imu_cube"].data.ang_acc_b), - prev_ang_acc_cube, - rtol=1e-3, - atol=1e-3, - ) - - # check the imu velocities - # NOTE: the expected lin_vel_b is the same as the set velocity, as write_root_velocity_to_sim is - # setting v_0 (initial velocity) and then a calculation step of v_i = v_0 + a*dt. Consequently, - # the data.lin_vel_b is returning approx. v_i. - torch.testing.assert_close( - wp.to_torch(scene.sensors["imu_ball"].data.lin_vel_b), - torch.tensor([[1.0, 0.0, -scene.physics_dt * 9.81]], dtype=torch.float32, device=scene.device).repeat( - scene.num_envs, 1 - ), - rtol=1e-4, - atol=1e-4, - ) - torch.testing.assert_close( - wp.to_torch(scene.sensors["imu_cube"].data.lin_vel_b), - torch.tensor([[1.0, 0.0, -scene.physics_dt * 9.81]], dtype=torch.float32, device=scene.device).repeat( - scene.num_envs, 1 - ), - rtol=1e-4, - atol=1e-4, - ) # update previous values - prev_lin_acc_ball = wp.to_torch(scene.sensors["imu_ball"].data.lin_acc_b).clone() - prev_ang_acc_ball = wp.to_torch(scene.sensors["imu_ball"].data.ang_acc_b).clone() - prev_lin_acc_cube = wp.to_torch(scene.sensors["imu_cube"].data.lin_acc_b).clone() - prev_ang_acc_cube = wp.to_torch(scene.sensors["imu_cube"].data.ang_acc_b).clone() + prev_lin_acc_ball = scene.sensors["imu_ball"].data.lin_acc_b.torch.clone() + prev_lin_acc_cube = scene.sensors["imu_cube"].data.lin_acc_b.torch.clone() @pytest.mark.isaacsim_ci @@ -349,13 +288,14 @@ def test_constant_acceleration(setup_sim): if idx < 1: continue - # check the imu data + # check the imu linear acceleration data (includes gravity since IMU always measures it) torch.testing.assert_close( - wp.to_torch(scene.sensors["imu_ball"].data.lin_acc_b), + scene.sensors["imu_ball"].data.lin_acc_b.torch, math_utils.quat_apply_inverse( - wp.to_torch(scene.rigid_objects["balls"].data.root_quat_w), + scene.rigid_objects["balls"].data.root_quat_w.torch, torch.tensor([[0.1, 0.0, 0.0]], dtype=torch.float32, device=scene.device).repeat(scene.num_envs, 1) - / sim.get_physics_dt(), + / sim.get_physics_dt() + + torch.tensor([[0.0, 0.0, 9.81]], dtype=torch.float32, device=scene.device).repeat(scene.num_envs, 1), ), rtol=1e-4, atol=1e-4, @@ -363,8 +303,8 @@ def test_constant_acceleration(setup_sim): # check the angular velocity torch.testing.assert_close( - wp.to_torch(scene.sensors["imu_ball"].data.ang_vel_b), - wp.to_torch(scene.rigid_objects["balls"].data.root_ang_vel_b), + scene.sensors["imu_ball"].data.ang_vel_b.torch, + scene.rigid_objects["balls"].data.root_ang_vel_b.torch, rtol=1e-4, atol=1e-4, ) @@ -374,10 +314,7 @@ def test_constant_acceleration(setup_sim): def test_single_dof_pendulum(setup_sim): """Test imu against analytical pendulum problem.""" sim, scene = setup_sim - # pendulum length - pend_length = PEND_POS_OFFSET[0] - # should achieve same results between the two imu sensors on the robot for idx in range(500): # write data to sim scene.write_data_to_sim() @@ -386,122 +323,26 @@ def test_single_dof_pendulum(setup_sim): # read data from sim scene.update(sim.get_physics_dt()) - # get pendulum joint state - joint_pos = wp.to_torch(scene.articulations["pendulum"].data.joint_pos) - joint_vel = wp.to_torch(scene.articulations["pendulum"].data.joint_vel) - joint_acc = wp.to_torch(scene.articulations["pendulum"].data.joint_acc) - - # IMU and base data + # IMU data imu_data = scene.sensors["imu_pendulum_imu_link"].data base_data = scene.sensors["imu_pendulum_base"].data - # extract imu_link imu_sensor dynamics - lin_vel_w_imu_link = math_utils.quat_apply(wp.to_torch(imu_data.quat_w), wp.to_torch(imu_data.lin_vel_b)) - lin_acc_w_imu_link = math_utils.quat_apply(wp.to_torch(imu_data.quat_w), wp.to_torch(imu_data.lin_acc_b)) - - # calculate the joint dynamics from the imu_sensor (y axis of imu_link is parallel to joint axis of pendulum) - joint_vel_imu = math_utils.quat_apply(wp.to_torch(imu_data.quat_w), wp.to_torch(imu_data.ang_vel_b))[ - ..., 1 - ].unsqueeze(-1) - joint_acc_imu = math_utils.quat_apply(wp.to_torch(imu_data.quat_w), wp.to_torch(imu_data.ang_acc_b))[ - ..., 1 - ].unsqueeze(-1) - - # calculate analytical solution - vx = -joint_vel * pend_length * torch.sin(joint_pos) - vy = torch.zeros(2, 1, device=scene.device) - vz = -joint_vel * pend_length * torch.cos(joint_pos) - gt_linear_vel_w = torch.cat([vx, vy, vz], dim=-1) - - ax = -joint_acc * pend_length * torch.sin(joint_pos) - joint_vel**2 * pend_length * torch.cos(joint_pos) - ay = torch.zeros(2, 1, device=scene.device) - az = -joint_acc * pend_length * torch.cos(joint_pos) + joint_vel**2 * pend_length * torch.sin(joint_pos) + 9.81 - gt_linear_acc_w = torch.cat([ax, ay, az], dim=-1) - # skip first step where initial velocity is zero if idx < 2: continue - # compare imu projected gravity - gravity_dir_w = torch.tensor((0.0, 0.0, -1.0), device=scene.device).repeat(2, 1) - gravity_dir_b = math_utils.quat_apply_inverse(wp.to_torch(imu_data.quat_w), gravity_dir_w) - torch.testing.assert_close( - wp.to_torch(imu_data.projected_gravity_b), - gravity_dir_b, - ) - - # compare imu angular velocity with joint velocity - torch.testing.assert_close( - joint_vel, - joint_vel_imu, - rtol=1e-1, - atol=1e-3, - ) - # compare imu angular acceleration with joint acceleration - torch.testing.assert_close( - joint_acc, - joint_acc_imu, - rtol=1e-1, - atol=1e-3, - ) - # compare imu linear velocity with simple pendulum calculation - torch.testing.assert_close( - gt_linear_vel_w, - lin_vel_w_imu_link, - rtol=1e-1, - atol=1e-3, - ) - # compare imu linear acceleration with simple pendulum calculation - torch.testing.assert_close( - gt_linear_acc_w, - lin_acc_w_imu_link, - rtol=1e-1, - atol=1e0, - ) - - # check the position between offset and imu definition + # check the angular velocities of the imus between offset and direct definition torch.testing.assert_close( - wp.to_torch(base_data.pos_w), - wp.to_torch(imu_data.pos_w), - rtol=1e-5, - atol=1e-5, - ) - - # check the orientation between offset and imu definition - torch.testing.assert_close( - wp.to_torch(base_data.quat_w), - wp.to_torch(imu_data.quat_w), + base_data.ang_vel_b.torch, + imu_data.ang_vel_b.torch, rtol=1e-4, atol=1e-4, ) - # check the angular velocities of the imus between offset and imu definition + # check the linear acceleration of the imus between offset and direct definition torch.testing.assert_close( - wp.to_torch(base_data.ang_vel_b), - wp.to_torch(imu_data.ang_vel_b), - rtol=1e-4, - atol=1e-4, - ) - # check the angular acceleration of the imus between offset and imu definition - torch.testing.assert_close( - wp.to_torch(base_data.ang_acc_b), - wp.to_torch(imu_data.ang_acc_b), - rtol=1e-4, - atol=1e-4, - ) - - # check the linear velocity of the imus between offset and imu definition - torch.testing.assert_close( - wp.to_torch(base_data.lin_vel_b), - wp.to_torch(imu_data.lin_vel_b), - rtol=1e-2, - atol=5e-3, - ) - - # check the linear acceleration of the imus between offset and imu definition - torch.testing.assert_close( - wp.to_torch(base_data.lin_acc_b), - wp.to_torch(imu_data.lin_acc_b), + base_data.lin_acc_b.torch, + imu_data.lin_acc_b.torch, rtol=1e-1, atol=1e-1, ) @@ -511,10 +352,7 @@ def test_single_dof_pendulum(setup_sim): def test_indirect_attachment(setup_sim): """Test attaching the imu through an xForm primitive configuration argument.""" sim, scene = setup_sim - # pendulum length - pend_length = PEND_POS_OFFSET[0] - # should achieve same results between the two imu sensors on the robot for idx in range(500): # write data to sim scene.write_data_to_sim() @@ -523,11 +361,6 @@ def test_indirect_attachment(setup_sim): # read data from sim scene.update(sim.get_physics_dt()) - # get pendulum joint state - joint_pos = wp.to_torch(scene.articulations["pendulum2"].data.joint_pos) - joint_vel = wp.to_torch(scene.articulations["pendulum2"].data.joint_vel) - joint_acc = wp.to_torch(scene.articulations["pendulum2"].data.joint_acc) - imu = scene.sensors["imu_indirect_pendulum_link"] imu_base = scene.sensors["imu_indirect_pendulum_base"] @@ -542,116 +375,26 @@ def test_indirect_attachment(setup_sim): atol=1e-4, ) - # IMU and base data + # IMU data imu_data = scene.sensors["imu_indirect_pendulum_link"].data base_data = scene.sensors["imu_indirect_pendulum_base"].data - # extract imu_link imu_sensor dynamics - lin_vel_w_imu_link = math_utils.quat_apply(wp.to_torch(imu_data.quat_w), wp.to_torch(imu_data.lin_vel_b)) - lin_acc_w_imu_link = math_utils.quat_apply(wp.to_torch(imu_data.quat_w), wp.to_torch(imu_data.lin_acc_b)) - - # calculate the joint dynamics from the imu_sensor (y axis of imu_link is parallel to joint axis of pendulum) - joint_vel_imu = math_utils.quat_apply(wp.to_torch(imu_data.quat_w), wp.to_torch(imu_data.ang_vel_b))[ - ..., 1 - ].unsqueeze(-1) - joint_acc_imu = math_utils.quat_apply(wp.to_torch(imu_data.quat_w), wp.to_torch(imu_data.ang_acc_b))[ - ..., 1 - ].unsqueeze(-1) - - # calculate analytical solution - vx = -joint_vel * pend_length * torch.sin(joint_pos) - vy = torch.zeros(2, 1, device=scene.device) - vz = -joint_vel * pend_length * torch.cos(joint_pos) - gt_linear_vel_w = torch.cat([vx, vy, vz], dim=-1) - - ax = -joint_acc * pend_length * torch.sin(joint_pos) - joint_vel**2 * pend_length * torch.cos(joint_pos) - ay = torch.zeros(2, 1, device=scene.device) - az = -joint_acc * pend_length * torch.cos(joint_pos) + joint_vel**2 * pend_length * torch.sin(joint_pos) + 9.81 - gt_linear_acc_w = torch.cat([ax, ay, az], dim=-1) # skip first step where initial velocity is zero if idx < 2: continue - # compare imu projected gravity - gravity_dir_w = torch.tensor((0.0, 0.0, -1.0), device=scene.device).repeat(2, 1) - gravity_dir_b = math_utils.quat_apply_inverse(wp.to_torch(imu_data.quat_w), gravity_dir_w) + # check the angular velocities of the imus between offset and direct definition torch.testing.assert_close( - wp.to_torch(imu_data.projected_gravity_b), - gravity_dir_b, - ) - - # compare imu angular velocity with joint velocity - torch.testing.assert_close( - joint_vel, - joint_vel_imu, - rtol=1e-1, - atol=1e-3, - ) - # compare imu angular acceleration with joint acceleration - torch.testing.assert_close( - joint_acc, - joint_acc_imu, - rtol=1e-1, - atol=1e-3, - ) - # compare imu linear velocity with simple pendulum calculation - torch.testing.assert_close( - gt_linear_vel_w, - lin_vel_w_imu_link, - rtol=1e-1, - atol=1e-3, - ) - # compare imu linear acceleration with simple pendulum calculation - torch.testing.assert_close( - gt_linear_acc_w, - lin_acc_w_imu_link, - rtol=1e-1, - atol=1e0, - ) - - # check the position between offset and imu definition - torch.testing.assert_close( - wp.to_torch(base_data.pos_w), - wp.to_torch(imu_data.pos_w), - rtol=1e-5, - atol=1e-5, - ) - - # check the orientation between offset and imu definition - torch.testing.assert_close( - wp.to_torch(base_data.quat_w), - wp.to_torch(imu_data.quat_w), + base_data.ang_vel_b.torch, + imu_data.ang_vel_b.torch, rtol=1e-4, atol=1e-4, ) - # check the angular velocities of the imus between offset and imu definition + # check the linear acceleration of the imus between offset and direct definition torch.testing.assert_close( - wp.to_torch(base_data.ang_vel_b), - wp.to_torch(imu_data.ang_vel_b), - rtol=1e-4, - atol=1e-4, - ) - # check the angular acceleration of the imus between offset and imu definition - torch.testing.assert_close( - wp.to_torch(base_data.ang_acc_b), - wp.to_torch(imu_data.ang_acc_b), - rtol=1e-4, - atol=1e-4, - ) - - # check the linear velocity of the imus between offset and imu definition - torch.testing.assert_close( - wp.to_torch(base_data.lin_vel_b), - wp.to_torch(imu_data.lin_vel_b), - rtol=1e-2, - atol=5e-3, - ) - - # check the linear acceleration of the imus between offset and imu definition - torch.testing.assert_close( - wp.to_torch(base_data.lin_acc_b), - wp.to_torch(imu_data.lin_acc_b), + base_data.lin_acc_b.torch, + imu_data.lin_acc_b.torch, rtol=1e-1, atol=1e-1, ) @@ -682,52 +425,18 @@ def test_offset_calculation(setup_sim): if idx < 1: continue - # check the accelerations - torch.testing.assert_close( - wp.to_torch(scene.sensors["imu_robot_base"].data.lin_acc_b), - wp.to_torch(scene.sensors["imu_robot_imu_link"].data.lin_acc_b), - rtol=1e-4, - atol=1e-4, - ) - torch.testing.assert_close( - wp.to_torch(scene.sensors["imu_robot_base"].data.ang_acc_b), - wp.to_torch(scene.sensors["imu_robot_imu_link"].data.ang_acc_b), - rtol=1e-4, - atol=1e-4, - ) - - # check the velocities + # check the linear accelerations torch.testing.assert_close( - wp.to_torch(scene.sensors["imu_robot_base"].data.ang_vel_b), - wp.to_torch(scene.sensors["imu_robot_imu_link"].data.ang_vel_b), - rtol=1e-4, - atol=1e-4, - ) - torch.testing.assert_close( - wp.to_torch(scene.sensors["imu_robot_base"].data.lin_vel_b), - wp.to_torch(scene.sensors["imu_robot_imu_link"].data.lin_vel_b), + scene.sensors["imu_robot_base"].data.lin_acc_b.torch, + scene.sensors["imu_robot_imu_link"].data.lin_acc_b.torch, rtol=1e-4, atol=1e-4, ) - # check the orientation + # check the angular velocities torch.testing.assert_close( - wp.to_torch(scene.sensors["imu_robot_base"].data.quat_w), - wp.to_torch(scene.sensors["imu_robot_imu_link"].data.quat_w), - rtol=1e-4, - atol=1e-4, - ) - # check the position - torch.testing.assert_close( - wp.to_torch(scene.sensors["imu_robot_base"].data.pos_w), - wp.to_torch(scene.sensors["imu_robot_imu_link"].data.pos_w), - rtol=1e-4, - atol=1e-4, - ) - # check the projected gravity - torch.testing.assert_close( - wp.to_torch(scene.sensors["imu_robot_base"].data.projected_gravity_b), - wp.to_torch(scene.sensors["imu_robot_imu_link"].data.projected_gravity_b), + scene.sensors["imu_robot_base"].data.ang_vel_b.torch, + scene.sensors["imu_robot_imu_link"].data.ang_vel_b.torch, rtol=1e-4, atol=1e-4, ) @@ -738,10 +447,7 @@ def test_attachment_validity(setup_sim): """Test invalid imu attachment. An imu cannot be attached directly to the world. It must be somehow attached to something implementing physics.""" sim, scene = setup_sim - imu_world_cfg = ImuCfg( - prim_path="/World/envs/env_0", - gravity_bias=(0.0, 0.0, 0.0), - ) + imu_world_cfg = ImuCfg(prim_path="/World/envs/env_0") with pytest.raises(RuntimeError) as exc_info: imu_world = Imu(imu_world_cfg) imu_world._initialize_impl() diff --git a/source/isaaclab_physx/test/sensors/test_joint_wrench_sensor.py b/source/isaaclab_physx/test/sensors/test_joint_wrench_sensor.py new file mode 100644 index 000000000000..4f10f2506ebb --- /dev/null +++ b/source/isaaclab_physx/test/sensors/test_joint_wrench_sensor.py @@ -0,0 +1,426 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Launch Isaac Sim Simulator first.""" + +from isaaclab.app import AppLauncher + +# launch omniverse app +simulation_app = AppLauncher(headless=True).app + +"""Rest everything follows.""" + +import math + +import pytest +import torch +import warp as wp +from isaaclab_physx.physics import PhysxCfg + +from pxr import Gf, UsdPhysics + +import isaaclab.sim as sim_utils +from isaaclab.actuators import ImplicitActuatorCfg +from isaaclab.assets import Articulation, ArticulationCfg +from isaaclab.scene import InteractiveScene, InteractiveSceneCfg +from isaaclab.sensors import JointWrenchSensor, JointWrenchSensorCfg +from isaaclab.sim import SimulationCfg +from isaaclab.terrains import TerrainImporterCfg +from isaaclab.utils import configclass +from isaaclab.utils import math as math_utils +from isaaclab.utils.assets import ISAAC_NUCLEUS_DIR, ISAACLAB_NUCLEUS_DIR + +from isaaclab_assets.robots.ant import ANT_CFG + + +def _make_single_joint_articulation_cfg() -> ArticulationCfg: + """Single-joint revolute test articulation (root ``CenterPivot`` + arm ``Arm``).""" + return ArticulationCfg( + prim_path="{ENV_REGEX_NS}/Robot", + spawn=sim_utils.UsdFileCfg( + usd_path=f"{ISAAC_NUCLEUS_DIR}/Robots/IsaacSim/SimpleArticulation/revolute_articulation.usd", + joint_drive_props=sim_utils.JointDrivePropertiesCfg(max_effort=80.0, max_velocity=5.0), + ), + actuators={ + "joint": ImplicitActuatorCfg( + joint_names_expr=[".*"], + stiffness=2000.0, + damping=100.0, + ), + }, + init_state=ArticulationCfg.InitialStateCfg(pos=(0.0, 0.0, 1.0)), + ) + + +def _make_cartpole_articulation_cfg(pole_damping: float = 0.0) -> ArticulationCfg: + """Two-joint cartpole articulation (cart + pole). + + Args: + pole_damping: Damping for the cart-to-pole revolute joint. + """ + return ArticulationCfg( + prim_path="{ENV_REGEX_NS}/Robot", + spawn=sim_utils.UsdFileCfg( + usd_path=f"{ISAACLAB_NUCLEUS_DIR}/Robots/Classic/Cartpole/cartpole.usd", + ), + init_state=ArticulationCfg.InitialStateCfg( + pos=(0.0, 0.0, 2.0), + joint_pos={"slider_to_cart": 0.0, "cart_to_pole": 0.0}, + ), + actuators={ + "cart_actuator": ImplicitActuatorCfg( + joint_names_expr=["slider_to_cart"], effort_limit_sim=400.0, stiffness=0.0, damping=10.0 + ), + "pole_actuator": ImplicitActuatorCfg( + joint_names_expr=["cart_to_pole"], effort_limit_sim=400.0, stiffness=0.0, damping=pole_damping + ), + }, + ) + + +@configclass +class _SingleJointSceneCfg(InteractiveSceneCfg): + """Scene with a single-joint articulation and the joint-wrench sensor.""" + + env_spacing = 2.0 + terrain = TerrainImporterCfg(prim_path="/World/ground", terrain_type="plane") + robot = _make_single_joint_articulation_cfg() + wrench = JointWrenchSensorCfg(prim_path="{ENV_REGEX_NS}/Robot") + + +@configclass +class _CartpoleSceneCfg(InteractiveSceneCfg): + """Scene with a cartpole (2-joint) articulation and the joint-wrench sensor.""" + + env_spacing = 4.0 + terrain = TerrainImporterCfg(prim_path="/World/ground", terrain_type="plane") + robot = _make_cartpole_articulation_cfg() + wrench = JointWrenchSensorCfg(prim_path="{ENV_REGEX_NS}/Robot") + + +@configclass +class _CartpoleDampedSceneCfg(InteractiveSceneCfg): + """Cartpole with pole damping for steady-state physics validation tests.""" + + env_spacing = 4.0 + terrain = TerrainImporterCfg(prim_path="/World/ground", terrain_type="plane") + robot = _make_cartpole_articulation_cfg(pole_damping=10.0) + wrench = JointWrenchSensorCfg(prim_path="{ENV_REGEX_NS}/Robot") + + +@configclass +class _NestedRootAntSceneCfg(InteractiveSceneCfg): + """Ant USD asset whose articulation root is nested under the configured asset prim.""" + + env_spacing = 4.0 + terrain = TerrainImporterCfg(prim_path="/World/ground", terrain_type="plane") + robot = ANT_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") + wrench = JointWrenchSensorCfg(prim_path="{ENV_REGEX_NS}/Robot") + + +@pytest.fixture +def sim(): + """Simulation context using the PhysX backend.""" + sim_cfg = SimulationCfg( + dt=1.0 / 120.0, + physics=PhysxCfg(), + ) + with sim_utils.build_simulation_context(sim_cfg=sim_cfg) as sim_ctx: + sim_ctx._app_control_on_stop_handle = None + yield sim_ctx + + +def _physx_incoming_joint_wrench(sensor: JointWrenchSensor) -> torch.Tensor: + """Read the raw PhysX incoming joint wrench tensor. + + PhysX reports spatial vectors as force followed by torque. Shape is + ``(num_envs, num_bodies, 6)``. + """ + raw_wrench = sensor._root_view.get_link_incoming_joint_force().view(wp.spatial_vectorf) + return wp.to_torch(raw_wrench) + + +def _assert_sensor_matches_physx_tensor(sensor: JointWrenchSensor) -> None: + """Compare sensor buffers to the raw PhysX tensor transformed into joint frames.""" + raw_wrench = _physx_incoming_joint_wrench(sensor) + sensor_data = sensor.data + + expected_force, expected_torque = _physx_incoming_joint_wrench_in_joint_frame(sensor, raw_wrench) + torch.testing.assert_close(sensor_data.force.torch, expected_force) + torch.testing.assert_close(sensor_data.torque.torch, expected_torque) + + +def _physx_incoming_joint_wrench_in_joint_frame( + sensor: JointWrenchSensor, raw_wrench: torch.Tensor +) -> tuple[torch.Tensor, torch.Tensor]: + """Transform raw PhysX body-frame incoming joint wrenches into the configured convention.""" + force_b = raw_wrench[..., :3] + torque_b = raw_wrench[..., 3:] + joint_pos_b = wp.to_torch(sensor._joint_pos_b).unsqueeze(0) + joint_quat_b = wp.to_torch(sensor._joint_quat_b).unsqueeze(0) + torque_joint_anchor_b = torque_b - torch.cross(joint_pos_b.expand_as(force_b), force_b, dim=-1) + + flat_joint_quat_b = joint_quat_b.expand_as(raw_wrench[..., :4]).reshape(-1, 4) + expected_force = math_utils.quat_apply_inverse(flat_joint_quat_b, force_b.reshape(-1, 3)).reshape(force_b.shape) + expected_torque = math_utils.quat_apply_inverse(flat_joint_quat_b, torque_joint_anchor_b.reshape(-1, 3)).reshape( + torque_b.shape + ) + return expected_force, expected_torque + + +def _set_child_joint_frame(scene: InteractiveScene, child_body_name: str) -> None: + """Set a non-identity child-side joint frame for the requested body in env 0.""" + for prim in scene.stage.Traverse(): + if not prim.GetPath().pathString.startswith("/World/envs/env_0/Robot"): + continue + joint = UsdPhysics.Joint(prim) + if joint and any(target.name == child_body_name for target in joint.GetBody1Rel().GetTargets()): + joint.GetLocalPos1Attr().Set(Gf.Vec3f(0.25, -0.15, 0.1)) + joint.GetLocalRot1Attr().Set( + Gf.Quatf( + math.cos(math.pi / 4.0), + Gf.Vec3f(math.sin(math.pi / 4.0), 0.0, 0.0), + ) + ) + return + raise RuntimeError(f"Failed to find a USD joint with child body '{child_body_name}'.") + + +# --------------------------------------------------------------------------- +# Sensor data — pre-init contract +# --------------------------------------------------------------------------- + + +def test_data_before_init_is_none(): + """``force``/``torque`` return ``None`` before :meth:`create_buffers` runs.""" + from isaaclab_physx.sensors.joint_wrench import JointWrenchSensorData + + data = JointWrenchSensorData() + assert data.force is None + assert data.torque is None + + +# --------------------------------------------------------------------------- +# Initialization and shapes +# --------------------------------------------------------------------------- + + +def test_initialization_and_shapes(sim): + """Sensor initializes on sim reset and exposes correctly-shaped buffers.""" + scene = InteractiveScene(_SingleJointSceneCfg(num_envs=2)) + sim.reset() + + robot: Articulation = scene["robot"] + sensor: JointWrenchSensor = scene["wrench"] + sim.step() + scene.update(sim.get_physics_dt()) + + # PhysX reports one incoming joint wrench per articulation link, including the root link. + num_envs = 2 + num_bodies = robot.num_bodies + assert sensor.data.force.torch.shape == (num_envs, num_bodies, 3) + assert sensor.data.torque.torch.shape == (num_envs, num_bodies, 3) + assert sensor.body_names == robot.body_names + assert sensor.find_bodies("Arm") == ([robot.body_names.index("Arm")], ["Arm"]) + _assert_sensor_matches_physx_tensor(sensor) + + +def test_multi_body_articulation(sim): + """Cartpole exposes a wrench for each link labelled by body name.""" + scene = InteractiveScene(_CartpoleSceneCfg(num_envs=2)) + sim.reset() + + robot: Articulation = scene["robot"] + sensor: JointWrenchSensor = scene["wrench"] + sim.step() + scene.update(sim.get_physics_dt()) + + num_envs = 2 + num_bodies = robot.num_bodies + assert sensor.data.force.torch.shape == (num_envs, num_bodies, 3) + assert sensor.data.torque.torch.shape == (num_envs, num_bodies, 3) + assert sensor.body_names == robot.body_names + assert len(sensor.body_names) == num_bodies + _assert_sensor_matches_physx_tensor(sensor) + + +def test_nested_articulation_root_resolution(sim): + """Sensor accepts an asset prim path whose articulation root is nested in the USD asset.""" + scene = InteractiveScene(_NestedRootAntSceneCfg(num_envs=1)) + sim.reset() + + robot: Articulation = scene["robot"] + sensor: JointWrenchSensor = scene["wrench"] + sim.step() + scene.update(sim.get_physics_dt()) + + assert sensor.body_names == robot.body_names + assert sensor.data.force.torch.shape == (1, robot.num_bodies, 3) + assert sensor.data.torque.torch.shape == (1, robot.num_bodies, 3) + _assert_sensor_matches_physx_tensor(sensor) + + +# --------------------------------------------------------------------------- +# Physical correctness +# --------------------------------------------------------------------------- + + +def test_force_and_torque_components_at_rest(sim): + """Component-level validation of force and torque against the PhysX tensor API.""" + scene = InteractiveScene(_SingleJointSceneCfg(num_envs=1)) + sim.reset() + + sensor: JointWrenchSensor = scene["wrench"] + robot: Articulation = scene["robot"] + for _ in range(400): + sim.step() + scene.update(sim.get_physics_dt()) + + _assert_sensor_matches_physx_tensor(sensor) + + arm_idx = robot.body_names.index("Arm") + raw_wrench = _physx_incoming_joint_wrench(sensor) + assert torch.any(raw_wrench[:, arm_idx, :] != 0.0) + + +def test_non_identity_joint_frame_transform(sim): + """PhysX raw body-frame wrench is converted to the child-side joint frame.""" + scene = InteractiveScene(_SingleJointSceneCfg(num_envs=1)) + _set_child_joint_frame(scene, "Arm") + sim.reset() + + sensor: JointWrenchSensor = scene["wrench"] + robot: Articulation = scene["robot"] + arm_idx = robot.body_names.index("Arm") + + for _ in range(400): + sim.step() + scene.update(sim.get_physics_dt()) + + raw_wrench = _physx_incoming_joint_wrench(sensor) + expected_force, expected_torque = _physx_incoming_joint_wrench_in_joint_frame(sensor, raw_wrench) + torch.testing.assert_close(sensor.data.force.torch, expected_force) + torch.testing.assert_close(sensor.data.torque.torch, expected_torque) + + raw_force = raw_wrench[:, arm_idx, :3] + raw_torque = raw_wrench[:, arm_idx, 3:] + assert not torch.allclose(sensor.data.force.torch[:, arm_idx], raw_force) + assert not torch.allclose(sensor.data.torque.torch[:, arm_idx], raw_torque) + + +def test_wrench_with_external_force_and_torque(sim): + """Full wrench validation with external force and torque applied.""" + scene = InteractiveScene(_SingleJointSceneCfg(num_envs=1)) + sim.reset() + + sensor: JointWrenchSensor = scene["wrench"] + robot: Articulation = scene["robot"] + arm_idx = robot.body_names.index("Arm") + + # Apply 10 N in body-Y and 10 N·m in body-Z on the arm (matches Newton test). + ext_force_b = torch.zeros((1, robot.num_bodies, 3), device=sim.device) + ext_force_b[:, arm_idx, 1] = 10.0 + ext_torque_b = torch.zeros((1, robot.num_bodies, 3), device=sim.device) + ext_torque_b[:, arm_idx, 2] = 10.0 + + for _ in range(800): + robot.permanent_wrench_composer.set_forces_and_torques_index(forces=ext_force_b, torques=ext_torque_b) + robot.write_data_to_sim() + sim.step() + scene.update(sim.get_physics_dt()) + + _assert_sensor_matches_physx_tensor(sensor) + + raw_wrench = _physx_incoming_joint_wrench(sensor) + assert torch.any(raw_wrench[:, arm_idx, :] != 0.0) + + +def test_interior_joint_wrench_at_rest(sim): + """Interior joint wrench matches the raw PhysX incoming-joint tensor. + + The cartpole has an interior joint (``slider_to_cart``) and a terminal + joint (``cart_to_pole``). PhysX reports one entry for every link, so this + test compares all link entries, including the cart link controlled by the + interior joint, against the underlying tensor API. + """ + scene = InteractiveScene(_CartpoleDampedSceneCfg(num_envs=1)) + sim.reset() + + sensor: JointWrenchSensor = scene["wrench"] + robot: Articulation = scene["robot"] + + for _ in range(800): + sim.step() + scene.update(sim.get_physics_dt()) + + _assert_sensor_matches_physx_tensor(sensor) + + cart_idx = robot.body_names.index("cart") + raw_wrench = _physx_incoming_joint_wrench(sensor) + assert torch.any(raw_wrench[:, cart_idx, :] != 0.0) + + +# --------------------------------------------------------------------------- +# String representation +# --------------------------------------------------------------------------- + + +def test_sensor_print(sim): + """Test that the sensor string representation works.""" + scene = InteractiveScene(_SingleJointSceneCfg(num_envs=2)) + sim.reset() + + sensor: JointWrenchSensor = scene["wrench"] + sensor_str = str(sensor) + assert "physx" in sensor_str + assert "Joint wrench sensor" in sensor_str + + +# --------------------------------------------------------------------------- +# Reset behavior +# --------------------------------------------------------------------------- + + +def test_reset_zeros_buffers(sim): + """Resetting the sensor clears the force / torque buffers.""" + scene = InteractiveScene(_SingleJointSceneCfg(num_envs=2)) + sim.reset() + + sensor: JointWrenchSensor = scene["wrench"] + for _ in range(100): + sim.step() + scene.update(sim.get_physics_dt()) + + assert torch.any(sensor.data.force.torch != 0), "Expected non-zero data before reset" + + sensor.reset() + + # Access raw buffers to skip lazy re-population from the PhysX view on the next data read. + force_after = wp.to_torch(sensor._data._force) + torque_after = wp.to_torch(sensor._data._torque) + torch.testing.assert_close(force_after, torch.zeros_like(force_after)) + torch.testing.assert_close(torque_after, torch.zeros_like(torque_after)) + + +def test_reset_with_env_ids_only_zeros_selected_envs(sim): + """Partial reset via env_ids should zero the selected envs and preserve the others.""" + scene = InteractiveScene(_SingleJointSceneCfg(num_envs=4)) + sim.reset() + + sensor: JointWrenchSensor = scene["wrench"] + for _ in range(100): + sim.step() + scene.update(sim.get_physics_dt()) + + force_before = sensor.data.force.torch.clone() + assert torch.any(force_before != 0), "Expected non-zero data before reset" + + sensor.reset(env_ids=[0, 2]) + + force_after = wp.to_torch(sensor._data._force) + torch.testing.assert_close(force_after[0], torch.zeros_like(force_after[0])) + torch.testing.assert_close(force_after[2], torch.zeros_like(force_after[2])) + torch.testing.assert_close(force_after[1], force_before[1]) + torch.testing.assert_close(force_after[3], force_before[3]) diff --git a/source/isaaclab_physx/test/sensors/test_pva.py b/source/isaaclab_physx/test/sensors/test_pva.py new file mode 100644 index 000000000000..feb527f88c62 --- /dev/null +++ b/source/isaaclab_physx/test/sensors/test_pva.py @@ -0,0 +1,765 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Launch Isaac Sim Simulator first.""" + +from isaaclab.app import AppLauncher + +# launch omniverse app +app_launcher = AppLauncher(headless=True, enable_cameras=True) +simulation_app = app_launcher.app + +"""Rest everything follows.""" + +import pathlib + +import pytest +import torch +import warp as wp +from isaaclab_physx.physics import PhysxCfg + +import isaaclab.sim as sim_utils +import isaaclab.utils.math as math_utils +from isaaclab.actuators import ImplicitActuatorCfg +from isaaclab.assets import ArticulationCfg, RigidObjectCfg +from isaaclab.markers.config import GREEN_ARROW_X_MARKER_CFG, RED_ARROW_X_MARKER_CFG +from isaaclab.scene import InteractiveScene, InteractiveSceneCfg +from isaaclab.sensors.pva import Pva, PvaCfg +from isaaclab.terrains import TerrainImporterCfg +from isaaclab.utils import configclass + +## +# Pre-defined configs +## +from isaaclab_assets.robots.anymal import ANYMAL_C_CFG # isort: skip +from isaaclab.utils.assets import ISAAC_NUCLEUS_DIR # isort: skip + +# offset of imu_link from base_link on anymal_c +POS_OFFSET = (0.2488, 0.00835, 0.04628) +ROT_OFFSET = (0, 0, 0.7071068, 0.7071068) + +# offset of imu_link from link_1 on simple_2_link +PEND_POS_OFFSET = (0.4, 0.0, 0.1) +PEND_ROT_OFFSET = (0.5, 0.5, 0.5, 0.5) + + +@configclass +class MySceneCfg(InteractiveSceneCfg): + """Example scene configuration.""" + + # terrain - flat terrain plane + terrain = TerrainImporterCfg( + prim_path="/World/ground", + terrain_type="plane", + max_init_terrain_level=None, + ) + + # rigid objects - balls + balls = RigidObjectCfg( + prim_path="{ENV_REGEX_NS}/ball", + init_state=RigidObjectCfg.InitialStateCfg(pos=(0.0, 0.0, 0.5)), + spawn=sim_utils.SphereCfg( + radius=0.25, + rigid_props=sim_utils.RigidBodyPropertiesCfg(), + mass_props=sim_utils.MassPropertiesCfg(mass=0.5), + collision_props=sim_utils.CollisionPropertiesCfg(), + visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(0.0, 0.0, 1.0)), + ), + ) + + cube = RigidObjectCfg( + prim_path="{ENV_REGEX_NS}/cube", + init_state=RigidObjectCfg.InitialStateCfg(pos=(0.0, -2.0, 0.5)), + spawn=sim_utils.CuboidCfg( + size=(0.25, 0.25, 0.25), + rigid_props=sim_utils.RigidBodyPropertiesCfg(), + mass_props=sim_utils.MassPropertiesCfg(mass=0.5), + collision_props=sim_utils.CollisionPropertiesCfg(), + visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(0.0, 0.0, 1.0)), + ), + ) + + # articulations - robot + robot = ANYMAL_C_CFG.replace(prim_path="{ENV_REGEX_NS}/robot") + # pendulum1 - uses merge_fixed_joints=True (same as pendulum2) so that fixed-joint + # child links (base, imu_link) are merged into their parents during URDF XML + # pre-processing. This avoids fixed-joint constraint violations at velocity level + # (the solver uses velocity_iteration_count=0). A non-physics imu_link Xform is + # created programmatically in the test fixture (see setup_sim). + pendulum = ArticulationCfg( + prim_path="{ENV_REGEX_NS}/pendulum", + spawn=sim_utils.UrdfFileCfg( + fix_base=True, + merge_fixed_joints=True, + make_instanceable=False, + asset_path=f"{pathlib.Path(__file__).parent.resolve()}/urdfs/simple_2_link.urdf", + articulation_props=sim_utils.ArticulationRootPropertiesCfg( + enabled_self_collisions=True, solver_position_iteration_count=4, solver_velocity_iteration_count=0 + ), + joint_drive=sim_utils.UrdfConverterCfg.JointDriveCfg( + gains=sim_utils.UrdfConverterCfg.JointDriveCfg.PDGainsCfg(stiffness=None, damping=None) + ), + ), + init_state=ArticulationCfg.InitialStateCfg(), + actuators={ + "joint_1_act": ImplicitActuatorCfg(joint_names_expr=["joint_.*"], stiffness=0.0, damping=0.3), + }, + ) + # pendulum2 - uses merge_fixed_joints=True so that the fixed-joint child links (base, imu_link) + # are merged into their parents during URDF XML pre-processing. A non-physics imu_link Xform + # is created programmatically in the test fixture to test indirect PVA attachment (see setup_sim). + pendulum2 = ArticulationCfg( + prim_path="{ENV_REGEX_NS}/pendulum2", + spawn=sim_utils.UrdfFileCfg( + fix_base=True, + merge_fixed_joints=True, + make_instanceable=False, + asset_path=f"{pathlib.Path(__file__).parent.resolve()}/urdfs/simple_2_link.urdf", + articulation_props=sim_utils.ArticulationRootPropertiesCfg( + enabled_self_collisions=True, solver_position_iteration_count=4, solver_velocity_iteration_count=0 + ), + joint_drive=sim_utils.UrdfConverterCfg.JointDriveCfg( + gains=sim_utils.UrdfConverterCfg.JointDriveCfg.PDGainsCfg(stiffness=None, damping=None) + ), + ), + init_state=ArticulationCfg.InitialStateCfg(), + actuators={ + "joint_1_act": ImplicitActuatorCfg(joint_names_expr=["joint_.*"], stiffness=0.0, damping=0.3), + }, + ) + + # sensors - pva (filled inside unit test) + pva_ball: PvaCfg = PvaCfg(prim_path="{ENV_REGEX_NS}/ball") + pva_cube: PvaCfg = PvaCfg(prim_path="{ENV_REGEX_NS}/cube") + pva_robot_imu_link: PvaCfg = PvaCfg(prim_path="{ENV_REGEX_NS}/robot/imu_link") + pva_robot_base: PvaCfg = PvaCfg( + prim_path="{ENV_REGEX_NS}/robot/base", + offset=PvaCfg.OffsetCfg( + pos=POS_OFFSET, + rot=ROT_OFFSET, + ), + ) + pva_robot_norb: PvaCfg = PvaCfg( + prim_path="{ENV_REGEX_NS}/robot/LF_HIP/LF_hip_fixed", + offset=PvaCfg.OffsetCfg( + pos=POS_OFFSET, + rot=ROT_OFFSET, + ), + ) + # The new URDF converter (urdf-usd-converter) places links under Geometry/ in a nested + # kinematic tree. With merge_fixed_joints=True the hierarchy for simple_2_link.urdf is: + # Geometry/world/link_1 (base merged into world, imu_link merged into link_1) + # A non-physics imu_link Xform is recreated in the test fixture (see setup_sim). + pva_indirect_pendulum_link: PvaCfg = PvaCfg( + prim_path="{ENV_REGEX_NS}/pendulum2/Geometry/world/link_1/imu_link", + debug_vis=not app_launcher._headless, + visualizer_cfg=RED_ARROW_X_MARKER_CFG.replace(prim_path="/Visuals/Acceleration/imu_link"), + ) + pva_indirect_pendulum_base: PvaCfg = PvaCfg( + prim_path="{ENV_REGEX_NS}/pendulum2/Geometry/world/link_1", + offset=PvaCfg.OffsetCfg( + pos=PEND_POS_OFFSET, + rot=PEND_ROT_OFFSET, + ), + debug_vis=not app_launcher._headless, + visualizer_cfg=GREEN_ARROW_X_MARKER_CFG.replace(prim_path="/Visuals/Acceleration/base"), + ) + pva_pendulum_imu_link: PvaCfg = PvaCfg( + prim_path="{ENV_REGEX_NS}/pendulum/Geometry/world/link_1/imu_link", + debug_vis=not app_launcher._headless, + visualizer_cfg=RED_ARROW_X_MARKER_CFG.replace(prim_path="/Visuals/Acceleration/imu_link"), + ) + pva_pendulum_base: PvaCfg = PvaCfg( + prim_path="{ENV_REGEX_NS}/pendulum/Geometry/world/link_1", + offset=PvaCfg.OffsetCfg( + pos=PEND_POS_OFFSET, + rot=PEND_ROT_OFFSET, + ), + debug_vis=not app_launcher._headless, + visualizer_cfg=GREEN_ARROW_X_MARKER_CFG.replace(prim_path="/Visuals/Acceleration/base"), + ) + + def __post_init__(self): + """Post initialization.""" + # change position of the robot + self.robot.init_state.pos = (0.0, 2.0, 1.0) + self.pendulum.init_state.pos = (-2.0, 1.0, 0.5) + self.pendulum2.init_state.pos = (2.0, 1.0, 0.5) + + # change asset + self.robot.spawn.usd_path = f"{ISAAC_NUCLEUS_DIR}/Robots/ANYbotics/anymal_c/anymal_c.usd" + # change iterations + self.robot.spawn.articulation_props.solver_position_iteration_count = 32 + self.robot.spawn.articulation_props.solver_velocity_iteration_count = 32 + + +@pytest.fixture +def setup_sim(): + """Create a simulation context and scene.""" + sim_cfg = sim_utils.SimulationCfg( + dt=0.001, physics=PhysxCfg(solver_type=0) + ) # 0: PGS, 1: TGS --> use PGS for more accurate results + with sim_utils.build_simulation_context(sim_cfg=sim_cfg) as sim: + sim._app_control_on_stop_handle = None + # construct scene + scene_cfg = MySceneCfg(num_envs=2, env_spacing=5.0, lazy_sensor_update=False, replicate_physics=False) + scene = InteractiveScene(scene_cfg) + # Both pendulum and pendulum2 use merge_fixed_joints=True, so the + # fixed-joint child link imu_link is removed from the URDF before USD + # conversion. Recreate it as a plain Xform (no RigidBodyAPI) under each + # pendulum's link_1 for every environment. The PVA sensor must then + # resolve the rigid-body ancestor (link_1) and cache the fixed offset — + # exercising the "indirect attachment" code path. + for i in range(scene_cfg.num_envs): + for art_name in ("pendulum", "pendulum2"): + prim_path = f"/World/envs/env_{i}/{art_name}/Geometry/world/link_1/imu_link" + sim_utils.create_prim(prim_path, "Xform", translation=PEND_POS_OFFSET, orientation=PEND_ROT_OFFSET) + # Play the simulator + sim.reset() + yield sim, scene + # Cleanup is handled by build_simulation_context + + +@pytest.mark.isaacsim_ci +def test_constant_velocity(setup_sim): + """Test the PVA sensor with a constant velocity. + + Expected behavior is that the linear and angular are approx the same at every time step as in each step we set + the same velocity and therefore reset the physx buffers. + """ + sim, scene = setup_sim + prev_lin_acc_ball = torch.zeros((scene.num_envs, 3), dtype=torch.float32, device=scene.device) + prev_ang_acc_ball = torch.zeros((scene.num_envs, 3), dtype=torch.float32, device=scene.device) + prev_lin_acc_cube = torch.zeros((scene.num_envs, 3), dtype=torch.float32, device=scene.device) + prev_ang_acc_cube = torch.zeros((scene.num_envs, 3), dtype=torch.float32, device=scene.device) + + for idx in range(200): + # set velocity + scene.rigid_objects["balls"].write_root_velocity_to_sim( + torch.tensor([[1.0, 0.0, 0.0, 0.0, 0.0, 0.0]], dtype=torch.float32, device=scene.device).repeat( + scene.num_envs, 1 + ) + ) + scene.rigid_objects["cube"].write_root_velocity_to_sim( + torch.tensor([[1.0, 0.0, 0.0, 0.0, 0.0, 0.0]], dtype=torch.float32, device=scene.device).repeat( + scene.num_envs, 1 + ) + ) + # write data to sim + scene.write_data_to_sim() + + # perform step + sim.step() + # read data from sim + scene.update(sim.get_physics_dt()) + + if idx > 1: + # check the pva accelerations + torch.testing.assert_close( + scene.sensors["pva_ball"].data.lin_acc_b.torch, + prev_lin_acc_ball, + rtol=1e-3, + atol=1e-3, + ) + torch.testing.assert_close( + scene.sensors["pva_ball"].data.ang_acc_b.torch, + prev_ang_acc_ball, + rtol=1e-3, + atol=1e-3, + ) + + torch.testing.assert_close( + scene.sensors["pva_cube"].data.lin_acc_b.torch, + prev_lin_acc_cube, + rtol=1e-3, + atol=1e-3, + ) + torch.testing.assert_close( + scene.sensors["pva_cube"].data.ang_acc_b.torch, + prev_ang_acc_cube, + rtol=1e-3, + atol=1e-3, + ) + + # check the pva velocities + # NOTE: the expected lin_vel_b is the same as the set velocity, as write_root_velocity_to_sim is + # setting v_0 (initial velocity) and then a calculation step of v_i = v_0 + a*dt. Consequently, + # the data.lin_vel_b is returning approx. v_i. + torch.testing.assert_close( + scene.sensors["pva_ball"].data.lin_vel_b.torch, + torch.tensor([[1.0, 0.0, -scene.physics_dt * 9.81]], dtype=torch.float32, device=scene.device).repeat( + scene.num_envs, 1 + ), + rtol=1e-4, + atol=1e-4, + ) + torch.testing.assert_close( + scene.sensors["pva_cube"].data.lin_vel_b.torch, + torch.tensor([[1.0, 0.0, -scene.physics_dt * 9.81]], dtype=torch.float32, device=scene.device).repeat( + scene.num_envs, 1 + ), + rtol=1e-4, + atol=1e-4, + ) + + # update previous values + prev_lin_acc_ball = scene.sensors["pva_ball"].data.lin_acc_b.torch.clone() + prev_ang_acc_ball = scene.sensors["pva_ball"].data.ang_acc_b.torch.clone() + prev_lin_acc_cube = scene.sensors["pva_cube"].data.lin_acc_b.torch.clone() + prev_ang_acc_cube = scene.sensors["pva_cube"].data.ang_acc_b.torch.clone() + + +@pytest.mark.isaacsim_ci +def test_constant_acceleration(setup_sim): + """Test the PVA sensor with a constant acceleration.""" + sim, scene = setup_sim + for idx in range(100): + # set acceleration + scene.rigid_objects["balls"].write_root_velocity_to_sim( + torch.tensor([[0.1, 0.0, 0.0, 0.0, 0.0, 0.0]], dtype=torch.float32, device=scene.device).repeat( + scene.num_envs, 1 + ) + * (idx + 1) + ) + # write data to sim + scene.write_data_to_sim() + # perform step + sim.step() + # read data from sim + scene.update(sim.get_physics_dt()) + + # skip first step where initial velocity is zero + if idx < 1: + continue + + # check the pva data + torch.testing.assert_close( + scene.sensors["pva_ball"].data.lin_acc_b.torch, + math_utils.quat_apply_inverse( + scene.rigid_objects["balls"].data.root_quat_w.torch, + torch.tensor([[0.1, 0.0, 0.0]], dtype=torch.float32, device=scene.device).repeat(scene.num_envs, 1) + / sim.get_physics_dt(), + ), + rtol=1e-4, + atol=1e-4, + ) + + # check the angular velocity + torch.testing.assert_close( + scene.sensors["pva_ball"].data.ang_vel_b.torch, + scene.rigid_objects["balls"].data.root_ang_vel_b.torch, + rtol=1e-4, + atol=1e-4, + ) + + +@pytest.mark.isaacsim_ci +def test_single_dof_pendulum(setup_sim): + """Test PVA against analytical pendulum problem.""" + sim, scene = setup_sim + # pendulum length + pend_length = PEND_POS_OFFSET[0] + + # should achieve same results between the two pva sensors on the robot + for idx in range(500): + # write data to sim + scene.write_data_to_sim() + # perform step + sim.step() + # read data from sim + scene.update(sim.get_physics_dt()) + + # get pendulum joint state + joint_pos = scene.articulations["pendulum"].data.joint_pos.torch + joint_vel = scene.articulations["pendulum"].data.joint_vel.torch + joint_acc = scene.articulations["pendulum"].data.joint_acc.torch + + # PVA and base data + pva_data = scene.sensors["pva_pendulum_imu_link"].data + base_data = scene.sensors["pva_pendulum_base"].data + + # extract imu_link pva_sensor dynamics + lin_vel_w_imu_link = math_utils.quat_apply(pva_data.quat_w.torch, pva_data.lin_vel_b.torch) + lin_acc_w_imu_link = math_utils.quat_apply(pva_data.quat_w.torch, pva_data.lin_acc_b.torch) + + # calculate the joint dynamics from the pva_sensor (y axis of imu_link is parallel to joint axis of pendulum) + joint_vel_pva = math_utils.quat_apply(pva_data.quat_w.torch, pva_data.ang_vel_b.torch)[..., 1].unsqueeze(-1) + joint_acc_pva = math_utils.quat_apply(pva_data.quat_w.torch, pva_data.ang_acc_b.torch)[..., 1].unsqueeze(-1) + + # calculate analytical solution + vx = -joint_vel * pend_length * torch.sin(joint_pos) + vy = torch.zeros(2, 1, device=scene.device) + vz = -joint_vel * pend_length * torch.cos(joint_pos) + gt_linear_vel_w = torch.cat([vx, vy, vz], dim=-1) + + ax = -joint_acc * pend_length * torch.sin(joint_pos) - joint_vel**2 * pend_length * torch.cos(joint_pos) + ay = torch.zeros(2, 1, device=scene.device) + az = -joint_acc * pend_length * torch.cos(joint_pos) + joint_vel**2 * pend_length * torch.sin(joint_pos) + gt_linear_acc_w = torch.cat([ax, ay, az], dim=-1) + + # skip first step where initial velocity is zero + if idx < 2: + continue + + # compare pva projected gravity + gravity_dir_w = torch.tensor((0.0, 0.0, -1.0), device=scene.device).repeat(2, 1) + gravity_dir_b = math_utils.quat_apply_inverse(pva_data.quat_w.torch, gravity_dir_w) + torch.testing.assert_close( + pva_data.projected_gravity_b.torch, + gravity_dir_b, + ) + + # compare pva angular velocity with joint velocity + torch.testing.assert_close( + joint_vel, + joint_vel_pva, + rtol=1e-1, + atol=1e-3, + ) + # compare pva angular acceleration with joint acceleration + torch.testing.assert_close( + joint_acc, + joint_acc_pva, + rtol=1e-1, + atol=1e-3, + ) + # compare pva linear velocity with simple pendulum calculation + torch.testing.assert_close( + gt_linear_vel_w, + lin_vel_w_imu_link, + rtol=1e-1, + atol=1e-3, + ) + # compare pva linear acceleration with simple pendulum calculation + torch.testing.assert_close( + gt_linear_acc_w, + lin_acc_w_imu_link, + rtol=1e-1, + atol=1e0, + ) + + # check the position between offset and pva definition + torch.testing.assert_close( + base_data.pos_w.torch, + pva_data.pos_w.torch, + rtol=1e-5, + atol=1e-5, + ) + + # check the orientation between offset and pva definition + torch.testing.assert_close( + base_data.quat_w.torch, + pva_data.quat_w.torch, + rtol=1e-4, + atol=1e-4, + ) + + # check the angular velocities of the pvas between offset and pva definition + torch.testing.assert_close( + base_data.ang_vel_b.torch, + pva_data.ang_vel_b.torch, + rtol=1e-4, + atol=1e-4, + ) + # check the angular acceleration of the pvas between offset and pva definition + torch.testing.assert_close( + base_data.ang_acc_b.torch, + pva_data.ang_acc_b.torch, + rtol=1e-4, + atol=1e-4, + ) + + # check the linear velocity of the pvas between offset and pva definition + torch.testing.assert_close( + base_data.lin_vel_b.torch, + pva_data.lin_vel_b.torch, + rtol=1e-2, + atol=5e-3, + ) + + # check the linear acceleration of the pvas between offset and pva definition + torch.testing.assert_close( + base_data.lin_acc_b.torch, + pva_data.lin_acc_b.torch, + rtol=1e-1, + atol=1e-1, + ) + + +@pytest.mark.isaacsim_ci +def test_indirect_attachment(setup_sim): + """Test attaching the PVA sensor through an xForm primitive configuration argument.""" + sim, scene = setup_sim + # pendulum length + pend_length = PEND_POS_OFFSET[0] + + # should achieve same results between the two pva sensors on the robot + for idx in range(500): + # write data to sim + scene.write_data_to_sim() + # perform step + sim.step() + # read data from sim + scene.update(sim.get_physics_dt()) + + # get pendulum joint state + joint_pos = scene.articulations["pendulum2"].data.joint_pos.torch + joint_vel = scene.articulations["pendulum2"].data.joint_vel.torch + joint_acc = scene.articulations["pendulum2"].data.joint_acc.torch + + pva = scene.sensors["pva_indirect_pendulum_link"] + pva_base = scene.sensors["pva_indirect_pendulum_base"] + + torch.testing.assert_close( + wp.to_torch(pva._offset_pos_b), + wp.to_torch(pva_base._offset_pos_b), + ) + torch.testing.assert_close( + wp.to_torch(pva._offset_quat_b), + wp.to_torch(pva_base._offset_quat_b), + rtol=1e-4, + atol=1e-4, + ) + + # PVA and base data + pva_data = scene.sensors["pva_indirect_pendulum_link"].data + base_data = scene.sensors["pva_indirect_pendulum_base"].data + # extract imu_link pva_sensor dynamics + lin_vel_w_imu_link = math_utils.quat_apply(pva_data.quat_w.torch, pva_data.lin_vel_b.torch) + lin_acc_w_imu_link = math_utils.quat_apply(pva_data.quat_w.torch, pva_data.lin_acc_b.torch) + + # calculate the joint dynamics from the pva_sensor (y axis of imu_link is parallel to joint axis of pendulum) + joint_vel_pva = math_utils.quat_apply(pva_data.quat_w.torch, pva_data.ang_vel_b.torch)[..., 1].unsqueeze(-1) + joint_acc_pva = math_utils.quat_apply(pva_data.quat_w.torch, pva_data.ang_acc_b.torch)[..., 1].unsqueeze(-1) + + # calculate analytical solution + vx = -joint_vel * pend_length * torch.sin(joint_pos) + vy = torch.zeros(2, 1, device=scene.device) + vz = -joint_vel * pend_length * torch.cos(joint_pos) + gt_linear_vel_w = torch.cat([vx, vy, vz], dim=-1) + + ax = -joint_acc * pend_length * torch.sin(joint_pos) - joint_vel**2 * pend_length * torch.cos(joint_pos) + ay = torch.zeros(2, 1, device=scene.device) + az = -joint_acc * pend_length * torch.cos(joint_pos) + joint_vel**2 * pend_length * torch.sin(joint_pos) + gt_linear_acc_w = torch.cat([ax, ay, az], dim=-1) + + # skip first step where initial velocity is zero + if idx < 2: + continue + + # compare pva projected gravity + gravity_dir_w = torch.tensor((0.0, 0.0, -1.0), device=scene.device).repeat(2, 1) + gravity_dir_b = math_utils.quat_apply_inverse(pva_data.quat_w.torch, gravity_dir_w) + torch.testing.assert_close( + pva_data.projected_gravity_b.torch, + gravity_dir_b, + ) + + # compare pva angular velocity with joint velocity + torch.testing.assert_close( + joint_vel, + joint_vel_pva, + rtol=1e-1, + atol=1e-3, + ) + # compare pva angular acceleration with joint acceleration + torch.testing.assert_close( + joint_acc, + joint_acc_pva, + rtol=1e-1, + atol=1e-3, + ) + # compare pva linear velocity with simple pendulum calculation + torch.testing.assert_close( + gt_linear_vel_w, + lin_vel_w_imu_link, + rtol=1e-1, + atol=1e-3, + ) + # compare pva linear acceleration with simple pendulum calculation + torch.testing.assert_close( + gt_linear_acc_w, + lin_acc_w_imu_link, + rtol=1e-1, + atol=1e0, + ) + + # check the position between offset and pva definition + torch.testing.assert_close( + base_data.pos_w.torch, + pva_data.pos_w.torch, + rtol=1e-5, + atol=1e-5, + ) + + # check the orientation between offset and pva definition + torch.testing.assert_close( + base_data.quat_w.torch, + pva_data.quat_w.torch, + rtol=1e-4, + atol=1e-4, + ) + + # check the angular velocities of the pvas between offset and pva definition + torch.testing.assert_close( + base_data.ang_vel_b.torch, + pva_data.ang_vel_b.torch, + rtol=1e-4, + atol=1e-4, + ) + # check the angular acceleration of the pvas between offset and pva definition + torch.testing.assert_close( + base_data.ang_acc_b.torch, + pva_data.ang_acc_b.torch, + rtol=1e-4, + atol=1e-4, + ) + + # check the linear velocity of the pvas between offset and pva definition + torch.testing.assert_close( + base_data.lin_vel_b.torch, + pva_data.lin_vel_b.torch, + rtol=1e-2, + atol=5e-3, + ) + + # check the linear acceleration of the pvas between offset and pva definition + torch.testing.assert_close( + base_data.lin_acc_b.torch, + pva_data.lin_acc_b.torch, + rtol=1e-1, + atol=1e-1, + ) + + +@pytest.mark.isaacsim_ci +def test_offset_calculation(setup_sim): + """Test offset configuration argument.""" + sim, scene = setup_sim + + # should achieve same results between the two pva sensors on the robot + for idx in range(500): + # set acceleration + scene.articulations["robot"].write_root_velocity_to_sim( + torch.tensor([[0.05, 0.0, 0.0, 0.0, 0.0, 0.0]], dtype=torch.float32, device=scene.device).repeat( + scene.num_envs, 1 + ) + * (idx + 1) + ) + # write data to sim + scene.write_data_to_sim() + # perform step + sim.step() + # read data from sim + scene.update(sim.get_physics_dt()) + + # skip first step where initial velocity is zero + if idx < 1: + continue + + # check the accelerations + torch.testing.assert_close( + scene.sensors["pva_robot_base"].data.lin_acc_b.torch, + scene.sensors["pva_robot_imu_link"].data.lin_acc_b.torch, + rtol=1e-4, + atol=1e-4, + ) + torch.testing.assert_close( + scene.sensors["pva_robot_base"].data.ang_acc_b.torch, + scene.sensors["pva_robot_imu_link"].data.ang_acc_b.torch, + rtol=1e-4, + atol=1e-4, + ) + + # check the velocities + torch.testing.assert_close( + scene.sensors["pva_robot_base"].data.ang_vel_b.torch, + scene.sensors["pva_robot_imu_link"].data.ang_vel_b.torch, + rtol=1e-4, + atol=1e-4, + ) + torch.testing.assert_close( + scene.sensors["pva_robot_base"].data.lin_vel_b.torch, + scene.sensors["pva_robot_imu_link"].data.lin_vel_b.torch, + rtol=1e-4, + atol=1e-4, + ) + + # check the orientation + torch.testing.assert_close( + scene.sensors["pva_robot_base"].data.quat_w.torch, + scene.sensors["pva_robot_imu_link"].data.quat_w.torch, + rtol=1e-4, + atol=1e-4, + ) + # check the position + torch.testing.assert_close( + scene.sensors["pva_robot_base"].data.pos_w.torch, + scene.sensors["pva_robot_imu_link"].data.pos_w.torch, + rtol=1e-4, + atol=1e-4, + ) + # check the projected gravity + torch.testing.assert_close( + scene.sensors["pva_robot_base"].data.projected_gravity_b.torch, + scene.sensors["pva_robot_imu_link"].data.projected_gravity_b.torch, + rtol=1e-4, + atol=1e-4, + ) + + +@pytest.mark.isaacsim_ci +def test_attachment_validity(setup_sim): + """Test invalid PVA attachment. A PVA sensor cannot be attached directly to the world. + + It must be somehow attached to something implementing physics. + """ + sim, scene = setup_sim + pva_world_cfg = PvaCfg(prim_path="/World/envs/env_0") + with pytest.raises(RuntimeError) as exc_info: + pva_world = Pva(pva_world_cfg) + pva_world._initialize_impl() + assert exc_info.type is RuntimeError and "find a rigid body ancestor prim" in str(exc_info.value) + + +@pytest.mark.isaacsim_ci +def test_env_ids_propagation(setup_sim): + """Test that env_ids argument propagates through update and reset methods""" + sim, scene = setup_sim + scene.reset() + + for idx in range(10): + # set acceleration + scene.articulations["robot"].write_root_velocity_to_sim( + torch.tensor([[0.5, 0.0, 0.0, 0.0, 0.0, 0.0]], dtype=torch.float32, device=scene.device).repeat( + scene.num_envs, 1 + ) + * (idx + 1) + ) + # write data to sim + scene.write_data_to_sim() + # perform step + sim.step() + # read data from sim + scene.update(sim.get_physics_dt()) + + # reset scene for env 1 + scene.reset(env_ids=[1]) + # read data from sim + scene.update(sim.get_physics_dt()) + # perform step + sim.step() + # read data from sim + scene.update(sim.get_physics_dt()) + + +@pytest.mark.isaacsim_ci +def test_sensor_print(setup_sim): + """Test sensor print is working correctly.""" + sim, scene = setup_sim + # Create sensor + sensor = scene.sensors["pva_ball"] + # print info + print(sensor) diff --git a/source/isaaclab_physx/test/sim/__init__.py b/source/isaaclab_physx/test/sim/__init__.py new file mode 100644 index 000000000000..460a30569089 --- /dev/null +++ b/source/isaaclab_physx/test/sim/__init__.py @@ -0,0 +1,4 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause diff --git a/source/isaaclab_physx/test/sim/test_cloner.py b/source/isaaclab_physx/test/sim/test_cloner.py index c5585fb0fca2..4bfba07d99e8 100644 --- a/source/isaaclab_physx/test/sim/test_cloner.py +++ b/source/isaaclab_physx/test/sim/test_cloner.py @@ -20,9 +20,20 @@ from isaaclab_physx.cloner import physx_replicate import isaaclab.sim as sim_utils -from isaaclab.cloner import TemplateCloneCfg, clone_from_template, sequential, usd_replicate +from isaaclab.cloner import ( + TemplateCloneCfg, + _fabric_notices, + clone_from_template, + disabled_fabric_change_notifies, + sequential, + usd_replicate, +) from isaaclab.sim import build_simulation_context +wp.init() + +pytestmark = pytest.mark.isaacsim_ci + @pytest.fixture(params=["cpu", "cuda"]) def sim(request): @@ -458,7 +469,6 @@ def _run_sphere_velocity_sim(sim, use_physx_replicate: bool, num_steps: int = 10 return torch.stack(velocities) -@pytest.mark.isaacsim_ci def test_physx_replicate_env_consistency(sim): """Test that env_0 and env_1 produce matching velocities when using physx_replicate.""" trajectory = _run_sphere_velocity_sim(sim, use_physx_replicate=True) @@ -471,7 +481,6 @@ def test_physx_replicate_env_consistency(sim): @pytest.mark.xfail(reason="Source env gets physics from replicator, not USD parsing; may diverge from baseline.") -@pytest.mark.isaacsim_ci @pytest.mark.parametrize("device", ["cpu", "cuda"]) def test_physx_replicate_vs_no_replicate(device): """Test that physx_replicate does not change the physics behavior of env_0. @@ -489,3 +498,147 @@ def test_physx_replicate_vs_no_replicate(device): for idx in range(baseline.shape[0]): diff = (with_rep[idx, 0] - baseline[idx, 0]).abs().max().item() assert diff < 1e-3, f"step {idx}: replicate vs no-replicate diverge, max_diff={diff}" + + +def test_disabled_fabric_change_notifies_toggles_ifabricusd_flag(sim): + """Regression: ``disabled_fabric_change_notifies`` actually toggles the IFabricUsd flag. + + The PR's perf win depends on ``setEnableChangeNotifies`` being driven correctly by the + ctypes binding in ``_fabric_notices.py``. That binding reads hardcoded vtable offsets + and could silently no-op if Kit's ABI shifts (offsets drift) or libcarb fails to load. + + A perf-delta assertion can't be done reliably in synthetic isolation — the listener's + cost only shows up under full Kit+PhysX integration paths that this test environment + doesn't reproduce; production-scene benchmarks are the PR's load-bearing perf evidence. + What this test guards is the mechanic itself: ``is_enabled`` flips on entry, restores + on exit when ``restore=True``, stays off when ``restore=False``, and re-entrant nested + blocks behave correctly. + """ + import usdrt + from pxr import UsdUtils + + bindings = _fabric_notices.get_bindings() + if bindings is None: + pytest.skip("omni::fabric::IFabricUsd unavailable — Fabric notice path inert here") + + stage = sim_utils.get_current_stage() + cache = UsdUtils.StageCache.Get() + cached_id = cache.GetId(stage) + stage_id = cached_id.ToLongInt() if cached_id.IsValid() else cache.Insert(stage).ToLongInt() + fabric_id = usdrt.Usd.Stage.Attach(stage_id).GetFabricId().id + + # 1. Listener starts enabled. + assert bindings.is_enabled(fabric_id), "Fabric notice listener should be enabled at test start" + + # 2. Default ``restore=True`` round-trips the flag. + with disabled_fabric_change_notifies(stage): + assert not bindings.is_enabled(fabric_id), "listener should be suspended inside the with block" + assert bindings.is_enabled(fabric_id), "listener should be restored on exit when restore=True" + + # 3. ``restore=False`` leaves the flag off. Manually re-enable to get back to a + # known state for subsequent assertions. + with disabled_fabric_change_notifies(stage, restore=False): + assert not bindings.is_enabled(fabric_id), "listener should be suspended inside the with block" + assert not bindings.is_enabled(fabric_id), "listener should remain suspended on exit when restore=False" + bindings.set_enable(fabric_id, True) + assert bindings.is_enabled(fabric_id) + + # 4. Re-entrant nesting: inner exits don't re-enable while outer still wants it suspended. + with disabled_fabric_change_notifies(stage): + assert not bindings.is_enabled(fabric_id) + with disabled_fabric_change_notifies(stage): + assert not bindings.is_enabled(fabric_id) + assert not bindings.is_enabled(fabric_id), "inner exit must not re-enable while outer is active" + assert bindings.is_enabled(fabric_id), "outer exit should restore the flag" + + +@pytest.mark.skip( + reason=( + "Local-only perf regression; correctness is covered by" + " test_disabled_fabric_change_notifies_toggles_ifabricusd_flag." + " Re-enable manually when touching listener suspension." + ) +) +def test_disabled_fabric_change_notifies_speedup_regression(): + """Local-only perf regression: listener suspension speeds up clone+reset by >= 1.2x. + + Skipped unconditionally — the suspension mechanism's correctness is covered by + :func:`test_disabled_fabric_change_notifies_toggles_ifabricusd_flag`; the wall-clock + win is platform-sensitive (deferred Fabric resync in ``sim.reset`` can offset the + scene-time savings on some hardware). Re-verify locally when touching the suspension. + + Scene knobs from bisection: ``rigid_props`` is required (plain Xforms give ~1.0x), + ``replicate_physics=True`` is required (drops to ~1.19x without), and 16 bodies x + 4096 envs ≈ 64K firings keeps listener cost above noise. See PR #5432. + """ + import time + + import isaaclab.cloner._fabric_notices as fabric_notices_mod + import isaaclab.sim as sim_utils + from isaaclab.assets import RigidObjectCfg + from isaaclab.scene import InteractiveScene, InteractiveSceneCfg + from isaaclab.utils import configclass + + if fabric_notices_mod.get_bindings() is None: + pytest.skip("omni::fabric::IFabricUsd unavailable") + + def _body(i: int) -> RigidObjectCfg: + return RigidObjectCfg( + prim_path=f"/World/envs/env_.*/Body_{i}", + spawn=sim_utils.SphereCfg(radius=0.1, rigid_props=sim_utils.RigidBodyPropertiesCfg()), + init_state=RigidObjectCfg.InitialStateCfg(pos=(0.3 * (i % 4), 0.3 * (i // 4), 0.5)), + ) + + @configclass + class _SceneCfg(InteractiveSceneCfg): + pass + + for _i in range(16): + setattr(_SceneCfg, f"body_{_i}", _body(_i)) + + def _probe_flag(stage) -> bool | None: + try: + import usdrt + from pxr import UsdUtils + + cid = UsdUtils.StageCache.Get().GetId(stage) + sid = cid.ToLongInt() if cid.IsValid() else UsdUtils.StageCache.Get().Insert(stage).ToLongInt() + fid = usdrt.Usd.Stage.Attach(sid).GetFabricId().id + b = fabric_notices_mod.get_bindings() + return None if b is None else bool(b.is_enabled(fid)) + except Exception: + return None + + def _measure(simulate_pre_pr: bool) -> tuple[float, float, bool | None]: + original = fabric_notices_mod.get_bindings + if simulate_pre_pr: + fabric_notices_mod.get_bindings = lambda: None + assert fabric_notices_mod.get_bindings() is None, "monkey-patch did not take effect" + try: + with build_simulation_context(device="cpu", dt=0.01, add_lighting=False) as sim: + t0 = time.perf_counter() + scene = InteractiveScene(_SceneCfg(num_envs=4096, env_spacing=4.0, replicate_physics=True)) + scene_dt = time.perf_counter() - t0 + # Probe before reset so we see whether suspension actually engaged. + fabric_notices_mod.get_bindings = original + flag = _probe_flag(scene.stage) + if simulate_pre_pr: + fabric_notices_mod.get_bindings = lambda: None + t0 = time.perf_counter() + sim.reset() + return scene_dt, time.perf_counter() - t0, flag + finally: + fabric_notices_mod.get_bindings = original + + _measure(simulate_pre_pr=False) # warmup + s_scene, s_reset, s_flag = _measure(simulate_pre_pr=False) + a_scene, a_reset, a_flag = _measure(simulate_pre_pr=True) + + suspended = s_scene + s_reset + active = a_scene + a_reset + speedup = active / suspended + print( + f"\n[fabric-notice perf] active={active:.2f}s (flag={a_flag})" + f" suspended={suspended:.2f}s (flag={s_flag}) speedup={speedup:.2f}x" + ) + assert speedup >= 1.2, f"expected >= 1.2x, got {speedup:.2f}x (active={active:.2f}s suspended={suspended:.2f}s)" diff --git a/source/isaaclab_physx/test/sim/test_spawn_materials.py b/source/isaaclab_physx/test/sim/test_spawn_materials.py new file mode 100644 index 000000000000..477132c5c5aa --- /dev/null +++ b/source/isaaclab_physx/test/sim/test_spawn_materials.py @@ -0,0 +1,55 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Launch Isaac Sim Simulator first.""" + +from isaaclab.app import AppLauncher + +# launch omniverse app +simulation_app = AppLauncher(headless=True).app + +"""Rest everything follows.""" + + +import pytest +from isaaclab_physx.sim.spawners.materials.physics_materials_cfg import DeformableBodyMaterialCfg + +import isaaclab.sim as sim_utils +from isaaclab.sim import SimulationCfg, SimulationContext + +pytestmark = pytest.mark.isaacsim_ci + + +@pytest.fixture +def sim(): + """Create a simulation context.""" + sim_utils.create_new_stage() + dt = 0.1 + sim = SimulationContext(SimulationCfg(dt=dt)) + sim_utils.update_stage() + yield sim + sim.stop() + sim.clear_instance() + + +def test_spawn_deformable_body_material(sim): + """Test spawning a deformable body material.""" + cfg = DeformableBodyMaterialCfg( + density=1.0, + dynamic_friction=0.25, + youngs_modulus=50000000.0, + poissons_ratio=0.5, + elasticity_damping=0.005, + ) + prim = cfg.func("/Looks/DeformableBodyMaterial", cfg) + # Check validity + assert prim.IsValid() + assert sim.stage.GetPrimAtPath("/Looks/DeformableBodyMaterial").IsValid() + # Check properties + assert prim.GetAttribute("omniphysics:density").Get() == cfg.density + assert prim.GetAttribute("omniphysics:dynamicFriction").Get() == cfg.dynamic_friction + assert prim.GetAttribute("omniphysics:youngsModulus").Get() == cfg.youngs_modulus + assert prim.GetAttribute("omniphysics:poissonsRatio").Get() == cfg.poissons_ratio + assert prim.GetAttribute("physxDeformableBody:elasticityDamping").Get() == pytest.approx(cfg.elasticity_damping) diff --git a/source/isaaclab_physx/test/sim/test_spawn_meshes.py b/source/isaaclab_physx/test/sim/test_spawn_meshes.py new file mode 100644 index 000000000000..7c24e289ef9f --- /dev/null +++ b/source/isaaclab_physx/test/sim/test_spawn_meshes.py @@ -0,0 +1,142 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Launch Isaac Sim Simulator first.""" + +from isaaclab.app import AppLauncher + +# launch omniverse app +simulation_app = AppLauncher(headless=True).app + +"""Rest everything follows.""" + + +import pytest +from isaaclab_physx.sim.schemas.schemas_cfg import DeformableBodyPropertiesCfg +from isaaclab_physx.sim.spawners.materials.physics_materials_cfg import DeformableBodyMaterialCfg + +import isaaclab.sim as sim_utils +from isaaclab.sim import SimulationCfg, SimulationContext + +pytestmark = pytest.mark.isaacsim_ci + + +@pytest.fixture +def sim(): + """Create a simulation context for testing.""" + # Create a new stage + sim_utils.create_new_stage() + # Simulation time-step + dt = 0.1 + # Load kit helper + sim = SimulationContext(SimulationCfg(dt=dt)) + # Wait for spawning + sim_utils.update_stage() + yield sim + # Cleanup + sim._disable_app_control_on_stop_handle = True # prevent timeout + sim.stop() + sim.clear_instance() + + +""" +Physics properties. +""" + + +def test_spawn_cone_with_deformable_props(sim): + """Test spawning of UsdGeomMesh prim for a cone with deformable body API.""" + # Spawn cone + cfg = sim_utils.MeshConeCfg( + radius=1.0, + height=2.0, + deformable_props=DeformableBodyPropertiesCfg(deformable_body_enabled=True), + ) + prim = cfg.func("/World/Cone", cfg) + + # Check validity + assert prim.IsValid() + assert sim.stage.GetPrimAtPath("/World/Cone").IsValid() + + # Check properties + # Unlike rigid body, deformable body properties are on the mesh prim + prim = sim.stage.GetPrimAtPath("/World/Cone") + assert prim.GetAttribute("omniphysics:deformableBodyEnabled").Get() == cfg.deformable_props.deformable_body_enabled + + +def test_spawn_cone_with_deformable_and_mass_props(sim): + """Test spawning of UsdGeomMesh prim for a cone with deformable body and mass API.""" + # Spawn cone + cfg = sim_utils.MeshConeCfg( + radius=1.0, + height=2.0, + deformable_props=DeformableBodyPropertiesCfg(deformable_body_enabled=True, mass=1.0), + ) + prim = cfg.func("/World/Cone", cfg) + + # Check validity + assert prim.IsValid() + assert sim.stage.GetPrimAtPath("/World/Cone").IsValid() + # Check properties + prim = sim.stage.GetPrimAtPath("/World/Cone") + assert prim.GetAttribute("omniphysics:mass").Get() == cfg.deformable_props.mass + + # check sim playing + sim.play() + for _ in range(10): + sim.step() + + +def test_spawn_cone_with_deformable_and_density_props(sim): + """Test spawning of UsdGeomMesh prim for a cone with deformable body and mass API, + specifying density instead of mass. + """ + # Spawn cone + cfg = sim_utils.MeshConeCfg( + radius=1.0, + height=2.0, + deformable_props=DeformableBodyPropertiesCfg(deformable_body_enabled=True), + physics_material=DeformableBodyMaterialCfg(density=10.0), + ) + prim = cfg.func("/World/Cone", cfg) + + # Check validity + assert prim.IsValid() + assert sim.stage.GetPrimAtPath("/World/Cone").IsValid() + assert sim.stage.GetPrimAtPath("/World/Cone/geometry/material").IsValid() + # Check properties + prim = sim.stage.GetPrimAtPath("/World/Cone/geometry/material") + assert prim.GetAttribute("omniphysics:density").Get() == cfg.physics_material.density + # check sim playing + sim.play() + for _ in range(10): + sim.step() + + +def test_spawn_cone_with_all_deformable_props(sim): + """Test spawning of UsdGeomMesh prim for a cone with all deformable properties.""" + # Spawn cone + cfg = sim_utils.MeshConeCfg( + radius=1.0, + height=2.0, + deformable_props=DeformableBodyPropertiesCfg(mass=1.0), + visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(0.0, 0.75, 0.5)), + physics_material=DeformableBodyMaterialCfg(), + ) + prim = cfg.func("/World/Cone", cfg) + + # Check validity + assert prim.IsValid() + assert sim.stage.GetPrimAtPath("/World/Cone").IsValid() + assert sim.stage.GetPrimAtPath("/World/Cone/geometry/material").IsValid() + # Check properties + # -- deformable body + prim = sim.stage.GetPrimAtPath("/World/Cone") + assert prim.GetAttribute("omniphysics:deformableBodyEnabled").Get() is True + + # check sim playing + sim.play() + for _ in range(10): + sim.step() diff --git a/source/isaaclab_physx/test/sim/test_views_xform_prim_fabric.py b/source/isaaclab_physx/test/sim/test_views_xform_prim_fabric.py new file mode 100644 index 000000000000..4376c0e0b8ea --- /dev/null +++ b/source/isaaclab_physx/test/sim/test_views_xform_prim_fabric.py @@ -0,0 +1,106 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""PhysX Fabric backend tests for FrameView. + +Imports the shared contract tests and provides the Fabric-specific +``view_factory`` fixture (SimulationContext with use_fabric=True, +Camera prim type for Fabric SelectPrims compatibility). +""" + +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[3] / "isaaclab" / "test" / "sim")) + +from isaaclab.app import AppLauncher + +simulation_app = AppLauncher(headless=True).app + +import pytest # noqa: E402 +import torch # noqa: E402 +from frame_view_contract_utils import * # noqa: F401, F403, E402 +from frame_view_contract_utils import CHILD_OFFSET, ViewBundle # noqa: E402 +from isaaclab_physx.sim.views import FabricFrameView as FrameView # noqa: E402 + +from pxr import Gf, UsdGeom # noqa: E402 + +import isaaclab.sim as sim_utils # noqa: E402 + +pytestmark = pytest.mark.isaacsim_ci +PARENT_POS = (0.0, 0.0, 1.0) + + +@pytest.fixture(autouse=True) +def test_setup_teardown(): + sim_utils.create_new_stage() + sim_utils.update_stage() + yield + sim_utils.clear_stage() + sim_utils.SimulationContext.clear_instance() + + +def _skip_if_unavailable(device: str): + if device.startswith("cuda") and not torch.cuda.is_available(): + pytest.skip("CUDA not available") + if device == "cpu": + pytest.skip("Warp fabricarray operations on CPU have known issues") + + +# ------------------------------------------------------------------ +# Parent position helpers (via USD xformOps) +# ------------------------------------------------------------------ + + +def _get_parent_positions(num_envs, device="cpu"): + stage = sim_utils.get_current_stage() + xform_cache = UsdGeom.XformCache() + positions = [] + for i in range(num_envs): + prim = stage.GetPrimAtPath(f"/World/Parent_{i}") + tf = xform_cache.GetLocalToWorldTransform(prim) + t = tf.ExtractTranslation() + positions.append([float(t[0]), float(t[1]), float(t[2])]) + return torch.tensor(positions, dtype=torch.float32, device=device) + + +def _set_parent_positions(positions, num_envs): + from pxr import Sdf # noqa: PLC0415 + + stage = sim_utils.get_current_stage() + with Sdf.ChangeBlock(): + for i in range(num_envs): + prim = stage.GetPrimAtPath(f"/World/Parent_{i}") + pos = positions[i] + prim.GetAttribute("xformOp:translate").Set(Gf.Vec3d(float(pos[0]), float(pos[1]), float(pos[2]))) + + +# ------------------------------------------------------------------ +# Contract fixture +# ------------------------------------------------------------------ + + +@pytest.fixture +def view_factory(): + """Fabric factory: Camera child at CHILD_OFFSET under parent Xforms, with Fabric enabled.""" + + def factory(num_envs: int, device: str) -> ViewBundle: + _skip_if_unavailable(device) + + stage = sim_utils.get_current_stage() + for i in range(num_envs): + sim_utils.create_prim(f"/World/Parent_{i}", "Xform", translation=PARENT_POS, stage=stage) + sim_utils.create_prim(f"/World/Parent_{i}/Child", "Camera", translation=CHILD_OFFSET, stage=stage) + + sim_utils.SimulationContext(sim_utils.SimulationCfg(dt=0.01, device=device, use_fabric=True)) + view = FrameView("/World/Parent_.*/Child", device=device, sync_usd_on_fabric_write=True) + return ViewBundle( + view=view, + get_parent_pos=_get_parent_positions, + set_parent_pos=_set_parent_positions, + teardown=lambda: None, + ) + + return factory diff --git a/source/isaaclab_rl/changelog.d/.gitkeep b/source/isaaclab_rl/changelog.d/.gitkeep new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/source/isaaclab_rl/changelog.d/leapp_export_integration.rst b/source/isaaclab_rl/changelog.d/leapp_export_integration.rst new file mode 100644 index 000000000000..8a9a65b18d7f --- /dev/null +++ b/source/isaaclab_rl/changelog.d/leapp_export_integration.rst @@ -0,0 +1,5 @@ +Added +^^^^^ + +* Added RSL-RL LEAPP export scripts and integration tests for exporting trained + policies with semantic input, output, and state annotations. diff --git a/source/isaaclab_rl/config/extension.toml b/source/isaaclab_rl/config/extension.toml index 35ce26490606..6b5ae668f03e 100644 --- a/source/isaaclab_rl/config/extension.toml +++ b/source/isaaclab_rl/config/extension.toml @@ -1,7 +1,7 @@ [package] # Note: Semantic Versioning is used: https://semver.org/ -version = "0.5.0" +version = "0.5.1" # Description title = "Isaac Lab RL" diff --git a/source/isaaclab_rl/docs/CHANGELOG.rst b/source/isaaclab_rl/docs/CHANGELOG.rst index 9666e7214e81..0c4c4323ced7 100644 --- a/source/isaaclab_rl/docs/CHANGELOG.rst +++ b/source/isaaclab_rl/docs/CHANGELOG.rst @@ -1,6 +1,16 @@ Changelog --------- +0.5.1 (2026-04-21) +~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Locked h5py dependency to last stable version 3.15.1 to prevent package import errors on Windows with version 3.16.0. +* Updated skrl wrapper to support the new version of skrl 2.0. + + 0.5.0 (2026-3-04) ~~~~~~~~~~~~~~~~~~ diff --git a/source/isaaclab_rl/isaaclab_rl/rl_games/rl_games.py b/source/isaaclab_rl/isaaclab_rl/rl_games/rl_games.py index 0fcc217977d3..ccc16d29abaf 100644 --- a/source/isaaclab_rl/isaaclab_rl/rl_games/rl_games.py +++ b/source/isaaclab_rl/isaaclab_rl/rl_games/rl_games.py @@ -34,6 +34,7 @@ # needed to import for allowing type-hinting:gym.spaces.Box | None from __future__ import annotations +import contextlib from collections.abc import Callable from typing import TYPE_CHECKING @@ -51,6 +52,9 @@ ManagerBasedRLEnv, ) + with contextlib.suppress(ImportError): + from isaaclab_experimental.envs import DirectRLEnvWarp, ManagerBasedRLEnvWarp + """ Vectorized environment wrapper. """ @@ -118,9 +122,22 @@ def __init__( # NOTE: import here (not at module level) to avoid loading heavy env classes before Isaac Sim is initialized. from isaaclab.envs import DirectMARLEnv, DirectRLEnv, ManagerBasedRLEnv - if not isinstance(env.unwrapped, (ManagerBasedRLEnv, DirectRLEnv, DirectMARLEnv)): + try: + from isaaclab_experimental.envs import DirectRLEnvWarp, ManagerBasedRLEnvWarp + except ImportError: + DirectRLEnvWarp = None + ManagerBasedRLEnvWarp = None + + allowed_types = (ManagerBasedRLEnv, DirectRLEnv, DirectMARLEnv) + if DirectRLEnvWarp is not None: + allowed_types += (DirectRLEnvWarp,) + if ManagerBasedRLEnvWarp is not None: + allowed_types += (ManagerBasedRLEnvWarp,) + + if not isinstance(env.unwrapped, allowed_types): raise ValueError( - "The environment must be inherited from ManagerBasedRLEnv or DirectRLEnv. Environment type:" + "The environment must be inherited from ManagerBasedRLEnv / DirectRLEnv / DirectRLEnvWarp /" + " ManagerBasedRLEnvWarp. Environment type:" f" {type(env)}" ) # initialize the wrapper @@ -220,7 +237,7 @@ def class_name(cls) -> str: return cls.__name__ @property - def unwrapped(self) -> ManagerBasedRLEnv | DirectRLEnv: + def unwrapped(self) -> ManagerBasedRLEnv | DirectRLEnv | DirectRLEnvWarp | ManagerBasedRLEnvWarp: """Returns the base environment of the wrapper. This will be the bare :class:`gymnasium.Env` environment, underneath all layers of wrappers. diff --git a/source/isaaclab_rl/isaaclab_rl/rsl_rl/vecenv_wrapper.py b/source/isaaclab_rl/isaaclab_rl/rsl_rl/vecenv_wrapper.py index 7e753c0f7a2a..5a3fdcd47164 100644 --- a/source/isaaclab_rl/isaaclab_rl/rsl_rl/vecenv_wrapper.py +++ b/source/isaaclab_rl/isaaclab_rl/rsl_rl/vecenv_wrapper.py @@ -4,6 +4,7 @@ # SPDX-License-Identifier: BSD-3-Clause from __future__ import annotations +import contextlib from typing import TYPE_CHECKING import gymnasium as gym @@ -17,6 +18,9 @@ ManagerBasedRLEnv, ) + with contextlib.suppress(ImportError): + from isaaclab_experimental.envs import DirectRLEnvWarp, ManagerBasedRLEnvWarp + class RslRlVecEnvWrapper(VecEnv): """Wraps around Isaac Lab environment for the RSL-RL library @@ -48,17 +52,24 @@ def __init__(self, env: ManagerBasedRLEnv | DirectRLEnv, clip_actions: float | N from isaaclab.envs import DirectRLEnv, ManagerBasedEnv, ManagerBasedRLEnv try: - from isaaclab_experimental.envs import DirectRLEnvWarp + from isaaclab_experimental.envs import DirectRLEnvWarp, ManagerBasedEnvWarp, ManagerBasedRLEnvWarp except ImportError: DirectRLEnvWarp = None + ManagerBasedEnvWarp = None + ManagerBasedRLEnvWarp = None allowed_types = (ManagerBasedRLEnv, ManagerBasedEnv, DirectRLEnv) if DirectRLEnvWarp is not None: allowed_types += (DirectRLEnvWarp,) + if ManagerBasedEnvWarp is not None: + allowed_types += (ManagerBasedEnvWarp,) + if ManagerBasedRLEnvWarp is not None: + allowed_types += (ManagerBasedRLEnvWarp,) if not isinstance(env.unwrapped, allowed_types): raise ValueError( - "The environment must be inherited from ManagerBasedRLEnv or DirectRLEnv. Environment type:" + "The environment must be inherited from ManagerBasedRLEnv / DirectRLEnv / DirectRLEnvWarp /" + " ManagerBasedRLEnvWarp. Environment type:" f" {type(env)}" ) @@ -121,7 +132,7 @@ def class_name(cls) -> str: return cls.__name__ @property - def unwrapped(self) -> ManagerBasedRLEnv | DirectRLEnv: + def unwrapped(self) -> ManagerBasedRLEnv | DirectRLEnv | DirectRLEnvWarp | ManagerBasedRLEnvWarp: """Returns the base environment of the wrapper. This will be the bare :class:`gymnasium.Env` environment, underneath all layers of wrappers. diff --git a/source/isaaclab_rl/isaaclab_rl/sb3.py b/source/isaaclab_rl/isaaclab_rl/sb3.py index 1b50f8be9c78..90ca0fd3b854 100644 --- a/source/isaaclab_rl/isaaclab_rl/sb3.py +++ b/source/isaaclab_rl/isaaclab_rl/sb3.py @@ -18,6 +18,7 @@ # needed to import for allowing type-hinting: torch.Tensor | dict[str, torch.Tensor] from __future__ import annotations +import contextlib import warnings from typing import TYPE_CHECKING, Any @@ -32,6 +33,9 @@ if TYPE_CHECKING: from isaaclab.envs import DirectRLEnv, ManagerBasedRLEnv + with contextlib.suppress(ImportError): + from isaaclab_experimental.envs import DirectRLEnvWarp, ManagerBasedRLEnvWarp + # remove SB3 warnings because PPO with bigger net actually benefits from GPU warnings.filterwarnings("ignore", message="You are trying to run PPO on the GPU") @@ -150,9 +154,22 @@ def __init__(self, env: ManagerBasedRLEnv | DirectRLEnv, fast_variant: bool = Tr # NOTE: import here (not at module level) to avoid loading heavy env classes before Isaac Sim is initialized. from isaaclab.envs import DirectRLEnv, ManagerBasedRLEnv - if not isinstance(env.unwrapped, (ManagerBasedRLEnv, DirectRLEnv)): + try: + from isaaclab_experimental.envs import DirectRLEnvWarp, ManagerBasedRLEnvWarp + except ImportError: + DirectRLEnvWarp = None + ManagerBasedRLEnvWarp = None + + allowed_types = (ManagerBasedRLEnv, DirectRLEnv) + if DirectRLEnvWarp is not None: + allowed_types += (DirectRLEnvWarp,) + if ManagerBasedRLEnvWarp is not None: + allowed_types += (ManagerBasedRLEnvWarp,) + + if not isinstance(env.unwrapped, allowed_types): raise ValueError( - "The environment must be inherited from ManagerBasedRLEnv or DirectRLEnv. Environment type:" + "The environment must be inherited from ManagerBasedRLEnv / DirectRLEnv / DirectRLEnvWarp /" + " ManagerBasedRLEnvWarp. Environment type:" f" {type(env)}" ) # initialize the wrapper @@ -186,7 +203,7 @@ def class_name(cls) -> str: return cls.__name__ @property - def unwrapped(self) -> ManagerBasedRLEnv | DirectRLEnv: + def unwrapped(self) -> ManagerBasedRLEnv | DirectRLEnv | DirectRLEnvWarp | ManagerBasedRLEnvWarp: """Returns the base environment of the wrapper. This will be the bare :class:`gymnasium.Env` environment, underneath all layers of wrappers. diff --git a/source/isaaclab_rl/isaaclab_rl/skrl.py b/source/isaaclab_rl/isaaclab_rl/skrl.py index 6ae5eb28f9b7..ebd66697fbb1 100644 --- a/source/isaaclab_rl/isaaclab_rl/skrl.py +++ b/source/isaaclab_rl/isaaclab_rl/skrl.py @@ -43,7 +43,7 @@ def SkrlVecEnvWrapper( env: ManagerBasedRLEnv | DirectRLEnv | DirectMARLEnv, - ml_framework: Literal["torch", "jax", "jax-numpy"] = "torch", + ml_framework: Literal["torch", "jax", "warp"] = "torch", wrapper: Literal["auto", "isaaclab", "isaaclab-single-agent", "isaaclab-multi-agent"] = "isaaclab", ): """Wraps around Isaac Lab environment for skrl. @@ -70,10 +70,22 @@ def SkrlVecEnvWrapper( # NOTE: import here (not at module level) to avoid loading heavy env classes before Isaac Sim is initialized. from isaaclab.envs import DirectMARLEnv, DirectRLEnv, ManagerBasedRLEnv - if not isinstance(env.unwrapped, (ManagerBasedRLEnv, DirectRLEnv, DirectMARLEnv)): + try: + from isaaclab_experimental.envs import DirectRLEnvWarp, ManagerBasedRLEnvWarp + except ImportError: + DirectRLEnvWarp = None + ManagerBasedRLEnvWarp = None + + allowed_types = (ManagerBasedRLEnv, DirectRLEnv, DirectMARLEnv) + if DirectRLEnvWarp is not None: + allowed_types += (DirectRLEnvWarp,) + if ManagerBasedRLEnvWarp is not None: + allowed_types += (ManagerBasedRLEnvWarp,) + + if not isinstance(env.unwrapped, allowed_types): raise ValueError( - "The environment must be inherited from ManagerBasedRLEnv, DirectRLEnv or DirectMARLEnv. Environment type:" - f" {type(env)}" + "The environment must be inherited from ManagerBasedRLEnv, DirectRLEnv, DirectMARLEnv," + f" DirectRLEnvWarp or ManagerBasedRLEnvWarp. Environment type: {type(env)}" ) # import statements according to the ML framework @@ -81,9 +93,11 @@ def SkrlVecEnvWrapper( from skrl.envs.wrappers.torch import wrap_env elif ml_framework.startswith("jax"): from skrl.envs.wrappers.jax import wrap_env + elif ml_framework.startswith("warp"): + from skrl.envs.wrappers.warp import wrap_env else: - ValueError( - f"Invalid ML framework for skrl: {ml_framework}. Available options are: 'torch', 'jax' or 'jax-numpy'" + raise ValueError( + f"Invalid ML framework for skrl: {ml_framework}. Available options are: 'torch', 'jax', 'warp'" ) # wrap and return the environment diff --git a/source/isaaclab_rl/setup.py b/source/isaaclab_rl/setup.py index 5357dcee6856..53255aa55b4f 100644 --- a/source/isaaclab_rl/setup.py +++ b/source/isaaclab_rl/setup.py @@ -26,7 +26,7 @@ # configuration management "hydra-core", # data collection - "h5py", + "h5py==3.15.1", # basic logger "tensorboard", # video recording @@ -40,7 +40,7 @@ # Extra dependencies for RL agents EXTRAS_REQUIRE = { "sb3": ["stable-baselines3>=2.6", "tqdm", "rich"], # tqdm/rich for progress bar - "skrl": ["skrl>=1.4.3"], + "skrl": ["skrl>=2.0.0"], "rl-games": [ "aiohttp==3.13.3", "rl-games @ git+https://github.com/isaac-sim/rl_games.git@python3.11", @@ -69,17 +69,14 @@ keywords=EXTENSION_TOML_DATA["package"]["keywords"], include_package_data=True, package_data={"": ["*.pyi"]}, - python_requires=">=3.10", + python_requires=">=3.12", install_requires=INSTALL_REQUIRES, dependency_links=PYTORCH_INDEX_URL, extras_require=EXTRAS_REQUIRE, packages=["isaaclab_rl"], classifiers=[ "Natural Language :: English", - "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", - "Isaac Sim :: 5.0.0", - "Isaac Sim :: 5.1.0", "Isaac Sim :: 6.0.0", ], zip_safe=False, diff --git a/source/isaaclab_rl/test/export/test_rsl_rl_direct_export_flow.py b/source/isaaclab_rl/test/export/test_rsl_rl_direct_export_flow.py new file mode 100644 index 000000000000..ecc155c666e5 --- /dev/null +++ b/source/isaaclab_rl/test/export/test_rsl_rl_direct_export_flow.py @@ -0,0 +1,194 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Direct-env export integration test with subprocess-side gym re-registration.""" + +from __future__ import annotations + +import argparse +import importlib +import importlib.util +import os +import runpy +import shutil +import subprocess +import sys +import tempfile +import types +from pathlib import Path + +import gymnasium as gym +import pytest + +_THIS_FILE = Path(__file__).resolve() +_REPO_ROOT = str(_THIS_FILE.parents[4]) +_EXPORT_SCRIPT = os.path.join(_REPO_ROOT, "scripts", "reinforcement_learning", "leapp", "rsl_rl", "export.py") +_THIS_SCRIPT = str(_THIS_FILE) +_TASK_NAME = "Isaac-Velocity-Flat-Anymal-C-Direct-v0" +_PACKAGE_NAME = "_isaaclab_test_tutorial_anymal_c" +_MODULE_NAME = f"{_PACKAGE_NAME}.anymal_c_env" +_CFG_MODULE_NAME = f"{_PACKAGE_NAME}.anymal_c_env_cfg" +_RUNTIME_MODULE_NAME = "_isaaclab_test_tutorial_anymal_c_runtime" +_TUTORIAL_ENV_PATH = Path(_REPO_ROOT) / "scripts" / "tutorials" / "06_deploy" / "anymal_c_env.py" + + +def _export_command(task_name: str, export_dir: str) -> list[str]: + """Build a subprocess command that runs this file in helper mode.""" + return [ + sys.executable, + _THIS_SCRIPT, + "--task", + task_name, + "--use_pretrained_checkpoint", + "--export_save_path", + export_dir, + "--disable_graph_visualization", + "--headless", + ] + + +def _artifact_dir(export_dir: str, task_name: str) -> str: + """Return the LEAPP artifact directory for the exported task.""" + return os.path.join(export_dir, task_name) + + +def _load_tutorial_env_class(): + """Load the tutorial env through a synthetic package for relative imports.""" + module = sys.modules.get(_MODULE_NAME) + if module is not None: + return module.AnymalCEnv + + package = types.ModuleType(_PACKAGE_NAME) + package.__path__ = [] # type: ignore[attr-defined] + sys.modules.setdefault(_PACKAGE_NAME, package) + + cfg_module = importlib.import_module("isaaclab_tasks.direct.anymal_c.anymal_c_env_cfg") + sys.modules[_CFG_MODULE_NAME] = cfg_module + + spec = importlib.util.spec_from_file_location(_MODULE_NAME, _TUTORIAL_ENV_PATH) + if spec is None or spec.loader is None: + raise ImportError(f"Could not create module spec for tutorial env: {_TUTORIAL_ENV_PATH}") + + module = importlib.util.module_from_spec(spec) + sys.modules[_MODULE_NAME] = module + spec.loader.exec_module(module) + return module.AnymalCEnv + + +class _LazyTutorialEnvModule(types.ModuleType): + """Resolve the tutorial env class only when gym imports the entrypoint.""" + + def __getattr__(self, name: str): + if name != "AnymalCEnv": + raise AttributeError(name) + env_class = _load_tutorial_env_class() + setattr(self, name, env_class) + return env_class + + +def _install_lazy_runtime_module() -> str: + """Install a lazy module so gym can defer tutorial env imports.""" + module = sys.modules.get(_RUNTIME_MODULE_NAME) + if module is None: + sys.modules[_RUNTIME_MODULE_NAME] = _LazyTutorialEnvModule(_RUNTIME_MODULE_NAME) + return _RUNTIME_MODULE_NAME + + +def _reregister_task(task_name: str) -> None: + """Override the direct task registration to point at the tutorial env.""" + import isaaclab_tasks.direct.anymal_c # noqa: F401 + + original_spec = gym.spec(task_name) + original_kwargs = dict(original_spec.kwargs) + runtime_module_name = _install_lazy_runtime_module() + + gym.registry.pop(task_name, None) + gym.register( + id=task_name, + entry_point=f"{runtime_module_name}:AnymalCEnv", + disable_env_checker=original_spec.disable_env_checker, + kwargs=original_kwargs, + ) + + +def _run_export_subprocess_entrypoint() -> None: + """Run export.py after re-registering the direct task in-process.""" + parser = argparse.ArgumentParser(add_help=False) + parser.add_argument("--task", required=True) + args, remaining_args = parser.parse_known_args() + + _reregister_task(args.task) + export_script_dir = os.path.dirname(_EXPORT_SCRIPT) + sys.argv = [_EXPORT_SCRIPT, "--task", args.task, *remaining_args] + if export_script_dir not in sys.path: + sys.path.insert(0, export_script_dir) + runpy.run_path(_EXPORT_SCRIPT, run_name="__main__") + + +def _build_failure_context(result: subprocess.CompletedProcess[str], artifact_dir: str) -> str: + """Return debug context for subprocess and export artifacts.""" + export_dir = os.path.dirname(artifact_dir) + log_txt_path = os.path.join(artifact_dir, "log.txt") + leapp_tail = "" + if os.path.isfile(log_txt_path): + with open(log_txt_path) as file: + last_lines = file.readlines()[-50:] + leapp_tail = f"\n--- leapp log.txt (last 50 lines) ---\n{''.join(last_lines)}" + + try: + export_dir_contents = sorted(os.listdir(export_dir)) + except FileNotFoundError: + export_dir_contents = [""] + + try: + artifact_dir_contents = sorted(os.listdir(artifact_dir)) + except FileNotFoundError: + artifact_dir_contents = [""] + + return ( + f"--- export_dir ---\n{export_dir}\n" + f"--- export_dir contents ---\n{export_dir_contents}\n" + f"--- artifact_dir ---\n{artifact_dir}\n" + f"--- artifact_dir contents ---\n{artifact_dir_contents}\n" + f"--- stdout ---\n{result.stdout[-3000:]}\n" + f"--- stderr ---\n{result.stderr[-3000:]}" + f"{leapp_tail}" + ) + + +def test_direct_env_export_flow(): + """Run export.py against the tutorial direct env and assert artifacts are created.""" + export_dir = tempfile.mkdtemp(prefix="isaaclab-direct-export-") + artifact_dir = _artifact_dir(export_dir, _TASK_NAME) + shutil.rmtree(artifact_dir, ignore_errors=True) + + result = subprocess.run( + _export_command(_TASK_NAME, export_dir), + cwd=_REPO_ROOT, + capture_output=True, + text=True, + timeout=6000, + ) + + if "pre-trained checkpoint is currently unavailable" in result.stdout: + pytest.skip(f"No pretrained checkpoint available for {_TASK_NAME}") + + if result.returncode != 0: + pytest.fail(f"export.py exited with code {result.returncode}.\n{_build_failure_context(result, artifact_dir)}") + + onnx_path = os.path.join(artifact_dir, f"{_TASK_NAME}.onnx") + yaml_path = os.path.join(artifact_dir, f"{_TASK_NAME}.yaml") + log_path = os.path.join(artifact_dir, "log.txt") + + if not os.path.isfile(onnx_path): + pytest.fail(f"Missing .onnx export at {onnx_path}.\n{_build_failure_context(result, artifact_dir)}") + if not os.path.isfile(yaml_path): + pytest.fail(f"Missing .yaml export at {yaml_path}.\n{_build_failure_context(result, artifact_dir)}") + if not os.path.isfile(log_path): + pytest.fail(f"Missing log.txt at {log_path}.\n{_build_failure_context(result, artifact_dir)}") + + +if __name__ == "__main__": + _run_export_subprocess_entrypoint() diff --git a/source/isaaclab_rl/test/export/test_rsl_rl_export_flow.py b/source/isaaclab_rl/test/export/test_rsl_rl_export_flow.py new file mode 100644 index 000000000000..5606be484286 --- /dev/null +++ b/source/isaaclab_rl/test/export/test_rsl_rl_export_flow.py @@ -0,0 +1,151 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Export pipeline integration tests. + +Each test calls ``export.py`` as a subprocess so that Isaac Sim's AppLauncher +is fully isolated per task and the export logic is not duplicated here. +The export artifacts land in the default checkpoint directory; only the +per-task export subdirectory is removed after each test. +""" + +import os +import shutil +import subprocess + +import pytest + +# Root of the repository (three levels up from this file). +_REPO_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", "..", "..")) +_EXPORT_SCRIPT = os.path.join("scripts", "reinforcement_learning", "leapp", "rsl_rl", "export.py") + + +# Tasks with confirmed pretrained checkpoints (Direct and no-checkpoint tasks excluded). +TASKS = [ + # Classic + "Isaac-Ant-v0", + "Isaac-Cartpole-v0", + # Navigation + "Isaac-Navigation-Flat-Anymal-C-v0", + "Isaac-Navigation-Flat-Anymal-C-Play-v0", + # Locomotion Velocity + "Isaac-Velocity-Flat-Anymal-B-v0", + "Isaac-Velocity-Flat-Anymal-B-Play-v0", + "Isaac-Velocity-Rough-Anymal-B-v0", + "Isaac-Velocity-Rough-Anymal-B-Play-v0", + "Isaac-Velocity-Flat-Anymal-C-v0", + "Isaac-Velocity-Flat-Anymal-C-Play-v0", + "Isaac-Velocity-Rough-Anymal-C-v0", + "Isaac-Velocity-Rough-Anymal-C-Play-v0", + "Isaac-Velocity-Flat-Anymal-D-v0", + "Isaac-Velocity-Flat-Anymal-D-Play-v0", + "Isaac-Velocity-Rough-Anymal-D-v0", + "Isaac-Velocity-Rough-Anymal-D-Play-v0", + "Isaac-Velocity-Flat-Cassie-v0", + "Isaac-Velocity-Flat-Cassie-Play-v0", + "Isaac-Velocity-Rough-Cassie-v0", + "Isaac-Velocity-Rough-Cassie-Play-v0", + "Isaac-Velocity-Flat-G1-v0", + "Isaac-Velocity-Flat-G1-Play-v0", + "Isaac-Velocity-Rough-G1-v0", + "Isaac-Velocity-Rough-G1-Play-v0", + "Isaac-Velocity-Flat-H1-v0", + "Isaac-Velocity-Flat-H1-Play-v0", + "Isaac-Velocity-Rough-H1-v0", + "Isaac-Velocity-Rough-H1-Play-v0", + "Isaac-Velocity-Flat-Spot-v0", + "Isaac-Velocity-Flat-Spot-Play-v0", + "Isaac-Velocity-Flat-Unitree-A1-v0", + "Isaac-Velocity-Flat-Unitree-A1-Play-v0", + "Isaac-Velocity-Rough-Unitree-A1-v0", + "Isaac-Velocity-Rough-Unitree-A1-Play-v0", + "Isaac-Velocity-Flat-Unitree-Go1-v0", + "Isaac-Velocity-Flat-Unitree-Go1-Play-v0", + "Isaac-Velocity-Rough-Unitree-Go1-v0", + "Isaac-Velocity-Rough-Unitree-Go1-Play-v0", + "Isaac-Velocity-Flat-Unitree-Go2-v0", + "Isaac-Velocity-Flat-Unitree-Go2-Play-v0", + "Isaac-Velocity-Rough-Unitree-Go2-v0", + "Isaac-Velocity-Rough-Unitree-Go2-Play-v0", + # Manipulation Reach + "Isaac-Reach-Franka-v0", + "Isaac-Reach-Franka-Play-v0", + "Isaac-Reach-UR10-v0", + "Isaac-Reach-UR10-Play-v0", + # Manipulation Lift + "Isaac-Lift-Cube-Franka-v0", + "Isaac-Lift-Cube-Franka-Play-v0", + # Manipulation Cabinet + "Isaac-Open-Drawer-Franka-v0", + "Isaac-Open-Drawer-Franka-Play-v0", + # Dexsuite + "Isaac-Dexsuite-Kuka-Allegro-Reorient-v0", + "Isaac-Dexsuite-Kuka-Allegro-Reorient-Play-v0", + "Isaac-Dexsuite-Kuka-Allegro-Lift-v0", + "Isaac-Dexsuite-Kuka-Allegro-Lift-Play-v0", +] + + +def _export_dir(task_name: str) -> str: + """Return the directory where export.py writes artifacts for *task_name*.""" + train_task = task_name.replace("-Play", "") + return os.path.join(_REPO_ROOT, ".pretrained_checkpoints", "rsl_rl", train_task, task_name) + + +@pytest.mark.parametrize("task_name", TASKS) +def test_export_flow(task_name): + """Run export.py for *task_name* and assert the expected artifacts are created.""" + export_dir = _export_dir(task_name) + + try: + result = subprocess.run( + [ + "./isaaclab.sh", + "-p", + _EXPORT_SCRIPT, + "--task", + task_name, + "--use_pretrained_checkpoint", + "--disable_graph_visualization", + "--headless", + ], + cwd=_REPO_ROOT, + capture_output=True, + text=True, + timeout=600, + ) + + # Gracefully skip tasks whose checkpoint isn't published yet + if "pre-trained checkpoint is currently unavailable" in result.stdout: + pytest.skip(f"No pretrained checkpoint available for {task_name.replace('-Play', '')}") + + # Skip tasks whose checkpoint was saved with an older rsl_rl architecture + # that does not use the 'actor_state_dict' key expected by the current runner + if "actor_state_dict" in result.stderr: + pytest.skip( + f"{task_name} checkpoint uses an older network architecture incompatible with the current rsl_rl runner" + ) + + # Surface stdout/stderr on failure for easier debugging + if result.returncode != 0: + log_txt_path = os.path.join(export_dir, "log.txt") + leapp_tail = "" + if os.path.isfile(log_txt_path): + with open(log_txt_path) as f: + last_lines = f.readlines()[-50:] + leapp_tail = f"\n--- leapp log.txt (last 50 lines) ---\n{''.join(last_lines)}" + pytest.fail( + f"export.py exited with code {result.returncode}.\n" + f"--- stdout ---\n{result.stdout[-3000:]}\n" + f"--- stderr ---\n{result.stderr[-3000:]}" + f"{leapp_tail}" + ) + + assert os.path.isfile(os.path.join(export_dir, f"{task_name}.onnx")), "Missing .onnx export" + assert os.path.isfile(os.path.join(export_dir, f"{task_name}.yaml")), "Missing .yaml export" + assert os.path.isfile(os.path.join(export_dir, "log.txt")), "Missing log.txt" + + finally: + shutil.rmtree(export_dir, ignore_errors=True) diff --git a/source/isaaclab_tasks/changelog.d/.gitkeep b/source/isaaclab_tasks/changelog.d/.gitkeep new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/source/isaaclab_tasks/changelog.d/antoiner-rename-newton-presets.rst b/source/isaaclab_tasks/changelog.d/antoiner-rename-newton-presets.rst new file mode 100644 index 000000000000..ae311dd1071b --- /dev/null +++ b/source/isaaclab_tasks/changelog.d/antoiner-rename-newton-presets.rst @@ -0,0 +1,25 @@ +Changed +^^^^^^^ + +* **Breaking:** Renamed the Newton-backend solver presets to a ``newton_`` + prefix so they group together in autocomplete and read distinctly from the + Newton backend label, package, and visualizer. The change is shimmed by + deprecation aliases (see ``Deprecated`` below), but workflows that iterate + ``__dataclass_fields__`` directly or treat :exc:`FutureWarning` as an error + will need updates. Migration: rename the field in any + :class:`~isaaclab_tasks.utils.hydra.PresetCfg` subclass and update CLI + invocations (``presets=...`` and ``env.=...``): + + - ``newton`` -> ``newton_mjwarp`` + - ``kamino`` -> ``newton_kamino`` + +Deprecated +^^^^^^^^^^ + +* Deprecated the legacy ``newton`` and ``kamino`` preset names. They still + resolve to ``newton_mjwarp`` and ``newton_kamino`` respectively but emit a + :exc:`FutureWarning` and will be removed in a future release. Update CLI + overrides (``presets=newton`` -> ``presets=newton_mjwarp``; + ``presets=kamino`` -> ``presets=newton_kamino``) and any + :class:`~isaaclab_tasks.utils.hydra.PresetCfg` field declarations + (``newton: NewtonCfg = ...`` -> ``newton_mjwarp: NewtonCfg = ...``). diff --git a/source/isaaclab_tasks/changelog.d/g1-rough-terrain-wip.rst b/source/isaaclab_tasks/changelog.d/g1-rough-terrain-wip.rst new file mode 100644 index 000000000000..9efbf82b8bf6 --- /dev/null +++ b/source/isaaclab_tasks/changelog.d/g1-rough-terrain-wip.rst @@ -0,0 +1,11 @@ +Added +^^^^^ + +* Added Newton rough terrain support for the G1 biped locomotion velocity + env. The only engine-specific change is a ~1.7x ``max_iterations`` preset on + :class:`~isaaclab_tasks.manager_based.locomotion.velocity.config.g1.agents.rsl_rl_ppo_cfg.G1RoughPPORunnerCfg` + (Newton = 5000, PhysX = 3000). PhysX saturates near iter 3000 on both + reward (≈ +18) and episode length (≈ 980) and does not meaningfully + improve further; Newton reaches the same (reward, ep_len) quality at + iter 5000. The iteration budget is bumped rather than tuning physics + or reward terms. diff --git a/source/isaaclab_tasks/changelog.d/leapp_export_integration.rst b/source/isaaclab_tasks/changelog.d/leapp_export_integration.rst new file mode 100644 index 000000000000..94a128b6416f --- /dev/null +++ b/source/isaaclab_tasks/changelog.d/leapp_export_integration.rst @@ -0,0 +1,5 @@ +Added +^^^^^ + +* Added LEAPP-compatible policy deployment tutorials and tracing-compatible task + observation helpers for exported policy workflows. diff --git a/source/isaaclab_tasks/changelog.d/mtrepte-expand_viz_markers.skip b/source/isaaclab_tasks/changelog.d/mtrepte-expand_viz_markers.skip new file mode 100644 index 000000000000..a23b7c7322b3 --- /dev/null +++ b/source/isaaclab_tasks/changelog.d/mtrepte-expand_viz_markers.skip @@ -0,0 +1 @@ +Marker visualization changes are covered by the isaaclab fragment. diff --git a/source/isaaclab_tasks/changelog.d/pr-5458-merge-develop.rst b/source/isaaclab_tasks/changelog.d/pr-5458-merge-develop.rst new file mode 100644 index 000000000000..cd4dc7e674d4 --- /dev/null +++ b/source/isaaclab_tasks/changelog.d/pr-5458-merge-develop.rst @@ -0,0 +1,10 @@ +Changed +^^^^^^^ + +* Updated classic Ant/Humanoid manager-based environments and direct in-hand + manipulation environments to read body incoming wrenches from + :class:`~isaaclab.sensors.JointWrenchSensor` instead of + ``ArticulationData.body_incoming_joint_wrench_b``. Add a + :class:`~isaaclab.sensors.JointWrenchSensorCfg` to the scene and pass its + :class:`~isaaclab.managers.SceneEntityCfg` as ``sensor_cfg``. The classic + Ant/Humanoid Newton presets now use the same wrench observations as PhysX. diff --git a/source/isaaclab_tasks/changelog.d/rendering-test-flakiness.skip b/source/isaaclab_tasks/changelog.d/rendering-test-flakiness.skip new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/source/isaaclab_tasks/changelog.d/rwiltz-restore-legacy-teleop.rst b/source/isaaclab_tasks/changelog.d/rwiltz-restore-legacy-teleop.rst new file mode 100644 index 000000000000..59e71ddc3984 --- /dev/null +++ b/source/isaaclab_tasks/changelog.d/rwiltz-restore-legacy-teleop.rst @@ -0,0 +1,8 @@ +Added +^^^^^ + +* Added legacy ``teleop_devices`` configuration (``OpenXRDeviceCfg``, + ``ManusViveCfg``, ``GR1T2RetargeterCfg``) to + :class:`~isaaclab_tasks.manager_based.manipulation.pick_place.pickplace_gr1t2_env_cfg.PickPlaceGR1T2EnvCfg` + alongside the existing ``isaac_teleop`` pipeline, enabling CI validation + via ``--teleop_device=handtracking``. diff --git a/source/isaaclab_tasks/config/extension.toml b/source/isaaclab_tasks/config/extension.toml index 1f005f0f52f2..273ae57d2cb9 100644 --- a/source/isaaclab_tasks/config/extension.toml +++ b/source/isaaclab_tasks/config/extension.toml @@ -1,7 +1,7 @@ [package] # Note: Semantic Versioning is used: https://semver.org/ -version = "1.5.18" +version = "1.5.34" # Description title = "Isaac Lab Environments" diff --git a/source/isaaclab_tasks/docs/CHANGELOG.rst b/source/isaaclab_tasks/docs/CHANGELOG.rst index 1eadbdb091f1..2044f807afc5 100644 --- a/source/isaaclab_tasks/docs/CHANGELOG.rst +++ b/source/isaaclab_tasks/docs/CHANGELOG.rst @@ -1,6 +1,232 @@ Changelog --------- +1.5.34 (2026-04-30) +~~~~~~~~~~~~~~~~~~~ +Added +^^^^^ + +* Added Flexiv Rizon 4s gear assembly environment with Grav parallel gripper, including + training, ROS inference, and deterministic play/debug configurations. +* Added EE-grasp keypoint reward terms (``keypoint_ee_grasp_error``, ``keypoint_ee_grasp_error_exp``) + for tracking end-effector alignment with the grasp-corrected pose. +* Added quaternion noise model (``ResetSampledQuaternionNoiseModelCfg``) for Rizon 4s + gear shaft orientation observations. + +Fixed +^^^^^ + +* Fixed quaternion w-component indexing in gear assembly observation functions to match XYZW convention. + + +1.5.33 (2026-04-30) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Re-enabled ``add_base_mass`` randomization on H1 and Cassie in their + rough-terrain configs (previously ``= None`` per the pre-existing biped + convention). H1 uses the shared log-uniform scale default from + ``EventsCfg``; Cassie overrides to ``(1.0, 1.25)`` asymmetric heavier-bias + (never lighter than nominal). Symmetric ±25% regressed Cassie reward by + 40% vs disabled due to closed-loop Achilles coupling destabilizing on + lighter pelvis mass; ``(1.0, 1.25)`` recovers to 90% of the + mass-rand-disabled baseline while retaining the domain-randomization + benefit. + + +1.5.32 (2026-04-30) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Refactored rendering correctness tests under ``source/isaaclab_tasks/test/``: shared ``rendering_test_utils.py``, + split ``test_rendering_*`` modules (cartpole, Dexsuite Kuka Allegro lift, shadow hand) with ``*_kitless`` variants, + and Newton + OVRTX golden images. Newton + ``ovrtx_renderer`` test cases remain skipped on GitHub Actions temporarily + until they can run on GitHub Actions. + + +1.5.31 (2026-04-29) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added benchmark extraction for ``Metrics/success_rate`` and survival + success logging for direct cartpole camera environments. + + +1.5.30 (2026-04-28) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added Kamino solver physics presets to direct and manager-based environment + configs: cartpole and ant. + +Changed +^^^^^^^ + +* Updated skrl agent configuration files to support skrl 2.0. + + +1.5.29 (2026-04-27) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Enabled Newton rough-terrain locomotion training on the remaining + quadrupeds (Go1, Go2, A1, Anymal-B, Anymal-C), bipeds (H1, Cassie), + Digit, and G1 on top of Octi's Anymal-D work cherry-picked from + PR #5225. +* Hoisted the per-env Anymal-D ``RoughPhysicsCfg`` (MJWarp solver + + collision pipeline) into the shared + :class:`~isaaclab_tasks.manager_based.locomotion.velocity.velocity_env_cfg.LocomotionVelocityRoughEnvCfg` + so every rough-terrain env inherits identical physics. The shared + preset opts in to ``default_shape_cfg=NewtonShapeCfg(margin=0.01)``, + which is the single most important Newton setting for rough terrain. +* Added Go1 Newton-only leg armature preset to improve rough-terrain + training stability on lightweight quadrupeds. + +Changed +^^^^^^^ + +* Replaced the additive ``(-5, 5)`` kg default on + ``EventsCfg.add_base_mass`` with a multiplicative ``(1/1.25, 1.25)`` + log-uniform scale (``operation="scale"``, + ``distribution="log_uniform"``). Scale-invariant across robot sizes + with geometric mean 1.0; removes the need for per-robot + ``(-1.0, 3.0)`` additive overrides on A1/Go1/Go2. + + +1.5.28 (2026-04-27) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Updated stack-event utilities to enable optional extensions via + ``isaacsim.core.experimental.utils.app.enable_extension`` (non-deprecated Isaac Sim path). + + +1.5.27 (2026-04-27) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Refactored Franka cube-stack manager-based environment configs (IK-relative, visuomotor, and joint-position + variants under ``stack/config/franka/``) to build on :class:`~isaaclab_tasks.manager_based.manipulation.stack.stack_env_cfg.StackEnvCfg`, + including explicit cube spawns with semantic tags, gripper actions where applicable, end-effector + :class:`~isaaclab.sensors.frame_transformer.frame_transformer_cfg.FrameTransformerCfg`, and default Franka poses + via articulation ``InitialStateCfg`` instead of a reset-time default-pose event. +* Changed GR1T2 and Unitree G1 Inspire pick-place environment configs to define ``idle_action`` as a plain Python + sequence instead of ``torch.tensor``, dropping the ``torch`` import from those modules. + + +1.5.26 (2026-04-27) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Migrated golden images ``source/isaaclab_tasks/test/golden_images/**/*.png`` to Git LFS. + + +1.5.25 (2026-04-23) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Migrated all data property accesses from ``wp.to_torch(data.property)`` to + ``data.property.torch`` to match the new :class:`~isaaclab.utils.warp.ProxyArray` + return type introduced in ``isaaclab`` 4.6.13. + + +1.5.24 (2026-04-22) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Updated locomotion :class:`~isaaclab.sensors.ray_caster.ray_caster_cfg.RayCasterCfg` + height-scanner defaults to spawn a ``raycaster`` Xform child under the robot attachment link + (using :class:`~isaaclab.sim.spawners.sensors.sensors_cfg.RayCasterXformCfg`) so the sensor + works with Newton site-based :class:`~isaaclab.sim.views.FrameView` tracking. +* Updated all sensor configurations to use :class:`~isaaclab.sim.views.FrameView` instead of + the deprecated ``XformPrimView``. + + +1.5.23 (2026-04-21) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Refreshed Newton Warp renderer golden images for Dexsuite Kuka-Allegro environment case in + ``test_rendering_correctness`` because Newton Warp renderer honors visibility of prims now. + + +1.5.22 (2026-04-20) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed rendering correctness tests to use a shared environment seed constant, pass ``seed`` into + :meth:`gymnasium.Env.reset`, and aggregate per-data-type validation failures into a single + ``pytest.fail`` message in ``test_rendering_correctness``. +* Refreshed Newton Warp renderer golden images in ``test_rendering_correctness`` so image baselines match the current + camera output after Newton shape color alignment and the clear background color change. + +1.5.21 (2026-04-13) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Replaced ``resolve_preset_defaults`` with :func:`~isaaclab_tasks.utils.hydra.resolve_presets` + which resolves all presets in one pass with CLI selection support. + +Added +^^^^^ + +* Unknown preset names now raise ``ValueError`` with a grouped listing of all + available presets and the config paths they affect. + +Fixed +^^^^^ + +* Fixed presets inside dict-valued alternatives and ``PresetCfg(default=None)`` + not being discovered or resolved, causing wrong defaults in deeply nested configs. +* Unresolvable ``PresetCfg`` (no ``default``, no matching selection) now raises + ``ValueError`` instead of silently lingering in the config tree. + + +1.5.20 (2026-04-06) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Change Franka visuomotor and GR1T2 nut pouring environments to use TiledCamera. + + +1.5.19 (2026-04-06) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Aligned :class:`~isaaclab_tasks.manager_based.manipulation.deploy.reach.config.rizon_4s.ros_inference_env_cfg.Rizon4sReachROSInferenceEnvCfg` + with the Flexiv Rizon 4s mount and workspace at NVIDIA Hubble Lab. + + 1.5.18 (2026-04-02) ~~~~~~~~~~~~~~~~~~~ @@ -41,6 +267,7 @@ Added * Added semantic segmentation to preset data types for the Cartpole Camera environment. * Added semantic segmentation to preset data types for the Shadow Hand environment. * Added semantic_segmentation64 to preset data types for for the Dexsuite Kuka-Allegro environment. +* Added ``Isaac-Deploy-Reach-Rizon4s-ROS`` environments. 1.5.13 (2026-03-18) ~~~~~~~~~~~~~~~~~~~ diff --git a/source/isaaclab_tasks/isaaclab_tasks/direct/allegro_hand/allegro_hand_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/direct/allegro_hand/allegro_hand_env_cfg.py index bcc738c95278..bd982c5d7105 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/direct/allegro_hand/allegro_hand_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/direct/allegro_hand/allegro_hand_env_cfg.py @@ -43,7 +43,7 @@ class ObjectCfg(PresetCfg): ), init_state=RigidObjectCfg.InitialStateCfg(pos=(0.0, -0.17, 0.56), rot=(0.0, 0.0, 0.0, 1.0)), ) - newton = ArticulationCfg( + newton_mjwarp = ArticulationCfg( prim_path="/World/envs/env_.*/object", spawn=sim_utils.UsdFileCfg( usd_path=f"{ISAAC_NUCLEUS_DIR}/Props/Blocks/DexCube/dex_cube_instanceable.usd", @@ -64,7 +64,7 @@ class PhysicsCfg(PresetCfg): physx = PhysxCfg( bounce_threshold_velocity=0.2, ) - newton = NewtonCfg( + newton_mjwarp = NewtonCfg( solver_cfg=MJWarpSolverCfg( solver="newton", integrator="implicitfast", @@ -161,6 +161,8 @@ class AllegroHandEnvCfg(DirectRLEnvCfg): vel_obs_scale = 0.2 success_tolerance = 0.2 max_consecutive_success = 0 + success_count_threshold: int = 1 + """Minimum number of goals reached in an episode to count it as a successful episode.""" av_factor = 0.1 act_moving_average = 1.0 force_torque_obs_scale = 10.0 diff --git a/source/isaaclab_tasks/isaaclab_tasks/direct/ant/ant_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/direct/ant/ant_env_cfg.py index b52f62dee9ea..7ee86abc0013 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/direct/ant/ant_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/direct/ant/ant_env_cfg.py @@ -5,7 +5,8 @@ from __future__ import annotations -from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg +from isaaclab_newton.physics import KaminoSolverCfg, MJWarpSolverCfg, NewtonCfg +from isaaclab_ovphysx.physics import OvPhysxCfg from isaaclab_physx.physics import PhysxCfg import isaaclab.sim as sim_utils @@ -25,7 +26,7 @@ class AntPhysicsCfg(PresetCfg): default: PhysxCfg = PhysxCfg() physx: PhysxCfg = PhysxCfg() - newton: NewtonCfg = NewtonCfg( + newton_mjwarp: NewtonCfg = NewtonCfg( solver_cfg=MJWarpSolverCfg( njmax=45, nconmax=25, @@ -36,6 +37,30 @@ class AntPhysicsCfg(PresetCfg): num_substeps=1, debug_mode=False, ) + newton_kamino: NewtonCfg = NewtonCfg( + solver_cfg=KaminoSolverCfg( + integrator="moreau", + use_collision_detector=False, + sparse_jacobian=True, + constraints_alpha=0.1, + padmm_max_iterations=100, + padmm_primal_tolerance=1e-4, + padmm_dual_tolerance=1e-4, + padmm_compl_tolerance=1e-4, + padmm_rho_0=0.05, + padmm_eta=1e-5, + padmm_use_acceleration=True, + padmm_warmstart_mode="containers", + padmm_contact_warmstart_method="geom_pair_net_force", + padmm_use_graph_conditionals=False, + collision_detector_pipeline="unified", + collision_detector_max_contacts_per_pair=8, + ), + num_substeps=2, + debug_mode=False, + use_cuda_graph=True, + ) + ovphysx: OvPhysxCfg = OvPhysxCfg() @configclass diff --git a/source/isaaclab_tasks/isaaclab_tasks/direct/anymal_c/anymal_c_env.py b/source/isaaclab_tasks/isaaclab_tasks/direct/anymal_c/anymal_c_env.py index ea95dfe5b98d..3c1c0aa0ef2f 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/direct/anymal_c/anymal_c_env.py +++ b/source/isaaclab_tasks/isaaclab_tasks/direct/anymal_c/anymal_c_env.py @@ -32,6 +32,13 @@ def __init__(self, cfg: AnymalCFlatEnvCfg | AnymalCRoughEnvCfg, render_mode: str # X/Y linear velocity and yaw angular velocity commands self._commands = torch.zeros(self.num_envs, 3, device=self.device) + # Per-episode tracking accumulators for the velocity-tracking success metric. + # Errors are summed over actual episode steps and the mean is finalized at reset, + # so logged values reflect the just-ended episode rather than the post-reset instant. + self._error_xy_sum = torch.zeros(self.num_envs, device=self.device) + self._error_yaw_sum = torch.zeros(self.num_envs, device=self.device) + self._step_count = torch.zeros(self.num_envs, device=self.device) + # Logging self._episode_sums = { key: torch.zeros(self.num_envs, dtype=torch.float, device=self.device) @@ -76,9 +83,7 @@ def _setup_scene(self): def _pre_physics_step(self, actions: torch.Tensor): self._actions = actions.clone() - self._processed_actions = self.cfg.action_scale * self._actions + wp.to_torch( - self._robot.data.default_joint_pos - ) + self._processed_actions = self.cfg.action_scale * self._actions + self._robot.data.default_joint_pos.torch def _apply_action(self): self._robot.set_joint_position_target_index(target=self._processed_actions) @@ -88,18 +93,20 @@ def _get_observations(self) -> dict: height_data = None if isinstance(self.cfg, AnymalCRoughEnvCfg): height_data = ( - self._height_scanner.data.pos_w[:, 2].unsqueeze(1) - self._height_scanner.data.ray_hits_w[..., 2] - 0.5 + self._height_scanner.data.pos_w.torch[:, 2].unsqueeze(1) + - self._height_scanner.data.ray_hits_w.torch[..., 2] + - 0.5 ).clip(-1.0, 1.0) obs = torch.cat( [ tensor for tensor in ( - wp.to_torch(self._robot.data.root_lin_vel_b), - wp.to_torch(self._robot.data.root_ang_vel_b), - wp.to_torch(self._robot.data.projected_gravity_b), + self._robot.data.root_lin_vel_b.torch, + self._robot.data.root_ang_vel_b.torch, + self._robot.data.projected_gravity_b.torch, self._commands, - wp.to_torch(self._robot.data.joint_pos) - wp.to_torch(self._robot.data.default_joint_pos), - wp.to_torch(self._robot.data.joint_vel), + self._robot.data.joint_pos.torch - self._robot.data.default_joint_pos.torch, + self._robot.data.joint_vel.torch, height_data, self._actions, ) @@ -113,37 +120,37 @@ def _get_observations(self) -> dict: def _get_rewards(self) -> torch.Tensor: # linear velocity tracking lin_vel_error = torch.sum( - torch.square(self._commands[:, :2] - wp.to_torch(self._robot.data.root_lin_vel_b)[:, :2]), dim=1 + torch.square(self._commands[:, :2] - self._robot.data.root_lin_vel_b.torch[:, :2]), dim=1 ) lin_vel_error_mapped = torch.exp(-lin_vel_error / 0.25) # yaw rate tracking - yaw_rate_error = torch.square(self._commands[:, 2] - wp.to_torch(self._robot.data.root_ang_vel_b)[:, 2]) + yaw_rate_error = torch.square(self._commands[:, 2] - self._robot.data.root_ang_vel_b.torch[:, 2]) yaw_rate_error_mapped = torch.exp(-yaw_rate_error / 0.25) # z velocity tracking - z_vel_error = torch.square(wp.to_torch(self._robot.data.root_lin_vel_b)[:, 2]) + z_vel_error = torch.square(self._robot.data.root_lin_vel_b.torch[:, 2]) # angular velocity x/y - ang_vel_error = torch.sum(torch.square(wp.to_torch(self._robot.data.root_ang_vel_b)[:, :2]), dim=1) + ang_vel_error = torch.sum(torch.square(self._robot.data.root_ang_vel_b.torch[:, :2]), dim=1) # joint torques - joint_torques = torch.sum(torch.square(wp.to_torch(self._robot.data.applied_torque)), dim=1) + joint_torques = torch.sum(torch.square(self._robot.data.applied_torque.torch), dim=1) # joint acceleration - joint_accel = torch.sum(torch.square(wp.to_torch(self._robot.data.joint_acc)), dim=1) + joint_accel = torch.sum(torch.square(self._robot.data.joint_acc.torch), dim=1) # action rate action_rate = torch.sum(torch.square(self._actions - self._previous_actions), dim=1) # feet air time - first_contact = wp.to_torch(self._contact_sensor.compute_first_contact(self.step_dt))[:, self._feet_ids] - last_air_time = wp.to_torch(self._contact_sensor.data.last_air_time)[:, self._feet_ids] + first_contact = self._contact_sensor.compute_first_contact(self.step_dt).torch[:, self._feet_ids] + last_air_time = self._contact_sensor.data.last_air_time.torch[:, self._feet_ids] air_time = torch.sum((last_air_time - 0.5) * first_contact, dim=1) * ( torch.linalg.norm(self._commands[:, :2], dim=1) > 0.1 ) # undesired contacts - net_contact_forces = wp.to_torch(self._contact_sensor.data.net_forces_w_history) + net_contact_forces = self._contact_sensor.data.net_forces_w_history.torch is_contact = ( torch.max(torch.linalg.norm(net_contact_forces[:, :, self._undesired_contact_body_ids], dim=-1), dim=1)[0] > 1.0 ) contacts = torch.sum(is_contact, dim=1) # flat orientation - flat_orientation = torch.sum(torch.square(wp.to_torch(self._robot.data.projected_gravity_b)[:, :2]), dim=1) + flat_orientation = torch.sum(torch.square(self._robot.data.projected_gravity_b.torch[:, :2]), dim=1) rewards = { "track_lin_vel_xy_exp": lin_vel_error_mapped * self.cfg.lin_vel_reward_scale * self.step_dt, @@ -158,6 +165,13 @@ def _get_rewards(self) -> torch.Tensor: "flat_orientation_l2": flat_orientation * self.cfg.flat_orientation_reward_scale * self.step_dt, } reward = torch.sum(torch.stack(list(rewards.values())), dim=0) + # Accumulate per-episode velocity tracking error sums; success is computed at reset + # as a per-env binary check on the *episode-mean* errors against the cfg thresholds. + error_xy = torch.linalg.norm(self._commands[:, :2] - self._robot.data.root_lin_vel_b.torch[:, :2], dim=-1) + error_yaw = torch.abs(self._commands[:, 2] - self._robot.data.root_ang_vel_b.torch[:, 2]) + self._error_xy_sum += error_xy + self._error_yaw_sum += error_yaw + self._step_count += 1.0 # Logging for key, value in rewards.items(): self._episode_sums[key] += value @@ -165,7 +179,7 @@ def _get_rewards(self) -> torch.Tensor: def _get_dones(self) -> tuple[torch.Tensor, torch.Tensor]: time_out = self.episode_length_buf >= self.max_episode_length - 1 - net_contact_forces = wp.to_torch(self._contact_sensor.data.net_forces_w_history) + net_contact_forces = self._contact_sensor.data.net_forces_w_history.torch died = torch.any( torch.max(torch.linalg.norm(net_contact_forces[:, :, self._base_id], dim=-1), dim=1)[0] > 1.0, dim=1 ) @@ -184,10 +198,10 @@ def _reset_idx(self, env_ids: torch.Tensor | None): # Sample new commands self._commands[env_ids] = torch.zeros_like(self._commands[env_ids]).uniform_(-1.0, 1.0) # Reset robot state - joint_pos = wp.to_torch(self._robot.data.default_joint_pos)[env_ids] - joint_vel = wp.to_torch(self._robot.data.default_joint_vel)[env_ids] - default_root_pose = wp.to_torch(self._robot.data.default_root_pose)[env_ids] - default_root_vel = wp.to_torch(self._robot.data.default_root_vel)[env_ids] + joint_pos = self._robot.data.default_joint_pos.torch[env_ids] + joint_vel = self._robot.data.default_joint_vel.torch[env_ids] + default_root_pose = self._robot.data.default_root_pose.torch[env_ids] + default_root_vel = self._robot.data.default_root_vel.torch[env_ids] default_root_pose[:, :3] += self._terrain.env_origins[env_ids] self._robot.write_root_pose_to_sim_index(root_pose=default_root_pose, env_ids=env_ids) self._robot.write_root_velocity_to_sim_index(root_velocity=default_root_vel, env_ids=env_ids) @@ -204,4 +218,23 @@ def _reset_idx(self, env_ids: torch.Tensor | None): extras = dict() extras["Episode_Termination/base_contact"] = torch.count_nonzero(self.reset_terminated[env_ids]).item() extras["Episode_Termination/time_out"] = torch.count_nonzero(self.reset_time_outs[env_ids]).item() + # Flush per-episode velocity tracking metrics. ``success_rate`` is per-env binary: + # the *episode-mean* error stayed below both thresholds, mean-reduced across env_ids. + denom = self._step_count[env_ids].clamp_min(1.0) + mean_error_xy = self._error_xy_sum[env_ids] / denom + mean_error_yaw = self._error_yaw_sum[env_ids] / denom + extras["Metrics/error_vel_xy"] = mean_error_xy.mean().item() + extras["Metrics/error_vel_yaw"] = mean_error_yaw.mean().item() + extras["Metrics/success_rate"] = ( + ( + (mean_error_xy < self.cfg.vel_xy_success_threshold) + & (mean_error_yaw < self.cfg.vel_yaw_success_threshold) + ) + .float() + .mean() + .item() + ) + self._error_xy_sum[env_ids] = 0.0 + self._error_yaw_sum[env_ids] = 0.0 + self._step_count[env_ids] = 0.0 self.extras["log"].update(extras) diff --git a/source/isaaclab_tasks/isaaclab_tasks/direct/anymal_c/anymal_c_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/direct/anymal_c/anymal_c_env_cfg.py index 09e4edcb55a7..f2939b661508 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/direct/anymal_c/anymal_c_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/direct/anymal_c/anymal_c_env_cfg.py @@ -112,6 +112,15 @@ class AnymalCFlatEnvCfg(DirectRLEnvCfg): undesired_contact_reward_scale = -1.0 flat_orientation_reward_scale = -5.0 + # success criteria — episode success_rate = per-env binary check that the *episode-mean* + # error stayed below both thresholds, mean-reduced across resetting envs. Matches the + # manager-based ``UniformVelocityCommandCfg`` defaults so flat/rough/direct curves are + # comparable on the unified ``Metrics/success_rate`` card. + vel_xy_success_threshold: float = 0.5 + """Threshold on the per-episode mean XY velocity error norm [m/s].""" + vel_yaw_success_threshold: float = 0.4 + """Threshold on the per-episode mean yaw velocity error [rad/s].""" + @configclass class AnymalCRoughEnvCfg(AnymalCFlatEnvCfg): diff --git a/source/isaaclab_tasks/isaaclab_tasks/direct/automate/assembly_env.py b/source/isaaclab_tasks/isaaclab_tasks/direct/automate/assembly_env.py index cdd39875486b..438f0f80603b 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/direct/automate/assembly_env.py +++ b/source/isaaclab_tasks/isaaclab_tasks/direct/automate/assembly_env.py @@ -275,18 +275,18 @@ def _setup_scene(self): def _compute_intermediate_values(self, dt): """Get values computed from raw tensors. This includes adding noise.""" # TODO: A lot of these can probably only be set once? - self.fixed_pos = wp.to_torch(self._fixed_asset.data.root_pos_w) - self.scene.env_origins - self.fixed_quat = wp.to_torch(self._fixed_asset.data.root_quat_w) + self.fixed_pos = self._fixed_asset.data.root_pos_w.torch - self.scene.env_origins + self.fixed_quat = self._fixed_asset.data.root_quat_w.torch - self.held_pos = wp.to_torch(self._held_asset.data.root_pos_w) - self.scene.env_origins - self.held_quat = wp.to_torch(self._held_asset.data.root_quat_w) + self.held_pos = self._held_asset.data.root_pos_w.torch - self.scene.env_origins + self.held_quat = self._held_asset.data.root_quat_w.torch self.fingertip_midpoint_pos = ( - wp.to_torch(self._robot.data.body_pos_w)[:, self.fingertip_body_idx] - self.scene.env_origins + self._robot.data.body_pos_w.torch[:, self.fingertip_body_idx] - self.scene.env_origins ) - self.fingertip_midpoint_quat = wp.to_torch(self._robot.data.body_quat_w)[:, self.fingertip_body_idx] - self.fingertip_midpoint_linvel = wp.to_torch(self._robot.data.body_lin_vel_w)[:, self.fingertip_body_idx] - self.fingertip_midpoint_angvel = wp.to_torch(self._robot.data.body_ang_vel_w)[:, self.fingertip_body_idx] + self.fingertip_midpoint_quat = self._robot.data.body_quat_w.torch[:, self.fingertip_body_idx] + self.fingertip_midpoint_linvel = self._robot.data.body_lin_vel_w.torch[:, self.fingertip_body_idx] + self.fingertip_midpoint_angvel = self._robot.data.body_ang_vel_w.torch[:, self.fingertip_body_idx] jacobians = wp.to_torch(self._robot.root_view.get_jacobians()) @@ -294,8 +294,8 @@ def _compute_intermediate_values(self, dt): self.right_finger_jacobian = jacobians[:, self.right_finger_body_idx - 1, 0:6, 0:7] self.fingertip_midpoint_jacobian = (self.left_finger_jacobian + self.right_finger_jacobian) * 0.5 self.arm_mass_matrix = wp.to_torch(self._robot.root_view.get_generalized_mass_matrices())[:, 0:7, 0:7] - self.joint_pos = wp.to_torch(self._robot.data.joint_pos).clone() - self.joint_vel = wp.to_torch(self._robot.data.joint_vel).clone() + self.joint_pos = self._robot.data.joint_pos.torch.clone() + self.joint_vel = self._robot.data.joint_vel.torch.clone() # Compute pose of gripper goal and top of socket in socket frame self.gripper_goal_pos, self.gripper_goal_quat = combine_frame_transforms( @@ -543,7 +543,9 @@ def _get_rewards(self): # Only log episode success rates at the end of an episode. if torch.any(self.reset_buf): - self.extras["successes"] = torch.count_nonzero(self.ep_succeeded) / self.num_envs + self.extras.setdefault("log", {})["Metrics/success_rate"] = ( + torch.count_nonzero(self.ep_succeeded) / self.num_envs + ).item() sbc_rwd_scale = automate_algo.get_curriculum_reward_scale( curr_max_disp=self.curr_max_disp, @@ -649,7 +651,7 @@ def _reset_idx(self, env_ids): def _set_assets_to_default_pose(self, env_ids): """Move assets to default pose before randomization.""" held_state = torch.cat( - [wp.to_torch(self._held_asset.data.default_root_pose), wp.to_torch(self._held_asset.data.default_root_vel)], + [self._held_asset.data.default_root_pose.torch, self._held_asset.data.default_root_vel.torch], dim=-1, )[env_ids].clone() held_state[:, 0:3] += self.scene.env_origins[env_ids] @@ -660,8 +662,8 @@ def _set_assets_to_default_pose(self, env_ids): fixed_state = torch.cat( [ - wp.to_torch(self._fixed_asset.data.default_root_pose), - wp.to_torch(self._fixed_asset.data.default_root_vel), + self._fixed_asset.data.default_root_pose.torch, + self._fixed_asset.data.default_root_vel.torch, ], dim=-1, )[env_ids].clone() @@ -739,7 +741,7 @@ def set_pos_inverse_kinematics(self, env_ids): def _set_franka_to_default_pose(self, joints, env_ids): """Return Franka to its default joint position.""" gripper_width = self.gripper_open_width - joint_pos = wp.to_torch(self._robot.data.default_joint_pos)[env_ids] + joint_pos = self._robot.data.default_joint_pos.torch[env_ids] joint_pos[:, 7:] = gripper_width # MIMIC joint_pos[:, :7] = torch.tensor(joints, device=self.device)[None, :] joint_vel = torch.zeros_like(joint_pos) @@ -764,8 +766,8 @@ def randomize_fixed_initial_state(self, env_ids): # (1.) Randomize fixed asset pose. fixed_state = torch.cat( [ - wp.to_torch(self._fixed_asset.data.default_root_pose), - wp.to_torch(self._fixed_asset.data.default_root_vel), + self._fixed_asset.data.default_root_pose.torch, + self._fixed_asset.data.default_root_vel.torch, ], dim=-1, )[env_ids].clone() @@ -819,7 +821,7 @@ def randomize_held_initial_state(self, env_ids, pre_grasp): # Set plug pos to assembled state, but offset plug Z-coordinate by height of socket, # minus curriculum displacement held_state = torch.cat( - [wp.to_torch(self._held_asset.data.default_root_pose), wp.to_torch(self._held_asset.data.default_root_vel)], + [self._held_asset.data.default_root_pose.torch, self._held_asset.data.default_root_vel.torch], dim=-1, ).clone() held_state[env_ids, 0:3] = self.fixed_pos[env_ids].clone() + self.scene.env_origins[env_ids] diff --git a/source/isaaclab_tasks/isaaclab_tasks/direct/automate/disassembly_env.py b/source/isaaclab_tasks/isaaclab_tasks/direct/automate/disassembly_env.py index 73822e43e9b9..c79441f223ae 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/direct/automate/disassembly_env.py +++ b/source/isaaclab_tasks/isaaclab_tasks/direct/automate/disassembly_env.py @@ -202,18 +202,18 @@ def _setup_scene(self): def _compute_intermediate_values(self, dt): """Get values computed from raw tensors. This includes adding noise.""" # TODO: A lot of these can probably only be set once? - self.fixed_pos = wp.to_torch(self._fixed_asset.data.root_pos_w) - self.scene.env_origins - self.fixed_quat = wp.to_torch(self._fixed_asset.data.root_quat_w) + self.fixed_pos = self._fixed_asset.data.root_pos_w.torch - self.scene.env_origins + self.fixed_quat = self._fixed_asset.data.root_quat_w.torch - self.held_pos = wp.to_torch(self._held_asset.data.root_pos_w) - self.scene.env_origins - self.held_quat = wp.to_torch(self._held_asset.data.root_quat_w) + self.held_pos = self._held_asset.data.root_pos_w.torch - self.scene.env_origins + self.held_quat = self._held_asset.data.root_quat_w.torch self.fingertip_midpoint_pos = ( - wp.to_torch(self._robot.data.body_pos_w)[:, self.fingertip_body_idx] - self.scene.env_origins + self._robot.data.body_pos_w.torch[:, self.fingertip_body_idx] - self.scene.env_origins ) - self.fingertip_midpoint_quat = wp.to_torch(self._robot.data.body_quat_w)[:, self.fingertip_body_idx] - self.fingertip_midpoint_linvel = wp.to_torch(self._robot.data.body_lin_vel_w)[:, self.fingertip_body_idx] - self.fingertip_midpoint_angvel = wp.to_torch(self._robot.data.body_ang_vel_w)[:, self.fingertip_body_idx] + self.fingertip_midpoint_quat = self._robot.data.body_quat_w.torch[:, self.fingertip_body_idx] + self.fingertip_midpoint_linvel = self._robot.data.body_lin_vel_w.torch[:, self.fingertip_body_idx] + self.fingertip_midpoint_angvel = self._robot.data.body_ang_vel_w.torch[:, self.fingertip_body_idx] jacobians = wp.to_torch(self._robot.root_view.get_jacobians()) @@ -221,8 +221,8 @@ def _compute_intermediate_values(self, dt): self.right_finger_jacobian = jacobians[:, self.right_finger_body_idx - 1, 0:6, 0:7] self.fingertip_midpoint_jacobian = (self.left_finger_jacobian + self.right_finger_jacobian) * 0.5 self.arm_mass_matrix = wp.to_torch(self._robot.root_view.get_generalized_mass_matrices())[:, 0:7, 0:7] - self.joint_pos = wp.to_torch(self._robot.data.joint_pos).clone() - self.joint_vel = wp.to_torch(self._robot.data.joint_vel).clone() + self.joint_pos = self._robot.data.joint_pos.torch.clone() + self.joint_vel = self._robot.data.joint_vel.torch.clone() # Compute pose of gripper goal and top of socket in socket frame self.gripper_goal_pos, self.gripper_goal_quat = combine_frame_transforms( @@ -448,9 +448,13 @@ def _get_dones(self): def _get_rewards(self): """Update rewards and compute success statistics.""" - # Get successful and failed envs at current timestep - rew_buf = self._update_rew_buf() + + if torch.any(self.reset_buf): + self.extras.setdefault("log", {})["Metrics/success_rate"] = ( + torch.count_nonzero(self.ep_succeeded) / self.num_envs + ).item() + return rew_buf def _update_rew_buf(self): @@ -480,7 +484,7 @@ def _reset_idx(self, env_ids): def _set_assets_to_default_pose(self, env_ids): """Move assets to default pose before randomization.""" held_state = torch.cat( - [wp.to_torch(self._held_asset.data.default_root_pose), wp.to_torch(self._held_asset.data.default_root_vel)], + [self._held_asset.data.default_root_pose.torch, self._held_asset.data.default_root_vel.torch], dim=-1, )[env_ids].clone() held_state[:, 0:3] += self.scene.env_origins[env_ids] @@ -491,8 +495,8 @@ def _set_assets_to_default_pose(self, env_ids): fixed_state = torch.cat( [ - wp.to_torch(self._fixed_asset.data.default_root_pose), - wp.to_torch(self._fixed_asset.data.default_root_vel), + self._fixed_asset.data.default_root_pose.torch, + self._fixed_asset.data.default_root_vel.torch, ], dim=-1, )[env_ids].clone() @@ -612,7 +616,7 @@ def _set_franka_to_default_pose(self, joints, env_ids): # gripper_width = self.cfg_task.held_asset_cfg.diameter / 2 * 1.25 # gripper_width = self.cfg_task.hand_width_max / 3.0 gripper_width = self.gripper_open_width - joint_pos = wp.to_torch(self._robot.data.default_joint_pos)[env_ids] + joint_pos = self._robot.data.default_joint_pos.torch[env_ids] joint_pos[:, 7:] = gripper_width # MIMIC joint_pos[:, :7] = torch.tensor(joints, device=self.device)[None, :] joint_vel = torch.zeros_like(joint_pos) @@ -637,8 +641,8 @@ def randomize_fixed_initial_state(self, env_ids): # (1.) Randomize fixed asset pose. fixed_state = torch.cat( [ - wp.to_torch(self._fixed_asset.data.default_root_pose), - wp.to_torch(self._fixed_asset.data.default_root_vel), + self._fixed_asset.data.default_root_pose.torch, + self._fixed_asset.data.default_root_vel.torch, ], dim=-1, )[env_ids].clone() @@ -678,7 +682,7 @@ def randomize_fixed_initial_state(self, env_ids): def randomize_held_initial_state(self, env_ids, pre_grasp): # Set plug pos to assembled state held_state = torch.cat( - [wp.to_torch(self._held_asset.data.default_root_pose), wp.to_torch(self._held_asset.data.default_root_vel)], + [self._held_asset.data.default_root_pose.torch, self._held_asset.data.default_root_vel.torch], dim=-1, ).clone() held_state[env_ids, 0:3] = self.fixed_pos[env_ids].clone() + self.scene.env_origins[env_ids] diff --git a/source/isaaclab_tasks/isaaclab_tasks/direct/cart_double_pendulum/agents/skrl_ippo_cfg.yaml b/source/isaaclab_tasks/isaaclab_tasks/direct/cart_double_pendulum/agents/skrl_ippo_cfg.yaml index f9298c9252ac..606d5634e92e 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/direct/cart_double_pendulum/agents/skrl_ippo_cfg.yaml +++ b/source/isaaclab_tasks/isaaclab_tasks/direct/cart_double_pendulum/agents/skrl_ippo_cfg.yaml @@ -54,7 +54,9 @@ agent: learning_rate_scheduler: KLAdaptiveLR learning_rate_scheduler_kwargs: kl_threshold: 0.008 - state_preprocessor: RunningStandardScaler + observation_preprocessor: RunningStandardScaler + observation_preprocessor_kwargs: null + state_preprocessor: null state_preprocessor_kwargs: null value_preprocessor: RunningStandardScaler value_preprocessor_kwargs: null diff --git a/source/isaaclab_tasks/isaaclab_tasks/direct/cart_double_pendulum/agents/skrl_mappo_cfg.yaml b/source/isaaclab_tasks/isaaclab_tasks/direct/cart_double_pendulum/agents/skrl_mappo_cfg.yaml index 8f192cf2988d..aef5480970a9 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/direct/cart_double_pendulum/agents/skrl_mappo_cfg.yaml +++ b/source/isaaclab_tasks/isaaclab_tasks/direct/cart_double_pendulum/agents/skrl_mappo_cfg.yaml @@ -28,7 +28,7 @@ models: clip_actions: False network: - name: net - input: OBSERVATIONS + input: STATES layers: [32, 32] activations: elu output: ONE @@ -54,10 +54,10 @@ agent: learning_rate_scheduler: KLAdaptiveLR learning_rate_scheduler_kwargs: kl_threshold: 0.008 + observation_preprocessor: RunningStandardScaler + observation_preprocessor_kwargs: null state_preprocessor: RunningStandardScaler state_preprocessor_kwargs: null - shared_state_preprocessor: RunningStandardScaler - shared_state_preprocessor_kwargs: null value_preprocessor: RunningStandardScaler value_preprocessor_kwargs: null random_timesteps: 0 diff --git a/source/isaaclab_tasks/isaaclab_tasks/direct/cart_double_pendulum/cart_double_pendulum_env.py b/source/isaaclab_tasks/isaaclab_tasks/direct/cart_double_pendulum/cart_double_pendulum_env.py index cd3fca731952..f146ef56330f 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/direct/cart_double_pendulum/cart_double_pendulum_env.py +++ b/source/isaaclab_tasks/isaaclab_tasks/direct/cart_double_pendulum/cart_double_pendulum_env.py @@ -9,7 +9,6 @@ from collections.abc import Sequence import torch -import warp as wp import isaaclab.sim as sim_utils from isaaclab.assets import Articulation, ArticulationCfg @@ -75,8 +74,8 @@ def __init__(self, cfg: CartDoublePendulumEnvCfg, render_mode: str | None = None self._pole_dof_idx, _ = self.robot.find_joints(self.cfg.pole_dof_name) self._pendulum_dof_idx, _ = self.robot.find_joints(self.cfg.pendulum_dof_name) - self.joint_pos = wp.to_torch(self.robot.data.joint_pos) - self.joint_vel = wp.to_torch(self.robot.data.joint_vel) + self.joint_pos = self.robot.data.joint_pos.torch + self.joint_vel = self.robot.data.joint_vel.torch def _setup_scene(self): self.robot = Articulation(self.cfg.robot_cfg) @@ -149,8 +148,8 @@ def _get_rewards(self) -> dict[str, torch.Tensor]: return total_reward def _get_dones(self) -> tuple[dict[str, torch.Tensor], dict[str, torch.Tensor]]: - self.joint_pos = wp.to_torch(self.robot.data.joint_pos) - self.joint_vel = wp.to_torch(self.robot.data.joint_vel) + self.joint_pos = self.robot.data.joint_pos.torch + self.joint_vel = self.robot.data.joint_vel.torch time_out = self.episode_length_buf >= self.max_episode_length - 1 out_of_bounds = torch.any(torch.abs(self.joint_pos[:, self._cart_dof_idx]) > self.cfg.max_cart_pos, dim=1) @@ -163,9 +162,16 @@ def _get_dones(self) -> tuple[dict[str, torch.Tensor], dict[str, torch.Tensor]]: def _reset_idx(self, env_ids: Sequence[int] | None): if env_ids is None: env_ids = self.robot._ALL_INDICES + # Episode success = timed out without leaving the cart/pole bounds. All agents share + # the same termination signal in this task, so reading any agent's flag is fine. + # DirectMARLEnv only sets these dicts inside step(), so skip on the initial reset. + if hasattr(self, "time_out_dict"): + any_agent = next(iter(self.cfg.possible_agents)) + survived = self.time_out_dict[any_agent][env_ids] & ~self.terminated_dict[any_agent][env_ids] + self.extras.setdefault("log", {})["Metrics/success_rate"] = survived.float().mean().item() super()._reset_idx(env_ids) - joint_pos = wp.to_torch(self.robot.data.default_joint_pos)[env_ids] + joint_pos = self.robot.data.default_joint_pos.torch[env_ids] joint_pos[:, self._pole_dof_idx] += sample_uniform( self.cfg.initial_pole_angle_range[0] * math.pi, self.cfg.initial_pole_angle_range[1] * math.pi, @@ -178,10 +184,10 @@ def _reset_idx(self, env_ids: Sequence[int] | None): joint_pos[:, self._pendulum_dof_idx].shape, joint_pos.device, ) - joint_vel = wp.to_torch(self.robot.data.default_joint_vel)[env_ids] + joint_vel = self.robot.data.default_joint_vel.torch[env_ids] - default_root_pose = wp.to_torch(self.robot.data.default_root_pose)[env_ids] - default_root_vel = wp.to_torch(self.robot.data.default_root_vel)[env_ids] + default_root_pose = self.robot.data.default_root_pose.torch[env_ids] + default_root_vel = self.robot.data.default_root_vel.torch[env_ids] default_root_pose[:, :3] += self.scene.env_origins[env_ids] self.joint_pos[env_ids] = joint_pos diff --git a/source/isaaclab_tasks/isaaclab_tasks/direct/cartpole/cartpole_camera_env.py b/source/isaaclab_tasks/isaaclab_tasks/direct/cartpole/cartpole_camera_env.py index 3c2a896766ea..807c0cc09d91 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/direct/cartpole/cartpole_camera_env.py +++ b/source/isaaclab_tasks/isaaclab_tasks/direct/cartpole/cartpole_camera_env.py @@ -10,12 +10,11 @@ from typing import TYPE_CHECKING import torch -import warp as wp import isaaclab.sim as sim_utils from isaaclab.assets import Articulation from isaaclab.envs import DirectRLEnv -from isaaclab.sensors import TiledCamera, save_images_to_file +from isaaclab.sensors import Camera, save_images_to_file from isaaclab.utils.math import sample_uniform if TYPE_CHECKING: @@ -58,8 +57,8 @@ def __init__( self._pole_dof_idx, _ = self._cartpole.find_joints(self.cfg.pole_dof_name) self.action_scale = self.cfg.action_scale - self.joint_pos = wp.to_torch(self._cartpole.data.joint_pos) - self.joint_vel = wp.to_torch(self._cartpole.data.joint_vel) + self.joint_pos = self._cartpole.data.joint_pos.torch + self.joint_vel = self._cartpole.data.joint_vel.torch if len(self.cfg.tiled_camera.data_types) != 1: raise ValueError( @@ -74,7 +73,7 @@ def close(self): def _setup_scene(self): """Setup the scene with the cartpole and camera.""" self._cartpole = Articulation(self.cfg.robot_cfg) - self._tiled_camera = TiledCamera(self.cfg.tiled_camera) + self._tiled_camera = Camera(self.cfg.tiled_camera) # clone and replicate self.scene.clone_environments(copy_from_source=False) @@ -141,8 +140,8 @@ def _get_rewards(self) -> torch.Tensor: return total_reward def _get_dones(self) -> tuple[torch.Tensor, torch.Tensor]: - self.joint_pos = wp.to_torch(self._cartpole.data.joint_pos) - self.joint_vel = wp.to_torch(self._cartpole.data.joint_vel) + self.joint_pos = self._cartpole.data.joint_pos.torch + self.joint_vel = self._cartpole.data.joint_vel.torch time_out = self.episode_length_buf >= self.max_episode_length - 1 out_of_bounds = torch.any(torch.abs(self.joint_pos[:, self._cart_dof_idx]) > self.cfg.max_cart_pos, dim=1) @@ -152,20 +151,25 @@ def _get_dones(self) -> tuple[torch.Tensor, torch.Tensor]: def _reset_idx(self, env_ids: Sequence[int] | None): if env_ids is None: env_ids = self._cartpole._ALL_INDICES + + # Log survival success rate before resetting. + survived = self.reset_time_outs[env_ids].float() + self.extras.setdefault("log", {})["Metrics/success_rate"] = survived.mean().item() + super()._reset_idx(env_ids) - joint_pos = wp.to_torch(self._cartpole.data.default_joint_pos)[env_ids] + joint_pos = self._cartpole.data.default_joint_pos.torch[env_ids] joint_pos[:, self._pole_dof_idx] += sample_uniform( self.cfg.initial_pole_angle_range[0] * math.pi, self.cfg.initial_pole_angle_range[1] * math.pi, joint_pos[:, self._pole_dof_idx].shape, joint_pos.device, ) - joint_vel = wp.to_torch(self._cartpole.data.default_joint_vel)[env_ids] + joint_vel = self._cartpole.data.default_joint_vel.torch[env_ids] - default_root_pose = wp.to_torch(self._cartpole.data.default_root_pose)[env_ids] + default_root_pose = self._cartpole.data.default_root_pose.torch[env_ids] default_root_pose[:, :3] += self.scene.env_origins[env_ids] - default_root_vel = wp.to_torch(self._cartpole.data.default_root_vel)[env_ids] + default_root_vel = self._cartpole.data.default_root_vel.torch[env_ids] self.joint_pos[env_ids] = joint_pos self.joint_vel[env_ids] = joint_vel diff --git a/source/isaaclab_tasks/isaaclab_tasks/direct/cartpole/cartpole_camera_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/direct/cartpole/cartpole_camera_env_cfg.py index dfbea0e203a7..9539b99bfb89 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/direct/cartpole/cartpole_camera_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/direct/cartpole/cartpole_camera_env_cfg.py @@ -9,7 +9,7 @@ from isaaclab.assets import ArticulationCfg from isaaclab.envs import DirectRLEnvCfg, ViewerCfg from isaaclab.scene import InteractiveSceneCfg -from isaaclab.sensors import TiledCameraCfg +from isaaclab.sensors import CameraCfg from isaaclab.sim import SimulationCfg from isaaclab.utils import configclass @@ -34,9 +34,9 @@ class CartpoleRGBCameraEnvCfg(DirectRLEnvCfg): pole_dof_name = "cart_to_pole" # camera: default=RTX, newton_renderer=Warp. Override: env.tiled_camera.renderer_cfg=newton_renderer - tiled_camera: TiledCameraCfg = TiledCameraCfg( + tiled_camera: CameraCfg = CameraCfg( prim_path="/World/envs/env_.*/Camera", - offset=TiledCameraCfg.OffsetCfg(pos=(-5.0, 0.0, 2.0), rot=(0.0, 0.0, 0.0, 1.0), convention="world"), + offset=CameraCfg.OffsetCfg(pos=(-5.0, 0.0, 2.0), rot=(0.0, 0.0, 0.0, 1.0), convention="world"), data_types=["rgb"], spawn=sim_utils.PinholeCameraCfg( focal_length=24.0, focus_distance=400.0, horizontal_aperture=20.955, clipping_range=(0.1, 20.0) @@ -73,9 +73,9 @@ class CartpoleRGBCameraEnvCfg(DirectRLEnvCfg): @configclass class CartpoleDepthCameraEnvCfg(CartpoleRGBCameraEnvCfg): # camera - tiled_camera: TiledCameraCfg = TiledCameraCfg( + tiled_camera: CameraCfg = CameraCfg( prim_path="/World/envs/env_.*/Camera", - offset=TiledCameraCfg.OffsetCfg(pos=(-5.0, 0.0, 2.0), rot=(0.0, 0.0, 0.0, 1.0), convention="world"), + offset=CameraCfg.OffsetCfg(pos=(-5.0, 0.0, 2.0), rot=(0.0, 0.0, 0.0, 1.0), convention="world"), data_types=["depth"], spawn=sim_utils.PinholeCameraCfg( focal_length=24.0, focus_distance=400.0, horizontal_aperture=20.955, clipping_range=(0.1, 20.0) @@ -91,9 +91,9 @@ class CartpoleDepthCameraEnvCfg(CartpoleRGBCameraEnvCfg): @configclass class CartpoleAlbedoCameraEnvCfg(CartpoleRGBCameraEnvCfg): # camera - tiled_camera: TiledCameraCfg = TiledCameraCfg( + tiled_camera: CameraCfg = CameraCfg( prim_path="/World/envs/env_.*/Camera", - offset=TiledCameraCfg.OffsetCfg(pos=(-5.0, 0.0, 2.0), rot=(1.0, 0.0, 0.0, 0.0), convention="world"), + offset=CameraCfg.OffsetCfg(pos=(-5.0, 0.0, 2.0), rot=(1.0, 0.0, 0.0, 0.0), convention="world"), data_types=["albedo"], spawn=sim_utils.PinholeCameraCfg( focal_length=24.0, focus_distance=400.0, horizontal_aperture=20.955, clipping_range=(0.1, 20.0) @@ -109,9 +109,9 @@ class CartpoleAlbedoCameraEnvCfg(CartpoleRGBCameraEnvCfg): @configclass class CartpoleSimpleShadingConstantCameraEnvCfg(CartpoleRGBCameraEnvCfg): # camera - tiled_camera: TiledCameraCfg = TiledCameraCfg( + tiled_camera: CameraCfg = CameraCfg( prim_path="/World/envs/env_.*/Camera", - offset=TiledCameraCfg.OffsetCfg(pos=(-5.0, 0.0, 2.0), rot=(1.0, 0.0, 0.0, 0.0), convention="world"), + offset=CameraCfg.OffsetCfg(pos=(-5.0, 0.0, 2.0), rot=(1.0, 0.0, 0.0, 0.0), convention="world"), data_types=["simple_shading_constant_diffuse"], spawn=sim_utils.PinholeCameraCfg( focal_length=24.0, focus_distance=400.0, horizontal_aperture=20.955, clipping_range=(0.1, 20.0) @@ -127,9 +127,9 @@ class CartpoleSimpleShadingConstantCameraEnvCfg(CartpoleRGBCameraEnvCfg): @configclass class CartpoleSimpleShadingDiffuseCameraEnvCfg(CartpoleRGBCameraEnvCfg): # camera - tiled_camera: TiledCameraCfg = TiledCameraCfg( + tiled_camera: CameraCfg = CameraCfg( prim_path="/World/envs/env_.*/Camera", - offset=TiledCameraCfg.OffsetCfg(pos=(-5.0, 0.0, 2.0), rot=(1.0, 0.0, 0.0, 0.0), convention="world"), + offset=CameraCfg.OffsetCfg(pos=(-5.0, 0.0, 2.0), rot=(1.0, 0.0, 0.0, 0.0), convention="world"), data_types=["simple_shading_diffuse_mdl"], spawn=sim_utils.PinholeCameraCfg( focal_length=24.0, focus_distance=400.0, horizontal_aperture=20.955, clipping_range=(0.1, 20.0) @@ -145,9 +145,9 @@ class CartpoleSimpleShadingDiffuseCameraEnvCfg(CartpoleRGBCameraEnvCfg): @configclass class CartpoleSimpleShadingFullCameraEnvCfg(CartpoleRGBCameraEnvCfg): # camera - tiled_camera: TiledCameraCfg = TiledCameraCfg( + tiled_camera: CameraCfg = CameraCfg( prim_path="/World/envs/env_.*/Camera", - offset=TiledCameraCfg.OffsetCfg(pos=(-5.0, 0.0, 2.0), rot=(1.0, 0.0, 0.0, 0.0), convention="world"), + offset=CameraCfg.OffsetCfg(pos=(-5.0, 0.0, 2.0), rot=(1.0, 0.0, 0.0, 0.0), convention="world"), data_types=["simple_shading_full_mdl"], spawn=sim_utils.PinholeCameraCfg( focal_length=24.0, focus_distance=400.0, horizontal_aperture=20.955, clipping_range=(0.1, 20.0) diff --git a/source/isaaclab_tasks/isaaclab_tasks/direct/cartpole/cartpole_camera_presets_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/direct/cartpole/cartpole_camera_presets_env_cfg.py index 33433153f386..4c27674ff7c6 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/direct/cartpole/cartpole_camera_presets_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/direct/cartpole/cartpole_camera_presets_env_cfg.py @@ -12,7 +12,7 @@ from isaaclab.assets import ArticulationCfg from isaaclab.envs import DirectRLEnvCfg, ViewerCfg from isaaclab.scene import InteractiveSceneCfg -from isaaclab.sensors import TiledCameraCfg +from isaaclab.sensors import CameraCfg from isaaclab.sim import SimulationCfg from isaaclab.utils import configclass @@ -26,15 +26,15 @@ class PhysicsCfg(PresetCfg): default = PhysxCfg() physx = PhysxCfg() - newton = NewtonCfg() + newton_mjwarp = NewtonCfg() @configclass class MultiDataTypeCartpoleTiledCameraCfg(PresetCfg): @configclass - class CartpoleTiledCameraCfg(TiledCameraCfg): + class CartpoleTiledCameraCfg(CameraCfg): prim_path: str = "/World/envs/env_.*/Camera" - offset: TiledCameraCfg.OffsetCfg = TiledCameraCfg.OffsetCfg( + offset: CameraCfg.OffsetCfg = CameraCfg.OffsetCfg( pos=(-5.0, 0.0, 2.0), rot=(0.0, 0.0, 0.0, 1.0), convention="world" ) data_types: list[str] = [] diff --git a/source/isaaclab_tasks/isaaclab_tasks/direct/cartpole/cartpole_env.py b/source/isaaclab_tasks/isaaclab_tasks/direct/cartpole/cartpole_env.py index 6c14fa8c2e18..10442ef08cc8 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/direct/cartpole/cartpole_env.py +++ b/source/isaaclab_tasks/isaaclab_tasks/direct/cartpole/cartpole_env.py @@ -10,7 +10,6 @@ from typing import TYPE_CHECKING import torch -import warp as wp import isaaclab.sim as sim_utils from isaaclab.assets import Articulation @@ -32,8 +31,8 @@ def __init__(self, cfg: CartpoleEnvCfg, render_mode: str | None = None, **kwargs self._pole_dof_idx, _ = self.cartpole.find_joints(self.cfg.pole_dof_name) self.action_scale = self.cfg.action_scale - self.joint_pos = wp.to_torch(self.cartpole.data.joint_pos) - self.joint_vel = wp.to_torch(self.cartpole.data.joint_vel) + self.joint_pos = self.cartpole.data.joint_pos.torch + self.joint_vel = self.cartpole.data.joint_vel.torch def _setup_scene(self): self.cartpole = Articulation(self.cfg.robot_cfg) @@ -85,8 +84,8 @@ def _get_rewards(self) -> torch.Tensor: return total_reward def _get_dones(self) -> tuple[torch.Tensor, torch.Tensor]: - self.joint_pos = wp.to_torch(self.cartpole.data.joint_pos) - self.joint_vel = wp.to_torch(self.cartpole.data.joint_vel) + self.joint_pos = self.cartpole.data.joint_pos.torch + self.joint_vel = self.cartpole.data.joint_vel.torch time_out = self.episode_length_buf >= self.max_episode_length - 1 out_of_bounds = torch.any(torch.abs(self.joint_pos[:, self._cart_dof_idx]) > self.cfg.max_cart_pos, dim=1) @@ -96,20 +95,25 @@ def _get_dones(self) -> tuple[torch.Tensor, torch.Tensor]: def _reset_idx(self, env_ids: Sequence[int] | None): if env_ids is None: env_ids = self.cartpole._ALL_INDICES + + # Log survival success rate before resetting + survived = self.reset_time_outs[env_ids].float() + self.extras.setdefault("log", {})["Metrics/success_rate"] = survived.mean().item() + super()._reset_idx(env_ids) - joint_pos = wp.to_torch(self.cartpole.data.default_joint_pos)[env_ids].clone() + joint_pos = self.cartpole.data.default_joint_pos.torch[env_ids].clone() joint_pos[:, self._pole_dof_idx] += sample_uniform( self.cfg.initial_pole_angle_range[0] * math.pi, self.cfg.initial_pole_angle_range[1] * math.pi, joint_pos[:, self._pole_dof_idx].shape, joint_pos.device, ) - joint_vel = wp.to_torch(self.cartpole.data.default_joint_vel)[env_ids].clone() + joint_vel = self.cartpole.data.default_joint_vel.torch[env_ids].clone() - default_root_pose = wp.to_torch(self.cartpole.data.default_root_pose)[env_ids].clone() + default_root_pose = self.cartpole.data.default_root_pose.torch[env_ids].clone() default_root_pose[:, :3] += self.scene.env_origins[env_ids] - default_root_vel = wp.to_torch(self.cartpole.data.default_root_vel)[env_ids].clone() + default_root_vel = self.cartpole.data.default_root_vel.torch[env_ids].clone() self.joint_pos[env_ids] = joint_pos self.joint_vel[env_ids] = joint_vel diff --git a/source/isaaclab_tasks/isaaclab_tasks/direct/cartpole/cartpole_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/direct/cartpole/cartpole_env_cfg.py index 2b38a7e0991a..2b93d0f0ed79 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/direct/cartpole/cartpole_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/direct/cartpole/cartpole_env_cfg.py @@ -5,7 +5,8 @@ from __future__ import annotations -from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg +from isaaclab_newton.physics import KaminoSolverCfg, MJWarpSolverCfg, NewtonCfg +from isaaclab_ovphysx.physics import OvPhysxCfg from isaaclab_physx.physics import PhysxCfg from isaaclab.assets import ArticulationCfg @@ -23,7 +24,7 @@ class CartpolePhysicsCfg(PresetCfg): default: PhysxCfg = PhysxCfg() physx: PhysxCfg = PhysxCfg() - newton: NewtonCfg = NewtonCfg( + newton_mjwarp: NewtonCfg = NewtonCfg( solver_cfg=MJWarpSolverCfg( njmax=5, nconmax=3, @@ -35,6 +36,30 @@ class CartpolePhysicsCfg(PresetCfg): debug_mode=False, use_cuda_graph=True, ) + newton_kamino: NewtonCfg = NewtonCfg( + solver_cfg=KaminoSolverCfg( + integrator="moreau", + use_collision_detector=True, + sparse_jacobian=True, + constraints_alpha=0.1, + padmm_max_iterations=100, + padmm_primal_tolerance=1e-4, + padmm_dual_tolerance=1e-4, + padmm_compl_tolerance=1e-4, + padmm_rho_0=0.05, + padmm_eta=1e-5, + padmm_use_acceleration=True, + padmm_warmstart_mode="containers", + padmm_contact_warmstart_method="geom_pair_net_force", + padmm_use_graph_conditionals=False, + collision_detector_pipeline="unified", + collision_detector_max_contacts_per_pair=8, + ), + num_substeps=1, + debug_mode=False, + use_cuda_graph=True, + ) + ovphysx: OvPhysxCfg = OvPhysxCfg() @configclass diff --git a/source/isaaclab_tasks/isaaclab_tasks/direct/cartpole_showcase/cartpole_camera/cartpole_camera_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/direct/cartpole_showcase/cartpole_camera/cartpole_camera_env_cfg.py index 0625bb2a1726..c81fe197bab1 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/direct/cartpole_showcase/cartpole_camera/cartpole_camera_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/direct/cartpole_showcase/cartpole_camera/cartpole_camera_env_cfg.py @@ -8,16 +8,16 @@ from gymnasium import spaces import isaaclab.sim as sim_utils -from isaaclab.sensors import TiledCameraCfg +from isaaclab.sensors import CameraCfg from isaaclab.utils import configclass from isaaclab_tasks.direct.cartpole.cartpole_camera_env_cfg import CartpoleRGBCameraEnvCfg as CartpoleCameraEnvCfg -def get_tiled_camera_cfg(data_type: str, width: int = 100, height: int = 100) -> TiledCameraCfg: - return TiledCameraCfg( +def get_tiled_camera_cfg(data_type: str, width: int = 100, height: int = 100) -> CameraCfg: + return CameraCfg( prim_path="/World/envs/env_.*/Camera", - offset=TiledCameraCfg.OffsetCfg(pos=(-5.0, 0.0, 2.0), rot=(0.0, 0.0, 0.0, 1.0), convention="world"), + offset=CameraCfg.OffsetCfg(pos=(-5.0, 0.0, 2.0), rot=(0.0, 0.0, 0.0, 1.0), convention="world"), data_types=[data_type], spawn=sim_utils.PinholeCameraCfg( focal_length=24.0, focus_distance=400.0, horizontal_aperture=20.955, clipping_range=(0.1, 20.0) @@ -53,7 +53,7 @@ class BoxBoxEnvCfg(CartpoleCameraEnvCfg): """ # camera - tiled_camera: TiledCameraCfg = get_tiled_camera_cfg("rgb") + tiled_camera: CameraCfg = get_tiled_camera_cfg("rgb") # spaces observation_space = spaces.Box( @@ -85,7 +85,7 @@ class BoxDiscreteEnvCfg(CartpoleCameraEnvCfg): """ # camera - tiled_camera: TiledCameraCfg = get_tiled_camera_cfg("rgb") + tiled_camera: CameraCfg = get_tiled_camera_cfg("rgb") # spaces observation_space = spaces.Box( @@ -124,7 +124,7 @@ class BoxMultiDiscreteEnvCfg(CartpoleCameraEnvCfg): """ # camera - tiled_camera: TiledCameraCfg = get_tiled_camera_cfg("rgb") + tiled_camera: CameraCfg = get_tiled_camera_cfg("rgb") # spaces observation_space = spaces.Box( @@ -160,7 +160,7 @@ class DictBoxEnvCfg(CartpoleCameraEnvCfg): """ # camera - tiled_camera: TiledCameraCfg = get_tiled_camera_cfg("rgb") + tiled_camera: CameraCfg = get_tiled_camera_cfg("rgb") # spaces observation_space = spaces.Dict( @@ -198,7 +198,7 @@ class DictDiscreteEnvCfg(CartpoleCameraEnvCfg): """ # camera - tiled_camera: TiledCameraCfg = get_tiled_camera_cfg("rgb") + tiled_camera: CameraCfg = get_tiled_camera_cfg("rgb") # spaces observation_space = spaces.Dict( @@ -243,7 +243,7 @@ class DictMultiDiscreteEnvCfg(CartpoleCameraEnvCfg): """ # camera - tiled_camera: TiledCameraCfg = get_tiled_camera_cfg("rgb") + tiled_camera: CameraCfg = get_tiled_camera_cfg("rgb") # spaces observation_space = spaces.Dict( @@ -284,7 +284,7 @@ class TupleBoxEnvCfg(CartpoleCameraEnvCfg): """ # camera - tiled_camera: TiledCameraCfg = get_tiled_camera_cfg("rgb") + tiled_camera: CameraCfg = get_tiled_camera_cfg("rgb") # spaces observation_space = spaces.Tuple( @@ -320,7 +320,7 @@ class TupleDiscreteEnvCfg(CartpoleCameraEnvCfg): """ # camera - tiled_camera: TiledCameraCfg = get_tiled_camera_cfg("rgb") + tiled_camera: CameraCfg = get_tiled_camera_cfg("rgb") # spaces observation_space = spaces.Tuple( @@ -363,7 +363,7 @@ class TupleMultiDiscreteEnvCfg(CartpoleCameraEnvCfg): """ # camera - tiled_camera: TiledCameraCfg = get_tiled_camera_cfg("rgb") + tiled_camera: CameraCfg = get_tiled_camera_cfg("rgb") # spaces observation_space = spaces.Tuple( diff --git a/source/isaaclab_tasks/isaaclab_tasks/direct/factory/factory_env.py b/source/isaaclab_tasks/isaaclab_tasks/direct/factory/factory_env.py index 10c1ad3e1a1a..ecc1ef33a038 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/direct/factory/factory_env.py +++ b/source/isaaclab_tasks/isaaclab_tasks/direct/factory/factory_env.py @@ -118,18 +118,18 @@ def _setup_scene(self): def _compute_intermediate_values(self, dt): """Get values computed from raw tensors. This includes adding noise.""" # TODO: A lot of these can probably only be set once? - self.fixed_pos = wp.to_torch(self._fixed_asset.data.root_pos_w) - self.scene.env_origins - self.fixed_quat = wp.to_torch(self._fixed_asset.data.root_quat_w) + self.fixed_pos = self._fixed_asset.data.root_pos_w.torch - self.scene.env_origins + self.fixed_quat = self._fixed_asset.data.root_quat_w.torch - self.held_pos = wp.to_torch(self._held_asset.data.root_pos_w) - self.scene.env_origins - self.held_quat = wp.to_torch(self._held_asset.data.root_quat_w) + self.held_pos = self._held_asset.data.root_pos_w.torch - self.scene.env_origins + self.held_quat = self._held_asset.data.root_quat_w.torch self.fingertip_midpoint_pos = ( - wp.to_torch(self._robot.data.body_pos_w)[:, self.fingertip_body_idx] - self.scene.env_origins + self._robot.data.body_pos_w.torch[:, self.fingertip_body_idx] - self.scene.env_origins ) - self.fingertip_midpoint_quat = wp.to_torch(self._robot.data.body_quat_w)[:, self.fingertip_body_idx] - self.fingertip_midpoint_linvel = wp.to_torch(self._robot.data.body_lin_vel_w)[:, self.fingertip_body_idx] - self.fingertip_midpoint_angvel = wp.to_torch(self._robot.data.body_ang_vel_w)[:, self.fingertip_body_idx] + self.fingertip_midpoint_quat = self._robot.data.body_quat_w.torch[:, self.fingertip_body_idx] + self.fingertip_midpoint_linvel = self._robot.data.body_lin_vel_w.torch[:, self.fingertip_body_idx] + self.fingertip_midpoint_angvel = self._robot.data.body_ang_vel_w.torch[:, self.fingertip_body_idx] jacobians = wp.to_torch(self._robot.root_view.get_jacobians()) @@ -137,8 +137,8 @@ def _compute_intermediate_values(self, dt): self.right_finger_jacobian = jacobians[:, self.right_finger_body_idx - 1, 0:6, 0:7] self.fingertip_midpoint_jacobian = (self.left_finger_jacobian + self.right_finger_jacobian) * 0.5 self.arm_mass_matrix = wp.to_torch(self._robot.root_view.get_generalized_mass_matrices())[:, 0:7, 0:7] - self.joint_pos = wp.to_torch(self._robot.data.joint_pos).clone() - self.joint_vel = wp.to_torch(self._robot.data.joint_vel).clone() + self.joint_pos = self._robot.data.joint_pos.torch.clone() + self.joint_vel = self._robot.data.joint_vel.torch.clone() # Finite-differencing results in more reliable velocity estimates. self.ee_linvel_fd = (self.fingertip_midpoint_pos - self.prev_fingertip_pos) / dt @@ -387,7 +387,9 @@ def _log_factory_metrics(self, rew_dict, curr_successes): """Keep track of episode statistics and log rewards.""" # Only log episode success rates at the end of an episode. if torch.any(self.reset_buf): - self.extras["successes"] = torch.count_nonzero(curr_successes) / self.num_envs + self.extras.setdefault("log", {})["Metrics/success_rate"] = ( + torch.count_nonzero(curr_successes) / self.num_envs + ).item() # Get the time at which an episode first succeeds. first_success = torch.logical_and(curr_successes, torch.logical_not(self.ep_succeeded)) @@ -499,16 +501,16 @@ def _reset_idx(self, env_ids): def _set_assets_to_default_pose(self, env_ids): """Move assets to default pose before randomization.""" - held_pose = wp.to_torch(self._held_asset.data.default_root_pose).clone()[env_ids] - held_vel = wp.to_torch(self._held_asset.data.default_root_vel).clone()[env_ids] + held_pose = self._held_asset.data.default_root_pose.torch.clone()[env_ids] + held_vel = self._held_asset.data.default_root_vel.torch.clone()[env_ids] held_pose[:, 0:3] += self.scene.env_origins[env_ids] held_vel[:] = 0.0 self._held_asset.write_root_pose_to_sim_index(root_pose=held_pose, env_ids=env_ids) self._held_asset.write_root_velocity_to_sim_index(root_velocity=held_vel, env_ids=env_ids) self._held_asset.reset() - fixed_pose = wp.to_torch(self._fixed_asset.data.default_root_pose).clone()[env_ids] - fixed_vel = wp.to_torch(self._fixed_asset.data.default_root_vel).clone()[env_ids] + fixed_pose = self._fixed_asset.data.default_root_pose.torch.clone()[env_ids] + fixed_vel = self._fixed_asset.data.default_root_vel.torch.clone()[env_ids] fixed_pose[:, 0:3] += self.scene.env_origins[env_ids] fixed_vel[:] = 0.0 self._fixed_asset.write_root_pose_to_sim_index(root_pose=fixed_pose, env_ids=env_ids) @@ -592,7 +594,7 @@ def get_handheld_asset_relative_pose(self): def _set_franka_to_default_pose(self, joints, env_ids): """Return Franka to its default joint position.""" gripper_width = self.cfg_task.held_asset_cfg.diameter / 2 * 1.25 - joint_pos = wp.to_torch(self._robot.data.default_joint_pos)[env_ids] + joint_pos = self._robot.data.default_joint_pos.torch[env_ids] joint_pos[:, 7:] = gripper_width # MIMIC joint_pos[:, :7] = torch.tensor(joints, device=self.device)[None, :] joint_vel = torch.zeros_like(joint_pos) @@ -624,8 +626,8 @@ def randomize_initial_state(self, env_ids): physics_sim_view.set_gravity(carb.Float3(0.0, 0.0, 0.0)) # (1.) Randomize fixed asset pose. - fixed_pose = wp.to_torch(self._fixed_asset.data.default_root_pose).clone()[env_ids] - fixed_vel = wp.to_torch(self._fixed_asset.data.default_root_vel).clone()[env_ids] + fixed_pose = self._fixed_asset.data.default_root_pose.torch.clone()[env_ids] + fixed_vel = self._fixed_asset.data.default_root_vel.torch.clone()[env_ids] # (1.a.) Position rand_sample = torch.rand((len(env_ids), 3), dtype=torch.float32, device=self.device) fixed_pos_init_rand = 2 * (rand_sample - 0.5) # [-1, 1] @@ -732,16 +734,16 @@ def randomize_initial_state(self, env_ids): # Add flanking gears after servo (so arm doesn't move them). if self.cfg_task.name == "gear_mesh" and self.cfg_task.add_flanking_gears: - small_gear_pose = wp.to_torch(self._small_gear_asset.data.default_root_pose).clone()[env_ids] - small_gear_vel = wp.to_torch(self._small_gear_asset.data.default_root_vel).clone()[env_ids] + small_gear_pose = self._small_gear_asset.data.default_root_pose.torch.clone()[env_ids] + small_gear_vel = self._small_gear_asset.data.default_root_vel.torch.clone()[env_ids] small_gear_pose[:, 0:7] = fixed_pose[:, 0:7] small_gear_vel[:] = 0.0 # vel self._small_gear_asset.write_root_pose_to_sim_index(root_pose=small_gear_pose, env_ids=env_ids) self._small_gear_asset.write_root_velocity_to_sim_index(root_velocity=small_gear_vel, env_ids=env_ids) self._small_gear_asset.reset() - large_gear_pose = wp.to_torch(self._large_gear_asset.data.default_root_pose).clone()[env_ids] - large_gear_vel = wp.to_torch(self._large_gear_asset.data.default_root_vel).clone()[env_ids] + large_gear_pose = self._large_gear_asset.data.default_root_pose.torch.clone()[env_ids] + large_gear_vel = self._large_gear_asset.data.default_root_vel.torch.clone()[env_ids] large_gear_pose[:, 0:7] = fixed_pose[:, 0:7] large_gear_vel[:] = 0.0 # vel self._large_gear_asset.write_root_pose_to_sim_index(root_pose=large_gear_pose, env_ids=env_ids) @@ -783,8 +785,8 @@ def randomize_initial_state(self, env_ids): torch.tensor([0.0, 0.0, 0.0, 1.0], device=self.device).unsqueeze(0).repeat(self.num_envs, 1), ) - held_pose = wp.to_torch(self._held_asset.data.default_root_pose).clone() - held_vel = wp.to_torch(self._held_asset.data.default_root_vel).clone() + held_pose = self._held_asset.data.default_root_pose.torch.clone() + held_vel = self._held_asset.data.default_root_vel.torch.clone() held_pose[:, 0:3] = translated_held_asset_pos + self.scene.env_origins held_pose[:, 3:7] = translated_held_asset_quat held_vel[:] = 0.0 diff --git a/source/isaaclab_tasks/isaaclab_tasks/direct/franka_cabinet/franka_cabinet_env.py b/source/isaaclab_tasks/isaaclab_tasks/direct/franka_cabinet/franka_cabinet_env.py index 0106e66c5950..3f3d341c1aad 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/direct/franka_cabinet/franka_cabinet_env.py +++ b/source/isaaclab_tasks/isaaclab_tasks/direct/franka_cabinet/franka_cabinet_env.py @@ -54,12 +54,8 @@ def get_env_local_pose(env_pos: torch.Tensor, xformable: UsdGeom.Xformable, devi self.dt = self.cfg.sim.dt * self.cfg.decimation # create auxiliary variables for computing applied action, observations and rewards - self.robot_dof_lower_limits = wp.to_torch(self._robot.data.soft_joint_pos_limits)[0, :, 0].to( - device=self.device - ) - self.robot_dof_upper_limits = wp.to_torch(self._robot.data.soft_joint_pos_limits)[0, :, 1].to( - device=self.device - ) + self.robot_dof_lower_limits = self._robot.data.soft_joint_pos_limits.torch[0, :, 0].to(device=self.device) + self.robot_dof_upper_limits = self._robot.data.soft_joint_pos_limits.torch[0, :, 1].to(device=self.device) self.robot_dof_speed_scales = torch.ones_like(self.robot_dof_lower_limits) self.robot_dof_speed_scales[self._robot.find_joints("panda_finger_joint1")[0]] = 0.1 @@ -126,6 +122,9 @@ def get_env_local_pose(env_pos: torch.Tensor, xformable: UsdGeom.Xformable, devi self.drawer_grasp_rot = torch.zeros((self.num_envs, 4), device=self.device) self.drawer_grasp_pos = torch.zeros((self.num_envs, 3), device=self.device) + # Sticky per-env flag: True once the drawer was opened past the success threshold. + self._episode_succeeded = torch.zeros(self.num_envs, dtype=torch.bool, device=self.device) + def _setup_scene(self): self._robot = Articulation(self.cfg.robot) self._cabinet = Articulation(self.cfg.cabinet) @@ -159,19 +158,19 @@ def _apply_action(self): # post-physics step calls def _get_dones(self) -> tuple[torch.Tensor, torch.Tensor]: - terminated = wp.to_torch(self._cabinet.data.joint_pos)[:, self.drawer_joint_idx] > 0.39 + terminated = self._cabinet.data.joint_pos.torch[:, self.drawer_joint_idx] > 0.39 truncated = self.episode_length_buf >= self.max_episode_length - 1 return terminated, truncated def _get_rewards(self) -> torch.Tensor: # Refresh the intermediate values after the physics steps self._compute_intermediate_values() - robot_left_finger_pos = wp.to_torch(self._robot.data.body_pos_w)[:, self.left_finger_link_idx] - robot_right_finger_pos = wp.to_torch(self._robot.data.body_pos_w)[:, self.right_finger_link_idx] + robot_left_finger_pos = self._robot.data.body_pos_w.torch[:, self.left_finger_link_idx] + robot_right_finger_pos = self._robot.data.body_pos_w.torch[:, self.right_finger_link_idx] - return self._compute_rewards( + reward = self._compute_rewards( self.actions, - wp.to_torch(self._cabinet.data.joint_pos), + self._cabinet.data.joint_pos.torch, self.robot_grasp_pos, self.drawer_grasp_pos, self.robot_grasp_rot, @@ -188,13 +187,23 @@ def _get_rewards(self) -> torch.Tensor: self.cfg.open_reward_scale, self.cfg.action_penalty_scale, self.cfg.finger_reward_scale, - wp.to_torch(self._robot.data.joint_pos), + self._robot.data.joint_pos.torch, ) + drawer_pos = self._cabinet.data.joint_pos.torch[:, self.drawer_joint_idx] + self._episode_succeeded |= drawer_pos > self.cfg.success_drawer_pos_threshold + return reward def _reset_idx(self, env_ids: torch.Tensor | None): + # Flush per-episode success (sticky binary: drawer ever opened past the cfg threshold). + drawer_pos = self._cabinet.data.joint_pos.torch[env_ids, self.drawer_joint_idx] + log = self.extras.setdefault("log", {}) + log["Metrics/success_rate"] = self._episode_succeeded[env_ids].float().mean().item() + log["Metrics/drawer_pos"] = drawer_pos.mean().item() + self._episode_succeeded[env_ids] = False + super()._reset_idx(env_ids) # robot state - joint_pos = wp.to_torch(self._robot.data.default_joint_pos)[env_ids] + sample_uniform( + joint_pos = self._robot.data.default_joint_pos.torch[env_ids] + sample_uniform( -0.125, 0.125, (len(env_ids), self._robot.num_joints), @@ -217,7 +226,7 @@ def _reset_idx(self, env_ids: torch.Tensor | None): def _get_observations(self) -> dict: dof_pos_scaled = ( 2.0 - * (wp.to_torch(self._robot.data.joint_pos) - self.robot_dof_lower_limits) + * (self._robot.data.joint_pos.torch - self.robot_dof_lower_limits) / (self.robot_dof_upper_limits - self.robot_dof_lower_limits) - 1.0 ) @@ -226,10 +235,10 @@ def _get_observations(self) -> dict: obs = torch.cat( ( dof_pos_scaled, - wp.to_torch(self._robot.data.joint_vel) * self.cfg.dof_velocity_scale, + self._robot.data.joint_vel.torch * self.cfg.dof_velocity_scale, to_target, - wp.to_torch(self._cabinet.data.joint_pos)[:, self.drawer_joint_idx].unsqueeze(-1), - wp.to_torch(self._cabinet.data.joint_vel)[:, self.drawer_joint_idx].unsqueeze(-1), + self._cabinet.data.joint_pos.torch[:, self.drawer_joint_idx].unsqueeze(-1), + self._cabinet.data.joint_vel.torch[:, self.drawer_joint_idx].unsqueeze(-1), ), dim=-1, ) @@ -241,10 +250,10 @@ def _compute_intermediate_values(self, env_ids: torch.Tensor | None = None): if env_ids is None: env_ids = wp.to_torch(self._robot._ALL_INDICES) - hand_pos = wp.to_torch(self._robot.data.body_pos_w)[env_ids, self.hand_link_idx] - hand_rot = wp.to_torch(self._robot.data.body_quat_w)[env_ids, self.hand_link_idx] - drawer_pos = wp.to_torch(self._cabinet.data.body_pos_w)[env_ids, self.drawer_link_idx] - drawer_rot = wp.to_torch(self._cabinet.data.body_quat_w)[env_ids, self.drawer_link_idx] + hand_pos = self._robot.data.body_pos_w.torch[env_ids, self.hand_link_idx] + hand_rot = self._robot.data.body_quat_w.torch[env_ids, self.hand_link_idx] + drawer_pos = self._cabinet.data.body_pos_w.torch[env_ids, self.drawer_link_idx] + drawer_rot = self._cabinet.data.body_quat_w.torch[env_ids, self.drawer_link_idx] ( self.robot_grasp_rot[env_ids], self.robot_grasp_pos[env_ids], diff --git a/source/isaaclab_tasks/isaaclab_tasks/direct/franka_cabinet/franka_cabinet_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/direct/franka_cabinet/franka_cabinet_env_cfg.py index 2114e5f184fb..32b7a88d3e9b 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/direct/franka_cabinet/franka_cabinet_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/direct/franka_cabinet/franka_cabinet_env_cfg.py @@ -149,3 +149,7 @@ class FrankaCabinetEnvCfg(DirectRLEnvCfg): open_reward_scale = 10.0 action_penalty_scale = 0.05 finger_reward_scale = 2.0 + + # success criteria + success_drawer_pos_threshold: float = 0.30 + """Drawer joint position above which the drawer is considered successfully opened [m].""" diff --git a/source/isaaclab_tasks/isaaclab_tasks/direct/humanoid/humanoid_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/direct/humanoid/humanoid_env_cfg.py index d68c6699e72c..b2b10dc2d911 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/direct/humanoid/humanoid_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/direct/humanoid/humanoid_env_cfg.py @@ -6,6 +6,7 @@ from __future__ import annotations from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg +from isaaclab_ovphysx.physics import OvPhysxCfg from isaaclab_physx.physics import PhysxCfg import isaaclab.sim as sim_utils @@ -25,7 +26,7 @@ class HumanoidPhysicsCfg(PresetCfg): default: PhysxCfg = PhysxCfg() physx: PhysxCfg = PhysxCfg() - newton: NewtonCfg = NewtonCfg( + newton_mjwarp: NewtonCfg = NewtonCfg( solver_cfg=MJWarpSolverCfg( njmax=80, nconmax=25, @@ -37,6 +38,7 @@ class HumanoidPhysicsCfg(PresetCfg): num_substeps=2, debug_mode=False, ) + ovphysx: OvPhysxCfg = OvPhysxCfg() @configclass diff --git a/source/isaaclab_tasks/isaaclab_tasks/direct/humanoid_amp/agents/skrl_dance_amp_cfg.yaml b/source/isaaclab_tasks/isaaclab_tasks/direct/humanoid_amp/agents/skrl_dance_amp_cfg.yaml index 3071d039b88c..437fa80c6058 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/direct/humanoid_amp/agents/skrl_dance_amp_cfg.yaml +++ b/source/isaaclab_tasks/isaaclab_tasks/direct/humanoid_amp/agents/skrl_dance_amp_cfg.yaml @@ -75,12 +75,14 @@ agent: learning_rate: 5.0e-05 learning_rate_scheduler: null learning_rate_scheduler_kwargs: null - state_preprocessor: RunningStandardScaler + observation_preprocessor: RunningStandardScaler + observation_preprocessor_kwargs: null + state_preprocessor: null state_preprocessor_kwargs: null value_preprocessor: RunningStandardScaler value_preprocessor_kwargs: null - amp_state_preprocessor: RunningStandardScaler - amp_state_preprocessor_kwargs: null + amp_observation_preprocessor: RunningStandardScaler + amp_observation_preprocessor_kwargs: null random_timesteps: 0 learning_starts: 0 grad_norm_clip: 0.0 @@ -91,10 +93,9 @@ agent: value_loss_scale: 2.5 discriminator_loss_scale: 5.0 amp_batch_size: 512 - task_reward_weight: 0.0 - style_reward_weight: 1.0 + task_reward_scale: 0.0 + style_reward_scale: 2.0 discriminator_batch_size: 4096 - discriminator_reward_scale: 2.0 discriminator_logit_regularization_scale: 0.05 discriminator_gradient_penalty_scale: 5.0 discriminator_weight_decay_scale: 1.0e-04 diff --git a/source/isaaclab_tasks/isaaclab_tasks/direct/humanoid_amp/agents/skrl_run_amp_cfg.yaml b/source/isaaclab_tasks/isaaclab_tasks/direct/humanoid_amp/agents/skrl_run_amp_cfg.yaml index 0f6fcdc1a03f..fa3c590a9584 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/direct/humanoid_amp/agents/skrl_run_amp_cfg.yaml +++ b/source/isaaclab_tasks/isaaclab_tasks/direct/humanoid_amp/agents/skrl_run_amp_cfg.yaml @@ -75,12 +75,14 @@ agent: learning_rate: 5.0e-05 learning_rate_scheduler: null learning_rate_scheduler_kwargs: null - state_preprocessor: RunningStandardScaler + observation_preprocessor: RunningStandardScaler + observation_preprocessor_kwargs: null + state_preprocessor: null state_preprocessor_kwargs: null value_preprocessor: RunningStandardScaler value_preprocessor_kwargs: null - amp_state_preprocessor: RunningStandardScaler - amp_state_preprocessor_kwargs: null + amp_observation_preprocessor: RunningStandardScaler + amp_observation_preprocessor_kwargs: null random_timesteps: 0 learning_starts: 0 grad_norm_clip: 0.0 @@ -91,10 +93,9 @@ agent: value_loss_scale: 2.5 discriminator_loss_scale: 5.0 amp_batch_size: 512 - task_reward_weight: 0.0 - style_reward_weight: 1.0 + task_reward_scale: 0.0 + style_reward_scale: 2.0 discriminator_batch_size: 4096 - discriminator_reward_scale: 2.0 discriminator_logit_regularization_scale: 0.05 discriminator_gradient_penalty_scale: 5.0 discriminator_weight_decay_scale: 1.0e-04 diff --git a/source/isaaclab_tasks/isaaclab_tasks/direct/humanoid_amp/agents/skrl_walk_amp_cfg.yaml b/source/isaaclab_tasks/isaaclab_tasks/direct/humanoid_amp/agents/skrl_walk_amp_cfg.yaml index efb34f0d2f5b..8b52c661d48b 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/direct/humanoid_amp/agents/skrl_walk_amp_cfg.yaml +++ b/source/isaaclab_tasks/isaaclab_tasks/direct/humanoid_amp/agents/skrl_walk_amp_cfg.yaml @@ -75,12 +75,14 @@ agent: learning_rate: 5.0e-05 learning_rate_scheduler: null learning_rate_scheduler_kwargs: null - state_preprocessor: RunningStandardScaler + observation_preprocessor: RunningStandardScaler + observation_preprocessor_kwargs: null + state_preprocessor: null state_preprocessor_kwargs: null value_preprocessor: RunningStandardScaler value_preprocessor_kwargs: null - amp_state_preprocessor: RunningStandardScaler - amp_state_preprocessor_kwargs: null + amp_observation_preprocessor: RunningStandardScaler + amp_observation_preprocessor_kwargs: null random_timesteps: 0 learning_starts: 0 grad_norm_clip: 0.0 @@ -91,10 +93,9 @@ agent: value_loss_scale: 2.5 discriminator_loss_scale: 5.0 amp_batch_size: 512 - task_reward_weight: 0.0 - style_reward_weight: 1.0 + task_reward_scale: 0.0 + style_reward_scale: 2.0 discriminator_batch_size: 4096 - discriminator_reward_scale: 2.0 discriminator_logit_regularization_scale: 0.05 discriminator_gradient_penalty_scale: 5.0 discriminator_weight_decay_scale: 1.0e-04 diff --git a/source/isaaclab_tasks/isaaclab_tasks/direct/humanoid_amp/humanoid_amp_env.py b/source/isaaclab_tasks/isaaclab_tasks/direct/humanoid_amp/humanoid_amp_env.py index ccd82d79dc5c..7c0fe5036132 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/direct/humanoid_amp/humanoid_amp_env.py +++ b/source/isaaclab_tasks/isaaclab_tasks/direct/humanoid_amp/humanoid_amp_env.py @@ -27,7 +27,7 @@ def __init__(self, cfg: HumanoidAmpEnvCfg, render_mode: str | None = None, **kwa super().__init__(cfg, render_mode, **kwargs) # action offset and scale - soft_joint_pos_limits = wp.to_torch(self.robot.data.soft_joint_pos_limits) + soft_joint_pos_limits = self.robot.data.soft_joint_pos_limits.torch dof_lower_limits = soft_joint_pos_limits[0, :, 0] dof_upper_limits = soft_joint_pos_limits[0, :, 1] self.action_offset = 0.5 * (dof_upper_limits + dof_lower_limits) @@ -86,13 +86,13 @@ def _apply_action(self): def _get_observations(self) -> dict: # build task observation obs = compute_obs( - wp.to_torch(self.robot.data.joint_pos), - wp.to_torch(self.robot.data.joint_vel), - wp.to_torch(self.robot.data.body_pos_w)[:, self.ref_body_index], - wp.to_torch(self.robot.data.body_quat_w)[:, self.ref_body_index], - wp.to_torch(self.robot.data.body_lin_vel_w)[:, self.ref_body_index], - wp.to_torch(self.robot.data.body_ang_vel_w)[:, self.ref_body_index], - wp.to_torch(self.robot.data.body_pos_w)[:, self.key_body_indexes], + self.robot.data.joint_pos.torch, + self.robot.data.joint_vel.torch, + self.robot.data.body_pos_w.torch[:, self.ref_body_index], + self.robot.data.body_quat_w.torch[:, self.ref_body_index], + self.robot.data.body_lin_vel_w.torch[:, self.ref_body_index], + self.robot.data.body_ang_vel_w.torch[:, self.ref_body_index], + self.robot.data.body_pos_w.torch[:, self.key_body_indexes], ) # update AMP observation history @@ -110,7 +110,7 @@ def _get_rewards(self) -> torch.Tensor: def _get_dones(self) -> tuple[torch.Tensor, torch.Tensor]: time_out = self.episode_length_buf >= self.max_episode_length - 1 if self.cfg.early_termination: - died = wp.to_torch(self.robot.data.body_pos_w)[:, self.ref_body_index, 2] < self.cfg.termination_height + died = self.robot.data.body_pos_w.torch[:, self.ref_body_index, 2] < self.cfg.termination_height else: died = torch.zeros_like(time_out) return died, time_out @@ -142,12 +142,12 @@ def _reset_idx(self, env_ids: torch.Tensor | None): # reset strategies def _reset_strategy_default(self, env_ids: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: - default_root_pose = wp.to_torch(self.robot.data.default_root_pose)[env_ids].clone() - default_root_vel = wp.to_torch(self.robot.data.default_root_vel)[env_ids].clone() + default_root_pose = self.robot.data.default_root_pose.torch[env_ids].clone() + default_root_vel = self.robot.data.default_root_vel.torch[env_ids].clone() default_root_pose[:, :3] += self.scene.env_origins[env_ids] root_state = torch.cat([default_root_pose, default_root_vel], dim=-1) - joint_pos = self.robot.data.default_joint_pos[env_ids].clone() - joint_vel = self.robot.data.default_joint_vel[env_ids].clone() + joint_pos = self.robot.data.default_joint_pos.torch[env_ids].clone() + joint_vel = self.robot.data.default_joint_vel.torch[env_ids].clone() return root_state, joint_pos, joint_vel def _reset_strategy_random( @@ -170,8 +170,8 @@ def _reset_strategy_random( motion_torso_index = self._motion_loader.get_body_index(["torso"])[0] root_state = torch.cat( [ - wp.to_torch(self.robot.data.default_root_pose)[env_ids], - wp.to_torch(self.robot.data.default_root_vel)[env_ids], + self.robot.data.default_root_pose.torch[env_ids], + self.robot.data.default_root_vel.torch[env_ids], ], dim=-1, ).clone() diff --git a/source/isaaclab_tasks/isaaclab_tasks/direct/inhand_manipulation/inhand_manipulation_env.py b/source/isaaclab_tasks/isaaclab_tasks/direct/inhand_manipulation/inhand_manipulation_env.py index 66a09e7e3cde..5969d8c9c4be 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/direct/inhand_manipulation/inhand_manipulation_env.py +++ b/source/isaaclab_tasks/isaaclab_tasks/direct/inhand_manipulation/inhand_manipulation_env.py @@ -11,12 +11,12 @@ import numpy as np import torch -import warp as wp import isaaclab.sim as sim_utils from isaaclab.assets import Articulation, RigidObject from isaaclab.envs import DirectRLEnv from isaaclab.markers import VisualizationMarkers +from isaaclab.sensors import JointWrenchSensor, JointWrenchSensorCfg from isaaclab.sim.spawners.from_files import GroundPlaneCfg, spawn_ground_plane from isaaclab.utils.math import quat_conjugate, quat_from_angle_axis, quat_mul, sample_uniform, saturate @@ -51,15 +51,21 @@ def __init__(self, cfg: AllegroHandEnvCfg | ShadowHandEnvCfg, render_mode: str | self.finger_bodies.sort() self.num_fingertips = len(self.finger_bodies) + self.finger_wrench_bodies = [] + if getattr(self, "_joint_wrench_sensor", None) is not None: + for body_name in self.cfg.fingertip_body_names: + self.finger_wrench_bodies.append(self._joint_wrench_sensor.body_names.index(body_name)) + self.finger_wrench_bodies.sort() + # joint limits - joint_pos_limits = wp.to_torch(self.hand.data.joint_limits).to(self.device) + joint_pos_limits = self.hand.data.joint_limits.torch.to(self.device) self.hand_dof_lower_limits = joint_pos_limits[..., 0] self.hand_dof_upper_limits = joint_pos_limits[..., 1] # track goal resets self.reset_goal_buf = torch.zeros(self.num_envs, dtype=torch.bool, device=self.device) # used to compare object position - self.in_hand_pos = wp.to_torch(self.object.data.default_root_pose)[:, 0:3].clone() + self.in_hand_pos = self.object.data.default_root_pose.torch[:, 0:3].clone() self.in_hand_pos[:, 2] -= 0.04 # default goal positions self.goal_rot = torch.zeros((self.num_envs, 4), dtype=torch.float, device=self.device) @@ -72,6 +78,7 @@ def __init__(self, cfg: AllegroHandEnvCfg | ShadowHandEnvCfg, render_mode: str | # track successes self.successes = torch.zeros(self.num_envs, dtype=torch.float, device=self.device) self.consecutive_successes = torch.zeros(1, dtype=torch.float, device=self.device) + self._last_episode_success = torch.zeros(self.num_envs, dtype=torch.bool, device=self.device) # unit tensors self.x_unit_tensor = torch.tensor([1, 0, 0], dtype=torch.float, device=self.device).repeat((self.num_envs, 1)) @@ -97,6 +104,9 @@ def _setup_scene(self): # add hand, in-hand object, and goal object self.hand = Articulation(self.cfg.robot_cfg) self.object: Articulation | RigidObject = self.cfg.object_cfg.class_type(self.cfg.object_cfg) + self._joint_wrench_sensor = None + if self.cfg.asymmetric_obs: + self._joint_wrench_sensor = self._create_joint_wrench_sensor() # add ground plane spawn_ground_plane(prim_path="/World/ground", cfg=GroundPlaneCfg()) # clone and replicate (no need to filter for this environment) @@ -104,10 +114,16 @@ def _setup_scene(self): # add articulation to scene - we must register to scene to randomize with EventManager self.scene.articulations["robot"] = self.hand self.scene.rigid_objects["object"] = self.object + if self._joint_wrench_sensor is not None: + self.scene.sensors["joint_wrench"] = self._joint_wrench_sensor # add lights light_cfg = sim_utils.DomeLightCfg(intensity=2000.0, color=(0.75, 0.75, 0.75)) light_cfg.func("/World/Light", light_cfg) + def _create_joint_wrench_sensor(self) -> JointWrenchSensor: + """Create the joint-wrench sensor used for fingertip force/torque observations.""" + return JointWrenchSensor(JointWrenchSensorCfg(prim_path=self.cfg.robot_cfg.prim_path)) + def _pre_physics_step(self, actions: torch.Tensor) -> None: self.actions = actions.clone() @@ -135,15 +151,7 @@ def _apply_action(self) -> None: def _get_observations(self) -> dict: if self.cfg.asymmetric_obs: - # Newton does not implement body_incoming_joint_wrench_b; fall back to zeros. - try: - self.fingertip_force_sensors = wp.to_torch(self.hand.data.body_incoming_joint_wrench_b)[ - :, self.finger_bodies - ] - except NotImplementedError: - self.fingertip_force_sensors = torch.zeros( - self.num_envs, len(self.finger_bodies), 6, dtype=torch.float32, device=self.device - ) + self._update_fingertip_force_sensors() if self.cfg.obs_type == "openai": obs = self.compute_reduced_observations() @@ -160,6 +168,27 @@ def _get_observations(self) -> dict: observations = {"policy": obs, "critic": states} return observations + def _update_fingertip_force_sensors(self) -> None: + """Update fingertip force/torque observations from the joint-wrench sensor.""" + if getattr(self, "_joint_wrench_sensor", None) is None: + self.fingertip_force_sensors = torch.zeros( + self.num_envs, len(self.finger_bodies), 6, dtype=torch.float32, device=self.device + ) + return + + sensor_data = self._joint_wrench_sensor.data + force_data = sensor_data.force + torque_data = sensor_data.torque + if force_data is None or torque_data is None: + self.fingertip_force_sensors = torch.zeros( + self.num_envs, len(self.finger_bodies), 6, dtype=torch.float32, device=self.device + ) + return + + force = force_data.torch[:, self.finger_wrench_bodies] + torque = torque_data.torch[:, self.finger_wrench_bodies] + self.fingertip_force_sensors = torch.cat((force, torque), dim=-1) + def _get_rewards(self) -> torch.Tensor: ( total_reward, @@ -222,14 +251,20 @@ def _get_dones(self) -> tuple[torch.Tensor, torch.Tensor]: return out_of_reach, time_out def _reset_idx(self, env_ids: Sequence[int]): + # Episode counts as successful when goals reached >= cfg.success_count_threshold. + self._last_episode_success[env_ids] = self.successes[env_ids] >= self.cfg.success_count_threshold + self.extras.setdefault("log", {})["Metrics/success_rate"] = ( + self._last_episode_success[env_ids].float().mean().item() + ) + super()._reset_idx(env_ids) # reset goals self._reset_target_pose(env_ids) # reset object - object_default_pose = wp.to_torch(self.object.data.default_root_pose).clone()[env_ids] - object_default_vel = wp.to_torch(self.object.data.default_root_vel).clone()[env_ids] + object_default_pose = self.object.data.default_root_pose.torch.clone()[env_ids] + object_default_vel = self.object.data.default_root_vel.torch.clone()[env_ids] pos_noise = sample_uniform(-1.0, 1.0, (len(env_ids), 3), device=self.device) # global object positions object_default_pose[:, 0:3] = ( @@ -246,15 +281,15 @@ def _reset_idx(self, env_ids: Sequence[int]): self._write_obj_root_vel(root_velocity=object_default_vel, env_ids=env_ids) # reset hand - delta_max = self.hand_dof_upper_limits[env_ids] - wp.to_torch(self.hand.data.default_joint_pos)[env_ids] - delta_min = self.hand_dof_lower_limits[env_ids] - wp.to_torch(self.hand.data.default_joint_pos)[env_ids] + delta_max = self.hand_dof_upper_limits[env_ids] - self.hand.data.default_joint_pos.torch[env_ids] + delta_min = self.hand_dof_lower_limits[env_ids] - self.hand.data.default_joint_pos.torch[env_ids] dof_pos_noise = sample_uniform(-1.0, 1.0, (len(env_ids), self.num_hand_dofs), device=self.device) rand_delta = delta_min + (delta_max - delta_min) * 0.5 * dof_pos_noise - dof_pos = wp.to_torch(self.hand.data.default_joint_pos)[env_ids] + self.cfg.reset_dof_pos_noise * rand_delta + dof_pos = self.hand.data.default_joint_pos.torch[env_ids] + self.cfg.reset_dof_pos_noise * rand_delta dof_vel_noise = sample_uniform(-1.0, 1.0, (len(env_ids), self.num_hand_dofs), device=self.device) - dof_vel = wp.to_torch(self.hand.data.default_joint_vel)[env_ids] + self.cfg.reset_dof_vel_noise * dof_vel_noise + dof_vel = self.hand.data.default_joint_vel.torch[env_ids] + self.cfg.reset_dof_vel_noise * dof_vel_noise self.prev_targets[env_ids] = dof_pos self.cur_targets[env_ids] = dof_pos @@ -283,22 +318,22 @@ def _reset_target_pose(self, env_ids): def _compute_intermediate_values(self): # data for hand - self.fingertip_pos = wp.to_torch(self.hand.data.body_pos_w)[:, self.finger_bodies] - self.fingertip_rot = wp.to_torch(self.hand.data.body_quat_w)[:, self.finger_bodies] + self.fingertip_pos = self.hand.data.body_pos_w.torch[:, self.finger_bodies] + self.fingertip_rot = self.hand.data.body_quat_w.torch[:, self.finger_bodies] self.fingertip_pos -= self.scene.env_origins.repeat((1, self.num_fingertips)).reshape( self.num_envs, self.num_fingertips, 3 ) - self.fingertip_velocities = wp.to_torch(self.hand.data.body_vel_w)[:, self.finger_bodies] + self.fingertip_velocities = self.hand.data.body_vel_w.torch[:, self.finger_bodies] - self.hand_dof_pos = wp.to_torch(self.hand.data.joint_pos) - self.hand_dof_vel = wp.to_torch(self.hand.data.joint_vel) + self.hand_dof_pos = self.hand.data.joint_pos.torch + self.hand_dof_vel = self.hand.data.joint_vel.torch # data for object - self.object_pos = wp.to_torch(self.object.data.root_pos_w) - self.scene.env_origins - self.object_rot = wp.to_torch(self.object.data.root_quat_w) - self.object_velocities = wp.to_torch(self.object.data.root_vel_w) - self.object_linvel = wp.to_torch(self.object.data.root_lin_vel_w) - self.object_angvel = wp.to_torch(self.object.data.root_ang_vel_w) + self.object_pos = self.object.data.root_pos_w.torch - self.scene.env_origins + self.object_rot = self.object.data.root_quat_w.torch + self.object_velocities = self.object.data.root_vel_w.torch + self.object_linvel = self.object.data.root_lin_vel_w.torch + self.object_angvel = self.object.data.root_ang_vel_w.torch def compute_reduced_observations(self): # Per https://arxiv.org/pdf/1808.00177.pdf Table 2 diff --git a/source/isaaclab_tasks/isaaclab_tasks/direct/locomotion/locomotion_env.py b/source/isaaclab_tasks/isaaclab_tasks/direct/locomotion/locomotion_env.py index f613efb02d86..f97871ca83bf 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/direct/locomotion/locomotion_env.py +++ b/source/isaaclab_tasks/isaaclab_tasks/direct/locomotion/locomotion_env.py @@ -8,6 +8,7 @@ import torch import warp as wp from isaaclab_newton.physics import NewtonCfg +from isaaclab_ovphysx.physics import OvPhysxCfg from isaaclab_physx.physics import PhysxCfg import isaaclab.sim as sim_utils @@ -79,7 +80,7 @@ def __init__(self, cfg: DirectRLEnvCfg, render_mode: str | None = None, **kwargs self.action_scale = self.cfg.action_scale # Resolve the joint gears based on the physics type, since they do not have the same joint ordering. if isinstance(self.cfg.joint_gears, dict): - if isinstance(self.cfg.sim.physics, PhysxCfg): + if isinstance(self.cfg.sim.physics, (PhysxCfg, OvPhysxCfg)): joint_gears = self.cfg.joint_gears["physx"] elif isinstance(self.cfg.sim.physics, NewtonCfg): joint_gears = self.cfg.joint_gears["newton"] @@ -132,14 +133,14 @@ def _apply_action(self): def _compute_intermediate_values(self): self.torso_position, self.torso_rotation = ( - wp.to_torch(self.robot.data.root_pos_w), - wp.to_torch(self.robot.data.root_quat_w), + self.robot.data.root_pos_w.torch, + self.robot.data.root_quat_w.torch, ) self.velocity, self.ang_velocity = ( - wp.to_torch(self.robot.data.root_lin_vel_w), - wp.to_torch(self.robot.data.root_ang_vel_w), + self.robot.data.root_lin_vel_w.torch, + self.robot.data.root_ang_vel_w.torch, ) - self.dof_pos, self.dof_vel = wp.to_torch(self.robot.data.joint_pos), wp.to_torch(self.robot.data.joint_vel) + self.dof_pos, self.dof_vel = self.robot.data.joint_pos.torch, self.robot.data.joint_vel.torch ( self.up_proj, @@ -162,8 +163,8 @@ def _compute_intermediate_values(self): self.velocity, self.ang_velocity, self.dof_pos, - wp.to_torch(self.robot.data.soft_joint_pos_limits)[0, :, 0], - wp.to_torch(self.robot.data.soft_joint_pos_limits)[0, :, 1], + self.robot.data.soft_joint_pos_limits.torch[0, :, 0], + self.robot.data.soft_joint_pos_limits.torch[0, :, 1], self.inv_start_rot, self.basis_vec0, self.basis_vec1, @@ -222,13 +223,18 @@ def _get_dones(self) -> tuple[torch.Tensor, torch.Tensor]: def _reset_idx(self, env_ids: torch.Tensor | None): if env_ids is None or len(env_ids) == self.num_envs: env_ids = wp.to_torch(self.robot._ALL_INDICES) + + # Log survival success rate (survived = timed out without falling) + survived = self.reset_time_outs[env_ids].float() + self.extras.setdefault("log", {})["Metrics/success_rate"] = survived.mean().item() + self.robot.reset(env_ids) super()._reset_idx(env_ids) - joint_pos = wp.to_torch(self.robot.data.default_joint_pos)[env_ids].clone() - joint_vel = wp.to_torch(self.robot.data.default_joint_vel)[env_ids].clone() - default_root_pose = wp.to_torch(self.robot.data.default_root_pose)[env_ids].clone() - default_root_vel = wp.to_torch(self.robot.data.default_root_vel)[env_ids].clone() + joint_pos = self.robot.data.default_joint_pos.torch[env_ids].clone() + joint_vel = self.robot.data.default_joint_vel.torch[env_ids].clone() + default_root_pose = self.robot.data.default_root_pose.torch[env_ids].clone() + default_root_vel = self.robot.data.default_root_vel.torch[env_ids].clone() default_root_pose[:, :3] += self.scene.env_origins[env_ids] self.robot.write_root_pose_to_sim_index(root_pose=default_root_pose, env_ids=env_ids) diff --git a/source/isaaclab_tasks/isaaclab_tasks/direct/quadcopter/quadcopter_env.py b/source/isaaclab_tasks/isaaclab_tasks/direct/quadcopter/quadcopter_env.py index 51ad02d88958..c1e3a1b3c9ee 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/direct/quadcopter/quadcopter_env.py +++ b/source/isaaclab_tasks/isaaclab_tasks/direct/quadcopter/quadcopter_env.py @@ -54,6 +54,9 @@ def __init__(self, cfg: QuadcopterEnvCfg, render_mode: str | None = None, **kwar # Goal position self._desired_pos_w = torch.zeros(self.num_envs, 3, device=self.device) + # per-env count of steps meeting the success condition + self._success_step_count = torch.zeros(self.num_envs, dtype=torch.long, device=self.device) + # Logging self._episode_sums = { key: torch.zeros(self.num_envs, dtype=torch.float, device=self.device) @@ -100,13 +103,13 @@ def _apply_action(self): def _get_observations(self) -> dict: desired_pos_b, _ = subtract_frame_transforms( - wp.to_torch(self._robot.data.root_pos_w), wp.to_torch(self._robot.data.root_quat_w), self._desired_pos_w + self._robot.data.root_pos_w.torch, self._robot.data.root_quat_w.torch, self._desired_pos_w ) obs = torch.cat( [ - wp.to_torch(self._robot.data.root_lin_vel_b), - wp.to_torch(self._robot.data.root_ang_vel_b), - wp.to_torch(self._robot.data.projected_gravity_b), + self._robot.data.root_lin_vel_b.torch, + self._robot.data.root_ang_vel_b.torch, + self._robot.data.projected_gravity_b.torch, desired_pos_b, ], dim=-1, @@ -115,9 +118,9 @@ def _get_observations(self) -> dict: return observations def _get_rewards(self) -> torch.Tensor: - lin_vel = torch.sum(torch.square(wp.to_torch(self._robot.data.root_lin_vel_b)), dim=1) - ang_vel = torch.sum(torch.square(wp.to_torch(self._robot.data.root_ang_vel_b)), dim=1) - distance_to_goal = torch.linalg.norm(self._desired_pos_w - wp.to_torch(self._robot.data.root_pos_w), dim=1) + lin_vel = torch.sum(torch.square(self._robot.data.root_lin_vel_b.torch), dim=1) + ang_vel = torch.sum(torch.square(self._robot.data.root_ang_vel_b.torch), dim=1) + distance_to_goal = torch.linalg.norm(self._desired_pos_w - self._robot.data.root_pos_w.torch, dim=1) distance_to_goal_mapped = 1 - torch.tanh(distance_to_goal / 0.8) rewards = { "lin_vel": lin_vel * self.cfg.lin_vel_reward_scale * self.step_dt, @@ -125,6 +128,8 @@ def _get_rewards(self) -> torch.Tensor: "distance_to_goal": distance_to_goal_mapped * self.cfg.distance_to_goal_reward_scale * self.step_dt, } reward = torch.sum(torch.stack(list(rewards.values())), dim=0) + # Accumulate per-step in-region count for the hover success criterion. + self._success_step_count += (distance_to_goal < self.cfg.success_distance_threshold).long() # Logging for key, value in rewards.items(): self._episode_sums[key] += value @@ -133,7 +138,7 @@ def _get_rewards(self) -> torch.Tensor: def _get_dones(self) -> tuple[torch.Tensor, torch.Tensor]: time_out = self.episode_length_buf >= self.max_episode_length - 1 died = torch.logical_or( - wp.to_torch(self._robot.data.root_pos_w)[:, 2] < 0.1, wp.to_torch(self._robot.data.root_pos_w)[:, 2] > 2.0 + self._robot.data.root_pos_w.torch[:, 2] < 0.1, self._robot.data.root_pos_w.torch[:, 2] > 2.0 ) return died, time_out @@ -143,7 +148,7 @@ def _reset_idx(self, env_ids: torch.Tensor | None): # Logging final_distance_to_goal = torch.linalg.norm( - self._desired_pos_w[env_ids] - wp.to_torch(self._robot.data.root_pos_w)[env_ids], dim=1 + self._desired_pos_w[env_ids] - self._robot.data.root_pos_w.torch[env_ids], dim=1 ).mean() extras = dict() for key in self._episode_sums.keys(): @@ -156,6 +161,11 @@ def _reset_idx(self, env_ids: torch.Tensor | None): extras["Episode_Termination/died"] = torch.count_nonzero(self.reset_terminated[env_ids]).item() extras["Episode_Termination/time_out"] = torch.count_nonzero(self.reset_time_outs[env_ids]).item() extras["Metrics/final_distance_to_goal"] = final_distance_to_goal.item() + success_step_threshold = int(self.max_episode_length * self.cfg.success_step_ratio) + extras["Metrics/success_rate"] = ( + (self._success_step_count[env_ids] >= success_step_threshold).float().mean().item() + ) + self._success_step_count[env_ids] = 0 self.extras["log"].update(extras) self._robot.reset(env_ids) @@ -170,10 +180,10 @@ def _reset_idx(self, env_ids: torch.Tensor | None): self._desired_pos_w[env_ids, :2] += self._terrain.env_origins[env_ids, :2] self._desired_pos_w[env_ids, 2] = torch.zeros_like(self._desired_pos_w[env_ids, 2]).uniform_(0.5, 1.5) # Reset robot state - joint_pos = wp.to_torch(self._robot.data.default_joint_pos)[env_ids] - joint_vel = wp.to_torch(self._robot.data.default_joint_vel)[env_ids] - default_root_pose = wp.to_torch(self._robot.data.default_root_pose)[env_ids] - default_root_vel = wp.to_torch(self._robot.data.default_root_vel)[env_ids] + joint_pos = self._robot.data.default_joint_pos.torch[env_ids] + joint_vel = self._robot.data.default_joint_vel.torch[env_ids] + default_root_pose = self._robot.data.default_root_pose.torch[env_ids] + default_root_vel = self._robot.data.default_root_vel.torch[env_ids] default_root_pose[:, :3] += self._terrain.env_origins[env_ids] self._robot.write_root_pose_to_sim_index(root_pose=default_root_pose, env_ids=env_ids) self._robot.write_root_velocity_to_sim_index(root_velocity=default_root_vel, env_ids=env_ids) diff --git a/source/isaaclab_tasks/isaaclab_tasks/direct/quadcopter/quadcopter_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/direct/quadcopter/quadcopter_env_cfg.py index bada387b80d4..d893535fe210 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/direct/quadcopter/quadcopter_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/direct/quadcopter/quadcopter_env_cfg.py @@ -68,3 +68,9 @@ class QuadcopterEnvCfg(DirectRLEnvCfg): lin_vel_reward_scale = -0.05 ang_vel_reward_scale = -0.01 distance_to_goal_reward_scale = 15.0 + + # success criteria (hovering task: success requires staying near goal for a fraction of the episode) + success_distance_threshold: float = 0.5 + """Distance to goal below which a step counts toward the hover success criterion [m].""" + success_step_ratio: float = 0.25 + """Fraction of episode steps that must satisfy the distance threshold for the episode to count as successful.""" diff --git a/source/isaaclab_tasks/isaaclab_tasks/direct/shadow_hand/feature_extractor.py b/source/isaaclab_tasks/isaaclab_tasks/direct/shadow_hand/feature_extractor.py index 84a2e8df2a54..d7dedbf196a6 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/direct/shadow_hand/feature_extractor.py +++ b/source/isaaclab_tasks/isaaclab_tasks/direct/shadow_hand/feature_extractor.py @@ -168,15 +168,15 @@ def __init__( cfg: Configuration for the feature extractor model. device: Device to run the model on. data_types: Ordered list of camera data types that form the CNN input channel - stack. Should match the resolved :attr:`~isaaclab.sensors.TiledCameraCfg.data_types` - of the tiled camera. Total input channels are derived from + stack. Should match the resolved :attr:`~isaaclab.sensors.CameraCfg.data_types` + of the camera. Total input channels are derived from :data:`_DATA_TYPE_CHANNELS`. log_dir: Directory to save checkpoints. Default is None, which uses the local "logs" folder resolved relative to this file. - height: Camera image height [px]. Must match the tiled camera - :attr:`~isaaclab.sensors.TiledCameraCfg.height`. Default is ``120``. - width: Camera image width [px]. Must match the tiled camera - :attr:`~isaaclab.sensors.TiledCameraCfg.width`. Default is ``120``. + height: Camera image height [px]. Must match the camera + :attr:`~isaaclab.sensors.CameraCfg.height`. Default is ``120``. + width: Camera image width [px]. Must match the camera + :attr:`~isaaclab.sensors.CameraCfg.width`. Default is ``120``. """ self.cfg = cfg self.device = device diff --git a/source/isaaclab_tasks/isaaclab_tasks/direct/shadow_hand/shadow_hand_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/direct/shadow_hand/shadow_hand_env_cfg.py index 37ac81cf1464..0a2258d0b0b1 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/direct/shadow_hand/shadow_hand_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/direct/shadow_hand/shadow_hand_env_cfg.py @@ -120,7 +120,7 @@ class PhysxEventCfg: @configclass class ShadowHandEventCfg(PresetCfg): physx = PhysxEventCfg() - newton = NewtonEventCfg() + newton_mjwarp = NewtonEventCfg() default = physx @@ -133,7 +133,7 @@ class ShadowHandRobotCfg(PresetCfg): joint_pos={".*": 0.0}, ) ) - newton = ArticulationCfg( + newton_mjwarp = ArticulationCfg( prim_path="/World/envs/env_.*/Robot", spawn=sim_utils.UsdFileCfg( # newton requires implicitactuators be specified in usd and there's a bug with physx tendons @@ -217,7 +217,7 @@ class ObjectCfg(PresetCfg): init_state=RigidObjectCfg.InitialStateCfg(pos=(0.0, -0.39, 0.6), rot=(0.0, 0.0, 0.0, 1.0)), ) - newton = ArticulationCfg( + newton_mjwarp = ArticulationCfg( prim_path="/World/envs/env_.*/object", spawn=sim_utils.UsdFileCfg( usd_path=f"{ISAAC_NUCLEUS_DIR}/Props/Blocks/DexCube/dex_cube_instanceable.usd", @@ -245,7 +245,7 @@ class ShadowHandSceneCfg(PresetCfg): physx: InteractiveSceneCfg = InteractiveSceneCfg( num_envs=8192, env_spacing=0.75, replicate_physics=True, clone_in_fabric=True ) - newton: InteractiveSceneCfg = InteractiveSceneCfg( + newton_mjwarp: InteractiveSceneCfg = InteractiveSceneCfg( num_envs=8192, env_spacing=0.75, replicate_physics=True, clone_in_fabric=False ) default: InteractiveSceneCfg = physx @@ -258,7 +258,7 @@ class PhysicsCfg(PresetCfg): gpu_max_rigid_contact_count=2**23, gpu_max_rigid_patch_count=2**23, ) - newton = NewtonCfg( + newton_mjwarp = NewtonCfg( solver_cfg=MJWarpSolverCfg( solver="newton", integrator="implicitfast", @@ -337,7 +337,7 @@ class ShadowHandEnvCfg(DirectRLEnvCfg): ) }, ) - # scene — use ShadowHandSceneCfg so that presets=newton disables clone_in_fabric automatically + # scene — use ShadowHandSceneCfg so that presets=newton_mjwarp disables clone_in_fabric automatically scene: ShadowHandSceneCfg = ShadowHandSceneCfg() # reset @@ -355,6 +355,8 @@ class ShadowHandEnvCfg(DirectRLEnvCfg): vel_obs_scale = 0.2 success_tolerance = 0.1 max_consecutive_success = 0 + success_count_threshold: int = 1 + """Minimum number of goals reached in an episode to count it as a successful episode.""" av_factor = 0.1 act_moving_average = 1.0 force_torque_obs_scale = 10.0 diff --git a/source/isaaclab_tasks/isaaclab_tasks/direct/shadow_hand/shadow_hand_vision_env.py b/source/isaaclab_tasks/isaaclab_tasks/direct/shadow_hand/shadow_hand_vision_env.py index 56f8c8fb8a56..7da4db48e853 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/direct/shadow_hand/shadow_hand_vision_env.py +++ b/source/isaaclab_tasks/isaaclab_tasks/direct/shadow_hand/shadow_hand_vision_env.py @@ -9,11 +9,10 @@ from typing import TYPE_CHECKING import torch -import warp as wp import isaaclab.sim as sim_utils from isaaclab.assets import Articulation, RigidObject -from isaaclab.sensors import TiledCamera +from isaaclab.sensors import Camera from isaaclab.utils.math import quat_apply from isaaclab_tasks.direct.inhand_manipulation.inhand_manipulation_env import InHandManipulationEnv, unscale @@ -50,12 +49,14 @@ def _setup_scene(self): # add hand, in-hand object, and goal object self.hand = Articulation(self.cfg.robot_cfg) self.object: Articulation | RigidObject = self.cfg.object_cfg.class_type(self.cfg.object_cfg) - self._tiled_camera = TiledCamera(self.cfg.tiled_camera) + self._joint_wrench_sensor = self._create_joint_wrench_sensor() + self._tiled_camera = Camera(self.cfg.tiled_camera) # clone and replicate (no need to filter for this environment) self.scene.clone_environments(copy_from_source=False) # add articulation to scene - we must register to scene to randomize with EventManager self.scene.articulations["robot"] = self.hand self.scene.rigid_objects["object"] = self.object + self.scene.sensors["joint_wrench"] = self._joint_wrench_sensor self.scene.sensors["tiled_camera"] = self._tiled_camera # add lights light_cfg = sim_utils.DomeLightCfg(intensity=2000.0, color=(0.75, 0.75, 0.75)) @@ -128,15 +129,7 @@ def _get_observations(self) -> dict: # vision observations from CMM image_obs = self._compute_image_observations() obs = torch.cat((state_obs, image_obs), dim=-1) - # asymmetric critic states — Newton does not implement body_incoming_joint_wrench_b - try: - self.fingertip_force_sensors = wp.to_torch(self.hand.data.body_incoming_joint_wrench_b)[ - :, self.finger_bodies - ] - except NotImplementedError: - self.fingertip_force_sensors = torch.zeros( - self.num_envs, len(self.finger_bodies), 6, dtype=torch.float32, device=self.device - ) + self._update_fingertip_force_sensors() state = self._compute_states() observations = {"policy": obs, "critic": state} diff --git a/source/isaaclab_tasks/isaaclab_tasks/direct/shadow_hand/shadow_hand_vision_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/direct/shadow_hand/shadow_hand_vision_env_cfg.py index 4f57500f5f8e..5612b8c6d54e 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/direct/shadow_hand/shadow_hand_vision_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/direct/shadow_hand/shadow_hand_vision_env_cfg.py @@ -7,7 +7,7 @@ import isaaclab.sim as sim_utils from isaaclab.scene import InteractiveSceneCfg -from isaaclab.sensors import TiledCameraCfg +from isaaclab.sensors import CameraCfg from isaaclab.utils import configclass from isaaclab_tasks.utils import PresetCfg @@ -18,8 +18,8 @@ @configclass -class _ShadowHandBaseTiledCameraCfg(TiledCameraCfg): - """Base tiled camera configuration for the shadow hand vision environment. +class _ShadowHandBaseTiledCameraCfg(CameraCfg): + """Base camera configuration for the shadow hand vision environment. This is an internal config used by :class:`ShadowHandVisionTiledCameraCfg` presets and by derived env configs that hard-code a specific data type. It embeds @@ -28,7 +28,7 @@ class _ShadowHandBaseTiledCameraCfg(TiledCameraCfg): """ prim_path: str = "/World/envs/env_.*/Camera" - offset: TiledCameraCfg.OffsetCfg = TiledCameraCfg.OffsetCfg( + offset: CameraCfg.OffsetCfg = CameraCfg.OffsetCfg( pos=(0, -0.35, 1.0), rot=(0.0, 0.7071, 0.0, 0.7071), convention="world" ) data_types: list[str] = [] diff --git a/source/isaaclab_tasks/isaaclab_tasks/direct/shadow_hand_over/agents/skrl_ippo_cfg.yaml b/source/isaaclab_tasks/isaaclab_tasks/direct/shadow_hand_over/agents/skrl_ippo_cfg.yaml index 60be7d18110e..793f972fb7ce 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/direct/shadow_hand_over/agents/skrl_ippo_cfg.yaml +++ b/source/isaaclab_tasks/isaaclab_tasks/direct/shadow_hand_over/agents/skrl_ippo_cfg.yaml @@ -54,7 +54,9 @@ agent: learning_rate_scheduler: KLAdaptiveLR learning_rate_scheduler_kwargs: kl_threshold: 0.016 - state_preprocessor: RunningStandardScaler + observation_preprocessor: RunningStandardScaler + observation_preprocessor_kwargs: null + state_preprocessor: null state_preprocessor_kwargs: null value_preprocessor: RunningStandardScaler value_preprocessor_kwargs: null diff --git a/source/isaaclab_tasks/isaaclab_tasks/direct/shadow_hand_over/agents/skrl_mappo_cfg.yaml b/source/isaaclab_tasks/isaaclab_tasks/direct/shadow_hand_over/agents/skrl_mappo_cfg.yaml index 57c1c455185d..31c6087f500a 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/direct/shadow_hand_over/agents/skrl_mappo_cfg.yaml +++ b/source/isaaclab_tasks/isaaclab_tasks/direct/shadow_hand_over/agents/skrl_mappo_cfg.yaml @@ -28,7 +28,7 @@ models: clip_actions: False network: - name: net - input: OBSERVATIONS + input: STATES layers: [512, 512, 256, 128] activations: elu output: ONE @@ -54,10 +54,10 @@ agent: learning_rate_scheduler: KLAdaptiveLR learning_rate_scheduler_kwargs: kl_threshold: 0.016 + observation_preprocessor: RunningStandardScaler + observation_preprocessor_kwargs: null state_preprocessor: RunningStandardScaler state_preprocessor_kwargs: null - shared_state_preprocessor: RunningStandardScaler - shared_state_preprocessor_kwargs: null value_preprocessor: RunningStandardScaler value_preprocessor_kwargs: null random_timesteps: 0 diff --git a/source/isaaclab_tasks/isaaclab_tasks/direct/shadow_hand_over/shadow_hand_over_env.py b/source/isaaclab_tasks/isaaclab_tasks/direct/shadow_hand_over/shadow_hand_over_env.py index 7662fe728341..a692253cf2fb 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/direct/shadow_hand_over/shadow_hand_over_env.py +++ b/source/isaaclab_tasks/isaaclab_tasks/direct/shadow_hand_over/shadow_hand_over_env.py @@ -69,7 +69,7 @@ def __init__(self, cfg: ShadowHandOverEnvCfg, render_mode: str | None = None, ** self.hand_dof_upper_limits = joint_pos_limits[..., 1] # used to compare object position - self.in_hand_pos = wp.to_torch(self.object.data.default_root_pose)[:, 0:3].clone() + self.in_hand_pos = self.object.data.default_root_pose.torch[:, 0:3].clone() self.in_hand_pos[:, 2] -= 0.04 # default goal positions self.goal_rot = torch.zeros((self.num_envs, 4), dtype=torch.float, device=self.device) @@ -79,6 +79,9 @@ def __init__(self, cfg: ShadowHandOverEnvCfg, render_mode: str | None = None, ** # initialize goal marker self.goal_markers = VisualizationMarkers(self.cfg.goal_object_cfg) + # Sticky per-env flag: True once the object reached the goal within threshold. + self._episode_succeeded = torch.zeros(self.num_envs, dtype=torch.bool, device=self.device) + # unit tensors self.x_unit_tensor = torch.tensor([1, 0, 0], dtype=torch.float, device=self.device).repeat((self.num_envs, 1)) self.y_unit_tensor = torch.tensor([0, 1, 0], dtype=torch.float, device=self.device).repeat((self.num_envs, 1)) @@ -286,6 +289,9 @@ def _get_rewards(self) -> dict[str, torch.Tensor]: self.extras["log"] = dict() self.extras["log"]["dist_reward"] = rew_dist.mean() self.extras["log"]["dist_goal"] = goal_dist.mean() + self.extras["log"]["Metrics/goal_distance"] = goal_dist.mean().item() + # Sticky per-env success: True once the object reached the goal within threshold. + self._episode_succeeded |= goal_dist < self.cfg.success_distance_threshold return {"right_hand": rew_dist, "left_hand": rew_dist} @@ -304,6 +310,11 @@ def _get_dones(self) -> tuple[dict[str, torch.Tensor], dict[str, torch.Tensor]]: def _reset_idx(self, env_ids: Sequence[int] | torch.Tensor | None): if env_ids is None: env_ids = self.right_hand._ALL_INDICES + # Flush per-episode success (sticky binary: object ever reached the goal within threshold). + self.extras.setdefault("log", {})["Metrics/success_rate"] = ( + self._episode_succeeded[env_ids].float().mean().item() + ) + self._episode_succeeded[env_ids] = False # reset articulation and rigid body attributes super()._reset_idx(env_ids) @@ -311,8 +322,8 @@ def _reset_idx(self, env_ids: Sequence[int] | torch.Tensor | None): self._reset_target_pose(env_ids) # reset object - object_default_pose = wp.to_torch(self.object.data.default_root_pose).clone()[env_ids] - object_default_vel = wp.to_torch(self.object.data.default_root_vel).clone()[env_ids] + object_default_pose = self.object.data.default_root_pose.torch.clone()[env_ids] + object_default_vel = self.object.data.default_root_vel.torch.clone()[env_ids] pos_noise = sample_uniform(-1.0, 1.0, (len(env_ids), 3), device=self.device) object_default_pose[:, 0:3] = ( @@ -329,19 +340,15 @@ def _reset_idx(self, env_ids: Sequence[int] | torch.Tensor | None): self.object.write_root_velocity_to_sim_index(root_velocity=object_default_vel, env_ids=env_ids) # reset right hand - delta_max = self.hand_dof_upper_limits[env_ids] - wp.to_torch(self.right_hand.data.default_joint_pos)[env_ids] - delta_min = self.hand_dof_lower_limits[env_ids] - wp.to_torch(self.right_hand.data.default_joint_pos)[env_ids] + delta_max = self.hand_dof_upper_limits[env_ids] - self.right_hand.data.default_joint_pos.torch[env_ids] + delta_min = self.hand_dof_lower_limits[env_ids] - self.right_hand.data.default_joint_pos.torch[env_ids] dof_pos_noise = sample_uniform(-1.0, 1.0, (len(env_ids), self.num_hand_dofs), device=self.device) rand_delta = delta_min + (delta_max - delta_min) * 0.5 * dof_pos_noise - dof_pos = ( - wp.to_torch(self.right_hand.data.default_joint_pos)[env_ids] + self.cfg.reset_dof_pos_noise * rand_delta - ) + dof_pos = self.right_hand.data.default_joint_pos.torch[env_ids] + self.cfg.reset_dof_pos_noise * rand_delta dof_vel_noise = sample_uniform(-1.0, 1.0, (len(env_ids), self.num_hand_dofs), device=self.device) - dof_vel = ( - wp.to_torch(self.right_hand.data.default_joint_vel)[env_ids] + self.cfg.reset_dof_vel_noise * dof_vel_noise - ) + dof_vel = self.right_hand.data.default_joint_vel.torch[env_ids] + self.cfg.reset_dof_vel_noise * dof_vel_noise self.right_hand_prev_targets[env_ids] = dof_pos self.right_hand_curr_targets[env_ids] = dof_pos @@ -352,19 +359,15 @@ def _reset_idx(self, env_ids: Sequence[int] | torch.Tensor | None): self.right_hand.write_joint_velocity_to_sim_index(velocity=dof_vel, env_ids=env_ids) # reset left hand - delta_max = self.hand_dof_upper_limits[env_ids] - wp.to_torch(self.left_hand.data.default_joint_pos)[env_ids] - delta_min = self.hand_dof_lower_limits[env_ids] - wp.to_torch(self.left_hand.data.default_joint_pos)[env_ids] + delta_max = self.hand_dof_upper_limits[env_ids] - self.left_hand.data.default_joint_pos.torch[env_ids] + delta_min = self.hand_dof_lower_limits[env_ids] - self.left_hand.data.default_joint_pos.torch[env_ids] dof_pos_noise = sample_uniform(-1.0, 1.0, (len(env_ids), self.num_hand_dofs), device=self.device) rand_delta = delta_min + (delta_max - delta_min) * 0.5 * dof_pos_noise - dof_pos = ( - wp.to_torch(self.left_hand.data.default_joint_pos)[env_ids] + self.cfg.reset_dof_pos_noise * rand_delta - ) + dof_pos = self.left_hand.data.default_joint_pos.torch[env_ids] + self.cfg.reset_dof_pos_noise * rand_delta dof_vel_noise = sample_uniform(-1.0, 1.0, (len(env_ids), self.num_hand_dofs), device=self.device) - dof_vel = ( - wp.to_torch(self.left_hand.data.default_joint_vel)[env_ids] + self.cfg.reset_dof_vel_noise * dof_vel_noise - ) + dof_vel = self.left_hand.data.default_joint_vel.torch[env_ids] + self.cfg.reset_dof_vel_noise * dof_vel_noise self.left_hand_prev_targets[env_ids] = dof_pos self.left_hand_curr_targets[env_ids] = dof_pos @@ -390,33 +393,33 @@ def _reset_target_pose(self, env_ids): def _compute_intermediate_values(self): # data for right hand - self.right_fingertip_pos = wp.to_torch(self.right_hand.data.body_pos_w)[:, self.finger_bodies] - self.right_fingertip_rot = wp.to_torch(self.right_hand.data.body_quat_w)[:, self.finger_bodies] + self.right_fingertip_pos = self.right_hand.data.body_pos_w.torch[:, self.finger_bodies] + self.right_fingertip_rot = self.right_hand.data.body_quat_w.torch[:, self.finger_bodies] self.right_fingertip_pos -= self.scene.env_origins.repeat((1, self.num_fingertips)).reshape( self.num_envs, self.num_fingertips, 3 ) - self.right_fingertip_velocities = wp.to_torch(self.right_hand.data.body_vel_w)[:, self.finger_bodies] + self.right_fingertip_velocities = self.right_hand.data.body_vel_w.torch[:, self.finger_bodies] - self.right_hand_dof_pos = wp.to_torch(self.right_hand.data.joint_pos) - self.right_hand_dof_vel = wp.to_torch(self.right_hand.data.joint_vel) + self.right_hand_dof_pos = self.right_hand.data.joint_pos.torch + self.right_hand_dof_vel = self.right_hand.data.joint_vel.torch # data for left hand - self.left_fingertip_pos = wp.to_torch(self.left_hand.data.body_pos_w)[:, self.finger_bodies] - self.left_fingertip_rot = wp.to_torch(self.left_hand.data.body_quat_w)[:, self.finger_bodies] + self.left_fingertip_pos = self.left_hand.data.body_pos_w.torch[:, self.finger_bodies] + self.left_fingertip_rot = self.left_hand.data.body_quat_w.torch[:, self.finger_bodies] self.left_fingertip_pos -= self.scene.env_origins.repeat((1, self.num_fingertips)).reshape( self.num_envs, self.num_fingertips, 3 ) - self.left_fingertip_velocities = wp.to_torch(self.left_hand.data.body_vel_w)[:, self.finger_bodies] + self.left_fingertip_velocities = self.left_hand.data.body_vel_w.torch[:, self.finger_bodies] - self.left_hand_dof_pos = wp.to_torch(self.left_hand.data.joint_pos) - self.left_hand_dof_vel = wp.to_torch(self.left_hand.data.joint_vel) + self.left_hand_dof_pos = self.left_hand.data.joint_pos.torch + self.left_hand_dof_vel = self.left_hand.data.joint_vel.torch # data for object - self.object_pos = wp.to_torch(self.object.data.root_pos_w) - self.scene.env_origins - self.object_rot = wp.to_torch(self.object.data.root_quat_w) - self.object_velocities = wp.to_torch(self.object.data.root_vel_w) - self.object_linvel = wp.to_torch(self.object.data.root_lin_vel_w) - self.object_angvel = wp.to_torch(self.object.data.root_ang_vel_w) + self.object_pos = self.object.data.root_pos_w.torch - self.scene.env_origins + self.object_rot = self.object.data.root_quat_w.torch + self.object_velocities = self.object.data.root_vel_w.torch + self.object_linvel = self.object.data.root_lin_vel_w.torch + self.object_angvel = self.object.data.root_ang_vel_w.torch @torch.jit.script diff --git a/source/isaaclab_tasks/isaaclab_tasks/direct/shadow_hand_over/shadow_hand_over_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/direct/shadow_hand_over/shadow_hand_over_env_cfg.py index 1c87da65ce8c..acf37a54c4b0 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/direct/shadow_hand_over/shadow_hand_over_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/direct/shadow_hand_over/shadow_hand_over_env_cfg.py @@ -223,5 +223,8 @@ class ShadowHandOverEnvCfg(DirectMARLEnvCfg): fall_dist = 0.24 vel_obs_scale = 0.2 act_moving_average = 1.0 + # success criteria + success_distance_threshold: float = 0.1 + """Object-to-goal distance below which the handover is considered successful [m].""" # reward-related scales dist_reward_scale = 20.0 diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/classic/ant/ant_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/classic/ant/ant_env_cfg.py index dc36023152b6..53781c0ced16 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/classic/ant/ant_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/classic/ant/ant_env_cfg.py @@ -3,7 +3,7 @@ # # SPDX-License-Identifier: BSD-3-Clause -from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg +from isaaclab_newton.physics import KaminoSolverCfg, MJWarpSolverCfg, NewtonCfg from isaaclab_physx.physics import PhysxCfg import isaaclab.sim as sim_utils @@ -16,6 +16,7 @@ from isaaclab.managers import SceneEntityCfg from isaaclab.managers import TerminationTermCfg as DoneTerm from isaaclab.scene import InteractiveSceneCfg +from isaaclab.sensors import JointWrenchSensorCfg from isaaclab.terrains import TerrainImporterCfg from isaaclab.utils import configclass @@ -32,7 +33,7 @@ class AntPhysicsCfg(PresetCfg): default: PhysxCfg = PhysxCfg(bounce_threshold_velocity=0.2) physx: PhysxCfg = PhysxCfg(bounce_threshold_velocity=0.2) - newton: NewtonCfg = NewtonCfg( + newton_mjwarp: NewtonCfg = NewtonCfg( solver_cfg=MJWarpSolverCfg( njmax=38, nconmax=15, @@ -43,6 +44,29 @@ class AntPhysicsCfg(PresetCfg): num_substeps=1, debug_mode=False, ) + newton_kamino: NewtonCfg = NewtonCfg( + solver_cfg=KaminoSolverCfg( + integrator="moreau", + use_collision_detector=False, + sparse_jacobian=True, + constraints_alpha=0.1, + padmm_max_iterations=100, + padmm_primal_tolerance=1e-4, + padmm_dual_tolerance=1e-4, + padmm_compl_tolerance=1e-4, + padmm_rho_0=0.05, + padmm_eta=1e-5, + padmm_use_acceleration=True, + padmm_warmstart_mode="containers", + padmm_contact_warmstart_method="geom_pair_net_force", + padmm_use_graph_conditionals=False, + collision_detector_pipeline="unified", + collision_detector_max_contacts_per_pair=8, + ), + num_substeps=2, + debug_mode=False, + use_cuda_graph=True, + ) @configclass @@ -67,6 +91,9 @@ class MySceneCfg(InteractiveSceneCfg): # robot robot = ANT_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") + # sensors + joint_wrench = JointWrenchSensorCfg(prim_path="{ENV_REGEX_NS}/Robot") + # lights light = AssetBaseCfg( prim_path="/World/light", @@ -107,8 +134,9 @@ class PolicyCfg(ObsGroup): func=mdp.body_incoming_wrench, scale=0.1, params={ - "asset_cfg": SceneEntityCfg( - "robot", body_names=["front_left_foot", "front_right_foot", "left_back_foot", "right_back_foot"] + "sensor_cfg": SceneEntityCfg( + "joint_wrench", + body_names=["front_left_foot", "front_right_foot", "left_back_foot", "right_back_foot"], ) }, ) @@ -122,38 +150,11 @@ def __post_init__(self): policy: PolicyCfg = PolicyCfg() -@configclass -class _AntNewtonObservationsCfg: - """Newton-compatible observations: excludes feet_body_forces (not implemented in Newton).""" - - @configclass - class PolicyCfg(ObsGroup): - """Observations for the policy.""" - - base_height = ObsTerm(func=mdp.base_pos_z) - base_lin_vel = ObsTerm(func=mdp.base_lin_vel) - base_ang_vel = ObsTerm(func=mdp.base_ang_vel) - base_yaw_roll = ObsTerm(func=mdp.base_yaw_roll) - base_angle_to_target = ObsTerm(func=mdp.base_angle_to_target, params={"target_pos": (1000.0, 0.0, 0.0)}) - base_up_proj = ObsTerm(func=mdp.base_up_proj) - base_heading_proj = ObsTerm(func=mdp.base_heading_proj, params={"target_pos": (1000.0, 0.0, 0.0)}) - joint_pos_norm = ObsTerm(func=mdp.joint_pos_limit_normalized) - joint_vel_rel = ObsTerm(func=mdp.joint_vel_rel, scale=0.2) - actions = ObsTerm(func=mdp.last_action) - - def __post_init__(self): - self.enable_corruption = False - self.concatenate_terms = True - - # observation groups - policy: PolicyCfg = PolicyCfg() - - @configclass class AntObservationsCfg(PresetCfg): default: ObservationsCfg = ObservationsCfg() physx: ObservationsCfg = ObservationsCfg() - newton: _AntNewtonObservationsCfg = _AntNewtonObservationsCfg() + newton_mjwarp: ObservationsCfg = ObservationsCfg() @configclass diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/classic/cartpole/cartpole_camera_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/classic/cartpole/cartpole_camera_env_cfg.py index dfccd3d36890..2c4092677fec 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/classic/cartpole/cartpole_camera_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/classic/cartpole/cartpole_camera_env_cfg.py @@ -7,7 +7,7 @@ from isaaclab.managers import ObservationGroupCfg as ObsGroup from isaaclab.managers import ObservationTermCfg as ObsTerm from isaaclab.managers import SceneEntityCfg -from isaaclab.sensors import TiledCameraCfg +from isaaclab.sensors import CameraCfg from isaaclab.utils import configclass import isaaclab_tasks.manager_based.classic.cartpole.mdp as mdp @@ -24,9 +24,9 @@ class CartpoleRGBCameraSceneCfg(CartpoleSceneCfg): """Configuration for the cartpole environment with RGB camera.""" # add camera to the scene - tiled_camera: TiledCameraCfg = TiledCameraCfg( + tiled_camera: CameraCfg = CameraCfg( prim_path="{ENV_REGEX_NS}/Camera", - offset=TiledCameraCfg.OffsetCfg(pos=(-7.0, 0.0, 3.0), rot=(0.0, 0.1045, 0.0, 0.9945), convention="world"), + offset=CameraCfg.OffsetCfg(pos=(-7.0, 0.0, 3.0), rot=(0.0, 0.1045, 0.0, 0.9945), convention="world"), data_types=["rgb"], spawn=sim_utils.PinholeCameraCfg( focal_length=24.0, focus_distance=400.0, horizontal_aperture=20.955, clipping_range=(0.1, 20.0) @@ -39,9 +39,9 @@ class CartpoleRGBCameraSceneCfg(CartpoleSceneCfg): @configclass class CartpoleDepthCameraSceneCfg(CartpoleSceneCfg): # add camera to the scene - tiled_camera: TiledCameraCfg = TiledCameraCfg( + tiled_camera: CameraCfg = CameraCfg( prim_path="{ENV_REGEX_NS}/Camera", - offset=TiledCameraCfg.OffsetCfg(pos=(-7.0, 0.0, 3.0), rot=(0.0, 0.1045, 0.0, 0.9945), convention="world"), + offset=CameraCfg.OffsetCfg(pos=(-7.0, 0.0, 3.0), rot=(0.0, 0.1045, 0.0, 0.9945), convention="world"), data_types=["distance_to_camera"], spawn=sim_utils.PinholeCameraCfg( focal_length=24.0, focus_distance=400.0, horizontal_aperture=20.955, clipping_range=(0.1, 20.0) diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/classic/cartpole/cartpole_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/classic/cartpole/cartpole_env_cfg.py index 660be6136e22..f351e635ff6a 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/classic/cartpole/cartpole_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/classic/cartpole/cartpole_env_cfg.py @@ -5,7 +5,7 @@ import math -from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg +from isaaclab_newton.physics import KaminoSolverCfg, MJWarpSolverCfg, NewtonCfg from isaaclab_physx.physics import PhysxCfg import isaaclab.sim as sim_utils @@ -38,7 +38,7 @@ class CartpolePhysicsCfg(PresetCfg): default: PhysxCfg = PhysxCfg() physx: PhysxCfg = PhysxCfg() - newton: NewtonCfg = NewtonCfg( + newton_mjwarp: NewtonCfg = NewtonCfg( solver_cfg=MJWarpSolverCfg( njmax=5, nconmax=3, @@ -50,6 +50,29 @@ class CartpolePhysicsCfg(PresetCfg): debug_mode=False, use_cuda_graph=True, ) + newton_kamino: NewtonCfg = NewtonCfg( + solver_cfg=KaminoSolverCfg( + integrator="moreau", + use_collision_detector=True, + sparse_jacobian=True, + constraints_alpha=0.1, + padmm_max_iterations=100, + padmm_primal_tolerance=1e-4, + padmm_dual_tolerance=1e-4, + padmm_compl_tolerance=1e-4, + padmm_rho_0=0.05, + padmm_eta=1e-5, + padmm_use_acceleration=True, + padmm_warmstart_mode="containers", + padmm_contact_warmstart_method="geom_pair_net_force", + padmm_use_graph_conditionals=False, + collision_detector_pipeline="unified", + collision_detector_max_contacts_per_pair=8, + ), + num_substeps=1, + debug_mode=False, + use_cuda_graph=True, + ) ## @@ -161,6 +184,8 @@ class RewardsCfg: weight=-0.005, params={"asset_cfg": SceneEntityCfg("robot", joint_names=["cart_to_pole"])}, ) + # (6) Success rate tracking (zero-weight, metric only) + success_rate = RewTerm(func=mdp.survival_success_rate, weight=0.0) @configclass diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/classic/cartpole/mdp/__init__.pyi b/source/isaaclab_tasks/isaaclab_tasks/manager_based/classic/cartpole/mdp/__init__.pyi index 8d3c2673c76d..c5601c1fd946 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/classic/cartpole/mdp/__init__.pyi +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/classic/cartpole/mdp/__init__.pyi @@ -5,7 +5,8 @@ __all__ = [ "joint_pos_target_l2", + "survival_success_rate", ] -from .rewards import joint_pos_target_l2 +from .rewards import joint_pos_target_l2, survival_success_rate from isaaclab.envs.mdp import * diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/classic/cartpole/mdp/rewards.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/classic/cartpole/mdp/rewards.py index 3bdb71d5606a..b2838a0cce9a 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/classic/cartpole/mdp/rewards.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/classic/cartpole/mdp/rewards.py @@ -8,9 +8,8 @@ from typing import TYPE_CHECKING import torch -import warp as wp -from isaaclab.managers import SceneEntityCfg +from isaaclab.managers import ManagerTermBase, RewardTermCfg, SceneEntityCfg from isaaclab.utils.math import wrap_to_pi if TYPE_CHECKING: @@ -23,6 +22,25 @@ def joint_pos_target_l2(env: ManagerBasedRLEnv, target: float, asset_cfg: SceneE # extract the used quantities (to enable type-hinting) asset: Articulation = env.scene[asset_cfg.name] # wrap the joint positions to (-pi, pi) - joint_pos = wrap_to_pi(wp.to_torch(asset.data.joint_pos)[:, asset_cfg.joint_ids]) + joint_pos = wrap_to_pi(asset.data.joint_pos.torch[:, asset_cfg.joint_ids]) # compute the reward return torch.sum(torch.square(joint_pos - target), dim=1) + + +class survival_success_rate(ManagerTermBase): + """Tracks episode survival as the success metric. + + Returns zero reward (pure metric tracking). Flushes ``Metrics/success_rate`` + into ``extras["log"]`` on episode reset, where success = timed out without + early termination. + """ + + def __init__(self, env: ManagerBasedRLEnv, cfg: RewardTermCfg): + super().__init__(cfg, env) + + def reset(self, env_ids: torch.Tensor): + survived = self._env.termination_manager.time_outs[env_ids] + self._env.extras.setdefault("log", {})["Metrics/success_rate"] = survived.float().mean().item() + + def __call__(self, env: ManagerBasedRLEnv) -> torch.Tensor: + return torch.zeros(env.num_envs, device=env.device) diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/classic/humanoid/humanoid_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/classic/humanoid/humanoid_env_cfg.py index c610159a5c51..3058fc02caf2 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/classic/humanoid/humanoid_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/classic/humanoid/humanoid_env_cfg.py @@ -16,6 +16,7 @@ from isaaclab.managers import SceneEntityCfg from isaaclab.managers import TerminationTermCfg as DoneTerm from isaaclab.scene import InteractiveSceneCfg +from isaaclab.sensors import JointWrenchSensorCfg from isaaclab.terrains import TerrainImporterCfg from isaaclab.utils import configclass @@ -29,7 +30,7 @@ class HumanoidPhysicsCfg(PresetCfg): default: PhysxCfg = PhysxCfg(bounce_threshold_velocity=0.2) physx: PhysxCfg = PhysxCfg(bounce_threshold_velocity=0.2) - newton: NewtonCfg = NewtonCfg( + newton_mjwarp: NewtonCfg = NewtonCfg( solver_cfg=MJWarpSolverCfg( njmax=80, nconmax=25, @@ -64,6 +65,9 @@ class MySceneCfg(InteractiveSceneCfg): # robot robot = HUMANOID_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") + # sensors + joint_wrench = JointWrenchSensorCfg(prim_path="{ENV_REGEX_NS}/Robot") + # lights light = AssetBaseCfg( prim_path="/World/light", @@ -117,7 +121,7 @@ class PolicyCfg(ObsGroup): feet_body_forces = ObsTerm( func=mdp.body_incoming_wrench, scale=0.01, - params={"asset_cfg": SceneEntityCfg("robot", body_names=["left_foot", "right_foot"])}, + params={"sensor_cfg": SceneEntityCfg("joint_wrench", body_names=["left_foot", "right_foot"])}, ) actions = ObsTerm(func=mdp.last_action) @@ -129,38 +133,11 @@ def __post_init__(self): policy: PolicyCfg = PolicyCfg() -@configclass -class _HumanoidNewtonObservationsCfg: - """Newton-compatible observations: excludes feet_body_forces (not implemented in Newton).""" - - @configclass - class PolicyCfg(ObsGroup): - """Observations for the policy.""" - - base_height = ObsTerm(func=mdp.base_pos_z) - base_lin_vel = ObsTerm(func=mdp.base_lin_vel) - base_ang_vel = ObsTerm(func=mdp.base_ang_vel, scale=0.25) - base_yaw_roll = ObsTerm(func=mdp.base_yaw_roll) - base_angle_to_target = ObsTerm(func=mdp.base_angle_to_target, params={"target_pos": (1000.0, 0.0, 0.0)}) - base_up_proj = ObsTerm(func=mdp.base_up_proj) - base_heading_proj = ObsTerm(func=mdp.base_heading_proj, params={"target_pos": (1000.0, 0.0, 0.0)}) - joint_pos_norm = ObsTerm(func=mdp.joint_pos_limit_normalized) - joint_vel_rel = ObsTerm(func=mdp.joint_vel_rel, scale=0.1) - actions = ObsTerm(func=mdp.last_action) - - def __post_init__(self): - self.enable_corruption = False - self.concatenate_terms = True - - # observation groups - policy: PolicyCfg = PolicyCfg() - - @configclass class HumanoidObservationsCfg(PresetCfg): default: ObservationsCfg = ObservationsCfg() physx: ObservationsCfg = ObservationsCfg() - newton: _HumanoidNewtonObservationsCfg = _HumanoidNewtonObservationsCfg() + newton_mjwarp: ObservationsCfg = ObservationsCfg() @configclass diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/classic/humanoid/mdp/observations.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/classic/humanoid/mdp/observations.py index 5445328cc175..d7195b0f380e 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/classic/humanoid/mdp/observations.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/classic/humanoid/mdp/observations.py @@ -8,7 +8,6 @@ from typing import TYPE_CHECKING import torch -import warp as wp import isaaclab.utils.math as math_utils from isaaclab.managers import SceneEntityCfg @@ -23,7 +22,7 @@ def base_yaw_roll(env: ManagerBasedEnv, asset_cfg: SceneEntityCfg = SceneEntityC # extract the used quantities (to enable type-hinting) asset: Articulation = env.scene[asset_cfg.name] # extract euler angles (in world frame) - roll, _, yaw = math_utils.euler_xyz_from_quat(wp.to_torch(asset.data.root_quat_w)) + roll, _, yaw = math_utils.euler_xyz_from_quat(asset.data.root_quat_w.torch) # normalize angle to [-pi, pi] roll = torch.atan2(torch.sin(roll), torch.cos(roll)) yaw = torch.atan2(torch.sin(yaw), torch.cos(yaw)) @@ -36,7 +35,7 @@ def base_up_proj(env: ManagerBasedEnv, asset_cfg: SceneEntityCfg = SceneEntityCf # extract the used quantities (to enable type-hinting) asset: Articulation = env.scene[asset_cfg.name] # compute base up vector - base_up_vec = -wp.to_torch(asset.data.projected_gravity_b) + base_up_vec = -asset.data.projected_gravity_b.torch return base_up_vec[:, 2].unsqueeze(-1) @@ -48,11 +47,11 @@ def base_heading_proj( # extract the used quantities (to enable type-hinting) asset: Articulation = env.scene[asset_cfg.name] # compute desired heading direction - to_target_pos = torch.tensor(target_pos, device=env.device) - wp.to_torch(asset.data.root_pos_w)[:, :3] - to_target_pos[:, 2] = 0.0 + to_target_pos = torch.tensor(target_pos, device=env.device) - asset.data.root_pos_w.torch[:, :3] + to_target_pos = torch.cat((to_target_pos[:, :2], torch.zeros_like(to_target_pos[:, 2:3])), dim=-1) to_target_dir = math_utils.normalize(to_target_pos) # compute base forward vector - heading_vec = math_utils.quat_apply(wp.to_torch(asset.data.root_quat_w), wp.to_torch(asset.data.FORWARD_VEC_B)) + heading_vec = math_utils.quat_apply(asset.data.root_quat_w.torch, asset.data.FORWARD_VEC_B.torch) # compute dot product between heading and target direction heading_proj = torch.bmm(heading_vec.view(env.num_envs, 1, 3), to_target_dir.view(env.num_envs, 3, 1)) @@ -66,10 +65,10 @@ def base_angle_to_target( # extract the used quantities (to enable type-hinting) asset: Articulation = env.scene[asset_cfg.name] # compute desired heading direction - to_target_pos = torch.tensor(target_pos, device=env.device) - wp.to_torch(asset.data.root_pos_w)[:, :3] + to_target_pos = torch.tensor(target_pos, device=env.device) - asset.data.root_pos_w.torch[:, :3] walk_target_angle = torch.atan2(to_target_pos[:, 1], to_target_pos[:, 0]) # compute base forward vector - _, _, yaw = math_utils.euler_xyz_from_quat(wp.to_torch(asset.data.root_quat_w)) + _, _, yaw = math_utils.euler_xyz_from_quat(asset.data.root_quat_w.torch) # normalize angle to target to [-pi, pi] angle_to_target = walk_target_angle - yaw angle_to_target = torch.atan2(torch.sin(angle_to_target), torch.cos(angle_to_target)) diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/classic/humanoid/mdp/rewards.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/classic/humanoid/mdp/rewards.py index ceaa1371b917..18e73a4f22eb 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/classic/humanoid/mdp/rewards.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/classic/humanoid/mdp/rewards.py @@ -8,7 +8,6 @@ from typing import TYPE_CHECKING import torch -import warp as wp import isaaclab.utils.math as math_utils import isaaclab.utils.string as string_utils @@ -55,10 +54,13 @@ def reset(self, env_ids: torch.Tensor): asset: Articulation = self._env.scene["robot"] # compute projection of current heading to desired heading vector target_pos = torch.tensor(self.cfg.params["target_pos"], device=self.device) - to_target_pos = target_pos - wp.to_torch(asset.data.root_pos_w)[env_ids, :3] + to_target_pos = target_pos - asset.data.root_pos_w.torch[env_ids, :3] # reward terms self.potentials[env_ids] = -torch.linalg.norm(to_target_pos, ord=2, dim=-1) / self._env.step_dt self.prev_potentials[env_ids] = self.potentials[env_ids] + # flush survival success rate (survived = timed out without falling) + survived = self._env.termination_manager.time_outs[env_ids] + self._env.extras.setdefault("log", {})["Metrics/success_rate"] = survived.float().mean().item() def __call__( self, @@ -70,7 +72,7 @@ def __call__( asset: Articulation = env.scene[asset_cfg.name] # compute vector to target target_pos = torch.tensor(target_pos, device=env.device) - to_target_pos = target_pos - wp.to_torch(asset.data.root_pos_w)[:, :3] + to_target_pos = target_pos - asset.data.root_pos_w.torch[:, :3] to_target_pos[:, 2] = 0.0 # update history buffer and compute new potential self.prev_potentials[:] = self.potentials[:] @@ -107,9 +109,9 @@ def __call__( asset: Articulation = env.scene[asset_cfg.name] # compute the penalty over normalized joints joint_pos_scaled = math_utils.scale_transform( - wp.to_torch(asset.data.joint_pos), - wp.to_torch(asset.data.soft_joint_pos_limits)[..., 0], - wp.to_torch(asset.data.soft_joint_pos_limits)[..., 1], + asset.data.joint_pos.torch, + asset.data.soft_joint_pos_limits.torch[..., 0], + asset.data.soft_joint_pos_limits.torch[..., 1], ) # scale the violation amount by the gear ratio violation_amount = (torch.abs(joint_pos_scaled) - threshold) / (1 - threshold) @@ -145,5 +147,5 @@ def __call__( asset: Articulation = env.scene[asset_cfg.name] # return power = torque * velocity (here actions: joint torques) return torch.sum( - torch.abs(env.action_manager.action * wp.to_torch(asset.data.joint_vel) * self.gear_ratio_scaled), dim=-1 + torch.abs(env.action_manager.action * asset.data.joint_vel.torch * self.gear_ratio_scaled), dim=-1 ) diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/drone_arl/mdp/commands/drone_pose_command.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/drone_arl/mdp/commands/drone_pose_command.py index f3364c05c220..a9072367c83b 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/drone_arl/mdp/commands/drone_pose_command.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/drone_arl/mdp/commands/drone_pose_command.py @@ -8,7 +8,6 @@ from __future__ import annotations import torch -import warp as wp from isaaclab.envs.mdp.commands.pose_command import UniformPoseCommand from isaaclab.utils.math import combine_frame_transforms, compute_pose_error @@ -36,8 +35,8 @@ class DroneUniformPoseCommand(UniformPoseCommand): def _update_metrics(self): # transform command from base frame to simulation world frame self.pose_command_w[:, :3], self.pose_command_w[:, 3:] = combine_frame_transforms( - wp.to_torch(self.robot.data.root_pos_w), - wp.to_torch(self.robot.data.root_quat_w), + self.robot.data.root_pos_w.torch, + self.robot.data.root_quat_w.torch, self.pose_command_b[:, :3], self.pose_command_b[:, 3:], ) @@ -46,8 +45,8 @@ def _update_metrics(self): # Sub-terrain shift for correct position error calculation @grzemal self.pose_command_b[:, :3] + self._env.scene.env_origins, self.pose_command_w[:, 3:], - wp.to_torch(self.robot.data.body_pos_w)[:, self.body_idx], - wp.to_torch(self.robot.data.body_quat_w)[:, self.body_idx], + self.robot.data.body_pos_w.torch[:, self.body_idx], + self.robot.data.body_quat_w.torch[:, self.body_idx], ) self.metrics["position_error"] = torch.linalg.norm(pos_error, dim=-1) self.metrics["orientation_error"] = torch.linalg.norm(rot_error, dim=-1) @@ -64,5 +63,5 @@ def _debug_vis_callback(self, event): self.pose_command_b[:, :3] + self._env.scene.env_origins, self.pose_command_b[:, 3:] ) # -- current body pose - body_link_pose_w = wp.to_torch(self.robot.data.body_link_pose_w)[:, self.body_idx] + body_link_pose_w = self.robot.data.body_link_pose_w.torch[:, self.body_idx] self.current_pose_visualizer.visualize(body_link_pose_w[:, :3], body_link_pose_w[:, 3:7]) diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/drone_arl/mdp/observations.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/drone_arl/mdp/observations.py index 5b67ec4f66c3..c8b8048bd68b 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/drone_arl/mdp/observations.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/drone_arl/mdp/observations.py @@ -14,7 +14,6 @@ from typing import TYPE_CHECKING import torch -import warp as wp import isaaclab.utils.math as math_utils from isaaclab.managers import SceneEntityCfg @@ -50,7 +49,7 @@ def base_roll_pitch(env: ManagerBasedEnv, asset_cfg: SceneEntityCfg = SceneEntit # extract the used quantities (to enable type-hinting) asset: Articulation = env.scene[asset_cfg.name] # extract euler angles (in world frame) - roll, pitch, _ = math_utils.euler_xyz_from_quat(wp.to_torch(asset.data.root_quat_w)) + roll, pitch, _ = math_utils.euler_xyz_from_quat(asset.data.root_quat_w.torch) # normalize angle to [-pi, pi] roll = math_utils.wrap_to_pi(roll) pitch = math_utils.wrap_to_pi(pitch) @@ -94,10 +93,10 @@ def generated_drone_commands( - A small epsilon (1e-8) is used to guard against zero-length direction vectors. """ asset: Multirotor = env.scene[asset_cfg.name] - current_position_w = wp.to_torch(asset.data.root_pos_w) - env.scene.env_origins + current_position_w = asset.data.root_pos_w.torch - env.scene.env_origins command = env.command_manager.get_command(command_name) current_position_b = math_utils.quat_apply_inverse( - wp.to_torch(asset.data.root_link_quat_w), command[:, :3] - current_position_w + asset.data.root_link_quat_w.torch, command[:, :3] - current_position_w ) current_position_b_dir = current_position_b / (torch.linalg.norm(current_position_b, dim=-1, keepdim=True) + 1e-8) current_position_b_mag = torch.linalg.norm(current_position_b, dim=-1, keepdim=True) diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/drone_arl/mdp/rewards.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/drone_arl/mdp/rewards.py index 840d694118d1..ce635cc544d8 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/drone_arl/mdp/rewards.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/drone_arl/mdp/rewards.py @@ -8,7 +8,6 @@ from typing import TYPE_CHECKING import torch -import warp as wp import isaaclab.utils.math as math_utils from isaaclab.managers import SceneEntityCfg @@ -51,7 +50,7 @@ def distance_to_goal_exp( command = env.command_manager.get_command(command_name) target_position_w = command[:, :3].clone() - current_position = wp.to_torch(asset.data.root_pos_w) - env.scene.env_origins + current_position = asset.data.root_pos_w.torch - env.scene.env_origins # compute the error position_error_square = torch.sum(torch.square(target_position_w - current_position), dim=1) @@ -82,7 +81,7 @@ def ang_vel_xyz_exp( asset: RigidObject = env.scene[asset_cfg.name] # compute squared magnitude of angular velocity (all axes) - ang_vel_squared = torch.sum(torch.square(wp.to_torch(asset.data.root_ang_vel_b)), dim=1) + ang_vel_squared = torch.sum(torch.square(asset.data.root_ang_vel_b.torch), dim=1) return torch.exp(-ang_vel_squared / std**2) @@ -109,7 +108,7 @@ def lin_vel_xyz_exp( asset: RigidObject = env.scene[asset_cfg.name] # compute squared magnitude of linear velocity (all axes) - lin_vel_squared = torch.sum(torch.square(wp.to_torch(asset.data.root_lin_vel_w)), dim=1) + lin_vel_squared = torch.sum(torch.square(asset.data.root_lin_vel_w.torch), dim=1) return torch.exp(-lin_vel_squared / std**2) @@ -138,7 +137,7 @@ def yaw_aligned( asset: RigidObject = env.scene[asset_cfg.name] # extract yaw from current orientation - _, _, yaw = math_utils.euler_xyz_from_quat(wp.to_torch(asset.data.root_quat_w)) + _, _, yaw = math_utils.euler_xyz_from_quat(asset.data.root_quat_w.torch) # normalize yaw to [-pi, pi] (target is 0) yaw = math_utils.wrap_to_pi(yaw) diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomanipulation/pick_place/mdp/actions.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomanipulation/pick_place/mdp/actions.py index 307dd026fdac..32c768981b3e 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomanipulation/pick_place/mdp/actions.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomanipulation/pick_place/mdp/actions.py @@ -8,7 +8,6 @@ from typing import TYPE_CHECKING import torch -import warp as wp from isaaclab.assets.articulation import Articulation from isaaclab.managers.action_manager import ActionTerm @@ -47,7 +46,7 @@ def __init__(self, cfg: AgileBasedLowerBodyActionCfg, env: ManagerBasedEnv): # Get the scale and offset from the configuration self._policy_output_scale = torch.tensor(cfg.policy_output_scale, device=env.device) - self._policy_output_offset = wp.to_torch(self._asset.data.default_joint_pos)[:, self._joint_ids].clone() + self._policy_output_offset = self._asset.data.default_joint_pos.torch[:, self._joint_ids].clone() # Create tensors to store raw and processed actions self._raw_actions = torch.zeros(self.num_envs, len(self._joint_ids), device=self.device) diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomanipulation/pick_place/mdp/observations.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomanipulation/pick_place/mdp/observations.py index 5e39567efa50..4057bc6fe590 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomanipulation/pick_place/mdp/observations.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomanipulation/pick_place/mdp/observations.py @@ -8,7 +8,6 @@ from typing import TYPE_CHECKING import torch -import warp as wp if TYPE_CHECKING: from isaaclab.envs import ManagerBasedRLEnv @@ -22,7 +21,7 @@ def upper_body_last_action( ) -> torch.Tensor: """Extract the last action of the upper body.""" asset = env.scene[asset_cfg.name] - joint_pos_target = wp.to_torch(asset.data.joint_pos_target) + joint_pos_target = asset.data.joint_pos_target.torch # Use joint_names from asset_cfg to find indices joint_names = asset_cfg.joint_names if hasattr(asset_cfg, "joint_names") else None diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomanipulation/pick_place/mdp/terminations.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomanipulation/pick_place/mdp/terminations.py index 2b87dc69df76..db89776c3e37 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomanipulation/pick_place/mdp/terminations.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomanipulation/pick_place/mdp/terminations.py @@ -10,7 +10,6 @@ from typing import TYPE_CHECKING import torch -import warp as wp from isaaclab.managers import SceneEntityCfg from isaaclab.utils.math import quat_apply_inverse @@ -51,7 +50,7 @@ def task_done_pick_place_table_frame( env: The RL environment instance. task_link_name: Name of the right wrist link on the robot. object_cfg: Configuration for the object entity. - table_cfg: Configuration for the destination table entity (must be an XformPrimView). + table_cfg: Configuration for the destination table entity (must be a FrameView). right_wrist_max_x: Maximum x position of the right wrist in table frame for task completion. min_x: Minimum x position of the object relative to the table for task completion. max_x: Maximum x position of the object relative to the table for task completion. @@ -75,9 +74,10 @@ def task_done_pick_place_table_frame( # Get table world pose table_pos_w, table_quat_w = table.get_world_poses() + table_pos_w, table_quat_w = table_pos_w.torch, table_quat_w.torch # Broadcast table pose if a single table is shared across all envs - object_root_pos_w = wp.to_torch(object.data.root_pos_w) # [num_envs, 3] + object_root_pos_w = object.data.root_pos_w.torch # [num_envs, 3] if table_pos_w.shape[0] == 1 and object_root_pos_w.shape[0] > 1: table_pos_w = table_pos_w.expand(object_root_pos_w.shape[0], -1) table_quat_w = table_quat_w.expand(object_root_pos_w.shape[0], -1) @@ -87,10 +87,10 @@ def task_done_pick_place_table_frame( object_x = object_to_table_pos[:, 0] object_y = object_to_table_pos[:, 1] object_height = object_to_table_pos[:, 2] - object_vel = torch.abs(wp.to_torch(object.data.root_vel_w)) + object_vel = torch.abs(object.data.root_vel_w.torch) # Right wrist position in table frame - robot_body_pos_w = wp.to_torch(env.scene["robot"].data.body_pos_w) + robot_body_pos_w = env.scene["robot"].data.body_pos_w.torch right_eef_idx = env.scene["robot"].data.body_names.index(task_link_name) right_wrist_pos_w = robot_body_pos_w[:, right_eef_idx, :] - table_pos_w right_wrist_x = quat_apply_inverse(table_quat_w, right_wrist_pos_w)[:, 0] @@ -146,8 +146,8 @@ def object_too_far_from_robot( robot: RigidObject = env.scene[robot_cfg.name] object: RigidObject = env.scene[object_cfg.name] - robot_pos = wp.to_torch(robot.data.root_pos_w)[:, :3] - object_pos = wp.to_torch(object.data.root_pos_w)[:, :3] + robot_pos = robot.data.root_pos_w.torch[:, :3] + object_pos = object.data.root_pos_w.torch[:, :3] distance = torch.norm(robot_pos - object_pos, dim=1) diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/a1/flat_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/a1/flat_env_cfg.py index a989c78f80cc..93541ff765ae 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/a1/flat_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/a1/flat_env_cfg.py @@ -17,7 +17,7 @@ @configclass class PhysicsCfg(PresetCfg): default = PhysxCfg(gpu_max_rigid_patch_count=10 * 2**15) - newton = NewtonCfg( + newton_mjwarp = NewtonCfg( solver_cfg=MJWarpSolverCfg( njmax=60, nconmax=30, diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/a1/rough_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/a1/rough_env_cfg.py index 6ee9dbe78505..2857d3dc0341 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/a1/rough_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/a1/rough_env_cfg.py @@ -3,14 +3,10 @@ # # SPDX-License-Identifier: BSD-3-Clause + from isaaclab.utils import configclass -from isaaclab_tasks.manager_based.locomotion.velocity.velocity_env_cfg import ( - EventsCfg, - LocomotionVelocityRoughEnvCfg, - StartupEventsCfg, -) -from isaaclab_tasks.utils import PresetCfg +from isaaclab_tasks.manager_based.locomotion.velocity.velocity_env_cfg import LocomotionVelocityRoughEnvCfg ## # Pre-defined configs @@ -18,46 +14,8 @@ from isaaclab_assets.robots.unitree import UNITREE_A1_CFG # isort: skip -@configclass -class A1NewtonEventsCfg(EventsCfg): - def __post_init__(self): - super().__post_init__() - self.push_robot = None - self.base_external_force_torque.params["asset_cfg"].body_names = "trunk" - self.reset_robot_joints.params["position_range"] = (1.0, 1.0) - self.reset_base.params = { - "pose_range": {"x": (-0.5, 0.5), "y": (-0.5, 0.5), "yaw": (-3.14, 3.14)}, - "velocity_range": { - "x": (0.0, 0.0), - "y": (0.0, 0.0), - "z": (0.0, 0.0), - "roll": (0.0, 0.0), - "pitch": (0.0, 0.0), - "yaw": (0.0, 0.0), - }, - } - - -@configclass -class A1PhysxEventsCfg(A1NewtonEventsCfg, StartupEventsCfg): - def __post_init__(self): - super().__post_init__() - self.add_base_mass.params["mass_distribution_params"] = (-1.0, 3.0) - self.add_base_mass.params["asset_cfg"].body_names = "trunk" - self.base_com = None - - -@configclass -class A1EventsCfg(PresetCfg): - default = A1PhysxEventsCfg() - newton = A1NewtonEventsCfg() - physx = default - - @configclass class UnitreeA1RoughEnvCfg(LocomotionVelocityRoughEnvCfg): - events: A1EventsCfg = A1EventsCfg() - def __post_init__(self): # post init of parent super().__post_init__() @@ -69,6 +27,11 @@ def __post_init__(self): self.scene.terrain.terrain_generator.sub_terrains["random_rough"].noise_range = (0.01, 0.06) self.scene.terrain.terrain_generator.sub_terrains["random_rough"].noise_step = 0.01 + # A1 uses "trunk" as base body + self.events.add_base_mass.params["asset_cfg"].body_names = "trunk" + self.events.base_external_force_torque.params["asset_cfg"].body_names = "trunk" + self.events.base_com.default.params["asset_cfg"].body_names = "trunk" + # reduce action scale self.actions.joint_pos.scale = 0.25 diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/anymal_b/flat_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/anymal_b/flat_env_cfg.py index 82182c33c800..7b745dfe1a07 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/anymal_b/flat_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/anymal_b/flat_env_cfg.py @@ -17,7 +17,7 @@ @configclass class PhysicsCfg(PresetCfg): default = PhysxCfg(gpu_max_rigid_patch_count=10 * 2**15) - newton = NewtonCfg( + newton_mjwarp = NewtonCfg( solver_cfg=MJWarpSolverCfg( njmax=75, nconmax=15, diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/anymal_b/rough_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/anymal_b/rough_env_cfg.py index aa67be58fc73..cf3fc2c3f232 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/anymal_b/rough_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/anymal_b/rough_env_cfg.py @@ -3,14 +3,10 @@ # # SPDX-License-Identifier: BSD-3-Clause + from isaaclab.utils import configclass -from isaaclab_tasks.manager_based.locomotion.velocity.velocity_env_cfg import ( - EventsCfg, - LocomotionVelocityRoughEnvCfg, - StartupEventsCfg, -) -from isaaclab_tasks.utils import PresetCfg +from isaaclab_tasks.manager_based.locomotion.velocity.velocity_env_cfg import LocomotionVelocityRoughEnvCfg ## # Pre-defined configs @@ -18,22 +14,8 @@ from isaaclab_assets import ANYMAL_B_CFG # isort: skip -@configclass -class AnymalBPhysxEventsCfg(EventsCfg, StartupEventsCfg): - pass - - -@configclass -class AnymalBEventsCfg(PresetCfg): - default = AnymalBPhysxEventsCfg() - newton = EventsCfg() - physx = default - - @configclass class AnymalBRoughEnvCfg(LocomotionVelocityRoughEnvCfg): - events: AnymalBEventsCfg = AnymalBEventsCfg() - def __post_init__(self): # post init of parent super().__post_init__() diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/anymal_c/flat_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/anymal_c/flat_env_cfg.py index 0a8cf3d43ad9..54c1076625a1 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/anymal_c/flat_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/anymal_c/flat_env_cfg.py @@ -17,7 +17,7 @@ @configclass class PhysicsCfg(PresetCfg): default = PhysxCfg(gpu_max_rigid_patch_count=10 * 2**15) - newton = NewtonCfg( + newton_mjwarp = NewtonCfg( solver_cfg=MJWarpSolverCfg( njmax=120, nconmax=15, diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/anymal_c/rough_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/anymal_c/rough_env_cfg.py index f8c24666ae2e..8c4cbb7a84c3 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/anymal_c/rough_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/anymal_c/rough_env_cfg.py @@ -3,14 +3,11 @@ # # SPDX-License-Identifier: BSD-3-Clause + from isaaclab.utils import configclass -from isaaclab_tasks.manager_based.locomotion.velocity.velocity_env_cfg import ( - EventsCfg, - LocomotionVelocityRoughEnvCfg, - StartupEventsCfg, -) -from isaaclab_tasks.utils import PresetCfg, preset +from isaaclab_tasks.manager_based.locomotion.velocity.velocity_env_cfg import LocomotionVelocityRoughEnvCfg +from isaaclab_tasks.utils import preset ## # Pre-defined configs @@ -18,28 +15,14 @@ from isaaclab_assets.robots.anymal import ANYMAL_C_CFG # isort: skip -@configclass -class AnymalCPhysxEventsCfg(EventsCfg, StartupEventsCfg): - pass - - -@configclass -class AnymalCEventsCfg(PresetCfg): - default = AnymalCPhysxEventsCfg() - newton = EventsCfg() - physx = default - - @configclass class AnymalCRoughEnvCfg(LocomotionVelocityRoughEnvCfg): - events: AnymalCEventsCfg = AnymalCEventsCfg() - def __post_init__(self): # post init of parent super().__post_init__() # switch robot to anymal-c self.scene.robot = ANYMAL_C_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") - self.scene.robot.actuators["legs"].armature = preset(default=0.0, newton=0.01, physx=0.0) + self.scene.robot.actuators["legs"].armature = preset(default=0.0, newton_mjwarp=0.01, physx=0.0) @configclass diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/anymal_d/flat_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/anymal_d/flat_env_cfg.py index 25b1fa19408c..9a213f9d0f64 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/anymal_d/flat_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/anymal_d/flat_env_cfg.py @@ -17,7 +17,7 @@ @configclass class PhysicsCfg(PresetCfg): default = PhysxCfg(gpu_max_rigid_patch_count=10 * 2**15) - newton = NewtonCfg( + newton_mjwarp = NewtonCfg( solver_cfg=MJWarpSolverCfg( njmax=60, nconmax=25, diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/anymal_d/rough_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/anymal_d/rough_env_cfg.py index 38d6b9d0546e..c1c49677e66a 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/anymal_d/rough_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/anymal_d/rough_env_cfg.py @@ -3,14 +3,10 @@ # # SPDX-License-Identifier: BSD-3-Clause + from isaaclab.utils import configclass -from isaaclab_tasks.manager_based.locomotion.velocity.velocity_env_cfg import ( - EventsCfg, - LocomotionVelocityRoughEnvCfg, - StartupEventsCfg, -) -from isaaclab_tasks.utils import PresetCfg +from isaaclab_tasks.manager_based.locomotion.velocity.velocity_env_cfg import LocomotionVelocityRoughEnvCfg ## # Pre-defined configs @@ -18,22 +14,8 @@ from isaaclab_assets.robots.anymal import ANYMAL_D_CFG # isort: skip -@configclass -class AnymalDPhysxEventsCfg(EventsCfg, StartupEventsCfg): - pass - - -@configclass -class AnymalDEventsCfg(PresetCfg): - default = AnymalDPhysxEventsCfg() - newton = EventsCfg() - physx = default - - @configclass class AnymalDRoughEnvCfg(LocomotionVelocityRoughEnvCfg): - events: AnymalDEventsCfg = AnymalDEventsCfg() - def __post_init__(self): # post init of parent super().__post_init__() diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/cassie/flat_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/cassie/flat_env_cfg.py index be97fed80a4a..e9539b6551c5 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/cassie/flat_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/cassie/flat_env_cfg.py @@ -17,7 +17,7 @@ @configclass class PhysicsCfg(PresetCfg): default = PhysxCfg(gpu_max_rigid_patch_count=10 * 2**15) - newton = NewtonCfg( + newton_mjwarp = NewtonCfg( solver_cfg=MJWarpSolverCfg( njmax=52, nconmax=15, diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/cassie/rough_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/cassie/rough_env_cfg.py index 5bd6ba28684f..d8a2ef0874dd 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/cassie/rough_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/cassie/rough_env_cfg.py @@ -3,18 +3,17 @@ # # SPDX-License-Identifier: BSD-3-Clause + from isaaclab.managers import RewardTermCfg as RewTerm from isaaclab.managers import SceneEntityCfg from isaaclab.utils import configclass import isaaclab_tasks.manager_based.locomotion.velocity.mdp as mdp from isaaclab_tasks.manager_based.locomotion.velocity.velocity_env_cfg import ( - EventsCfg, LocomotionVelocityRoughEnvCfg, RewardsCfg, - StartupEventsCfg, ) -from isaaclab_tasks.utils import PresetCfg +from isaaclab_tasks.utils import preset ## # Pre-defined configs @@ -52,54 +51,38 @@ class CassieRewardsCfg(RewardsCfg): ) -@configclass -class CassieNewtonEventsCfg(EventsCfg): - def __post_init__(self): - super().__post_init__() - self.push_robot = None - self.reset_robot_joints.params["position_range"] = (1.0, 1.0) - self.base_external_force_torque.params["asset_cfg"].body_names = [".*pelvis"] - self.reset_base.params = { - "pose_range": {"x": (-0.5, 0.5), "y": (-0.5, 0.5), "yaw": (-3.14, 3.14)}, - "velocity_range": { - "x": (0.0, 0.0), - "y": (0.0, 0.0), - "z": (0.0, 0.0), - "roll": (0.0, 0.0), - "pitch": (0.0, 0.0), - "yaw": (0.0, 0.0), - }, - } - - -@configclass -class CassiePhysxEventsCfg(CassieNewtonEventsCfg, StartupEventsCfg): - def __post_init__(self): - super().__post_init__() - self.add_base_mass = None - self.base_com = None - - -@configclass -class CassieEventsCfg(PresetCfg): - default = CassiePhysxEventsCfg() - newton = CassieNewtonEventsCfg() - physx = default - - @configclass class CassieRoughEnvCfg(LocomotionVelocityRoughEnvCfg): """Cassie rough environment configuration.""" rewards: CassieRewardsCfg = CassieRewardsCfg() - events: CassieEventsCfg = CassieEventsCfg() def __post_init__(self): super().__post_init__() + + # biped yaw control is harder than quadruped — relax the per-episode-mean yaw + # threshold to 0.8 rad/s (defaults work for quadrupeds). + self.commands.base_velocity.vel_yaw_success_threshold = 0.8 # scene self.scene.robot = CASSIE_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") + # Cassie Newton-only armature for biped stability on rough terrain; PhysX unchanged + self.scene.robot.actuators["legs"].armature = preset(default=0.0, newton_mjwarp=0.02) + self.scene.height_scanner.prim_path = "{ENV_REGEX_NS}/Robot/pelvis" + # Cassie uses "pelvis" as base body. Override the shared symmetric + # (1/1.25, 1.25) log-uniform scale with asymmetric (1.0, 1.25) — + # lighter-than-nominal pelvis destabilizes Cassie's closed-loop + # Achilles coupling + hip PD response, so only heavier perturbations + # are safe. Symmetric ±25% regressed reward 40% vs disabled; + # (1.0, 1.25) recovers to 90% of baseline. + self.events.add_base_mass.params["asset_cfg"].body_names = "pelvis" + self.events.add_base_mass.params["mass_distribution_params"] = (1.0, 1.25) + self.events.base_com = None + self.events.base_external_force_torque.params["asset_cfg"].body_names = ".*pelvis" + # Cassie has precise initial pose — don't scale joint defaults randomly on reset + self.events.reset_robot_joints.params["position_range"] = (1.0, 1.0) + # actions self.actions.joint_pos.scale = 0.5 diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/digit/rough_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/digit/rough_env_cfg.py index 185e9019a7c1..aa0f433e4ecc 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/digit/rough_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/digit/rough_env_cfg.py @@ -5,17 +5,13 @@ import math +from isaaclab.actuators import ImplicitActuatorCfg from isaaclab.managers import ObservationGroupCfg, ObservationTermCfg, RewardTermCfg, SceneEntityCfg, TerminationTermCfg from isaaclab.utils import configclass from isaaclab.utils.noise import UniformNoiseCfg as Unoise import isaaclab_tasks.manager_based.locomotion.velocity.mdp as mdp -from isaaclab_tasks.manager_based.locomotion.velocity.velocity_env_cfg import ( - EventsCfg, - LocomotionVelocityRoughEnvCfg, - StartupEventsCfg, -) -from isaaclab_tasks.utils import PresetCfg +from isaaclab_tasks.manager_based.locomotion.velocity.velocity_env_cfg import LocomotionVelocityRoughEnvCfg from isaaclab_assets.robots.agility import ARM_JOINT_NAMES, DIGIT_V4_CFG, LEG_JOINT_NAMES @@ -213,36 +209,12 @@ class DigitActionsCfg: ) -@configclass -class DigitNewtonEventsCfg(EventsCfg): - def __post_init__(self): - super().__post_init__() - self.base_external_force_torque.params["asset_cfg"] = SceneEntityCfg("robot", body_names="torso_base") - self.reset_robot_joints.params["position_range"] = (1.0, 1.0) - - -@configclass -class DigitPhysxEventsCfg(DigitNewtonEventsCfg, StartupEventsCfg): - def __post_init__(self): - super().__post_init__() - self.add_base_mass.params["asset_cfg"] = SceneEntityCfg("robot", body_names="torso_base") - self.base_com = None - - -@configclass -class DigitEventsCfg(PresetCfg): - default = DigitPhysxEventsCfg() - newton = DigitNewtonEventsCfg() - physx = default - - @configclass class DigitRoughEnvCfg(LocomotionVelocityRoughEnvCfg): rewards: DigitRewards = DigitRewards() observations: DigitObservations = DigitObservations() terminations: DigitTerminationsCfg = DigitTerminationsCfg() actions: DigitActionsCfg = DigitActionsCfg() - events: DigitEventsCfg = DigitEventsCfg() def __post_init__(self): super().__post_init__() @@ -256,6 +228,25 @@ def __post_init__(self): self.scene.contact_forces.update_period = self.sim.dt self.scene.height_scanner.update_period = self.decimation * self.sim.dt + # Digit uses "torso_base" as base body + self.events.add_base_mass.params["asset_cfg"].body_names = "torso_base" + self.events.base_external_force_torque.params["asset_cfg"].body_names = "torso_base" + self.events.base_com.default.params["asset_cfg"].body_names = "torso_base" + # Digit has precise initial pose — don't scale joint defaults randomly on reset + self.events.reset_robot_joints.params["position_range"] = (1.0, 1.0) + + # Override actuator to target only actuated joints. Digit has ball joints (rod constraints) + # that MuJoCo represents with 4 DoFs instead of 3, inflating joint_pos to 74 columns while + # joint_pos_target stays at 64. Using ".*" gives slice(None) which indexes both buffers + # differently. Explicit joint names produce a concrete index tensor that works correctly. + self.scene.robot.actuators = { + "legs_arms": ImplicitActuatorCfg( + joint_names_expr=LEG_JOINT_NAMES + ARM_JOINT_NAMES, + stiffness=None, + damping=None, + ), + } + # Commands self.commands.base_velocity.ranges.lin_vel_x = (-0.8, 0.8) self.commands.base_velocity.ranges.lin_vel_y = (-0.5, 0.5) diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/g1/agents/rsl_rl_ppo_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/g1/agents/rsl_rl_ppo_cfg.py index 61a6d0261b9f..7b61c184d353 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/g1/agents/rsl_rl_ppo_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/g1/agents/rsl_rl_ppo_cfg.py @@ -7,11 +7,19 @@ from isaaclab_rl.rsl_rl import RslRlOnPolicyRunnerCfg, RslRlPpoActorCriticCfg, RslRlPpoAlgorithmCfg +from isaaclab_tasks.utils import preset + @configclass class G1RoughPPORunnerCfg(RslRlOnPolicyRunnerCfg): num_steps_per_env = 24 - max_iterations = 3000 + # Newton needs ~1.7x the PPO iterations to match PhysX on G1. PhysX saturates near iter 3000 + # (reward ≈ +18, ep_len ≈ 980) and does not meaningfully improve on either metric past that — + # reward oscillates +16 to +19 through iter 7500, ep_len stays flat. Newton reaches the same + # (reward, ep_len) quality at iter 5000 (+16 / 984). Comparing reward alone is misleading: + # ep_len confirms the robot is stable in both cases. The gap is sample-efficiency, not a + # ceiling — no physics or reward tuning closes it. + max_iterations = preset(default=3000, newton=5000) save_interval = 50 experiment_name = "g1_rough" policy = RslRlPpoActorCriticCfg( diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/g1/flat_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/g1/flat_env_cfg.py index 6d43a02b3b66..1df1a91447ea 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/g1/flat_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/g1/flat_env_cfg.py @@ -18,7 +18,7 @@ @configclass class PhysicsCfg(PresetCfg): default = PhysxCfg(gpu_max_rigid_patch_count=10 * 2**15) - newton = NewtonCfg( + newton_mjwarp = NewtonCfg( solver_cfg=MJWarpSolverCfg( njmax=95, nconmax=10, diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/g1/rough_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/g1/rough_env_cfg.py index 6a7035416ab3..65dbb157c177 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/g1/rough_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/g1/rough_env_cfg.py @@ -3,18 +3,16 @@ # # SPDX-License-Identifier: BSD-3-Clause + from isaaclab.managers import RewardTermCfg as RewTerm from isaaclab.managers import SceneEntityCfg from isaaclab.utils import configclass import isaaclab_tasks.manager_based.locomotion.velocity.mdp as mdp from isaaclab_tasks.manager_based.locomotion.velocity.velocity_env_cfg import ( - EventsCfg, LocomotionVelocityRoughEnvCfg, RewardsCfg, - StartupEventsCfg, ) -from isaaclab_tasks.utils import PresetCfg ## # Pre-defined configs @@ -106,53 +104,28 @@ class G1Rewards(RewardsCfg): ) -@configclass -class G1NewtonEventsCfg(EventsCfg): - def __post_init__(self): - super().__post_init__() - self.push_robot = None - self.reset_robot_joints.params["position_range"] = (1.0, 1.0) - self.base_external_force_torque.params["asset_cfg"].body_names = ["torso_link"] - self.reset_base.params = { - "pose_range": {"x": (-0.5, 0.5), "y": (-0.5, 0.5), "yaw": (-3.14, 3.14)}, - "velocity_range": { - "x": (0.0, 0.0), - "y": (0.0, 0.0), - "z": (0.0, 0.0), - "roll": (0.0, 0.0), - "pitch": (0.0, 0.0), - "yaw": (0.0, 0.0), - }, - } - - -@configclass -class G1PhysxEventsCfg(G1NewtonEventsCfg, StartupEventsCfg): - def __post_init__(self): - super().__post_init__() - self.add_base_mass = None - self.base_com = None - - -@configclass -class G1EventsCfg(PresetCfg): - default = G1PhysxEventsCfg() - newton = G1NewtonEventsCfg() - physx = default - - @configclass class G1RoughEnvCfg(LocomotionVelocityRoughEnvCfg): rewards: G1Rewards = G1Rewards() - events: G1EventsCfg = G1EventsCfg() def __post_init__(self): # post init of parent super().__post_init__() + + # biped yaw control is harder than quadruped — relax the per-episode-mean yaw + # threshold to 0.8 rad/s (defaults work for quadrupeds). + self.commands.base_velocity.vel_yaw_success_threshold = 0.8 # Scene self.scene.robot = G1_MINIMAL_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") self.scene.height_scanner.prim_path = "{ENV_REGEX_NS}/Robot/torso_link" + # G1 uses "torso_link" as base body — disable mass randomization for bipeds + self.events.add_base_mass = None + self.events.base_com = None + self.events.base_external_force_torque.params["asset_cfg"].body_names = "torso_link" + # G1 has precise initial pose — don't scale joint defaults randomly on reset + self.events.reset_robot_joints.params["position_range"] = (1.0, 1.0) + # Rewards self.rewards.lin_vel_z_l2.weight = 0.0 self.rewards.undesired_contacts = None diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/go1/flat_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/go1/flat_env_cfg.py index a79ee3a51132..03f62cd96642 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/go1/flat_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/go1/flat_env_cfg.py @@ -17,7 +17,7 @@ @configclass class PhysicsCfg(PresetCfg): default = PhysxCfg(gpu_max_rigid_patch_count=10 * 2**15) - newton = NewtonCfg( + newton_mjwarp = NewtonCfg( solver_cfg=MJWarpSolverCfg( njmax=60, nconmax=25, diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/go1/rough_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/go1/rough_env_cfg.py index eafd3da45f30..e09ceee0d49d 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/go1/rough_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/go1/rough_env_cfg.py @@ -3,14 +3,11 @@ # # SPDX-License-Identifier: BSD-3-Clause + from isaaclab.utils import configclass -from isaaclab_tasks.manager_based.locomotion.velocity.velocity_env_cfg import ( - EventsCfg, - LocomotionVelocityRoughEnvCfg, - StartupEventsCfg, -) -from isaaclab_tasks.utils import PresetCfg +from isaaclab_tasks.manager_based.locomotion.velocity.velocity_env_cfg import LocomotionVelocityRoughEnvCfg +from isaaclab_tasks.utils import preset ## # Pre-defined configs @@ -18,57 +15,25 @@ from isaaclab_assets.robots.unitree import UNITREE_GO1_CFG # isort: skip -@configclass -class Go1NewtonEventsCfg(EventsCfg): - def __post_init__(self): - super().__post_init__() - self.push_robot = None - self.base_external_force_torque.params["asset_cfg"].body_names = "trunk" - self.reset_robot_joints.params["position_range"] = (1.0, 1.0) - self.reset_base.params = { - "pose_range": {"x": (-0.5, 0.5), "y": (-0.5, 0.5), "yaw": (-3.14, 3.14)}, - "velocity_range": { - "x": (0.0, 0.0), - "y": (0.0, 0.0), - "z": (0.0, 0.0), - "roll": (0.0, 0.0), - "pitch": (0.0, 0.0), - "yaw": (0.0, 0.0), - }, - } - - -@configclass -class Go1PhysxEventsCfg(Go1NewtonEventsCfg, StartupEventsCfg): - def __post_init__(self): - super().__post_init__() - self.add_base_mass.params["mass_distribution_params"] = (-1.0, 3.0) - self.add_base_mass.params["asset_cfg"].body_names = "trunk" - self.base_com = None - - -@configclass -class Go1EventsCfg(PresetCfg): - default = Go1PhysxEventsCfg() - newton = Go1NewtonEventsCfg() - physx = default - - @configclass class UnitreeGo1RoughEnvCfg(LocomotionVelocityRoughEnvCfg): - events: Go1EventsCfg = Go1EventsCfg() - def __post_init__(self): # post init of parent super().__post_init__() self.scene.robot = UNITREE_GO1_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") + self.scene.robot.actuators["base_legs"].armature = preset(default=0.0, newton_mjwarp=0.02) self.scene.height_scanner.prim_path = "{ENV_REGEX_NS}/Robot/trunk" # scale down the terrains because the robot is small self.scene.terrain.terrain_generator.sub_terrains["boxes"].grid_height_range = (0.025, 0.1) self.scene.terrain.terrain_generator.sub_terrains["random_rough"].noise_range = (0.01, 0.06) self.scene.terrain.terrain_generator.sub_terrains["random_rough"].noise_step = 0.01 + # Go1 uses "trunk" as base body + self.events.add_base_mass.params["asset_cfg"].body_names = "trunk" + self.events.base_external_force_torque.params["asset_cfg"].body_names = "trunk" + self.events.base_com.default.params["asset_cfg"].body_names = "trunk" + # reduce action scale self.actions.joint_pos.scale = 0.25 diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/go2/flat_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/go2/flat_env_cfg.py index db4331e87ebd..9a1d481876d5 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/go2/flat_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/go2/flat_env_cfg.py @@ -17,7 +17,7 @@ @configclass class PhysicsCfg(PresetCfg): default = PhysxCfg(gpu_max_rigid_patch_count=10 * 2**15) - newton = NewtonCfg( + newton_mjwarp = NewtonCfg( solver_cfg=MJWarpSolverCfg( njmax=65, nconmax=35, diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/go2/rough_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/go2/rough_env_cfg.py index 40fbef99e27e..758e9c4dbb09 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/go2/rough_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/go2/rough_env_cfg.py @@ -3,24 +3,11 @@ # # SPDX-License-Identifier: BSD-3-Clause -from isaaclab_physx.physics import PhysxCfg -from isaaclab.sim import SimulationCfg from isaaclab.utils import configclass -from isaaclab_tasks.manager_based.locomotion.velocity.velocity_env_cfg import ( - EventsCfg, - LocomotionVelocityRoughEnvCfg, - StartupEventsCfg, -) -from isaaclab_tasks.utils import PresetCfg - - -@configclass -class PhysicsCfg(PresetCfg): - default = PhysxCfg(gpu_max_rigid_patch_count=10 * 2**15) - physx = default - +from isaaclab_tasks.manager_based.locomotion.velocity.velocity_env_cfg import LocomotionVelocityRoughEnvCfg +from isaaclab_tasks.utils import preset ## # Pre-defined configs @@ -28,52 +15,14 @@ class PhysicsCfg(PresetCfg): from isaaclab_assets.robots.unitree import UNITREE_GO2_CFG # isort: skip -@configclass -class Go2NewtonEventsCfg(EventsCfg): - def __post_init__(self): - super().__post_init__() - self.push_robot = None - self.base_external_force_torque.params["asset_cfg"].body_names = "base" - self.reset_robot_joints.params["position_range"] = (1.0, 1.0) - self.reset_base.params = { - "pose_range": {"x": (-0.5, 0.5), "y": (-0.5, 0.5), "yaw": (-3.14, 3.14)}, - "velocity_range": { - "x": (0.0, 0.0), - "y": (0.0, 0.0), - "z": (0.0, 0.0), - "roll": (0.0, 0.0), - "pitch": (0.0, 0.0), - "yaw": (0.0, 0.0), - }, - } - - -@configclass -class Go2PhysxEventsCfg(Go2NewtonEventsCfg, StartupEventsCfg): - def __post_init__(self): - super().__post_init__() - self.add_base_mass.params["mass_distribution_params"] = (-1.0, 3.0) - self.add_base_mass.params["asset_cfg"].body_names = "base" - self.base_com = None - - -@configclass -class Go2EventsCfg(PresetCfg): - default = Go2PhysxEventsCfg() - newton = Go2NewtonEventsCfg() - physx = default - - @configclass class UnitreeGo2RoughEnvCfg(LocomotionVelocityRoughEnvCfg): - sim: SimulationCfg = SimulationCfg(physics=PhysicsCfg()) - events: Go2EventsCfg = Go2EventsCfg() - def __post_init__(self): # post init of parent super().__post_init__() self.scene.robot = UNITREE_GO2_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") + self.scene.robot.actuators["base_legs"].armature = preset(default=0.0, newton_mjwarp=0.02) self.scene.height_scanner.prim_path = "{ENV_REGEX_NS}/Robot/base" # scale down the terrains because the robot is small self.scene.terrain.terrain_generator.sub_terrains["boxes"].grid_height_range = (0.025, 0.1) diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/h1/flat_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/h1/flat_env_cfg.py index 4552a00a330e..eb501ad12ba7 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/h1/flat_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/h1/flat_env_cfg.py @@ -17,7 +17,7 @@ @configclass class PhysicsCfg(PresetCfg): default = PhysxCfg(gpu_max_rigid_patch_count=10 * 2**15) - newton = NewtonCfg( + newton_mjwarp = NewtonCfg( solver_cfg=MJWarpSolverCfg( njmax=65, nconmax=15, diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/h1/rough_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/h1/rough_env_cfg.py index 496aa4007fef..167141c1747e 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/h1/rough_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/h1/rough_env_cfg.py @@ -3,18 +3,16 @@ # # SPDX-License-Identifier: BSD-3-Clause + from isaaclab.managers import RewardTermCfg as RewTerm from isaaclab.managers import SceneEntityCfg from isaaclab.utils import configclass import isaaclab_tasks.manager_based.locomotion.velocity.mdp as mdp from isaaclab_tasks.manager_based.locomotion.velocity.velocity_env_cfg import ( - EventsCfg, LocomotionVelocityRoughEnvCfg, RewardsCfg, - StartupEventsCfg, ) -from isaaclab_tasks.utils import PresetCfg ## # Pre-defined configs @@ -73,54 +71,30 @@ class H1Rewards(RewardsCfg): ) -@configclass -class H1NewtonEventsCfg(EventsCfg): - def __post_init__(self): - super().__post_init__() - self.push_robot = None - self.reset_robot_joints.params["position_range"] = (1.0, 1.0) - self.base_external_force_torque.params["asset_cfg"].body_names = [".*torso_link"] - self.reset_base.params = { - "pose_range": {"x": (-0.5, 0.5), "y": (-0.5, 0.5), "yaw": (-3.14, 3.14)}, - "velocity_range": { - "x": (0.0, 0.0), - "y": (0.0, 0.0), - "z": (0.0, 0.0), - "roll": (0.0, 0.0), - "pitch": (0.0, 0.0), - "yaw": (0.0, 0.0), - }, - } - - -@configclass -class H1PhysxEventsCfg(H1NewtonEventsCfg, StartupEventsCfg): - def __post_init__(self): - super().__post_init__() - self.add_base_mass = None - self.base_com = None - - -@configclass -class H1EventsCfg(PresetCfg): - default = H1PhysxEventsCfg() - newton = H1NewtonEventsCfg() - physx = default - - @configclass class H1RoughEnvCfg(LocomotionVelocityRoughEnvCfg): rewards: H1Rewards = H1Rewards() - events: H1EventsCfg = H1EventsCfg() def __post_init__(self): # post init of parent super().__post_init__() + + # biped yaw control is harder than quadruped — relax the per-episode-mean yaw + # threshold to 0.8 rad/s (defaults work for quadrupeds). + self.commands.base_velocity.vel_yaw_success_threshold = 0.8 # Scene self.scene.robot = H1_MINIMAL_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") if self.scene.height_scanner: self.scene.height_scanner.prim_path = "{ENV_REGEX_NS}/Robot/torso_link" + # H1 uses "torso_link" as base body; inherits the shared log-uniform mass + # randomization scale from EventsCfg (no per-H1 override needed). + self.events.add_base_mass.params["asset_cfg"].body_names = "torso_link" + # H1 has precise initial pose — don't scale joint defaults randomly on reset + self.events.reset_robot_joints.params["position_range"] = (1.0, 1.0) + self.events.base_com = None + self.events.base_external_force_torque.params["asset_cfg"].body_names = ".*torso_link" + # Rewards self.rewards.undesired_contacts = None self.rewards.flat_orientation_l2.weight = -1.0 diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/spot/flat_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/spot/flat_env_cfg.py index f015857dd110..cffe129dca7a 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/spot/flat_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/spot/flat_env_cfg.py @@ -29,7 +29,7 @@ @configclass class PhysicsCfg(PresetCfg): default = PhysxCfg(gpu_max_rigid_patch_count=10 * 2**15) - newton = NewtonCfg( + newton_mjwarp = NewtonCfg( solver_cfg=MJWarpSolverCfg( njmax=45, nconmax=30, @@ -218,7 +218,7 @@ class SpotPhysxEventCfg(SpotNewtonEventCfg, SpotStartupEventCfg): @configclass class SpotEventCfg(PresetCfg): default = SpotPhysxEventCfg() - newton = SpotNewtonEventCfg() + newton_mjwarp = SpotNewtonEventCfg() physx = default diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/spot/mdp/events.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/spot/mdp/events.py index bd89176fc5d1..eb9929ada4e1 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/spot/mdp/events.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/spot/mdp/events.py @@ -15,7 +15,6 @@ from typing import TYPE_CHECKING import torch -import warp as wp from isaaclab.managers import SceneEntityCfg from isaaclab.utils.math import sample_uniform @@ -41,16 +40,16 @@ def reset_joints_around_default( # extract the used quantities (to enable type-hinting) asset: Articulation = env.scene[asset_cfg.name] # get default joint state - joint_min_pos = wp.to_torch(asset.data.default_joint_pos)[env_ids] + position_range[0] - joint_max_pos = wp.to_torch(asset.data.default_joint_pos)[env_ids] + position_range[1] - joint_min_vel = wp.to_torch(asset.data.default_joint_vel)[env_ids] + velocity_range[0] - joint_max_vel = wp.to_torch(asset.data.default_joint_vel)[env_ids] + velocity_range[1] + joint_min_pos = asset.data.default_joint_pos.torch[env_ids] + position_range[0] + joint_max_pos = asset.data.default_joint_pos.torch[env_ids] + position_range[1] + joint_min_vel = asset.data.default_joint_vel.torch[env_ids] + velocity_range[0] + joint_max_vel = asset.data.default_joint_vel.torch[env_ids] + velocity_range[1] # clip pos to range - joint_pos_limits = wp.to_torch(asset.data.soft_joint_pos_limits)[env_ids, ...] + joint_pos_limits = asset.data.soft_joint_pos_limits.torch[env_ids, ...] joint_min_pos = torch.clamp(joint_min_pos, min=joint_pos_limits[..., 0], max=joint_pos_limits[..., 1]) joint_max_pos = torch.clamp(joint_max_pos, min=joint_pos_limits[..., 0], max=joint_pos_limits[..., 1]) # clip vel to range - joint_vel_abs_limits = wp.to_torch(asset.data.soft_joint_vel_limits)[env_ids] + joint_vel_abs_limits = asset.data.soft_joint_vel_limits.torch[env_ids] joint_min_vel = torch.clamp(joint_min_vel, min=-joint_vel_abs_limits, max=joint_vel_abs_limits) joint_max_vel = torch.clamp(joint_max_vel, min=-joint_vel_abs_limits, max=joint_vel_abs_limits) # sample these values randomly diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/spot/mdp/rewards.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/spot/mdp/rewards.py index 81e72ee50727..5cb88e0420aa 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/spot/mdp/rewards.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/config/spot/mdp/rewards.py @@ -14,7 +14,6 @@ from typing import TYPE_CHECKING import torch -import warp as wp from isaaclab.managers import ManagerTermBase, SceneEntityCfg @@ -44,14 +43,14 @@ def air_time_reward( if contact_sensor.cfg.track_air_time is False: raise RuntimeError("Activate ContactSensor's track_air_time!") # compute the reward - current_air_time = wp.to_torch(contact_sensor.data.current_air_time)[:, sensor_cfg.body_ids] - current_contact_time = wp.to_torch(contact_sensor.data.current_contact_time)[:, sensor_cfg.body_ids] + current_air_time = contact_sensor.data.current_air_time.torch[:, sensor_cfg.body_ids] + current_contact_time = contact_sensor.data.current_contact_time.torch[:, sensor_cfg.body_ids] t_max = torch.max(current_air_time, current_contact_time) t_min = torch.clip(t_max, max=mode_time) stance_cmd_reward = torch.clip(current_contact_time - current_air_time, -mode_time, mode_time) cmd = torch.linalg.norm(env.command_manager.get_command("base_velocity"), dim=1).unsqueeze(dim=1).expand(-1, 4) - body_vel = torch.linalg.norm(wp.to_torch(asset.data.root_lin_vel_b)[:, :2], dim=1).unsqueeze(dim=1).expand(-1, 4) + body_vel = torch.linalg.norm(asset.data.root_lin_vel_b.torch[:, :2], dim=1).unsqueeze(dim=1).expand(-1, 4) reward = torch.where( torch.logical_or(cmd > 0.0, body_vel > velocity_threshold), torch.where(t_max < mode_time, t_min, 0), @@ -66,7 +65,7 @@ def base_angular_velocity_reward(env: ManagerBasedRLEnv, asset_cfg: SceneEntityC asset: RigidObject = env.scene[asset_cfg.name] # compute the error target = env.command_manager.get_command("base_velocity")[:, 2] - ang_vel_error = torch.linalg.norm((target - wp.to_torch(asset.data.root_ang_vel_b)[:, 2]).unsqueeze(1), dim=1) + ang_vel_error = torch.linalg.norm((target - asset.data.root_ang_vel_b.torch[:, 2]).unsqueeze(1), dim=1) return torch.exp(-ang_vel_error / std) @@ -78,7 +77,7 @@ def base_linear_velocity_reward( asset: RigidObject = env.scene[asset_cfg.name] # compute the error target = env.command_manager.get_command("base_velocity")[:, :2] - lin_vel_error = torch.linalg.norm((target - wp.to_torch(asset.data.root_lin_vel_b)[:, :2]), dim=1) + lin_vel_error = torch.linalg.norm((target - asset.data.root_lin_vel_b.torch[:, :2]), dim=1) # fixed 1.0 multiple for tracking below the ramp_at_vel value, then scale by the rate above vel_cmd_magnitude = torch.linalg.norm(target, dim=1) velocity_scaling_multiple = torch.clamp(1.0 + ramp_rate * (vel_cmd_magnitude - ramp_at_vel), min=1.0) @@ -151,7 +150,7 @@ def __call__( async_reward = async_reward_0 * async_reward_1 * async_reward_2 * async_reward_3 # only enforce gait if cmd > 0 cmd = torch.linalg.norm(env.command_manager.get_command("base_velocity"), dim=1) - body_vel = torch.linalg.norm(wp.to_torch(self.asset.data.root_lin_vel_b)[:, :2], dim=1) + body_vel = torch.linalg.norm(self.asset.data.root_lin_vel_b.torch[:, :2], dim=1) return torch.where( torch.logical_or(cmd > 0.0, body_vel > self.velocity_threshold), sync_reward * async_reward, 0.0 ) @@ -162,8 +161,8 @@ def __call__( def _sync_reward_func(self, foot_0: int, foot_1: int) -> torch.Tensor: """Reward synchronization of two feet.""" - air_time = wp.to_torch(self.contact_sensor.data.current_air_time) - contact_time = wp.to_torch(self.contact_sensor.data.current_contact_time) + air_time = self.contact_sensor.data.current_air_time.torch + contact_time = self.contact_sensor.data.current_contact_time.torch # penalize the difference between the most recent air time and contact time of synced feet pairs. se_air = torch.clip(torch.square(air_time[:, foot_0] - air_time[:, foot_1]), max=self.max_err**2) se_contact = torch.clip(torch.square(contact_time[:, foot_0] - contact_time[:, foot_1]), max=self.max_err**2) @@ -171,8 +170,8 @@ def _sync_reward_func(self, foot_0: int, foot_1: int) -> torch.Tensor: def _async_reward_func(self, foot_0: int, foot_1: int) -> torch.Tensor: """Reward anti-synchronization of two feet.""" - air_time = wp.to_torch(self.contact_sensor.data.current_air_time) - contact_time = wp.to_torch(self.contact_sensor.data.current_contact_time) + air_time = self.contact_sensor.data.current_air_time.torch + contact_time = self.contact_sensor.data.current_contact_time.torch # penalize the difference between opposing contact modes air time of feet 1 to contact time of feet 2 # and contact time of feet 1 to air time of feet 2) of feet pairs that are not in sync with each other. se_act_0 = torch.clip(torch.square(air_time[:, foot_0] - contact_time[:, foot_1]), max=self.max_err**2) @@ -185,9 +184,9 @@ def foot_clearance_reward( ) -> torch.Tensor: """Reward the swinging feet for clearing a specified height off the ground""" asset: RigidObject = env.scene[asset_cfg.name] - foot_z_target_error = torch.square(wp.to_torch(asset.data.body_pos_w)[:, asset_cfg.body_ids, 2] - target_height) + foot_z_target_error = torch.square(asset.data.body_pos_w.torch[:, asset_cfg.body_ids, 2] - target_height) foot_velocity_tanh = torch.tanh( - tanh_mult * torch.linalg.norm(wp.to_torch(asset.data.body_lin_vel_w)[:, asset_cfg.body_ids, :2], dim=2) + tanh_mult * torch.linalg.norm(asset.data.body_lin_vel_w.torch[:, asset_cfg.body_ids, :2], dim=2) ) reward = foot_z_target_error * foot_velocity_tanh return torch.exp(-torch.sum(reward, dim=1) / std) @@ -210,8 +209,8 @@ def air_time_variance_penalty(env: ManagerBasedRLEnv, sensor_cfg: SceneEntityCfg if contact_sensor.cfg.track_air_time is False: raise RuntimeError("Activate ContactSensor's track_air_time!") # compute the reward - last_air_time = wp.to_torch(contact_sensor.data.last_air_time)[:, sensor_cfg.body_ids] - last_contact_time = wp.to_torch(contact_sensor.data.last_contact_time)[:, sensor_cfg.body_ids] + last_air_time = contact_sensor.data.last_air_time.torch[:, sensor_cfg.body_ids] + last_contact_time = contact_sensor.data.last_contact_time.torch[:, sensor_cfg.body_ids] return torch.var(torch.clip(last_air_time, max=0.5), dim=1) + torch.var( torch.clip(last_contact_time, max=0.5), dim=1 ) @@ -222,8 +221,8 @@ def base_motion_penalty(env: ManagerBasedRLEnv, asset_cfg: SceneEntityCfg) -> to """Penalize base vertical and roll/pitch velocity""" # extract the used quantities (to enable type-hinting) asset: RigidObject = env.scene[asset_cfg.name] - return 0.8 * torch.square(wp.to_torch(asset.data.root_lin_vel_b)[:, 2]) + 0.2 * torch.sum( - torch.abs(wp.to_torch(asset.data.root_ang_vel_b)[:, :2]), dim=1 + return 0.8 * torch.square(asset.data.root_lin_vel_b.torch[:, 2]) + 0.2 * torch.sum( + torch.abs(asset.data.root_ang_vel_b.torch[:, :2]), dim=1 ) @@ -234,7 +233,7 @@ def base_orientation_penalty(env: ManagerBasedRLEnv, asset_cfg: SceneEntityCfg) """ # extract the used quantities (to enable type-hinting) asset: RigidObject = env.scene[asset_cfg.name] - return torch.linalg.norm((wp.to_torch(asset.data.projected_gravity_b)[:, :2]), dim=1) + return torch.linalg.norm((asset.data.projected_gravity_b.torch[:, :2]), dim=1) def foot_slip_penalty( @@ -246,11 +245,11 @@ def foot_slip_penalty( contact_sensor: ContactSensor = env.scene.sensors[sensor_cfg.name] # check if contact force is above threshold - net_contact_forces = wp.to_torch(contact_sensor.data.net_forces_w_history) + net_contact_forces = contact_sensor.data.net_forces_w_history.torch is_contact = ( torch.max(torch.linalg.norm(net_contact_forces[:, :, sensor_cfg.body_ids], dim=-1), dim=1)[0] > threshold ) - foot_planar_velocity = torch.linalg.norm(wp.to_torch(asset.data.body_lin_vel_w)[:, asset_cfg.body_ids, :2], dim=2) + foot_planar_velocity = torch.linalg.norm(asset.data.body_lin_vel_w.torch[:, asset_cfg.body_ids, :2], dim=2) reward = is_contact * foot_planar_velocity return torch.sum(reward, dim=1) @@ -260,7 +259,7 @@ def joint_acceleration_penalty(env: ManagerBasedRLEnv, asset_cfg: SceneEntityCfg """Penalize joint accelerations on the articulation.""" # extract the used quantities (to enable type-hinting) asset: Articulation = env.scene[asset_cfg.name] - return torch.linalg.norm((wp.to_torch(asset.data.joint_acc)), dim=1) + return torch.linalg.norm((asset.data.joint_acc.torch), dim=1) def joint_position_penalty( @@ -270,8 +269,8 @@ def joint_position_penalty( # extract the used quantities (to enable type-hinting) asset: Articulation = env.scene[asset_cfg.name] cmd = torch.linalg.norm(env.command_manager.get_command("base_velocity"), dim=1) - body_vel = torch.linalg.norm(wp.to_torch(asset.data.root_lin_vel_b)[:, :2], dim=1) - reward = torch.linalg.norm((wp.to_torch(asset.data.joint_pos) - wp.to_torch(asset.data.default_joint_pos)), dim=1) + body_vel = torch.linalg.norm(asset.data.root_lin_vel_b.torch[:, :2], dim=1) + reward = torch.linalg.norm((asset.data.joint_pos.torch - asset.data.default_joint_pos.torch), dim=1) return torch.where(torch.logical_or(cmd > 0.0, body_vel > velocity_threshold), reward, stand_still_scale * reward) @@ -279,11 +278,11 @@ def joint_torques_penalty(env: ManagerBasedRLEnv, asset_cfg: SceneEntityCfg) -> """Penalize joint torques on the articulation.""" # extract the used quantities (to enable type-hinting) asset: Articulation = env.scene[asset_cfg.name] - return torch.linalg.norm((wp.to_torch(asset.data.applied_torque)), dim=1) + return torch.linalg.norm((asset.data.applied_torque.torch), dim=1) def joint_velocity_penalty(env: ManagerBasedRLEnv, asset_cfg: SceneEntityCfg) -> torch.Tensor: """Penalize joint velocities on the articulation.""" # extract the used quantities (to enable type-hinting) asset: Articulation = env.scene[asset_cfg.name] - return torch.linalg.norm((wp.to_torch(asset.data.joint_vel)), dim=1) + return torch.linalg.norm((asset.data.joint_vel.torch), dim=1) diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/mdp/curriculums.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/mdp/curriculums.py index ece0a6161150..1438cbf03801 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/mdp/curriculums.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/mdp/curriculums.py @@ -15,7 +15,6 @@ from typing import TYPE_CHECKING import torch -import warp as wp from isaaclab.managers import SceneEntityCfg @@ -45,9 +44,7 @@ def terrain_levels_vel( terrain: TerrainImporter = env.scene.terrain command = env.command_manager.get_command("base_velocity") # compute the distance the robot walked - distance = torch.linalg.norm( - wp.to_torch(asset.data.root_pos_w)[env_ids, :2] - env.scene.env_origins[env_ids, :2], dim=1 - ) + distance = torch.linalg.norm(asset.data.root_pos_w.torch[env_ids, :2] - env.scene.env_origins[env_ids, :2], dim=1) # robots that walked far enough progress to harder terrains move_up = distance > terrain.cfg.terrain_generator.size[0] / 2 # robots that walked less than half of their required distance go to simpler terrains diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/mdp/rewards.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/mdp/rewards.py index 2198cff0cead..a5168f6c95d9 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/mdp/rewards.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/mdp/rewards.py @@ -14,7 +14,6 @@ from typing import TYPE_CHECKING import torch -import warp as wp from isaaclab.envs import mdp from isaaclab.managers import SceneEntityCfg @@ -39,8 +38,8 @@ def feet_air_time( # extract the used quantities (to enable type-hinting) contact_sensor: ContactSensor = env.scene.sensors[sensor_cfg.name] # compute the reward - first_contact = wp.to_torch(contact_sensor.compute_first_contact(env.step_dt))[:, sensor_cfg.body_ids] - last_air_time = wp.to_torch(contact_sensor.data.last_air_time)[:, sensor_cfg.body_ids] + first_contact = contact_sensor.compute_first_contact(env.step_dt).torch[:, sensor_cfg.body_ids] + last_air_time = contact_sensor.data.last_air_time.torch[:, sensor_cfg.body_ids] reward = torch.sum((last_air_time - threshold) * first_contact, dim=1) # no reward for zero command reward *= torch.linalg.norm(env.command_manager.get_command(command_name)[:, :2], dim=1) > 0.1 @@ -57,8 +56,8 @@ def feet_air_time_positive_biped(env, command_name: str, threshold: float, senso """ contact_sensor: ContactSensor = env.scene.sensors[sensor_cfg.name] # compute the reward - air_time = wp.to_torch(contact_sensor.data.current_air_time)[:, sensor_cfg.body_ids] - contact_time = wp.to_torch(contact_sensor.data.current_contact_time)[:, sensor_cfg.body_ids] + air_time = contact_sensor.data.current_air_time.torch[:, sensor_cfg.body_ids] + contact_time = contact_sensor.data.current_contact_time.torch[:, sensor_cfg.body_ids] in_contact = contact_time > 0.0 in_mode_time = torch.where(in_contact, contact_time, air_time) single_stance = torch.sum(in_contact.int(), dim=1) == 1 @@ -79,12 +78,11 @@ def feet_slide(env, sensor_cfg: SceneEntityCfg, asset_cfg: SceneEntityCfg = Scen # Penalize feet sliding contact_sensor: ContactSensor = env.scene.sensors[sensor_cfg.name] contacts = ( - wp.to_torch(contact_sensor.data.net_forces_w_history)[:, :, sensor_cfg.body_ids, :].norm(dim=-1).max(dim=1)[0] - > 1.0 + contact_sensor.data.net_forces_w_history.torch[:, :, sensor_cfg.body_ids, :].norm(dim=-1).max(dim=1)[0] > 1.0 ) asset = env.scene[asset_cfg.name] - body_vel = wp.to_torch(asset.data.body_lin_vel_w)[:, asset_cfg.body_ids, :2] + body_vel = asset.data.body_lin_vel_w.torch[:, asset_cfg.body_ids, :2] reward = torch.sum(body_vel.norm(dim=-1) * contacts, dim=1) return reward @@ -97,9 +95,7 @@ def track_lin_vel_xy_yaw_frame_exp( """ # extract the used quantities (to enable type-hinting) asset = env.scene[asset_cfg.name] - vel_yaw = quat_apply_inverse( - yaw_quat(wp.to_torch(asset.data.root_quat_w)), wp.to_torch(asset.data.root_lin_vel_w)[:, :3] - ) + vel_yaw = quat_apply_inverse(yaw_quat(asset.data.root_quat_w.torch), asset.data.root_lin_vel_w.torch[:, :3]) lin_vel_error = torch.sum( torch.square(env.command_manager.get_command(command_name)[:, :2] - vel_yaw[:, :2]), dim=1 ) @@ -113,7 +109,7 @@ def track_ang_vel_z_world_exp( # extract the used quantities (to enable type-hinting) asset = env.scene[asset_cfg.name] ang_vel_error = torch.square( - env.command_manager.get_command(command_name)[:, 2] - wp.to_torch(asset.data.root_ang_vel_w)[:, 2] + env.command_manager.get_command(command_name)[:, 2] - asset.data.root_ang_vel_w.torch[:, 2] ) return torch.exp(-ang_vel_error / std**2) diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/mdp/terminations.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/mdp/terminations.py index 63add623c465..5559250d9555 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/mdp/terminations.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/mdp/terminations.py @@ -14,7 +14,6 @@ from typing import TYPE_CHECKING import torch -import warp as wp from isaaclab.managers import SceneEntityCfg @@ -48,8 +47,8 @@ def terrain_out_of_bounds( asset: RigidObject = env.scene[asset_cfg.name] # check if the agent is out of bounds - x_out_of_bounds = torch.abs(wp.to_torch(asset.data.root_pos_w)[:, 0]) > 0.5 * map_width - distance_buffer - y_out_of_bounds = torch.abs(wp.to_torch(asset.data.root_pos_w)[:, 1]) > 0.5 * map_height - distance_buffer + x_out_of_bounds = torch.abs(asset.data.root_pos_w.torch[:, 0]) > 0.5 * map_width - distance_buffer + y_out_of_bounds = torch.abs(asset.data.root_pos_w.torch[:, 1]) > 0.5 * map_height - distance_buffer return torch.logical_or(x_out_of_bounds, y_out_of_bounds) else: raise ValueError("Received unsupported terrain type, must be either 'plane' or 'generator'.") diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/velocity_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/velocity_env_cfg.py index 81f38e756975..7ee1d811734b 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/velocity_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/locomotion/velocity/velocity_env_cfg.py @@ -6,7 +6,9 @@ import math from dataclasses import MISSING +from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg, NewtonCollisionPipelineCfg, NewtonShapeCfg from isaaclab_newton.sensors import ContactSensorCfg as NewtonContactSensorCfg +from isaaclab_physx.physics import PhysxCfg from isaaclab_physx.sensors import ContactSensorCfg as PhysXContactSensorCfg import isaaclab.sim as sim_utils @@ -21,13 +23,14 @@ from isaaclab.managers import TerminationTermCfg as DoneTerm from isaaclab.scene import InteractiveSceneCfg from isaaclab.sensors import RayCasterCfg, patterns +from isaaclab.sim import SimulationCfg from isaaclab.terrains import TerrainImporterCfg from isaaclab.utils import configclass from isaaclab.utils.assets import ISAAC_NUCLEUS_DIR, ISAACLAB_NUCLEUS_DIR from isaaclab.utils.noise import UniformNoiseCfg as Unoise import isaaclab_tasks.manager_based.locomotion.velocity.mdp as mdp -from isaaclab_tasks.utils import PresetCfg +from isaaclab_tasks.utils import PresetCfg, preset ## # Pre-defined configs @@ -35,6 +38,36 @@ from isaaclab.terrains.config.rough import ROUGH_TERRAINS_CFG # isort: skip +## +# Physics presets +## + + +@configclass +class RoughPhysicsCfg(PresetCfg): + """Shared physics preset for all rough-terrain locomotion envs.""" + + default = PhysxCfg(gpu_max_rigid_patch_count=10 * 2**15) + newton_mjwarp = NewtonCfg( + solver_cfg=MJWarpSolverCfg( + njmax=200, + nconmax=100, + cone="pyramidal", + impratio=1.0, + integrator="implicitfast", + use_mujoco_contacts=False, + ), + collision_cfg=NewtonCollisionPipelineCfg(max_triangle_pairs=2_500_000), + num_substeps=1, + debug_mode=False, + # 1 cm shape margin is the single most important Newton setting for rough + # terrain — without it, non-Anymal-D robots fail to learn stable contact + # on triangle-mesh terrain. See isaaclab_newton 0.5.22 changelog. + default_shape_cfg=NewtonShapeCfg(margin=0.01), + ) + physx = default + + ## # Scene definition ## @@ -43,7 +76,7 @@ @configclass class VelocityEnvContactSensorCfg(PresetCfg): default = PhysXContactSensorCfg(prim_path="{ENV_REGEX_NS}/Robot/.*", history_length=3, track_air_time=True) - newton = NewtonContactSensorCfg(prim_path="{ENV_REGEX_NS}/Robot/.*", history_length=3, track_air_time=True) + newton_mjwarp = NewtonContactSensorCfg(prim_path="{ENV_REGEX_NS}/Robot/.*", history_length=3, track_air_time=True) physx = default @@ -161,6 +194,45 @@ def __post_init__(self): class EventsCfg: """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, + }, + ) + + add_base_mass = EventTerm( + func=mdp.randomize_rigid_body_mass, + mode="startup", + params={ + "asset_cfg": SceneEntityCfg("robot", body_names="base"), + # Multiplicative ±25% log-uniform. Scale-invariant across robot sizes + # (no per-robot kg overrides needed) with geometric mean 1.0 and + # symmetric inverse perturbation (acceleration symmetric around nominal). + "mass_distribution_params": (1 / 1.25, 1.25), + "operation": "scale", + "distribution": "log_uniform", + }, + ) + + base_com = preset( + default=EventTerm( + func=mdp.randomize_rigid_body_com, + mode="startup", + params={ + "asset_cfg": SceneEntityCfg("robot", body_names="base"), + "com_range": {"x": (-0.05, 0.05), "y": (-0.05, 0.05), "z": (-0.01, 0.01)}, + }, + ), + newton_mjwarp=None, + ) + # reset base_external_force_torque = EventTerm( func=mdp.apply_external_force_torque, @@ -206,41 +278,6 @@ class EventsCfg: ) -@configclass -class StartupEventsCfg: - # 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, - }, - ) - - add_base_mass = EventTerm( - func=mdp.randomize_rigid_body_mass, - mode="startup", - params={ - "asset_cfg": SceneEntityCfg("robot", body_names="base"), - "mass_distribution_params": (-5.0, 5.0), - "operation": "add", - }, - ) - - base_com = EventTerm( - func=mdp.randomize_rigid_body_com, - mode="startup", - params={ - "asset_cfg": SceneEntityCfg("robot", body_names="base"), - "com_range": {"x": (-0.05, 0.05), "y": (-0.05, 0.05), "z": (-0.01, 0.01)}, - }, - ) - - @configclass class RewardsCfg: """Reward terms for the MDP.""" @@ -304,6 +341,8 @@ class CurriculumCfg: class LocomotionVelocityRoughEnvCfg(ManagerBasedRLEnvCfg): """Configuration for the locomotion velocity-tracking environment.""" + # Simulation settings — shared physics preset (PhysX + MJWarp) for all rough-terrain envs + sim: SimulationCfg = SimulationCfg(physics=RoughPhysicsCfg()) # Scene settings scene: MySceneCfg = MySceneCfg(num_envs=4096, env_spacing=2.5) # Basic settings @@ -313,7 +352,7 @@ class LocomotionVelocityRoughEnvCfg(ManagerBasedRLEnvCfg): # MDP settings rewards: RewardsCfg = RewardsCfg() terminations: TerminationsCfg = TerminationsCfg() - events: EventsCfg = MISSING + events: EventsCfg = EventsCfg() curriculum: CurriculumCfg = CurriculumCfg() def __post_init__(self): diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/cabinet/cabinet_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/cabinet/cabinet_env_cfg.py index 2714b2cd40a2..43601c83b95e 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/cabinet/cabinet_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/cabinet/cabinet_env_cfg.py @@ -58,7 +58,7 @@ class CabinetSimCfg(PresetCfg): render_interval=1, physics=PhysxCfg(bounce_threshold_velocity=0.01, friction_correlation_distance=0.00625), ) - newton: SimulationCfg = SimulationCfg( + newton_mjwarp: SimulationCfg = SimulationCfg( dt=1 / 600, render_interval=1, physics=NewtonCfg( @@ -260,7 +260,7 @@ class _CabinetNewtonEventCfg: class CabinetEventCfg(PresetCfg): default: EventCfg = EventCfg() physx: EventCfg = EventCfg() - newton: _CabinetNewtonEventCfg = _CabinetNewtonEventCfg() + newton_mjwarp: _CabinetNewtonEventCfg = _CabinetNewtonEventCfg() @configclass @@ -285,10 +285,16 @@ class RewardsCfg: ) # 3. Open the drawer + # ``open_drawer_bonus`` doubles as the success metric host: passing ``success_threshold`` + # tells the term to flip a sticky per-env bit when the drawer crosses that joint position + # and to log the per-env mean as ``Metrics/success_rate`` on episode reset. open_drawer_bonus = RewTerm( func=mdp.open_drawer_bonus, weight=7.5, - params={"asset_cfg": SceneEntityCfg("cabinet", joint_names=["drawer_top_joint"])}, + params={ + "asset_cfg": SceneEntityCfg("cabinet", joint_names=["drawer_top_joint"]), + "success_threshold": 0.30, + }, ) multi_stage_open_drawer = RewTerm( func=mdp.multi_stage_open_drawer, diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/cabinet/mdp/observations.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/cabinet/mdp/observations.py index 75e1ff44157f..1da8557cc0ca 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/cabinet/mdp/observations.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/cabinet/mdp/observations.py @@ -8,7 +8,6 @@ from typing import TYPE_CHECKING import torch -import warp as wp import isaaclab.utils.math as math_utils @@ -23,7 +22,7 @@ def rel_ee_object_distance(env: ManagerBasedRLEnv) -> torch.Tensor: ee_tf_data: FrameTransformerData = env.scene["ee_frame"].data object_data: ArticulationData = env.scene["object"].data - return wp.to_torch(object_data.root_pos_w) - wp.to_torch(ee_tf_data.target_pos_w)[..., 0, :] + return object_data.root_pos_w.torch - ee_tf_data.target_pos_w.torch[..., 0, :] def rel_ee_drawer_distance(env: ManagerBasedRLEnv) -> torch.Tensor: @@ -31,13 +30,13 @@ def rel_ee_drawer_distance(env: ManagerBasedRLEnv) -> torch.Tensor: ee_tf_data: FrameTransformerData = env.scene["ee_frame"].data cabinet_tf_data: FrameTransformerData = env.scene["cabinet_frame"].data - return wp.to_torch(cabinet_tf_data.target_pos_w)[..., 0, :] - wp.to_torch(ee_tf_data.target_pos_w)[..., 0, :] + return cabinet_tf_data.target_pos_w.torch[..., 0, :] - ee_tf_data.target_pos_w.torch[..., 0, :] def fingertips_pos(env: ManagerBasedRLEnv) -> torch.Tensor: """The position of the fingertips relative to the environment origins.""" ee_tf_data: FrameTransformerData = env.scene["ee_frame"].data - fingertips_pos = wp.to_torch(ee_tf_data.target_pos_w)[..., 1:, :] - env.scene.env_origins.unsqueeze(1) + fingertips_pos = ee_tf_data.target_pos_w.torch[..., 1:, :] - env.scene.env_origins.unsqueeze(1) return fingertips_pos.view(env.num_envs, -1) @@ -45,7 +44,7 @@ def fingertips_pos(env: ManagerBasedRLEnv) -> torch.Tensor: def ee_pos(env: ManagerBasedRLEnv) -> torch.Tensor: """The position of the end-effector relative to the environment origins.""" ee_tf_data: FrameTransformerData = env.scene["ee_frame"].data - ee_pos = wp.to_torch(ee_tf_data.target_pos_w)[..., 0, :] - env.scene.env_origins + ee_pos = ee_tf_data.target_pos_w.torch[..., 0, :] - env.scene.env_origins return ee_pos @@ -56,6 +55,6 @@ def ee_quat(env: ManagerBasedRLEnv, make_quat_unique: bool = True) -> torch.Tens If :attr:`make_quat_unique` is True, the quaternion is made unique by ensuring the real part is positive. """ ee_tf_data: FrameTransformerData = env.scene["ee_frame"].data - ee_quat = wp.to_torch(ee_tf_data.target_quat_w)[..., 0, :] + ee_quat = ee_tf_data.target_quat_w.torch[..., 0, :] # make first element of quaternion positive return math_utils.quat_unique(ee_quat) if make_quat_unique else ee_quat diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/cabinet/mdp/rewards.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/cabinet/mdp/rewards.py index aeb87e29e224..3847894db46a 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/cabinet/mdp/rewards.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/cabinet/mdp/rewards.py @@ -8,9 +8,8 @@ from typing import TYPE_CHECKING import torch -import warp as wp -from isaaclab.managers import SceneEntityCfg +from isaaclab.managers import ManagerTermBase, RewardTermCfg, SceneEntityCfg from isaaclab.utils.math import matrix_from_quat if TYPE_CHECKING: @@ -30,8 +29,8 @@ def approach_ee_handle(env: ManagerBasedRLEnv, threshold: float) -> torch.Tensor \end{cases} """ - ee_tcp_pos = wp.to_torch(env.scene["ee_frame"].data.target_pos_w)[..., 0, :] - handle_pos = wp.to_torch(env.scene["cabinet_frame"].data.target_pos_w)[..., 0, :] + ee_tcp_pos = env.scene["ee_frame"].data.target_pos_w.torch[..., 0, :] + handle_pos = env.scene["cabinet_frame"].data.target_pos_w.torch[..., 0, :] # Compute the distance of the end-effector to the handle distance = torch.linalg.norm(handle_pos - ee_tcp_pos, dim=-1, ord=2) @@ -54,8 +53,8 @@ def align_ee_handle(env: ManagerBasedRLEnv) -> torch.Tensor: where :math:`align_z` is the dot product of the z direction of the gripper and the -x direction of the handle and :math:`align_x` is the dot product of the x direction of the gripper and the -y direction of the handle. """ - ee_tcp_quat = wp.to_torch(env.scene["ee_frame"].data.target_quat_w)[..., 0, :] - handle_quat = wp.to_torch(env.scene["cabinet_frame"].data.target_quat_w)[..., 0, :] + ee_tcp_quat = env.scene["ee_frame"].data.target_quat_w.torch[..., 0, :] + handle_quat = env.scene["cabinet_frame"].data.target_quat_w.torch[..., 0, :] ee_tcp_rot_mat = matrix_from_quat(ee_tcp_quat) handle_mat = matrix_from_quat(handle_quat) @@ -80,9 +79,9 @@ def align_grasp_around_handle(env: ManagerBasedRLEnv) -> torch.Tensor: The correct hand orientation is when the left finger is above the handle and the right finger is below the handle. """ # Target object position: (num_envs, 3) - handle_pos = wp.to_torch(env.scene["cabinet_frame"].data.target_pos_w)[..., 0, :] + handle_pos = env.scene["cabinet_frame"].data.target_pos_w.torch[..., 0, :] # Fingertips position: (num_envs, n_fingertips, 3) - ee_fingertips_w = wp.to_torch(env.scene["ee_frame"].data.target_pos_w)[..., 1:, :] + ee_fingertips_w = env.scene["ee_frame"].data.target_pos_w.torch[..., 1:, :] lfinger_pos = ee_fingertips_w[..., 0, :] rfinger_pos = ee_fingertips_w[..., 1, :] @@ -100,9 +99,9 @@ def approach_gripper_handle(env: ManagerBasedRLEnv, offset: float = 0.04) -> tor (i.e., the left finger is above the handle and the right finger is below the handle). Otherwise, it returns zero. """ # Target object position: (num_envs, 3) - handle_pos = wp.to_torch(env.scene["cabinet_frame"].data.target_pos_w)[..., 0, :] + handle_pos = env.scene["cabinet_frame"].data.target_pos_w.torch[..., 0, :] # Fingertips position: (num_envs, n_fingertips, 3) - ee_fingertips_w = wp.to_torch(env.scene["ee_frame"].data.target_pos_w)[..., 1:, :] + ee_fingertips_w = env.scene["ee_frame"].data.target_pos_w.torch[..., 1:, :] lfinger_pos = ee_fingertips_w[..., 0, :] rfinger_pos = ee_fingertips_w[..., 1, :] @@ -127,9 +126,9 @@ def grasp_handle( Note: It is assumed that zero joint position corresponds to the fingers being closed. """ - ee_tcp_pos = wp.to_torch(env.scene["ee_frame"].data.target_pos_w)[..., 0, :] - handle_pos = wp.to_torch(env.scene["cabinet_frame"].data.target_pos_w)[..., 0, :] - gripper_joint_pos = wp.to_torch(env.scene[asset_cfg.name].data.joint_pos)[:, asset_cfg.joint_ids] + ee_tcp_pos = env.scene["ee_frame"].data.target_pos_w.torch[..., 0, :] + handle_pos = env.scene["cabinet_frame"].data.target_pos_w.torch[..., 0, :] + gripper_joint_pos = env.scene[asset_cfg.name].data.joint_pos.torch[:, asset_cfg.joint_ids] distance = torch.linalg.norm(handle_pos - ee_tcp_pos, dim=-1, ord=2) is_close = distance <= threshold @@ -137,15 +136,37 @@ def grasp_handle( return is_close * torch.sum(open_joint_pos - gripper_joint_pos, dim=-1) -def open_drawer_bonus(env: ManagerBasedRLEnv, asset_cfg: SceneEntityCfg) -> torch.Tensor: +class open_drawer_bonus(ManagerTermBase): """Bonus for opening the drawer given by the joint position of the drawer. The bonus is given when the drawer is open. If the grasp is around the handle, the bonus is doubled. + + If ``success_threshold`` is provided in the term params, this also tracks per-episode success + (sticky binary: drawer ever opened past ``success_threshold``) and logs the mean across + environments under ``Metrics/success_rate`` on reset. """ - drawer_pos = wp.to_torch(env.scene[asset_cfg.name].data.joint_pos)[:, asset_cfg.joint_ids[0]] - is_graspable = align_grasp_around_handle(env).float() - return (is_graspable + 1.0) * drawer_pos + def __init__(self, cfg: RewardTermCfg, env: ManagerBasedRLEnv): + super().__init__(cfg, env) + self._track_success = cfg.params.get("success_threshold") is not None + if self._track_success: + self.succeeded = torch.zeros(env.num_envs, dtype=torch.bool, device=env.device) + + def reset(self, env_ids: torch.Tensor): + if self._track_success: + self._env.extras.setdefault("log", {})["Metrics/success_rate"] = ( + self.succeeded[env_ids].float().mean().item() + ) + self.succeeded[env_ids] = False + + def __call__( + self, env: ManagerBasedRLEnv, asset_cfg: SceneEntityCfg, success_threshold: float | None = None + ) -> torch.Tensor: + drawer_pos = env.scene[asset_cfg.name].data.joint_pos.torch[:, asset_cfg.joint_ids[0]] + is_graspable = align_grasp_around_handle(env).float() + if success_threshold is not None: + self.succeeded |= drawer_pos > success_threshold + return (is_graspable + 1.0) * drawer_pos def multi_stage_open_drawer(env: ManagerBasedRLEnv, asset_cfg: SceneEntityCfg) -> torch.Tensor: @@ -154,7 +175,7 @@ def multi_stage_open_drawer(env: ManagerBasedRLEnv, asset_cfg: SceneEntityCfg) - Depending on the drawer's position, the reward is given in three stages: easy, medium, and hard. This helps the agent to learn to open the drawer in a controlled manner. """ - drawer_pos = wp.to_torch(env.scene[asset_cfg.name].data.joint_pos)[:, asset_cfg.joint_ids[0]] + drawer_pos = env.scene[asset_cfg.name].data.joint_pos.torch[:, asset_cfg.joint_ids[0]] is_graspable = align_grasp_around_handle(env).float() open_easy = (drawer_pos > 0.01) * 0.5 diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/deploy/gear_assembly/config/rizon_4s/__init__.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/deploy/gear_assembly/config/rizon_4s/__init__.py new file mode 100644 index 000000000000..6940800ead36 --- /dev/null +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/deploy/gear_assembly/config/rizon_4s/__init__.py @@ -0,0 +1,46 @@ +# Copyright (c) 2025-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +import gymnasium as gym + +from . import agents + +## +# Register Gym environments. +## + + +# Flexiv Rizon 4s +gym.register( + id="Isaac-Deploy-GearAssembly-Rizon4s-Grav-v0", + entry_point="isaaclab.envs:ManagerBasedRLEnv", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": f"{__name__}.joint_pos_env_cfg:Rizon4sGearAssemblyEnvCfg", + "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:Rizon4sGearAssemblyRNNPPORunnerCfg", + }, +) + +# Flexiv Rizon 4s - Play / Debug (deterministic, no randomization) +gym.register( + id="Isaac-Deploy-GearAssembly-Rizon4s-Grav-Play-v0", + entry_point="isaaclab.envs:ManagerBasedRLEnv", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": f"{__name__}.ros_inference_env_cfg:Rizon4sGearAssemblyEnvCfg_PLAY", + "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:Rizon4sGearAssemblyRNNPPORunnerCfg", + }, +) + +# Flexiv Rizon 4s - ROS Inference +gym.register( + id="Isaac-Deploy-GearAssembly-Rizon4s-Grav-ROS-Inference-v0", + entry_point="isaaclab.envs:ManagerBasedRLEnv", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": f"{__name__}.ros_inference_env_cfg:Rizon4sGearAssemblyROSInferenceEnvCfg", + "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:Rizon4sGearAssemblyRNNPPORunnerCfg", + }, +) diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/deploy/gear_assembly/config/rizon_4s/agents/__init__.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/deploy/gear_assembly/config/rizon_4s/agents/__init__.py new file mode 100644 index 000000000000..cf59b16a1e2e --- /dev/null +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/deploy/gear_assembly/config/rizon_4s/agents/__init__.py @@ -0,0 +1,4 @@ +# Copyright (c) 2025-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/deploy/gear_assembly/config/rizon_4s/agents/rsl_rl_ppo_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/deploy/gear_assembly/config/rizon_4s/agents/rsl_rl_ppo_cfg.py new file mode 100644 index 000000000000..06f64e731afc --- /dev/null +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/deploy/gear_assembly/config/rizon_4s/agents/rsl_rl_ppo_cfg.py @@ -0,0 +1,49 @@ +# Copyright (c) 2025-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from isaaclab.utils import configclass + +from isaaclab_rl.rsl_rl import RslRlOnPolicyRunnerCfg, RslRlPpoActorCriticRecurrentCfg, RslRlPpoAlgorithmCfg + + +@configclass +class Rizon4sGearAssemblyRNNPPORunnerCfg(RslRlOnPolicyRunnerCfg): + num_steps_per_env = 512 + max_iterations = 1500 + save_interval = 50 + experiment_name = "gear_assembly_rizon4s" + clip_actions = 1.0 + resume = False + obs_groups = { + "policy": ["policy"], + "critic": ["critic"], + } + policy = RslRlPpoActorCriticRecurrentCfg( + state_dependent_std=True, + init_noise_std=1.0, + actor_obs_normalization=True, + critic_obs_normalization=True, + actor_hidden_dims=[256, 128, 64], + critic_hidden_dims=[256, 128, 64], + noise_std_type="log", + activation="elu", + rnn_type="lstm", + rnn_hidden_dim=256, + rnn_num_layers=2, + ) + algorithm = RslRlPpoAlgorithmCfg( + value_loss_coef=1.0, + use_clipped_value_loss=True, + clip_param=0.2, + entropy_coef=0.0, + num_learning_epochs=8, + num_mini_batches=16, + learning_rate=5.0e-4, + schedule="adaptive", + gamma=0.99, + lam=0.95, + desired_kl=0.008, + max_grad_norm=1.0, + ) diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/deploy/gear_assembly/config/rizon_4s/joint_pos_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/deploy/gear_assembly/config/rizon_4s/joint_pos_env_cfg.py new file mode 100644 index 000000000000..bd8382b55212 --- /dev/null +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/deploy/gear_assembly/config/rizon_4s/joint_pos_env_cfg.py @@ -0,0 +1,425 @@ +# Copyright (c) 2025-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +import math + +import torch + +import isaaclab.sim as sim_utils +from isaaclab.actuators import ImplicitActuatorCfg +from isaaclab.assets import ArticulationCfg, RigidObjectCfg +from isaaclab.managers import EventTermCfg as EventTerm +from isaaclab.managers import RewardTermCfg as RewTerm +from isaaclab.managers import SceneEntityCfg +from isaaclab.utils import configclass +from isaaclab.utils.noise import UniformNoiseCfg + +import isaaclab_tasks.manager_based.manipulation.deploy.mdp as mdp +import isaaclab_tasks.manager_based.manipulation.deploy.mdp.events as gear_assembly_events +from isaaclab_tasks.manager_based.manipulation.deploy.gear_assembly.gear_assembly_env_cfg import GearAssemblyEnvCfg +from isaaclab_tasks.manager_based.manipulation.deploy.mdp.noise_models import ( + ResetSampledConstantNoiseModelCfg, + ResetSampledQuaternionNoiseModelCfg, +) + +## +# Pre-defined configs +## +from isaaclab_assets import FLEXIV_RIZON4S_GRAV_GRIPPER_CFG # isort: skip + + +## +# Gripper-specific helper functions +## + + +def set_finger_joint_pos_grav( + joint_pos: torch.Tensor, + reset_ind_joint_pos: list[int], + finger_joints: list[int], + finger_joint_position: float, +): + """Set finger joint positions for Grav gripper. + + Args: + joint_pos: Joint positions tensor + reset_ind_joint_pos: Row indices into the sliced joint_pos tensor + finger_joints: List of all gripper joint indices (6 joints total) + finger_joint_position: Target position for main finger joint (in radians) + + Note: + Grav gripper joint structure (indices from finger_joints list): + [0] finger_joint - main controllable joint + [1] left_inner_knuckle_joint - mimic with -1 gearing + [2] right_inner_knuckle_joint - mimic with -1 gearing + [3] right_outer_knuckle_joint - mimic with -1 gearing + [4] left_outer_finger_joint - mimic with +1 gearing + [5] right_outer_finger_joint - mimic with +1 gearing + """ + for idx in reset_ind_joint_pos: + if len(finger_joints) < 6: + raise ValueError(f"Grav gripper requires at least 6 finger joints, got {len(finger_joints)}") + + # Main controllable joint + joint_pos[idx, finger_joints[0]] = finger_joint_position + + # Mimic joints with -1 gearing + joint_pos[idx, finger_joints[1]] = finger_joint_position # left_inner_knuckle_joint + joint_pos[idx, finger_joints[2]] = finger_joint_position # right_inner_knuckle_joint + joint_pos[idx, finger_joints[3]] = finger_joint_position # right_outer_knuckle_joint + + # Mimic joints with +1 gearing + joint_pos[idx, finger_joints[4]] = -finger_joint_position # left_outer_finger_joint + joint_pos[idx, finger_joints[5]] = -finger_joint_position # right_outer_finger_joint + + +## +# Environment configuration +## + + +@configclass +class EventCfg: + """Configuration for events.""" + + small_gear_physics_material = EventTerm( + func=mdp.randomize_rigid_body_material, + mode="startup", + params={ + "asset_cfg": SceneEntityCfg("factory_gear_small", body_names=".*"), + "static_friction_range": (0.75, 0.75), + "dynamic_friction_range": (0.75, 0.75), + "restitution_range": (0.0, 0.0), + "num_buckets": 16, + }, + ) + + medium_gear_physics_material = EventTerm( + func=mdp.randomize_rigid_body_material, + mode="startup", + params={ + "asset_cfg": SceneEntityCfg("factory_gear_medium", body_names=".*"), + "static_friction_range": (0.75, 0.75), + "dynamic_friction_range": (0.75, 0.75), + "restitution_range": (0.0, 0.0), + "num_buckets": 16, + }, + ) + + large_gear_physics_material = EventTerm( + func=mdp.randomize_rigid_body_material, + mode="startup", + params={ + "asset_cfg": SceneEntityCfg("factory_gear_large", body_names=".*"), + "static_friction_range": (0.75, 0.75), + "dynamic_friction_range": (0.75, 0.75), + "restitution_range": (0.0, 0.0), + "num_buckets": 16, + }, + ) + + gear_base_physics_material = EventTerm( + func=mdp.randomize_rigid_body_material, + mode="startup", + params={ + "asset_cfg": SceneEntityCfg("factory_gear_base", body_names=".*"), + "static_friction_range": (0.0, 0.0), + "dynamic_friction_range": (0.0, 0.0), + "restitution_range": (0.0, 0.0), + "num_buckets": 16, + }, + ) + + robot_physics_material = EventTerm( + func=mdp.randomize_rigid_body_material, + mode="startup", + params={ + "asset_cfg": SceneEntityCfg("robot", body_names=".*finger.*"), + "static_friction_range": (3.0, 3.0), + "dynamic_friction_range": (3.0, 3.0), + "restitution_range": (0.0, 0.0), + "num_buckets": 16, + }, + ) + + randomize_gear_type = EventTerm( + func=gear_assembly_events.randomize_gear_type, + mode="reset", + params={"gear_types": ["gear_small", "gear_medium", "gear_large"]}, + ) + + reset_all = EventTerm(func=mdp.reset_scene_to_default, mode="reset") + + randomize_gears_and_base_pose = EventTerm( + func=gear_assembly_events.randomize_gears_and_base_pose, + mode="reset", + params={ + "pose_range": { + "x": [-0.1, 0.1], + "y": [-0.25, 0.25], + "z": [-0.1, 0.1], + "roll": [-math.pi / 90, math.pi / 90], # 2 degree + "pitch": [-math.pi / 90, math.pi / 90], # 2 degree + "yaw": [-math.pi / 6, math.pi / 6], # 30 degree + }, + "gear_pos_range": { + "x": [-0.02, 0.02], + "y": [-0.02, 0.02], + "z": [0.0575, 0.0775], + }, + "velocity_range": {}, + }, + ) + + set_robot_to_grasp_pose = EventTerm( + func=gear_assembly_events.set_robot_to_grasp_pose, + mode="reset", + params={ + "robot_asset_cfg": SceneEntityCfg("robot"), + "pos_randomization_range": {"x": [-0.0, 0.0], "y": [-0.0, 0.0], "z": [-0.0, 0.0]}, + }, + ) + + +@configclass +class Rizon4sGearAssemblyEnvCfg(GearAssemblyEnvCfg): + """Configuration for Flexiv Rizon 4s with Grav Gripper Gear Assembly Environment. + + The Flexiv Rizon 4s is a 7-DOF collaborative robot arm equipped with the + Flexiv Grav parallel gripper for gear manipulation tasks. + """ + + ee_grasp_weight_ramp_steps: int = 512_000 + + def __post_init__(self): + # post init of parent + super().__post_init__() + + # Flexiv-specific observation noise overrides + self.observations.policy.gear_shaft_pos.noise = ResetSampledConstantNoiseModelCfg( + noise_cfg=UniformNoiseCfg(n_min=-0.01, n_max=0.01, operation="add") + ) + self.observations.policy.gear_shaft_quat.noise = ResetSampledQuaternionNoiseModelCfg( + roll_range=(-0.03491, 0.03491), + pitch_range=(-0.03491, 0.03491), + yaw_range=(-0.03491, 0.03491), + ) + + # Robot-specific parameters for Flexiv Rizon 4s with Grav gripper + self.end_effector_body_name = "link7" # End effector body name for IK + self.num_arm_joints = 7 # Number of arm joints (Rizon 4s has 7 DOF) + # Rotation offset for grasp pose (quaternion [x, y, z, w]) + # Computed from IK convergence for downward-facing end effector + self.grasp_rot_offset = [ + -0.707, + 0.707, + 0.0, + 0.0, + ] + self.gripper_joint_setter_func = set_finger_joint_pos_grav # Grav gripper joint setter function + + # Gear orientation termination thresholds (in degrees) + self.gear_orientation_roll_threshold_deg = 15.0 # Maximum allowed roll deviation + self.gear_orientation_pitch_threshold_deg = 15.0 # Maximum allowed pitch deviation + self.gear_orientation_yaw_threshold_deg = 180.0 # Maximum allowed yaw deviation + + # Common observation configuration for Rizon 4s joints (arm only, not gripper) + self.observations.policy.joint_pos.params["asset_cfg"].joint_names = [ + "joint1", + "joint2", + "joint3", + "joint4", + "joint5", + "joint6", + "joint7", + ] + self.observations.policy.joint_vel.params["asset_cfg"].joint_names = [ + "joint1", + "joint2", + "joint3", + "joint4", + "joint5", + "joint6", + "joint7", + ] + + # override events + self.events = EventCfg() + + # Update termination thresholds from config + self.terminations.gear_orientation_exceeded.params["roll_threshold_deg"] = ( + self.gear_orientation_roll_threshold_deg + ) + self.terminations.gear_orientation_exceeded.params["pitch_threshold_deg"] = ( + self.gear_orientation_pitch_threshold_deg + ) + self.terminations.gear_orientation_exceeded.params["yaw_threshold_deg"] = ( + self.gear_orientation_yaw_threshold_deg + ) + + # Action configuration for Rizon 4s arm + # Using smaller action scale for stability + self.joint_action_scale = 0.025 + self.actions.arm_action = mdp.RelativeJointPositionActionCfg( + asset_name="robot", + joint_names=[ + "joint1", + "joint2", + "joint3", + "joint4", + "joint5", + "joint6", + "joint7", + ], + scale=self.joint_action_scale, + use_zero_offset=True, + ) + + # Switch robot to Flexiv Rizon 4s with Grav gripper + self.scene.robot = FLEXIV_RIZON4S_GRAV_GRIPPER_CFG.replace( + prim_path="{ENV_REGEX_NS}/Robot", + spawn=FLEXIV_RIZON4S_GRAV_GRIPPER_CFG.spawn.replace( + rigid_props=sim_utils.RigidBodyPropertiesCfg( + disable_gravity=True, + max_depenetration_velocity=5.0, + linear_damping=0.0, + angular_damping=0.0, + max_linear_velocity=1000.0, + max_angular_velocity=3666.0, + enable_gyroscopic_forces=True, + solver_position_iteration_count=4, + solver_velocity_iteration_count=1, + max_contact_impulse=1e32, + ), + articulation_props=sim_utils.ArticulationRootPropertiesCfg( + enabled_self_collisions=False, solver_position_iteration_count=4, solver_velocity_iteration_count=1 + ), + collision_props=sim_utils.CollisionPropertiesCfg(contact_offset=0.005, rest_offset=0.0), + ), + # Joint positions based on IK from center of distribution for randomized gear positions + init_state=ArticulationCfg.InitialStateCfg( + joint_pos={ + "joint1": 0.0, + "joint2": -0.698, + "joint3": 0.0, + "joint4": 1.571, + "joint5": 0.0, + "joint6": 0.698, + "joint7": 0.0, + }, + pos=(0.0, 0.0, 0.0), + rot=(0.0, 0.0, 0.0, 1.0), + ), + ) + + # Grav gripper actuator configuration for gear manipulation + self.scene.robot.actuators["gripper_drive"] = ImplicitActuatorCfg( + joint_names_expr=["finger_joint"], + effort_limit_sim=2.0, + velocity_limit_sim=1.0, + stiffness=2e3, + damping=1e1, + friction=0.0, + armature=0.0, + ) + + # Passive/mimic joints in the gripper - set to zero stiffness/damping + self.scene.robot.actuators["gripper_passive"] = ImplicitActuatorCfg( + joint_names_expr=[".*_knuckle_joint"], + effort_limit_sim=1.0, + velocity_limit_sim=1.0, + stiffness=0.0, + damping=0.0, + friction=0.0, + armature=0.0, + ) + + # Override gear initial states for Rizon (closer to robot, centered) + self.scene.factory_gear_base.init_state = RigidObjectCfg.InitialStateCfg( + pos=(0.481, -0.073, 0.071), + rot=(0.0, 0.0, 0.70711, -0.70711), + ) + self.scene.factory_gear_small.init_state = RigidObjectCfg.InitialStateCfg( + pos=(0.481, -0.073, 0.071), + rot=(0.0, 0.0, 0.70711, -0.70711), + ) + self.scene.factory_gear_medium.init_state = RigidObjectCfg.InitialStateCfg( + pos=(0.481, -0.073, 0.071), + rot=(0.0, 0.0, 0.70711, -0.70711), + ) + self.scene.factory_gear_large.init_state = RigidObjectCfg.InitialStateCfg( + pos=(0.481, -0.073, 0.071), + rot=(0.0, 0.0, 0.70711, -0.70711), + ) + + # Gear offsets and grasp positions for Rizon 4s with Grav gripper + # These offsets are relative to the end effector frame (link7) + # Z offset accounts for the gripper length from link7 to finger tip + self.gear_offsets_grasp = { + "gear_small": [0.0, -self.gear_offsets["gear_small"][0], -0.35], + "gear_medium": [0.0, -self.gear_offsets["gear_medium"][0], -0.35], + "gear_large": [0.0, -self.gear_offsets["gear_large"][0], -0.35], + } + + # Grasp widths for Grav gripper (raw radian values for finger_joint) + self.hand_grasp_width = { + "gear_small": 0.05, + "gear_medium": 0.2, + "gear_large": 0.28, + } + + # Close widths for Grav gripper (raw radian values for finger_joint) + self.hand_close_width = { + "gear_small": 0.0, + "gear_medium": 0.139626, + "gear_large": 0.139626, + } + + # Populate event term parameters + self.events.set_robot_to_grasp_pose.params["gear_offsets_grasp"] = self.gear_offsets_grasp + self.events.set_robot_to_grasp_pose.params["end_effector_body_name"] = self.end_effector_body_name + self.events.set_robot_to_grasp_pose.params["num_arm_joints"] = self.num_arm_joints + self.events.set_robot_to_grasp_pose.params["grasp_rot_offset"] = self.grasp_rot_offset + self.events.set_robot_to_grasp_pose.params["gripper_joint_setter_func"] = self.gripper_joint_setter_func + + # Flexiv-specific reward terms for EE-grasp keypoint tracking + self.rewards.end_effector_grasp_keypoint_tracking = RewTerm( + func=mdp.keypoint_ee_grasp_error, + weight=-0.5, + params={ + "robot_asset_cfg": SceneEntityCfg("robot"), + "keypoint_scale": 0.15, + "ee_grasp_threshold": 0.00, + "weight_ramp_start": 0.0, + "weight_ramp_steps": self.ee_grasp_weight_ramp_steps, + "end_effector_body_name": self.end_effector_body_name, + "grasp_rot_offset": self.grasp_rot_offset, + "gear_offsets_grasp": self.gear_offsets_grasp, + }, + ) + self.rewards.end_effector_grasp_keypoint_tracking_exp = RewTerm( + func=mdp.keypoint_ee_grasp_error_exp, + weight=0.5, + params={ + "robot_asset_cfg": SceneEntityCfg("robot"), + "kp_exp_coeffs": [(50, 0.0001), (300, 0.0001)], + "kp_use_sum_of_exps": False, + "keypoint_scale": 0.15, + "ee_grasp_threshold": 0.00, + "weight_ramp_start": 0.0, + "weight_ramp_steps": self.ee_grasp_weight_ramp_steps, + "end_effector_body_name": self.end_effector_body_name, + "grasp_rot_offset": self.grasp_rot_offset, + "gear_offsets_grasp": self.gear_offsets_grasp, + }, + ) + + # Populate termination term parameters + self.terminations.gear_dropped.params["gear_offsets_grasp"] = self.gear_offsets_grasp + self.terminations.gear_dropped.params["end_effector_body_name"] = self.end_effector_body_name + self.terminations.gear_dropped.params["grasp_rot_offset"] = self.grasp_rot_offset + + self.terminations.gear_orientation_exceeded.params["end_effector_body_name"] = self.end_effector_body_name + self.terminations.gear_orientation_exceeded.params["grasp_rot_offset"] = self.grasp_rot_offset diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/deploy/gear_assembly/config/rizon_4s/ros_inference_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/deploy/gear_assembly/config/rizon_4s/ros_inference_env_cfg.py new file mode 100644 index 000000000000..504a3ccda288 --- /dev/null +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/deploy/gear_assembly/config/rizon_4s/ros_inference_env_cfg.py @@ -0,0 +1,197 @@ +# Copyright (c) 2025-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +import math + +import torch + +from isaaclab.assets import RigidObjectCfg +from isaaclab.managers import ObservationTermCfg as ObsTerm +from isaaclab.utils import configclass + +from .joint_pos_env_cfg import Rizon4sGearAssemblyEnvCfg + + +def constant_obs(env, value: tuple) -> torch.Tensor: + """Observation function that returns a fixed tensor every step.""" + return torch.tensor([value], device=env.device, dtype=torch.float32).expand(env.num_envs, -1) + + +@configclass +class Rizon4sGearAssemblyROSInferenceEnvCfg(Rizon4sGearAssemblyEnvCfg): + """Configuration for ROS inference with Flexiv Rizon 4s and Grav gripper. + + This configuration: + - Exposes variables needed for ROS inference + - Overrides robot and gear initial poses for fixed/deterministic setup + """ + + def __post_init__(self): + # post init of parent + super().__post_init__() + + # Variables used by Isaac Manipulator for on robot inference + # These parameters allow the ROS inference node to validate environment configuration, + # perform checks during inference, and correctly interpret observations and actions. + self.obs_order = ["arm_dof_pos", "arm_dof_vel", "shaft_pos", "shaft_quat"] + self.policy_action_space = "joint" + # Use inherited joint names from parent's observation configuration + self.arm_joint_names = self.observations.policy.joint_pos.params["asset_cfg"].joint_names + # Use inherited num_arm_joints from parent + self.action_space = self.num_arm_joints + # State space and observation space for Rizon 4s with Grav gripper (7 DOF arm + 1 gripper) + # State: 7 joint pos + 7 joint vel + 3 shaft pos + 4 shaft quat + 3 gear pos + 4 gear quat = 28 + # For critic: additional gear observations + self.state_space = 28 + # Observation: 7 joint pos + 7 joint vel + 3 shaft pos + 4 shaft quat = 21 + self.observation_space = 21 + + # Set joint_action_scale from the existing arm_action.scale + self.joint_action_scale = self.actions.arm_action.scale + + # Dynamically generate action_scale_joint_space based on action_space + self.action_scale_joint_space = [self.joint_action_scale] * self.action_space + + # Override robot initial pose for ROS inference (fixed pose, no randomization) + # Joint positions and pos are inherited from parent, only override rotation to be deterministic + self.scene.robot.init_state.rot = (0.0, 0.0, 0.0, 1.0) # Identity quaternion (x, y, z, w) + + # Override gear base initial pose (fixed pose for ROS inference) + # Position configured for Rizon 4s workspace + self.scene.factory_gear_base.init_state = RigidObjectCfg.InitialStateCfg( + pos=(0.481, -0.073, -0.005), + rot=(0.0, 0.0, 0.70711, -0.70711), + ) + + # Override gear initial poses (fixed poses for ROS inference) + # Small gear + self.scene.factory_gear_small.init_state = RigidObjectCfg.InitialStateCfg( + pos=(0.481, -0.073, -0.005), + rot=(0.0, 0.0, 0.70711, -0.70711), + ) + + # Medium gear + self.scene.factory_gear_medium.init_state = RigidObjectCfg.InitialStateCfg( + pos=(0.481, -0.073, -0.005), + rot=(0.0, 0.0, 0.70711, -0.70711), + ) + + # Large gear + self.scene.factory_gear_large.init_state = RigidObjectCfg.InitialStateCfg( + pos=(0.481, -0.073, -0.005), + rot=(0.0, 0.0, 0.70711, -0.70711), + ) + + # Fixed asset parameters for ROS inference - derived from configuration + # These parameters are used by the ROS inference node to validate the environment setup + # and apply appropriate noise models for robust real-world deployment. + # Derive position center from gear base init state + self.fixed_asset_init_pos_center = list(self.scene.factory_gear_base.init_state.pos) + # Derive position range from parent's randomize_gears_and_base_pose event pose_range + pose_range = self.events.randomize_gears_and_base_pose.params["pose_range"] + self.fixed_asset_init_pos_range = [ + pose_range["x"][1], # max value + pose_range["y"][1], # max value + pose_range["z"][1], # max value + ] + # Orientation in degrees (quaternion (0.0, 0.0, 0.70711, -0.70711) = -90° around Z) + self.fixed_asset_init_orn_deg = [0.0, 0.0, -90.0] + # Derive orientation range from parent's pose_range (radians to degrees) + self.fixed_asset_init_orn_deg_range = [ + math.degrees(pose_range["roll"][1]), # convert radians to degrees + math.degrees(pose_range["pitch"][1]), + math.degrees(pose_range["yaw"][1]), + ] + # Derive observation noise level from parent's gear_shaft_pos noise configuration + gear_shaft_pos_noise = self.observations.policy.gear_shaft_pos.noise.noise_cfg.n_max + self.fixed_asset_pos_obs_noise_level = [ + gear_shaft_pos_noise, + gear_shaft_pos_noise, + gear_shaft_pos_noise, + ] + + +@configclass +class Rizon4sGearAssemblyEnvCfg_PLAY(Rizon4sGearAssemblyROSInferenceEnvCfg): + """Deterministic play/debug configuration for Flexiv Rizon 4s gear assembly. + + Inherits the full ROS-inference configuration and then disables all + randomization so the simulation is identical on every reset. Useful for + comparing simulated and real-world policy behavior at a known pose. + + To debug a specific real-world scenario, edit the constants below to match + the physical setup, then run:: + + python scripts/reinforcement_learning/rsl_rl/play.py \\ + --task Isaac-Deploy-GearAssembly-Rizon4s-Grav-Play-v0 \\ + --num_envs 1 --checkpoint + + Observation overrides (``OBS_SHAFT_POS``, ``OBS_SHAFT_QUAT``) let you + inject fixed values into the policy's observation tensor regardless of + simulation state. Set to ``None`` to use the simulated values. + """ + + # ╔══════════════════════════════════════════════════════════════════════╗ + # ║ SCENE SETUP — edit to match your real-world setup ║ + # ╚══════════════════════════════════════════════════════════════════════╝ + + GEAR_TYPE: str = "gear_large" + GEAR_BASE_POS: tuple = (0.481, -0.073, -0.005) + GEAR_BASE_ROT: tuple = (0.0, 0.0, -0.70711, 0.70711) + GEAR_Z_OFFSET: float = 0.0675 + + # ╔══════════════════════════════════════════════════════════════════════╗ + # ║ OBSERVATION OVERRIDES — set to None to use simulated values ║ + # ║ ║ + # ║ Obs layout: [joint_pos(7) | joint_vel(7) | shaft_pos(3) | ║ + # ║ shaft_quat(4)] ║ + # ╚══════════════════════════════════════════════════════════════════════╝ + + OBS_SHAFT_POS: tuple | None = None # e.g. (0.481, -0.028, -0.005) + OBS_SHAFT_QUAT: tuple | None = None # e.g. (0.0, 0.0, -0.70711, 0.70711) + + def __post_init__(self): + super().__post_init__() + + self.scene.num_envs = 1 + self.scene.env_spacing = 2.5 + + # ── Fix gear type (no random selection) ─────────────────────────── + self.events.randomize_gear_type.params["gear_types"] = [self.GEAR_TYPE] + + # ── Override gear base pose ─────────────────────────────────────── + self.scene.factory_gear_base.init_state = RigidObjectCfg.InitialStateCfg( + pos=self.GEAR_BASE_POS, + rot=self.GEAR_BASE_ROT, + ) + for attr in ("factory_gear_small", "factory_gear_medium", "factory_gear_large"): + getattr(self.scene, attr).init_state = RigidObjectCfg.InitialStateCfg( + pos=self.GEAR_BASE_POS, + rot=self.GEAR_BASE_ROT, + ) + + # ── Zero out all pose randomization ─────────────────────────────── + self.events.randomize_gears_and_base_pose.params["pose_range"] = { + "x": [0.0, 0.0], + "y": [0.0, 0.0], + "z": [0.0, 0.0], + "roll": [0.0, 0.0], + "pitch": [0.0, 0.0], + "yaw": [0.0, 0.0], + } + self.events.randomize_gears_and_base_pose.params["gear_pos_range"] = { + "x": [0.0, 0.0], + "y": [0.0, 0.0], + "z": [self.GEAR_Z_OFFSET, self.GEAR_Z_OFFSET], + } + + # ── Disable observation noise ───────────────────────────────────── + self.observations.policy.enable_corruption = False + + # ── Observation overrides (replace terms with constant functions) ─ + if self.OBS_SHAFT_POS is not None: + self.observations.policy.gear_shaft_pos = ObsTerm(func=constant_obs, params={"value": self.OBS_SHAFT_POS}) + if self.OBS_SHAFT_QUAT is not None: + self.observations.policy.gear_shaft_quat = ObsTerm(func=constant_obs, params={"value": self.OBS_SHAFT_QUAT}) diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/deploy/mdp/__init__.pyi b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/deploy/mdp/__init__.pyi index 9f27fc7560c6..2a200c888bc0 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/deploy/mdp/__init__.pyi +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/deploy/mdp/__init__.pyi @@ -17,6 +17,8 @@ __all__ = [ "keypoint_command_error_exp", "keypoint_entity_error", "keypoint_entity_error_exp", + "keypoint_ee_grasp_error", + "keypoint_ee_grasp_error_exp", "reset_when_gear_dropped", "reset_when_gear_orientation_exceeds_threshold", ] @@ -29,6 +31,8 @@ from .rewards import ( keypoint_command_error_exp, keypoint_entity_error, keypoint_entity_error_exp, + keypoint_ee_grasp_error, + keypoint_ee_grasp_error_exp, ) from .terminations import reset_when_gear_dropped, reset_when_gear_orientation_exceeds_threshold from isaaclab.envs.mdp import * diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/deploy/mdp/events.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/deploy/mdp/events.py index 503fd3af75d8..b651a002966e 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/deploy/mdp/events.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/deploy/mdp/events.py @@ -216,7 +216,7 @@ def __call__( robot_asset_cfg: SceneEntityCfg = SceneEntityCfg("robot"), pos_threshold: float = 1e-6, rot_threshold: float = 1e-6, - max_iterations: int = 10, + max_iterations: int = 50, pos_randomization_range: dict | None = None, gear_offsets_grasp: dict | None = None, end_effector_body_name: str | None = None, @@ -254,24 +254,24 @@ def __call__( # IK loop for i in range(max_iterations): # Get current joint state - joint_pos = wp.to_torch(self.robot_asset.data.joint_pos)[env_ids].clone() - joint_vel = wp.to_torch(self.robot_asset.data.joint_vel)[env_ids].clone() + joint_pos = self.robot_asset.data.joint_pos.torch[env_ids].clone() + joint_vel = self.robot_asset.data.joint_vel.torch[env_ids].clone() # Stack all gear positions and quaternions all_gear_pos = torch.stack( [ - wp.to_torch(env.scene["factory_gear_small"].data.root_link_pos_w), - wp.to_torch(env.scene["factory_gear_medium"].data.root_link_pos_w), - wp.to_torch(env.scene["factory_gear_large"].data.root_link_pos_w), + env.scene["factory_gear_small"].data.root_link_pos_w.torch, + env.scene["factory_gear_medium"].data.root_link_pos_w.torch, + env.scene["factory_gear_large"].data.root_link_pos_w.torch, ], dim=1, )[env_ids] all_gear_quat = torch.stack( [ - wp.to_torch(env.scene["factory_gear_small"].data.root_link_quat_w), - wp.to_torch(env.scene["factory_gear_medium"].data.root_link_quat_w), - wp.to_torch(env.scene["factory_gear_large"].data.root_link_quat_w), + env.scene["factory_gear_small"].data.root_link_quat_w.torch, + env.scene["factory_gear_medium"].data.root_link_quat_w.torch, + env.scene["factory_gear_large"].data.root_link_quat_w.torch, ], dim=1, )[env_ids] @@ -306,8 +306,8 @@ def __call__( ) # Get end effector pose - eef_pos = wp.to_torch(self.robot_asset.data.body_pos_w)[env_ids, self.eef_idx] - eef_quat = wp.to_torch(self.robot_asset.data.body_quat_w)[env_ids, self.eef_idx] + eef_pos = self.robot_asset.data.body_pos_w.torch[env_ids, self.eef_idx] + eef_quat = self.robot_asset.data.body_quat_w.torch[env_ids, self.eef_idx] # Compute pose error pos_error, axis_angle_error = fc.get_pose_error( @@ -340,6 +340,22 @@ def __call__( # Update joint positions joint_pos = joint_pos + delta_dof_pos + + # Wrap arm joint positions to fall within robot's actual joint limits + joint_pos_limits = self.robot_asset.data.joint_pos_limits.torch[env_ids, : self.num_arm_joints, :] + joint_min = joint_pos_limits[:, :, 0] + joint_max = joint_pos_limits[:, :, 1] + joint_range = joint_max - joint_min + + # Wrap only the arm joint positions (not gripper joints) + arm_joint_pos = joint_pos[:, : self.num_arm_joints] + arm_joint_pos = torch.where( + joint_range > 0, + joint_min + torch.remainder(arm_joint_pos - joint_min, joint_range), + arm_joint_pos, + ) + joint_pos[:, : self.num_arm_joints] = arm_joint_pos + joint_vel = torch.zeros_like(joint_pos) # Write to sim @@ -348,8 +364,11 @@ def __call__( self.robot_asset.write_joint_position_to_sim_index(position=joint_pos, env_ids=env_ids) self.robot_asset.write_joint_velocity_to_sim_index(velocity=joint_vel, env_ids=env_ids) + # Reset joint velocities to zero after IK convergence + joint_vel = torch.zeros_like(self.robot_asset.data.joint_vel.torch[env_ids]) + # Set gripper to grasp position - joint_pos = wp.to_torch(self.robot_asset.data.joint_pos)[env_ids].clone() + joint_pos = self.robot_asset.data.joint_pos.torch[env_ids].clone() # Get gear types for all environments all_gear_types = gear_type_manager.get_all_gear_types() @@ -447,8 +466,8 @@ def __call__( asset_names_to_process = [self.base_asset_name] + self.gear_asset_names for asset_name in asset_names_to_process: asset: RigidObject | Articulation = env.scene[asset_name] - default_root_pose = wp.to_torch(asset.data.default_root_pose)[env_ids].clone() - default_root_vel = wp.to_torch(asset.data.default_root_vel)[env_ids].clone() + default_root_pose = asset.data.default_root_pose.torch[env_ids].clone() + default_root_vel = asset.data.default_root_vel.torch[env_ids].clone() positions = default_root_pose[:, 0:3] + env.scene.env_origins[env_ids] + rand_pose_samples[:, 0:3] orientations = math_utils.quat_mul(default_root_pose[:, 3:7], orientations_delta) velocities = default_root_vel + rand_vel_samples diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/deploy/mdp/noise_models.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/deploy/mdp/noise_models.py index 2d5411e96977..740099a169ee 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/deploy/mdp/noise_models.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/deploy/mdp/noise_models.py @@ -7,7 +7,12 @@ from __future__ import annotations -__all__ = ["ResetSampledConstantNoiseModel", "ResetSampledConstantNoiseModelCfg"] +__all__ = [ + "ResetSampledConstantNoiseModel", + "ResetSampledConstantNoiseModelCfg", + "ResetSampledQuaternionNoiseModel", + "ResetSampledQuaternionNoiseModelCfg", +] from collections.abc import Sequence from dataclasses import MISSING @@ -16,7 +21,8 @@ import torch from isaaclab.utils import configclass -from isaaclab.utils.noise import NoiseModel, NoiseModelCfg +from isaaclab.utils.math import quat_from_euler_xyz, quat_mul +from isaaclab.utils.noise import ConstantNoiseCfg, NoiseModel, NoiseModelCfg if TYPE_CHECKING: from isaaclab.utils.noise import NoiseCfg @@ -107,3 +113,77 @@ class ResetSampledConstantNoiseModelCfg(NoiseModelCfg): Based on this configuration, the noise is sampled at every reset of the noise model. """ + + +class ResetSampledQuaternionNoiseModel(NoiseModel): + """Noise model that applies a rotation perturbation to quaternion observations. + + At each episode reset, small Euler angle perturbations (roll, pitch, yaw) are sampled + uniformly from configurable ranges and converted to a perturbation quaternion. This + perturbation is then applied via quaternion multiplication at every step, producing a + geometrically valid rotated quaternion (unlike additive noise on raw components). + + The perturbation is held constant for the entire episode until the next reset. + """ + + def __init__(self, noise_model_cfg: NoiseModelCfg, num_envs: int, device: str): + super().__init__(noise_model_cfg, num_envs, device) + self._roll_range = noise_model_cfg.roll_range + self._pitch_range = noise_model_cfg.pitch_range + self._yaw_range = noise_model_cfg.yaw_range + # Identity quaternion in (x, y, z, w) format + self._perturbation_quat = torch.zeros((num_envs, 4), device=device) + self._perturbation_quat[:, 3] = 1.0 + + def reset(self, env_ids: Sequence[int] | None = None): + """Sample new rotation perturbations for the specified environments. + + Args: + env_ids: The environment ids to reset. Defaults to None (all environments). + """ + if env_ids is None: + env_ids = slice(None) + + num_resets = env_ids.stop - env_ids.start if isinstance(env_ids, slice) else len(env_ids) + + roll = torch.empty(num_resets, device=self._device).uniform_(*self._roll_range) + pitch = torch.empty(num_resets, device=self._device).uniform_(*self._pitch_range) + yaw = torch.empty(num_resets, device=self._device).uniform_(*self._yaw_range) + + self._perturbation_quat[env_ids] = quat_from_euler_xyz(roll, pitch, yaw) + + def __call__(self, data: torch.Tensor) -> torch.Tensor: + """Apply the pre-sampled rotation perturbation to the quaternion data. + + Args: + data: Quaternion observations in (x, y, z, w) format. Shape is (num_envs, 4). + + Returns: + Perturbed quaternions in (x, y, z, w) format. Shape is (num_envs, 4). + """ + return quat_mul(self._perturbation_quat, data) + + +@configclass +class ResetSampledQuaternionNoiseModelCfg(NoiseModelCfg): + """Configuration for a quaternion noise model that samples rotation perturbations at reset. + + The perturbation is specified as independent uniform ranges for roll, pitch, and yaw + (in radians). At each episode reset, Euler angles are sampled and converted to a + perturbation quaternion that is multiplied with the observed quaternion. + """ + + class_type: type = ResetSampledQuaternionNoiseModel + + noise_cfg: ConstantNoiseCfg = ConstantNoiseCfg(bias=0.0) + """Unused placeholder inherited from NoiseModelCfg. Quaternion perturbation is + controlled by roll_range, pitch_range, and yaw_range instead.""" + + roll_range: tuple[float, float] = (-0.01745, 0.01745) + """Uniform range for roll perturbation in radians. Default is ±1 degree.""" + + pitch_range: tuple[float, float] = (-0.01745, 0.01745) + """Uniform range for pitch perturbation in radians. Default is ±1 degree.""" + + yaw_range: tuple[float, float] = (-0.01745, 0.01745) + """Uniform range for yaw perturbation in radians. Default is ±1 degree.""" diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/deploy/mdp/observations.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/deploy/mdp/observations.py index e70b77d7d8f9..ac12d8b22f7f 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/deploy/mdp/observations.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/deploy/mdp/observations.py @@ -10,7 +10,6 @@ from typing import TYPE_CHECKING import torch -import warp as wp from isaaclab.managers import ManagerTermBase, ObservationTermCfg, SceneEntityCfg from isaaclab.utils.math import combine_frame_transforms @@ -128,8 +127,8 @@ def __call__( gear_type_indices = gear_type_manager.get_all_gear_type_indices() # Get base gear position and orientation - base_pos = wp.to_torch(self.asset.data.root_pos_w) - base_quat = wp.to_torch(self.asset.data.root_quat_w) + base_pos = self.asset.data.root_pos_w.torch + base_quat = self.asset.data.root_quat_w.torch # Update offsets using vectorized indexing self.offsets_buffer = self.gear_offsets_stacked[gear_type_indices] @@ -182,13 +181,12 @@ def __call__( Gear shaft orientation tensor of shape (num_envs, 4) """ # Get base quaternion - base_quat = wp.to_torch(self.asset.data.root_quat_w) + base_quat = self.asset.data.root_quat_w.torch # Ensure w component is positive (q and -q represent the same rotation) # Pick one canonical form to reduce observation variation seen by the policy - w_negative = base_quat[:, 0] < 0 - positive_quat = base_quat.clone() - positive_quat[w_negative] = -base_quat[w_negative] + w_negative = base_quat[:, 3] < 0 + positive_quat = torch.where(w_negative.unsqueeze(-1), -base_quat, base_quat) return positive_quat @@ -250,9 +248,9 @@ def __call__(self, env: ManagerBasedRLEnv) -> torch.Tensor: # Stack all gear positions all_gear_positions = torch.stack( [ - wp.to_torch(self.gear_assets["gear_small"].data.root_pos_w), - wp.to_torch(self.gear_assets["gear_medium"].data.root_pos_w), - wp.to_torch(self.gear_assets["gear_large"].data.root_pos_w), + self.gear_assets["gear_small"].data.root_pos_w.torch, + self.gear_assets["gear_medium"].data.root_pos_w.torch, + self.gear_assets["gear_large"].data.root_pos_w.torch, ], dim=1, ) @@ -323,9 +321,9 @@ def __call__(self, env: ManagerBasedRLEnv) -> torch.Tensor: # Stack all gear quaternions all_gear_quat = torch.stack( [ - wp.to_torch(self.gear_assets["gear_small"].data.root_quat_w), - wp.to_torch(self.gear_assets["gear_medium"].data.root_quat_w), - wp.to_torch(self.gear_assets["gear_large"].data.root_quat_w), + self.gear_assets["gear_small"].data.root_quat_w.torch, + self.gear_assets["gear_medium"].data.root_quat_w.torch, + self.gear_assets["gear_large"].data.root_quat_w.torch, ], dim=1, ) @@ -335,7 +333,7 @@ def __call__(self, env: ManagerBasedRLEnv) -> torch.Tensor: # Ensure w component is positive (q and -q represent the same rotation) # Pick one canonical form to reduce observation variation seen by the policy - w_negative = gear_quat[:, 0] < 0 + w_negative = gear_quat[:, 3] < 0 gear_positive_quat = gear_quat.clone() gear_positive_quat[w_negative] = -gear_quat[w_negative] diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/deploy/mdp/rewards.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/deploy/mdp/rewards.py index 2204a0186bc0..c776168e5b48 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/deploy/mdp/rewards.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/deploy/mdp/rewards.py @@ -10,12 +10,12 @@ from typing import TYPE_CHECKING import torch -import warp as wp from isaaclab.managers import ManagerTermBase, RewardTermCfg, SceneEntityCfg -from isaaclab.utils.math import combine_frame_transforms +from isaaclab.utils.math import combine_frame_transforms, quat_apply, quat_mul if TYPE_CHECKING: + from isaaclab.assets import Articulation from isaaclab.envs import ManagerBasedRLEnv from isaaclab.sensors.frame_transformer.frame_transformer import FrameTransformer @@ -73,8 +73,8 @@ def __call__( des_quat_w = command[:, 3:7] # Get current pose from frame transformer - curr_pos_w = wp.to_torch(asset.data.target_pos_source)[:, 0] - curr_quat_w = wp.to_torch(asset.data.target_quat_source)[:, 0] + curr_pos_w = asset.data.target_pos_source.torch[:, 0] + curr_quat_w = asset.data.target_quat_source.torch[:, 0] # Compute keypoint distance keypoint_dist_sep = self.keypoint_computer.compute( @@ -144,8 +144,8 @@ def __call__( des_quat_w = command[:, 3:7] # Get current pose from frame transformer - curr_pos_w = wp.to_torch(asset.data.target_pos_source)[:, 0] - curr_quat_w = wp.to_torch(asset.data.target_quat_source)[:, 0] + curr_pos_w = asset.data.target_pos_source.torch[:, 0] + curr_quat_w = asset.data.target_quat_source.torch[:, 0] # Compute keypoint distance keypoint_dist_sep = self.keypoint_computer.compute( @@ -193,44 +193,29 @@ def __init__(self, cfg: RewardTermCfg, env: ManagerBasedRLEnv): self.asset_cfg_1: SceneEntityCfg = cfg.params.get("asset_cfg_1", SceneEntityCfg("factory_gear_base")) self.asset_1 = env.scene[self.asset_cfg_1.name] - # Pre-allocate gear type mapping and indices + self._init_gear_selection(env) + + # Create keypoint distance computer + self.keypoint_computer = _compute_keypoint_distance(cfg, env) + + def _init_gear_selection(self, env: ManagerBasedRLEnv) -> None: + """Pre-allocate gear type mapping, index tensors, and cache gear scene assets.""" self.gear_type_map = {"gear_small": 0, "gear_medium": 1, "gear_large": 2} self.gear_type_indices = torch.zeros(env.num_envs, device=env.device, dtype=torch.long) self.env_indices = torch.arange(env.num_envs, device=env.device) - # Cache gear assets self.gear_assets = { "gear_small": env.scene["factory_gear_small"], "gear_medium": env.scene["factory_gear_medium"], "gear_large": env.scene["factory_gear_large"], } - # Create keypoint distance computer - self.keypoint_computer = _compute_keypoint_distance(cfg, env) - - def __call__( - self, - env: ManagerBasedRLEnv, - asset_cfg_1: SceneEntityCfg, - keypoint_scale: float = 1.0, - add_cube_center_kp: bool = True, - ) -> torch.Tensor: - """Compute keypoint distance error. - - Args: - env: Environment instance - asset_cfg_1: Configuration of the first asset (RigidObject) - keypoint_scale: Scale factor for keypoint offsets - add_cube_center_kp: Whether to include center keypoint + def _get_selected_gear_poses(self, env: ManagerBasedRLEnv) -> tuple[torch.Tensor, torch.Tensor]: + """Retrieve world-frame position and quaternion of the active gear per environment. Returns: - Mean keypoint distance tensor of shape (num_envs,) + Tuple of (gear_pos, gear_quat) with shapes (num_envs, 3) and (num_envs, 4). """ - # Get current pose of asset_1 (RigidObject) - curr_pos_1 = wp.to_torch(self.asset_1.data.body_pos_w)[:, 0] - curr_quat_1 = wp.to_torch(self.asset_1.data.body_quat_w)[:, 0] - - # Check if gear type manager exists if not hasattr(env, "_gear_type_manager"): raise RuntimeError( "Gear type manager not initialized. Ensure randomize_gear_type event is configured " @@ -238,31 +223,55 @@ def __call__( ) gear_type_manager: randomize_gear_type = env._gear_type_manager - # Get gear type indices directly as tensor self.gear_type_indices = gear_type_manager.get_all_gear_type_indices() - # Stack all gear positions and quaternions all_gear_pos = torch.stack( [ - wp.to_torch(self.gear_assets["gear_small"].data.body_pos_w)[:, 0], - wp.to_torch(self.gear_assets["gear_medium"].data.body_pos_w)[:, 0], - wp.to_torch(self.gear_assets["gear_large"].data.body_pos_w)[:, 0], + self.gear_assets["gear_small"].data.body_pos_w.torch[:, 0], + self.gear_assets["gear_medium"].data.body_pos_w.torch[:, 0], + self.gear_assets["gear_large"].data.body_pos_w.torch[:, 0], ], dim=1, ) all_gear_quat = torch.stack( [ - wp.to_torch(self.gear_assets["gear_small"].data.body_quat_w)[:, 0], - wp.to_torch(self.gear_assets["gear_medium"].data.body_quat_w)[:, 0], - wp.to_torch(self.gear_assets["gear_large"].data.body_quat_w)[:, 0], + self.gear_assets["gear_small"].data.body_quat_w.torch[:, 0], + self.gear_assets["gear_medium"].data.body_quat_w.torch[:, 0], + self.gear_assets["gear_large"].data.body_quat_w.torch[:, 0], ], dim=1, ) - # Select positions and quaternions using advanced indexing - curr_pos_2 = all_gear_pos[self.env_indices, self.gear_type_indices] - curr_quat_2 = all_gear_quat[self.env_indices, self.gear_type_indices] + gear_pos = all_gear_pos[self.env_indices, self.gear_type_indices] + gear_quat = all_gear_quat[self.env_indices, self.gear_type_indices] + + return gear_pos, gear_quat + + def __call__( + self, + env: ManagerBasedRLEnv, + asset_cfg_1: SceneEntityCfg, + keypoint_scale: float = 1.0, + add_cube_center_kp: bool = True, + ) -> torch.Tensor: + """Compute keypoint distance error. + + Args: + env: Environment instance + asset_cfg_1: Configuration of the first asset (RigidObject) + keypoint_scale: Scale factor for keypoint offsets + add_cube_center_kp: Whether to include center keypoint + + Returns: + Mean keypoint distance tensor of shape (num_envs,) + """ + # Get current pose of asset_1 (RigidObject) + curr_pos_1 = self.asset_1.data.body_pos_w.torch[:, 0] + curr_quat_1 = self.asset_1.data.body_quat_w.torch[:, 0] + + # Get selected gear pose + curr_pos_2, curr_quat_2 = self._get_selected_gear_poses(env) # Compute keypoint distance keypoint_dist_sep = self.keypoint_computer.compute( @@ -276,40 +285,13 @@ def __call__( return keypoint_dist_sep.mean(-1) -class keypoint_entity_error_exp(ManagerTermBase): +class keypoint_entity_error_exp(keypoint_entity_error): """Compute exponential keypoint reward between a RigidObject and the dynamically selected gear. - This class-based term pre-caches gear type mapping and asset references. + Inherits gear selection and initialization from :class:`keypoint_entity_error` + and applies an exponential reward transformation to the keypoint distances. """ - def __init__(self, cfg: RewardTermCfg, env: ManagerBasedRLEnv): - """Initialize the keypoint entity error exponential term. - - Args: - cfg: Reward term configuration - env: Environment instance - """ - super().__init__(cfg, env) - - # Cache asset configuration - self.asset_cfg_1: SceneEntityCfg = cfg.params.get("asset_cfg_1", SceneEntityCfg("factory_gear_base")) - self.asset_1 = env.scene[self.asset_cfg_1.name] - - # Pre-allocate gear type mapping and indices - self.gear_type_map = {"gear_small": 0, "gear_medium": 1, "gear_large": 2} - self.gear_type_indices = torch.zeros(env.num_envs, device=env.device, dtype=torch.long) - self.env_indices = torch.arange(env.num_envs, device=env.device) - - # Cache gear assets - self.gear_assets = { - "gear_small": env.scene["factory_gear_small"], - "gear_medium": env.scene["factory_gear_medium"], - "gear_large": env.scene["factory_gear_large"], - } - - # Create keypoint distance computer - self.keypoint_computer = _compute_keypoint_distance(cfg, env) - def __call__( self, env: ManagerBasedRLEnv, @@ -333,42 +315,11 @@ def __call__( Exponential keypoint reward tensor of shape (num_envs,) """ # Get current pose of asset_1 (RigidObject) - curr_pos_1 = wp.to_torch(self.asset_1.data.body_pos_w)[:, 0] - curr_quat_1 = wp.to_torch(self.asset_1.data.body_quat_w)[:, 0] - - # Check if gear type manager exists - if not hasattr(env, "_gear_type_manager"): - raise RuntimeError( - "Gear type manager not initialized. Ensure randomize_gear_type event is configured " - "in your environment's event configuration before this reward term is used." - ) - - gear_type_manager: randomize_gear_type = env._gear_type_manager - # Get gear type indices directly as tensor - self.gear_type_indices = gear_type_manager.get_all_gear_type_indices() - - # Stack all gear positions and quaternions - all_gear_pos = torch.stack( - [ - wp.to_torch(self.gear_assets["gear_small"].data.body_pos_w)[:, 0], - wp.to_torch(self.gear_assets["gear_medium"].data.body_pos_w)[:, 0], - wp.to_torch(self.gear_assets["gear_large"].data.body_pos_w)[:, 0], - ], - dim=1, - ) - - all_gear_quat = torch.stack( - [ - wp.to_torch(self.gear_assets["gear_small"].data.body_quat_w)[:, 0], - wp.to_torch(self.gear_assets["gear_medium"].data.body_quat_w)[:, 0], - wp.to_torch(self.gear_assets["gear_large"].data.body_quat_w)[:, 0], - ], - dim=1, - ) + curr_pos_1 = self.asset_1.data.body_pos_w.torch[:, 0] + curr_quat_1 = self.asset_1.data.body_quat_w.torch[:, 0] - # Select positions and quaternions using advanced indexing - curr_pos_2 = all_gear_pos[self.env_indices, self.gear_type_indices] - curr_quat_2 = all_gear_quat[self.env_indices, self.gear_type_indices] + # Get selected gear pose + curr_pos_2, curr_quat_2 = self._get_selected_gear_poses(env) # Compute keypoint distance keypoint_dist_sep = self.keypoint_computer.compute( @@ -397,6 +348,226 @@ def __call__( return keypoint_reward_exp +class keypoint_ee_grasp_error(keypoint_entity_error): + """Compute keypoint distance between the robot end effector and the gear's grasp-corrected pose. + + Transforms the gear's actual world pose into the expected EE position/orientation + using grasp offsets, so that the distance is ~0 when properly holding the gear + and increases when the gripper drifts away. + + The penalty is gated by ``ee_grasp_threshold``: It only activates when the mean + keypoint error exceeds the threshold, i.e., when the EE has drifted away from the + expected grasp pose. With threshold=0.0, the penalty is effectively always active. + + Supports linear weight ramp-up: The returned reward is scaled by a factor that + linearly increases from ``weight_ramp_start`` to 1.0 over ``weight_ramp_steps`` + env steps, allowing the reward to grow in importance as training progresses. + """ + + def __init__(self, cfg: RewardTermCfg, env: ManagerBasedRLEnv): + ManagerTermBase.__init__(self, cfg, env) + + self._init_gear_selection(env) + self.keypoint_computer = _compute_keypoint_distance(cfg, env) + + self.robot_asset_cfg: SceneEntityCfg = cfg.params.get("robot_asset_cfg", SceneEntityCfg("robot")) + self.robot_asset: Articulation = env.scene[self.robot_asset_cfg.name] + + self.end_effector_body_name: str = cfg.params["end_effector_body_name"] + grasp_rot_offset = cfg.params["grasp_rot_offset"] + self.grasp_rot_offset_tensor = ( + torch.tensor(grasp_rot_offset, device=env.device, dtype=torch.float32).unsqueeze(0).repeat(env.num_envs, 1) + ) + + gear_offsets_grasp = cfg.params["gear_offsets_grasp"] + self.gear_grasp_offsets_stacked = torch.stack( + [ + torch.tensor(gear_offsets_grasp["gear_small"], device=env.device, dtype=torch.float32), + torch.tensor(gear_offsets_grasp["gear_medium"], device=env.device, dtype=torch.float32), + torch.tensor(gear_offsets_grasp["gear_large"], device=env.device, dtype=torch.float32), + ], + dim=0, + ) + + self.weight_ramp_start: float = cfg.params.get("weight_ramp_start", 0.0) + self.weight_ramp_steps: int = cfg.params.get("weight_ramp_steps", 1) + self.ee_grasp_threshold: float = cfg.params.get("ee_grasp_threshold", 0.0) + + eef_indices, _ = self.robot_asset.find_bodies([self.end_effector_body_name]) + self.eef_idx = eef_indices[0] if len(eef_indices) > 0 else None + self._step_count = 0 + + def _get_weight_scale(self, env: ManagerBasedRLEnv) -> float: + progress = min(env.common_step_counter / max(self.weight_ramp_steps, 1), 1.0) + return self.weight_ramp_start + (1.0 - self.weight_ramp_start) * progress + + def _get_grasp_corrected_target( + self, env: ManagerBasedRLEnv + ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + """Compute EE pose and grasp-corrected target pose. + + Returns: + Tuple of (eef_pos, eef_quat, gear_grasp_pos, gear_quat_grasp). + """ + eef_pos = self.robot_asset.data.body_link_pos_w.torch[:, self.eef_idx] + eef_quat = self.robot_asset.data.body_link_quat_w.torch[:, self.eef_idx] + + gear_pos, gear_quat = self._get_selected_gear_poses(env) + + gear_quat_grasp = quat_mul(gear_quat, self.grasp_rot_offset_tensor) + grasp_offsets = self.gear_grasp_offsets_stacked[self.gear_type_indices] + gear_grasp_pos = gear_pos + quat_apply(gear_quat_grasp, grasp_offsets) + + return eef_pos, eef_quat, gear_grasp_pos, gear_quat_grasp + + def __call__( + self, + env: ManagerBasedRLEnv, + robot_asset_cfg: SceneEntityCfg = SceneEntityCfg("robot"), + end_effector_body_name: str = "", + grasp_rot_offset: list | None = None, + gear_offsets_grasp: dict | None = None, + keypoint_scale: float = 1.0, + add_cube_center_kp: bool = True, + weight_ramp_start: float = 0.0, + weight_ramp_steps: int = 1, + ee_grasp_threshold: float = 0.0, + ) -> torch.Tensor: + if self.eef_idx is None: + return torch.zeros(env.num_envs, device=env.device) + + eef_pos, eef_quat, gear_grasp_pos, gear_quat_grasp = self._get_grasp_corrected_target(env) + + keypoint_dist_sep = self.keypoint_computer.compute( + current_pos=eef_pos, + current_quat=eef_quat, + target_pos=gear_grasp_pos, + target_quat=gear_quat_grasp, + keypoint_scale=keypoint_scale, + ) + + mean_kp_error = keypoint_dist_sep.mean(-1) + + is_active = (mean_kp_error > self.ee_grasp_threshold).float() + + weight_scale = self._get_weight_scale(env) + scaled_reward = mean_kp_error * weight_scale * is_active + + mean_error_scalar = mean_kp_error.mean().item() + pct_active = is_active.mean().item() + + if not hasattr(env, "extras"): + env.extras = {} + if "log" not in env.extras: + env.extras["log"] = {} + env.extras["log"]["ee_grasp_kp_error/mean_keypoint_dist"] = mean_error_scalar + env.extras["log"]["ee_grasp_kp_error/pct_envs_active"] = pct_active + env.extras["log"]["ee_grasp_kp_error/weight_scale"] = weight_scale + + self._step_count += 1 + import carb + + carb.log_info( + f"[ee_grasp_kp_error] step={self._step_count}" + f" | mean_kp_error={mean_error_scalar:.5f}" + f" | pct_active={pct_active:.3f}" + f" | weight_scale={weight_scale:.4f}" + ) + + return scaled_reward + + +class keypoint_ee_grasp_error_exp(keypoint_ee_grasp_error): + """Compute exponential keypoint reward between the robot end effector and the gear's grasp-corrected pose. + + Transforms the gear's actual world pose into the expected EE position/orientation + using grasp offsets, so that the reward is high (~1) when properly holding the gear + and drops sharply when the gripper drifts away. + + The reward is gated by ``ee_grasp_threshold``: It only activates when the mean + keypoint error exceeds the threshold, i.e. when the EE has drifted away from the + expected grasp pose. With threshold=0.0 the reward is effectively always active. + + Supports linear weight ramp-up: The returned reward is scaled by a factor that + linearly increases from ``weight_ramp_start`` to 1.0 over ``weight_ramp_steps`` + env steps, allowing the reward to grow in importance as training progresses. + """ + + def __call__( + self, + env: ManagerBasedRLEnv, + robot_asset_cfg: SceneEntityCfg = SceneEntityCfg("robot"), + end_effector_body_name: str = "", + grasp_rot_offset: list | None = None, + gear_offsets_grasp: dict | None = None, + kp_exp_coeffs: list[tuple[float, float]] = [(1.0, 0.1)], + kp_use_sum_of_exps: bool = True, + keypoint_scale: float = 1.0, + add_cube_center_kp: bool = True, + weight_ramp_start: float = 0.0, + weight_ramp_steps: int = 1, + ee_grasp_threshold: float = 0.0, + ) -> torch.Tensor: + if self.eef_idx is None: + return torch.zeros(env.num_envs, device=env.device) + + eef_pos, eef_quat, gear_grasp_pos, gear_quat_grasp = self._get_grasp_corrected_target(env) + + keypoint_dist_sep = self.keypoint_computer.compute( + current_pos=eef_pos, + current_quat=eef_quat, + target_pos=gear_grasp_pos, + target_quat=gear_quat_grasp, + keypoint_scale=keypoint_scale, + ) + + mean_kp_error = keypoint_dist_sep.mean(-1) + + is_active = (mean_kp_error > self.ee_grasp_threshold).float() + + keypoint_reward_exp = torch.zeros_like(keypoint_dist_sep[:, 0]) + if kp_use_sum_of_exps: + for coeff in kp_exp_coeffs: + a, b = coeff + keypoint_reward_exp += ( + 1.0 / (torch.exp(a * keypoint_dist_sep) + b + torch.exp(-a * keypoint_dist_sep)) + ).mean(-1) + else: + kp_dist_mean = keypoint_dist_sep.mean(-1) + for coeff in kp_exp_coeffs: + a, b = coeff + keypoint_reward_exp += 1.0 / (torch.exp(a * kp_dist_mean) + b + torch.exp(-a * kp_dist_mean)) + + weight_scale = self._get_weight_scale(env) + scaled_reward = keypoint_reward_exp * weight_scale * is_active + + mean_error_scalar = mean_kp_error.mean().item() + mean_reward_scalar = keypoint_reward_exp.mean().item() + pct_active = is_active.mean().item() + + if not hasattr(env, "extras"): + env.extras = {} + if "log" not in env.extras: + env.extras["log"] = {} + env.extras["log"]["ee_grasp_kp_error_exp/mean_keypoint_dist"] = mean_error_scalar + env.extras["log"]["ee_grasp_kp_error_exp/mean_exp_reward"] = mean_reward_scalar + env.extras["log"]["ee_grasp_kp_error_exp/pct_envs_active"] = pct_active + env.extras["log"]["ee_grasp_kp_error_exp/weight_scale"] = weight_scale + + self._step_count += 1 + import carb + + carb.log_info( + f"[ee_grasp_kp_error_exp] step={self._step_count}" + f" | mean_kp_error={mean_error_scalar:.5f}" + f" | pct_active={pct_active:.3f}" + f" | weight_scale={weight_scale:.4f}" + f" | mean_exp_reward={mean_reward_scalar:.5f}" + ) + + return scaled_reward + + ## # Helper functions and classes ## diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/deploy/mdp/terminations.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/deploy/mdp/terminations.py index 1fd2b1ad9bc3..9f217c316372 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/deploy/mdp/terminations.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/deploy/mdp/terminations.py @@ -11,7 +11,6 @@ from typing import TYPE_CHECKING import torch -import warp as wp import isaaclab.utils.math as math_utils from isaaclab.managers import ManagerTermBase, SceneEntityCfg, TerminationTermCfg @@ -162,16 +161,16 @@ def __call__( self.gear_type_indices = gear_type_manager.get_all_gear_type_indices() # Get end effector position - eef_pos_world = wp.to_torch(self.robot_asset.data.body_link_pos_w)[:, self.eef_idx] + eef_pos_world = self.robot_asset.data.body_link_pos_w.torch[:, self.eef_idx] # Update gear positions and quaternions in buffers - self.all_gear_pos_buffer[:, 0, :] = wp.to_torch(self.gear_assets["gear_small"].data.root_link_pos_w) - self.all_gear_pos_buffer[:, 1, :] = wp.to_torch(self.gear_assets["gear_medium"].data.root_link_pos_w) - self.all_gear_pos_buffer[:, 2, :] = wp.to_torch(self.gear_assets["gear_large"].data.root_link_pos_w) + self.all_gear_pos_buffer[:, 0, :] = self.gear_assets["gear_small"].data.root_link_pos_w.torch + self.all_gear_pos_buffer[:, 1, :] = self.gear_assets["gear_medium"].data.root_link_pos_w.torch + self.all_gear_pos_buffer[:, 2, :] = self.gear_assets["gear_large"].data.root_link_pos_w.torch - self.all_gear_quat_buffer[:, 0, :] = wp.to_torch(self.gear_assets["gear_small"].data.root_link_quat_w) - self.all_gear_quat_buffer[:, 1, :] = wp.to_torch(self.gear_assets["gear_medium"].data.root_link_quat_w) - self.all_gear_quat_buffer[:, 2, :] = wp.to_torch(self.gear_assets["gear_large"].data.root_link_quat_w) + self.all_gear_quat_buffer[:, 0, :] = self.gear_assets["gear_small"].data.root_link_quat_w.torch + self.all_gear_quat_buffer[:, 1, :] = self.gear_assets["gear_medium"].data.root_link_quat_w.torch + self.all_gear_quat_buffer[:, 2, :] = self.gear_assets["gear_large"].data.root_link_quat_w.torch # Select gear data using advanced indexing gear_pos_world = self.all_gear_pos_buffer[self.env_indices, self.gear_type_indices] @@ -303,12 +302,12 @@ def __call__( yaw_threshold_rad = torch.deg2rad(torch.tensor(yaw_threshold_deg, device=env.device)) # Get end effector orientation - eef_quat_world = wp.to_torch(self.robot_asset.data.body_link_quat_w)[:, self.eef_idx] + eef_quat_world = self.robot_asset.data.body_link_quat_w.torch[:, self.eef_idx] # Update gear quaternions in buffer - self.all_gear_quat_buffer[:, 0, :] = wp.to_torch(self.gear_assets["gear_small"].data.root_link_quat_w) - self.all_gear_quat_buffer[:, 1, :] = wp.to_torch(self.gear_assets["gear_medium"].data.root_link_quat_w) - self.all_gear_quat_buffer[:, 2, :] = wp.to_torch(self.gear_assets["gear_large"].data.root_link_quat_w) + self.all_gear_quat_buffer[:, 0, :] = self.gear_assets["gear_small"].data.root_link_quat_w.torch + self.all_gear_quat_buffer[:, 1, :] = self.gear_assets["gear_medium"].data.root_link_quat_w.torch + self.all_gear_quat_buffer[:, 2, :] = self.gear_assets["gear_large"].data.root_link_quat_w.torch # Select gear data using advanced indexing gear_quat_world = self.all_gear_quat_buffer[self.env_indices, self.gear_type_indices] diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/deploy/reach/config/rizon_4s/__init__.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/deploy/reach/config/rizon_4s/__init__.py new file mode 100644 index 000000000000..4409ddee18b6 --- /dev/null +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/deploy/reach/config/rizon_4s/__init__.py @@ -0,0 +1,42 @@ +# Copyright (c) 2026-2027, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +import gymnasium as gym + +from . import agents + +## +# Register Gym environments. +## + +gym.register( + id="Isaac-Deploy-Reach-Rizon4s-v0", + entry_point="isaaclab.envs:ManagerBasedRLEnv", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": f"{__name__}.joint_pos_env_cfg:Rizon4sReachEnvCfg", + "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:Rizon4sReachPPORunnerCfg", + }, +) + +gym.register( + id="Isaac-Deploy-Reach-Rizon4s-Play-v0", + entry_point="isaaclab.envs:ManagerBasedRLEnv", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": f"{__name__}.joint_pos_env_cfg:Rizon4sReachEnvCfg_PLAY", + "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:Rizon4sReachPPORunnerCfg", + }, +) + +gym.register( + id="Isaac-Deploy-Reach-Rizon4s-ROS-Inference-v0", + entry_point="isaaclab.envs:ManagerBasedRLEnv", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": f"{__name__}.ros_inference_env_cfg:Rizon4sReachROSInferenceEnvCfg", + "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:Rizon4sReachPPORunnerCfg", + }, +) diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/deploy/reach/config/rizon_4s/agents/__init__.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/deploy/reach/config/rizon_4s/agents/__init__.py new file mode 100644 index 000000000000..7acda4b49bdd --- /dev/null +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/deploy/reach/config/rizon_4s/agents/__init__.py @@ -0,0 +1,4 @@ +# Copyright (c) 2026-2027, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/deploy/reach/config/rizon_4s/agents/rsl_rl_ppo_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/deploy/reach/config/rizon_4s/agents/rsl_rl_ppo_cfg.py new file mode 100644 index 000000000000..cb37cb700181 --- /dev/null +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/deploy/reach/config/rizon_4s/agents/rsl_rl_ppo_cfg.py @@ -0,0 +1,38 @@ +# Copyright (c) 2026-2027, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from isaaclab.utils import configclass + +from isaaclab_rl.rsl_rl import RslRlOnPolicyRunnerCfg, RslRlPpoActorCriticCfg, RslRlPpoAlgorithmCfg + + +@configclass +class Rizon4sReachPPORunnerCfg(RslRlOnPolicyRunnerCfg): + num_steps_per_env = 512 + max_iterations = 1500 + save_interval = 50 + experiment_name = "reach_rizon4s" + empirical_normalization = True + obs_groups = {"policy": ["policy"], "critic": ["policy"]} + policy = RslRlPpoActorCriticCfg( + init_noise_std=1.0, + actor_hidden_dims=[256, 128, 64], + critic_hidden_dims=[256, 128, 64], + activation="elu", + ) + algorithm = RslRlPpoAlgorithmCfg( + value_loss_coef=1.0, + use_clipped_value_loss=True, + clip_param=0.2, + entropy_coef=0.0, + num_learning_epochs=8, + num_mini_batches=8, + learning_rate=5.0e-4, + schedule="adaptive", + gamma=0.99, + lam=0.95, + desired_kl=0.008, + max_grad_norm=1.0, + ) diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/deploy/reach/config/rizon_4s/joint_pos_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/deploy/reach/config/rizon_4s/joint_pos_env_cfg.py new file mode 100644 index 000000000000..d453af36e4eb --- /dev/null +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/deploy/reach/config/rizon_4s/joint_pos_env_cfg.py @@ -0,0 +1,107 @@ +# Copyright (c) 2026-2027, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +import math + +from isaaclab.managers import SceneEntityCfg +from isaaclab.markers.config import FRAME_MARKER_CFG +from isaaclab.sensors.frame_transformer.frame_transformer_cfg import FrameTransformerCfg, OffsetCfg +from isaaclab.utils import configclass + +import isaaclab_tasks.manager_based.manipulation.deploy.mdp as mdp +from isaaclab_tasks.manager_based.manipulation.deploy.reach.reach_env_cfg import ReachEnvCfg + +## +# Pre-defined configs +## +from isaaclab_assets import FLEXIV_RIZON4S_CFG # isort: skip + + +## +# Environment configuration +## + + +@configclass +class Rizon4sReachEnvCfg(ReachEnvCfg): + def __post_init__(self): + # post init of parent + super().__post_init__() + + self.events.robot_joint_stiffness_and_damping.params["asset_cfg"].joint_names = [ + "joint[1-2]", + "joint[3-4]", + "joint[5-7]", + ] + self.events.joint_friction.params["asset_cfg"].joint_names = ["joint[1-2]", "joint[3-4]", "joint[5-7]"] + + # switch robot to Flexiv Rizon 4s + self.scene.robot = FLEXIV_RIZON4S_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") + + # Configure the end-effector frame relative to base frame for Rizon 4s + self.rewards.end_effector_keypoint_tracking.params["asset_cfg"] = SceneEntityCfg("ee_frame_wrt_base_frame") + self.rewards.end_effector_keypoint_tracking_exp.params["asset_cfg"] = SceneEntityCfg("ee_frame_wrt_base_frame") + self.scene.ee_frame_wrt_base_frame = FrameTransformerCfg( + prim_path="{ENV_REGEX_NS}/Robot/base_link", + visualizer_cfg=FRAME_MARKER_CFG.replace(prim_path="/Visuals/FrameTransformer"), + source_frame_offset=OffsetCfg(pos=(0.0, 0.0, 0.0), rot=(0.0, 0.0, 0.0, 1.0)), + target_frames=[ + FrameTransformerCfg.FrameCfg( + prim_path="{ENV_REGEX_NS}/Robot/flange", + name="end_effector", + ), + ], + ) + + self.commands.ee_pose.debug_vis = True + + # Incremental joint position action configuration + self.actions.arm_action = mdp.RelativeJointPositionActionCfg( + asset_name="robot", joint_names=["joint[1-7]"], scale=0.0625, use_zero_offset=True + ) + # override command generator body + # end-effector is along z-direction for Rizon 4s + self.target_pos_centre = (0.4, 0.0, 0.4) + self.target_pos_range = (0.4, 0.4, 0.35) + self.commands.ee_pose.body_name = "flange" + self.commands.ee_pose.ranges.pos_x = ( + self.target_pos_centre[0] - self.target_pos_range[0], + self.target_pos_centre[0] + self.target_pos_range[0], + ) + self.commands.ee_pose.ranges.pos_y = ( + self.target_pos_centre[1] - self.target_pos_range[1], + self.target_pos_centre[1] + self.target_pos_range[1], + ) + self.commands.ee_pose.ranges.pos_z = ( + self.target_pos_centre[2] - self.target_pos_range[2], + self.target_pos_centre[2] + self.target_pos_range[2], + ) + + self.target_rot_centre = (math.pi, 0.0, 0.0) # end-effector facing down + self.target_rot_range = (math.pi / 2, math.pi / 2, math.pi) + self.commands.ee_pose.ranges.roll = ( + self.target_rot_centre[0] - self.target_rot_range[0], + self.target_rot_centre[0] + self.target_rot_range[0], + ) + self.commands.ee_pose.ranges.pitch = ( + self.target_rot_centre[1] - self.target_rot_range[1], + self.target_rot_centre[1] + self.target_rot_range[1], + ) + self.commands.ee_pose.ranges.yaw = ( + self.target_rot_centre[2] - self.target_rot_range[2], + self.target_rot_centre[2] + self.target_rot_range[2], + ) + + +@configclass +class Rizon4sReachEnvCfg_PLAY(Rizon4sReachEnvCfg): + def __post_init__(self): + # post init of parent + super().__post_init__() + # make a smaller scene for play + self.scene.num_envs = 50 + self.scene.env_spacing = 2.5 + # disable randomization for play + self.observations.policy.enable_corruption = False diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/deploy/reach/config/rizon_4s/ros_inference_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/deploy/reach/config/rizon_4s/ros_inference_env_cfg.py new file mode 100644 index 000000000000..91de220071bc --- /dev/null +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/deploy/reach/config/rizon_4s/ros_inference_env_cfg.py @@ -0,0 +1,111 @@ +# Copyright (c) 2026-2027, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +import math + +from isaaclab.utils import configclass + +from .joint_pos_env_cfg import Rizon4sReachEnvCfg + + +@configclass +class Rizon4sReachROSInferenceEnvCfg(Rizon4sReachEnvCfg): + """ROS / Isaac Manipulator inference fields plus deployment alignment for NVIDIA Hubble Lab. + + The Hubble-specific block in this config matches how the Flexiv Rizon 4s is mounted there. + """ + + def __post_init__(self): + # post init of parent + super().__post_init__() + + # --- NVIDIA Hubble Lab: Flexiv Rizon 4s mount and workspace --- + # Remove vertical mount stand since Hubble deployment does not use the sim stand asset + self.scene.table = None + + # Lab home joint pose (radians); aligns sim defaults / reset with the physical stand + self.scene.robot.init_state.joint_pos = { + "joint1": math.radians(-90.0), + "joint2": math.radians(90.0), + "joint3": 0.0, + "joint4": math.radians(90.0), + "joint5": 0.0, + "joint6": 0.0, + "joint7": 0.0, + } + + # Orientation of robot is based on the Flexiv Rizon 4s mount in the Hubble Lab + self.scene.robot.init_state.pos = (0.0, 0.0, 0.0) + self.scene.robot.init_state.rot = (0.5, 0.5, 0.5, 0.5) + + # end-effector is along z-direction for Rizon 4s + # target_pos_centre and target_rot_centre are approximately the end effector pose when + # the robot is in the self.scene.robot.init_state.joint_pos pose + self.target_pos_centre = (0.0, 0.3, 0.9) + self.target_pos_range = (0.4, 0.4, 0.35) + self.commands.ee_pose.body_name = "flange" + self.commands.ee_pose.ranges.pos_x = ( + self.target_pos_centre[0] - self.target_pos_range[0], + self.target_pos_centre[0] + self.target_pos_range[0], + ) + self.commands.ee_pose.ranges.pos_y = ( + self.target_pos_centre[1] - self.target_pos_range[1], + self.target_pos_centre[1] + self.target_pos_range[1], + ) + self.commands.ee_pose.ranges.pos_z = ( + self.target_pos_centre[2] - self.target_pos_range[2], + self.target_pos_centre[2] + self.target_pos_range[2], + ) + + self.target_rot_centre = (math.pi / 2, math.pi / 2, 0.0) # end-effector facing down + self.target_rot_range = (math.pi / 2, math.pi / 2, math.pi) + self.commands.ee_pose.ranges.roll = ( + self.target_rot_centre[0] - self.target_rot_range[0], + self.target_rot_centre[0] + self.target_rot_range[0], + ) + self.commands.ee_pose.ranges.pitch = ( + self.target_rot_centre[1] - self.target_rot_range[1], + self.target_rot_centre[1] + self.target_rot_range[1], + ) + self.commands.ee_pose.ranges.yaw = ( + self.target_rot_centre[2] - self.target_rot_range[2], + self.target_rot_centre[2] + self.target_rot_range[2], + ) + + # Variables used by Isaac Manipulator for on robot inference + # TODO: @ashwinvk: Remove these from env cfg once the generic inference node has been implemented + self.obs_order = ["arm_dof_pos", "arm_dof_vel", "target_pos", "target_quat"] + self.policy_action_space = "joint" + self.arm_joint_names = [ + "joint1", + "joint2", + "joint3", + "joint4", + "joint5", + "joint6", + "joint7", + ] + self.policy_action_space = "joint" + self.action_space = 7 + self.state_space = 21 + self.observation_space = 21 + + # Set joint_action_scale from the existing arm_action.scale + self.joint_action_scale = self.actions.arm_action.scale + + self.action_scale_joint_space = [ + self.joint_action_scale, + self.joint_action_scale, + self.joint_action_scale, + self.joint_action_scale, + self.joint_action_scale, + self.joint_action_scale, + self.joint_action_scale, + ] + + # Extract initial joint positions from robot configuration + self.initial_joint_pos = [ + self.scene.robot.init_state.joint_pos[joint_name] for joint_name in self.arm_joint_names + ] diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/dexsuite/config/kuka_allegro/agents/rsl_rl_ppo_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/dexsuite/config/kuka_allegro/agents/rsl_rl_ppo_cfg.py index d77f0e9fc57c..907777f9614c 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/dexsuite/config/kuka_allegro/agents/rsl_rl_ppo_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/dexsuite/config/kuka_allegro/agents/rsl_rl_ppo_cfg.py @@ -23,7 +23,6 @@ activation="elu", ) - STATE_CRITIC_CFG = RslRlMLPModelCfg( obs_normalization=True, hidden_dims=[512, 256, 128], @@ -35,12 +34,10 @@ hidden_dims=[512, 256, 128], distribution_cfg=RslRlCNNModelCfg.GaussianDistributionCfg(init_std=1.0), cnn_cfg=RslRlCNNModelCfg.CNNCfg( - output_channels=[16, 32], - kernel_size=[3, 3], + output_channels=[32, 64, 64], + kernel_size=[8, 4, 3], + stride=[4, 2, 1], activation="elu", - max_pool=[True, True], - norm="batch", - global_pool="avg", ), activation="elu", ) @@ -89,7 +86,7 @@ class DexsuiteKukaAllegroPPORunnerCfg(PresetCfg): obs_groups={"actor": ["policy", "proprio", "base_image"], "critic": ["policy", "proprio", "perception"]}, actor=CNN_POLICY_CFG, critic=STATE_CRITIC_CFG, - algorithm=ALGO_CFG.replace(num_mini_batches=16), + algorithm=ALGO_CFG.replace(num_mini_batches=2), ) duo_camera = DexsuiteKukaAllegroPPOBaseRunnerCfg().replace( @@ -100,5 +97,5 @@ class DexsuiteKukaAllegroPPORunnerCfg(PresetCfg): }, actor=CNN_POLICY_CFG, critic=STATE_CRITIC_CFG, - algorithm=ALGO_CFG.replace(num_mini_batches=16), + algorithm=ALGO_CFG.replace(num_mini_batches=2), ) diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/dexsuite/config/kuka_allegro/camera_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/dexsuite/config/kuka_allegro/camera_cfg.py index 2e35f20ba81e..cfaae6bbca4c 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/dexsuite/config/kuka_allegro/camera_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/dexsuite/config/kuka_allegro/camera_cfg.py @@ -9,7 +9,7 @@ from isaaclab.managers import ObservationGroupCfg as ObsGroup from isaaclab.managers import ObservationTermCfg as ObsTerm from isaaclab.managers import SceneEntityCfg -from isaaclab.sensors import TiledCameraCfg +from isaaclab.sensors import CameraCfg from isaaclab.utils import configclass from isaaclab.utils.noise import UniformNoiseCfg as Unoise @@ -22,9 +22,9 @@ FINGERTIP_LIST = ["index_link_3", "middle_link_3", "ring_link_3", "thumb_link_3"] -BASE_CAMERA_CFG = TiledCameraCfg( +BASE_CAMERA_CFG = CameraCfg( prim_path="/World/envs/env_.*/Camera", - offset=TiledCameraCfg.OffsetCfg( + offset=CameraCfg.OffsetCfg( pos=(0.57, -0.8, 0.5), rot=(0.6124, 0.3536, 0.3536, 0.6124), convention="opengl", @@ -36,9 +36,9 @@ renderer_cfg=MultiBackendRendererCfg(), ) -WRIST_CAMERA_CFG = TiledCameraCfg( +WRIST_CAMERA_CFG = CameraCfg( prim_path="/World/envs/env_.*/Robot/ee_link/palm_link/Camera", - offset=TiledCameraCfg.OffsetCfg( + offset=CameraCfg.OffsetCfg( pos=(0.038, -0.38, -0.18), rot=(0.641, 0.641, -0.299, 0.299), convention="opengl", diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/dexsuite/config/kuka_allegro/dexsuite_kuka_allegro_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/dexsuite/config/kuka_allegro/dexsuite_kuka_allegro_env_cfg.py index f7d45344ac69..4492d197f763 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/dexsuite/config/kuka_allegro/dexsuite_kuka_allegro_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/dexsuite/config/kuka_allegro/dexsuite_kuka_allegro_env_cfg.py @@ -9,7 +9,7 @@ from isaaclab.assets import ArticulationCfg from isaaclab.managers import RewardTermCfg as RewTerm from isaaclab.managers import SceneEntityCfg -from isaaclab.sensors import ContactSensorCfg, TiledCameraCfg +from isaaclab.sensors import CameraCfg, ContactSensorCfg from isaaclab.utils import configclass from isaaclab_tasks.utils import PresetCfg @@ -38,7 +38,7 @@ class KukaAllegroPhysicsCfg(PresetCfg): gpu_max_rigid_patch_count=4 * 5 * 2**15, gpu_found_lost_pairs_capacity=2**26, ) - newton = NewtonCfg( + newton_mjwarp = NewtonCfg( solver_cfg=MJWarpSolverCfg( solver="newton", integrator="implicitfast", @@ -67,9 +67,9 @@ class KukaAllegroSceneCfg(dexsuite.SceneCfg): robot: ArticulationCfg = KUKA_ALLEGRO_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") - base_camera: TiledCameraCfg | None = None + base_camera: CameraCfg | None = None - wrist_camera: TiledCameraCfg | None = None + wrist_camera: CameraCfg | None = None def __post_init__(self: dexsuite.SceneCfg): super().__post_init__() @@ -139,7 +139,7 @@ class KukaAllegroPhysxEventCfg(dexsuite.StartupEventCfg, dexsuite.EventCfg): pass default = KukaAllegroPhysxEventCfg() - newton = dexsuite.EventCfg() + newton_mjwarp = dexsuite.EventCfg() physx = default diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/dexsuite/dexsuite_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/dexsuite/dexsuite_env_cfg.py index f1e43a51d42b..449043e3977b 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/dexsuite/dexsuite_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/dexsuite/dexsuite_env_cfg.py @@ -77,7 +77,7 @@ class ObjectCfg(PresetCfg): collision_props=sim_utils.CollisionPropertiesCfg(), mass_props=sim_utils.MassPropertiesCfg(mass=0.2), ) - newton = cube # newton does not support multi-asset spawning yet + newton_mjwarp = cube # newton does not support multi-asset spawning yet default = shapes @@ -106,7 +106,7 @@ class SceneCfg(InteractiveSceneCfg): plane = AssetBaseCfg( prim_path="/World/GroundPlane", init_state=AssetBaseCfg.InitialStateCfg(), - spawn=sim_utils.GroundPlaneCfg(), + spawn=sim_utils.GroundPlaneCfg(color=(1.0, 1.0, 1.0)), collision_group=-1, ) diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/dexsuite/mdp/commands/pose_commands.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/dexsuite/mdp/commands/pose_commands.py index 35549df614ab..710fef931ee4 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/dexsuite/mdp/commands/pose_commands.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/dexsuite/mdp/commands/pose_commands.py @@ -12,9 +12,9 @@ from typing import TYPE_CHECKING import torch -import warp as wp from isaaclab.managers import CommandTerm +from isaaclab.utils.leapp import POSE7_ELEMENT_NAMES from isaaclab.utils.math import combine_frame_transforms, compute_pose_error, quat_from_euler_xyz, quat_unique if TYPE_CHECKING: @@ -30,7 +30,7 @@ class ObjectUniformPoseCommand(CommandTerm): This command term samples target object poses by: • Drawing (x, y, z) uniformly within configured Cartesian bounds, and • Drawing roll-pitch-yaw uniformly within configured ranges, then converting - to a quaternion (w, x, y, z). Optionally makes quaternions unique by enforcing + to a quaternion (x, y, z, w). Optionally makes quaternions unique by enforcing a positive real part. Frames: @@ -38,7 +38,7 @@ class ObjectUniformPoseCommand(CommandTerm): targets are transformed into the *world frame* using the robot root pose. Outputs: - The command buffer has shape (num_envs, 7): `(x, y, z, qw, qx, qy, qz)`. + The command buffer has shape (num_envs, 7): ``(x, y, z, qx, qy, qz, qw)``. Metrics: `position_error` and `orientation_error` are computed between the commanded @@ -71,7 +71,7 @@ def __init__(self, cfg: dex_cmd_cfgs.ObjectUniformPoseCommandCfg, env: ManagerBa self.success_vis_asset = None # create buffers - # -- commands: (x, y, z, qw, qx, qy, qz) in root frame + # -- commands: (x, y, z, qx, qy, qz, qw) in root frame self.pose_command_b = torch.zeros(self.num_envs, 7, device=self.device) self.pose_command_b[:, 3] = 1.0 self.pose_command_w = torch.zeros_like(self.pose_command_b) @@ -83,6 +83,11 @@ def __init__(self, cfg: dex_cmd_cfgs.ObjectUniformPoseCommandCfg, env: ManagerBa self.success_visualizer = VisualizationMarkers(self.cfg.success_visualizer_cfg) self.success_visualizer.set_visibility(True) + # adds (optional) cmd kind and element names for leapp export + # during export, semantic data about this command will be used to annotate the command input + self.cfg.cmd_kind = self.cfg.cmd_kind or "command/body/pose" + self.cfg.element_names = self.cfg.element_names or POSE7_ELEMENT_NAMES + def __str__(self) -> str: msg = "UniformPoseCommand:\n" msg += f"\tCommand dimension: {tuple(self.command.shape[1:])}\n" @@ -97,7 +102,7 @@ def __str__(self) -> str: def command(self) -> torch.Tensor: """The desired pose command. Shape is (num_envs, 7). - The first three elements correspond to the position, followed by the quaternion orientation in (w, x, y, z). + The first three elements correspond to the position, followed by the quaternion orientation in (x, y, z, w). """ return self.pose_command_b @@ -108,13 +113,13 @@ def command(self) -> torch.Tensor: def _update_metrics(self): # transform command from base frame to simulation world frame self.pose_command_w[:, :3], self.pose_command_w[:, 3:] = combine_frame_transforms( - wp.to_torch(self.robot.data.root_pos_w), - wp.to_torch(self.robot.data.root_quat_w), + self.robot.data.root_pos_w.torch, + self.robot.data.root_quat_w.torch, self.pose_command_b[:, :3], self.pose_command_b[:, 3:], ) # compute the error - object_root_pose_w = wp.to_torch(self.object.data.root_link_pose_w) + object_root_pose_w = self.object.data.root_link_pose_w.torch pos_error, rot_error = compute_pose_error( self.pose_command_w[:, :3], self.pose_command_w[:, 3:], @@ -129,7 +134,7 @@ def _update_metrics(self): success_id &= self.metrics["orientation_error"] < 0.5 if self.success_vis_asset is not None: self.success_visualizer.visualize( - wp.to_torch(self.success_vis_asset.data.root_pos_w), marker_indices=success_id.int() + self.success_vis_asset.data.root_pos_w.torch, marker_indices=success_id.int() ) def _resample_command(self, env_ids: Sequence[int]): @@ -176,11 +181,11 @@ def _debug_vis_callback(self, event): # -- goal pose self.goal_visualizer.visualize(self.pose_command_w[:, :3], self.pose_command_w[:, 3:]) # -- current object pose - obj_pos = wp.to_torch(self.object.data.root_pos_w) - obj_quat = wp.to_torch(self.object.data.root_quat_w) + obj_pos = self.object.data.root_pos_w.torch + obj_quat = self.object.data.root_quat_w.torch self.curr_visualizer.visualize(obj_pos, obj_quat) else: - obj_pos = wp.to_torch(self.object.data.root_pos_w) + obj_pos = self.object.data.root_pos_w.torch distance = torch.linalg.norm(self.pose_command_w[:, :3] - obj_pos, dim=1) success_id = (distance < 0.05).int() # note: since marker indices for position is 1(far) and 2(near), we can simply shift the success_id by 1. diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/dexsuite/mdp/observations.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/dexsuite/mdp/observations.py index c3f0777f6d63..fe666a7ecffe 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/dexsuite/mdp/observations.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/dexsuite/mdp/observations.py @@ -8,7 +8,6 @@ from typing import TYPE_CHECKING import torch -import warp as wp from isaaclab.managers import ManagerTermBase, SceneEntityCfg from isaaclab.utils.math import quat_apply, quat_apply_inverse, quat_inv, quat_mul, subtract_frame_transforms @@ -16,7 +15,7 @@ if TYPE_CHECKING: from isaaclab.assets import Articulation, RigidObject from isaaclab.envs import ManagerBasedRLEnv - from isaaclab.sensors import TiledCamera + from isaaclab.sensors import Camera def object_pos_b( @@ -36,9 +35,7 @@ def object_pos_b( """ robot: RigidObject = env.scene[robot_cfg.name] object: RigidObject = env.scene[object_cfg.name] - return quat_apply_inverse( - wp.to_torch(robot.data.root_quat_w), wp.to_torch(object.data.root_pos_w) - wp.to_torch(robot.data.root_pos_w) - ) + return quat_apply_inverse(robot.data.root_quat_w.torch, object.data.root_pos_w.torch - robot.data.root_pos_w.torch) def object_quat_b( @@ -58,7 +55,7 @@ def object_quat_b( """ robot: RigidObject = env.scene[robot_cfg.name] object: RigidObject = env.scene[object_cfg.name] - return quat_mul(quat_inv(wp.to_torch(robot.data.root_quat_w)), wp.to_torch(object.data.root_quat_w)) + return quat_mul(quat_inv(robot.data.root_quat_w.torch), object.data.root_quat_w.torch) def body_state_b( @@ -82,18 +79,14 @@ def body_state_b( body_asset: Articulation = env.scene[body_asset_cfg.name] base_asset: Articulation = env.scene[base_asset_cfg.name] # get world pose of bodies - body_pos_w = wp.to_torch(body_asset.data.body_pos_w)[:, body_asset_cfg.body_ids].view(-1, 3) - body_quat_w = wp.to_torch(body_asset.data.body_quat_w)[:, body_asset_cfg.body_ids].view(-1, 4) - body_lin_vel_w = wp.to_torch(body_asset.data.body_lin_vel_w)[:, body_asset_cfg.body_ids].view(-1, 3) - body_ang_vel_w = wp.to_torch(body_asset.data.body_ang_vel_w)[:, body_asset_cfg.body_ids].view(-1, 3) + body_pos_w = body_asset.data.body_pos_w.torch[:, body_asset_cfg.body_ids].view(-1, 3) + body_quat_w = body_asset.data.body_quat_w.torch[:, body_asset_cfg.body_ids].view(-1, 4) + body_lin_vel_w = body_asset.data.body_lin_vel_w.torch[:, body_asset_cfg.body_ids].view(-1, 3) + body_ang_vel_w = body_asset.data.body_ang_vel_w.torch[:, body_asset_cfg.body_ids].view(-1, 3) num_bodies = int(body_pos_w.shape[0] / env.num_envs) # get world pose of base frame - root_pos_w = ( - wp.to_torch(base_asset.data.root_link_pos_w).unsqueeze(1).repeat_interleave(num_bodies, dim=1).view(-1, 3) - ) - root_quat_w = ( - wp.to_torch(base_asset.data.root_link_quat_w).unsqueeze(1).repeat_interleave(num_bodies, dim=1).view(-1, 4) - ) + root_pos_w = base_asset.data.root_link_pos_w.torch.unsqueeze(1).repeat_interleave(num_bodies, dim=1).view(-1, 3) + root_quat_w = base_asset.data.root_link_quat_w.torch.unsqueeze(1).repeat_interleave(num_bodies, dim=1).view(-1, 4) # transform from world body pose to local body pose body_pos_b, body_quat_b = subtract_frame_transforms(root_pos_w, root_quat_w, body_pos_w, body_quat_w) body_lin_vel_b = quat_apply_inverse(root_quat_w, body_lin_vel_w) @@ -170,11 +163,11 @@ def __call__( Returns: Tensor of shape ``(num_envs, num_points, 3)`` or flattened if requested. """ - ref_pos_w = wp.to_torch(self.ref_asset.data.root_pos_w).unsqueeze(1).repeat(1, num_points, 1) - ref_quat_w = wp.to_torch(self.ref_asset.data.root_quat_w).unsqueeze(1).repeat(1, num_points, 1) + ref_pos_w = self.ref_asset.data.root_pos_w.torch.unsqueeze(1).repeat(1, num_points, 1) + ref_quat_w = self.ref_asset.data.root_quat_w.torch.unsqueeze(1).repeat(1, num_points, 1) - object_pos_w = wp.to_torch(self.object.data.root_pos_w).unsqueeze(1).repeat(1, num_points, 1) - object_quat_w = wp.to_torch(self.object.data.root_quat_w).unsqueeze(1).repeat(1, num_points, 1) + object_pos_w = self.object.data.root_pos_w.torch.unsqueeze(1).repeat(1, num_points, 1) + object_quat_w = self.object.data.root_quat_w.torch.unsqueeze(1).repeat(1, num_points, 1) # apply rotation + translation self.points_w = quat_apply(object_quat_w, self.points_local) + object_pos_w if visualize: @@ -199,12 +192,10 @@ def fingers_contact_force_b( Tensor of shape ``(num_envs, 3 * num_sensors)`` with forces stacked horizontally as ``[fx, fy, fz]`` per sensor. """ - force_w = [ - wp.to_torch(env.scene.sensors[name].data.force_matrix_w).view(env.num_envs, 3) for name in contact_sensor_names - ] + force_w = [env.scene.sensors[name].data.force_matrix_w.torch.view(env.num_envs, 3) for name in contact_sensor_names] force_w = torch.stack(force_w, dim=1) robot: Articulation = env.scene[asset_cfg.name] - root_link_quat_w = wp.to_torch(robot.data.root_link_quat_w) + root_link_quat_w = robot.data.root_link_quat_w.torch forces_b = quat_apply_inverse(root_link_quat_w.unsqueeze(1).repeat(1, force_w.shape[1], 1), force_w) return forces_b.view(env.num_envs, -1) @@ -213,7 +204,7 @@ class vision_camera(ManagerTermBase): def __init__(self, cfg, env: ManagerBasedRLEnv): super().__init__(cfg, env) sensor_cfg: SceneEntityCfg = cfg.params.get("sensor_cfg", SceneEntityCfg("tiled_camera")) - self.sensor: TiledCamera = env.scene.sensors[sensor_cfg.name] + self.sensor: Camera = env.scene.sensors[sensor_cfg.name] self.sensor_type = self.sensor.cfg.data_types[0] self.norm_fn = ( self._depth_norm diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/dexsuite/mdp/rewards.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/dexsuite/mdp/rewards.py index 2958352ded1f..8a5a013ea846 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/dexsuite/mdp/rewards.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/dexsuite/mdp/rewards.py @@ -9,7 +9,6 @@ from typing import TYPE_CHECKING import torch -import warp as wp from isaaclab.managers import ManagerTermBase, SceneEntityCfg from isaaclab.utils import math as math_utils @@ -57,8 +56,8 @@ def object_ee_distance( """ asset: RigidObject = env.scene[asset_cfg.name] obj: RigidObject = env.scene[object_cfg.name] - asset_pos = wp.to_torch(asset.data.body_pos_w)[:, asset_cfg.body_ids] - object_pos = wp.to_torch(obj.data.root_pos_w) + asset_pos = asset.data.body_pos_w.torch[:, asset_cfg.body_ids] + object_pos = obj.data.root_pos_w.torch distance = torch.linalg.norm(asset_pos - object_pos[:, None, :], dim=-1).max(dim=-1).values contact_bonus = contacts(env, contact_threshold, thumb_name, finger_names).float().clamp(0.1, 1.0) return (1 - torch.tanh(distance / std)) * contact_bonus @@ -66,7 +65,7 @@ def object_ee_distance( def _contact_force_mag(sensor: ContactSensor, num_envs: int) -> torch.Tensor: """Extract per-environment contact force magnitude from a sensor's force_matrix_w.""" - force = wp.to_torch(sensor.data.force_matrix_w).view(num_envs, 3) + force = sensor.data.force_matrix_w.torch.view(num_envs, 3) return torch.linalg.norm(force, dim=-1) @@ -133,9 +132,10 @@ def __init__(self, cfg, env: ManagerBasedRLEnv): def reset(self, env_ids: Sequence[int] | None = None): if env_ids is None: - self.succeeded[:] = False - else: - self.succeeded[env_ids] = False + env_ids = slice(None) + # Episode success = whether the success condition was met at any point this episode. + self._env.extras.setdefault("log", {})["Metrics/success_rate"] = self.succeeded[env_ids].float().mean().item() + self.succeeded[env_ids] = False def __call__( self, @@ -153,16 +153,16 @@ def __call__( obj: RigidObject = env.scene[align_asset_cfg.name] command = env.command_manager.get_command(command_name) des_pos_w, des_quat_w = combine_frame_transforms( - wp.to_torch(asset.data.root_pos_w), - wp.to_torch(asset.data.root_quat_w), + asset.data.root_pos_w.torch, + asset.data.root_quat_w.torch, command[:, :3], command[:, 3:7], ) pos_err, rot_err = compute_pose_error( des_pos_w, des_quat_w, - wp.to_torch(obj.data.root_pos_w), - wp.to_torch(obj.data.root_quat_w), + obj.data.root_pos_w.torch, + obj.data.root_quat_w.torch, ) pos_dist = torch.linalg.norm(pos_err, dim=1) contact_mask = contacts(env, contact_threshold, thumb_name, finger_names) @@ -195,11 +195,11 @@ def position_command_error_tanh( command = env.command_manager.get_command(command_name) des_pos_b = command[:, :3] des_pos_w, _ = combine_frame_transforms( - wp.to_torch(asset.data.root_pos_w), - wp.to_torch(asset.data.root_quat_w), + asset.data.root_pos_w.torch, + asset.data.root_quat_w.torch, des_pos_b, ) - distance = torch.linalg.norm(wp.to_torch(obj.data.root_pos_w) - des_pos_w, dim=1) + distance = torch.linalg.norm(obj.data.root_pos_w.torch - des_pos_w, dim=1) return (1 - torch.tanh(distance / std)) * contacts(env, contact_threshold, thumb_name, finger_names).float() @@ -219,8 +219,8 @@ def orientation_command_error_tanh( obj: RigidObject = env.scene[align_asset_cfg.name] command = env.command_manager.get_command(command_name) des_quat_b = command[:, 3:7] - root_state = wp.to_torch(asset.data.root_state_w) + root_state = asset.data.root_state_w.torch des_quat_w = math_utils.quat_mul(root_state[:, 3:7], des_quat_b) - quat_distance = math_utils.quat_error_magnitude(wp.to_torch(obj.data.root_quat_w), des_quat_w) + quat_distance = math_utils.quat_error_magnitude(obj.data.root_quat_w.torch, des_quat_w) return (1 - torch.tanh(quat_distance / std)) * contacts(env, contact_threshold, thumb_name, finger_names).float() diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/dexsuite/mdp/terminations.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/dexsuite/mdp/terminations.py index 8490847814d6..13fd1d9d3666 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/dexsuite/mdp/terminations.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/dexsuite/mdp/terminations.py @@ -14,7 +14,6 @@ from typing import TYPE_CHECKING import torch -import warp as wp from isaaclab.managers import ManagerTermBase, SceneEntityCfg, TerminationTermCfg @@ -51,7 +50,7 @@ def __call__( asset_cfg: SceneEntityCfg = SceneEntityCfg("object"), in_bound_range: dict[str, tuple[float, float]] = {}, ) -> torch.Tensor: - pos_w = wp.to_torch(self._object.data.root_pos_w) + pos_w = self._object.data.root_pos_w.torch return ((pos_w < self._lower) | (pos_w > self._upper)).any(dim=1) @@ -59,6 +58,6 @@ def abnormal_robot_state(env: ManagerBasedRLEnv, asset_cfg: SceneEntityCfg = Sce """Terminating environment when violation of velocity limits detects, this usually indicates unstable physics caused by very bad, or aggressive action""" robot: Articulation = env.scene[asset_cfg.name] - joint_vel = wp.to_torch(robot.data.joint_vel) - joint_vel_limits = wp.to_torch(robot.data.joint_vel_limits) + joint_vel = robot.data.joint_vel.torch + joint_vel_limits = robot.data.joint_vel_limits.torch return (joint_vel.abs() > (joint_vel_limits * 2)).any(dim=1) diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/inhand/mdp/commands/orientation_command.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/inhand/mdp/commands/orientation_command.py index 468ae2764743..7c6d250f2147 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/inhand/mdp/commands/orientation_command.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/inhand/mdp/commands/orientation_command.py @@ -11,11 +11,11 @@ from typing import TYPE_CHECKING import torch -import warp as wp import isaaclab.utils.math as math_utils from isaaclab.managers import CommandTerm from isaaclab.markers import VisualizationMarkers +from isaaclab.utils.leapp import POSE7_ELEMENT_NAMES if TYPE_CHECKING: from isaaclab.assets import RigidObject @@ -59,7 +59,7 @@ def __init__(self, cfg: InHandReOrientationCommandCfg, env: ManagerBasedRLEnv): # create buffers to store the command # -- command: (x, y, z) init_pos_offset = torch.tensor(cfg.init_pos_offset, dtype=torch.float, device=self.device) - self.pos_command_e = wp.to_torch(self.object.data.default_root_pose)[:, :3] + init_pos_offset + self.pos_command_e = self.object.data.default_root_pose.torch[:, :3] + init_pos_offset self.pos_command_w = self.pos_command_e + self._env.scene.env_origins # -- orientation: (x, y, z, w) self.quat_command_w = torch.zeros(self.num_envs, 4, device=self.device) @@ -74,6 +74,15 @@ def __init__(self, cfg: InHandReOrientationCommandCfg, env: ManagerBasedRLEnv): self.metrics["orientation_error"] = torch.zeros(self.num_envs, device=self.device) self.metrics["position_error"] = torch.zeros(self.num_envs, device=self.device) self.metrics["consecutive_success"] = torch.zeros(self.num_envs, device=self.device) + self.metrics["success_rate"] = torch.zeros(self.num_envs, device=self.device) + # -- per-attempt success accounting: each success-driven resample completes one attempt; + # the trailing attempt at episode end counts as one unsuccessful attempt. + self._completed_attempts = torch.zeros(self.num_envs, device=self.device) + + # adds (optional) cmd kind and element names for leapp export + # during export, semantic data about this command will be used to annotate the command input + self.cfg.cmd_kind = self.cfg.cmd_kind or "command/body/pose" + self.cfg.element_names = self.cfg.element_names or POSE7_ELEMENT_NAMES def __str__(self) -> str: msg = "InHandManipulationCommandGenerator:\n" @@ -97,17 +106,37 @@ def _update_metrics(self): # logs data # -- compute the orientation error self.metrics["orientation_error"] = math_utils.quat_error_magnitude( - wp.to_torch(self.object.data.root_quat_w), self.quat_command_w + self.object.data.root_quat_w.torch, self.quat_command_w ) # -- compute the position error self.metrics["position_error"] = torch.linalg.norm( - wp.to_torch(self.object.data.root_pos_w) - self.pos_command_w, dim=1 + self.object.data.root_pos_w.torch - self.pos_command_w, dim=1 ) # -- compute the number of consecutive successes successes = self.metrics["orientation_error"] < self.cfg.orientation_success_threshold self.metrics["consecutive_success"] += successes.float() + def reset(self, env_ids: Sequence[int] | None = None) -> dict[str, float]: + # Snapshot per-attempt success rate BEFORE the base class logs and zeros metrics. + # success_rate = completed_attempts / (completed_attempts + 1 trailing in-progress). + if env_ids is None: + env_ids = slice(None) + completed = self._completed_attempts[env_ids] + self.metrics["success_rate"][env_ids] = completed / (completed + 1.0) + extras = super().reset(env_ids) + # super().reset() invoked _resample_command for the new initial goal, which + # incremented _completed_attempts; zero it back out so the new episode starts clean. + self._completed_attempts[env_ids] = 0.0 + # Route success_rate to the unified ``Metrics/success_rate`` path (shared TensorBoard + # card across tasks); pop it from the returned dict so CommandManager does not + # additionally log it under ``Metrics//success_rate``. + self._env.extras.setdefault("log", {})["Metrics/success_rate"] = extras.pop("success_rate") + return extras + def _resample_command(self, env_ids: Sequence[int]): + # Each call corresponds to a success-driven (or initial) resample; count it as a + # completed attempt. The post-reset increment is cleared by ``reset()`` afterwards. + self._completed_attempts[env_ids] += 1.0 # sample new orientation targets rand_floats = 2.0 * torch.rand((len(env_ids), 2), device=self.device) - 1.0 # rotate randomly about x-axis and then y-axis diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/inhand/mdp/events.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/inhand/mdp/events.py index 4382e1daa08e..c118cd16a506 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/inhand/mdp/events.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/inhand/mdp/events.py @@ -10,7 +10,6 @@ from typing import TYPE_CHECKING, Literal import torch -import warp as wp from isaaclab.managers import EventTermCfg, ManagerTermBase, SceneEntityCfg from isaaclab.utils.math import sample_uniform @@ -78,11 +77,11 @@ def __init__(self, cfg: EventTermCfg, env: ManagerBasedEnv): # extract the used quantities (to enable type-hinting) self._asset: Articulation = env.scene[asset_cfg.name] - default_joint_pos = wp.to_torch(self._asset.data.default_joint_pos)[0] - default_joint_vel = wp.to_torch(self._asset.data.default_joint_vel)[0] + default_joint_pos = self._asset.data.default_joint_pos.torch[0] + default_joint_vel = self._asset.data.default_joint_vel.torch[0] # create buffers to store the joint position range - self._pos_ranges = wp.to_torch(self._asset.data.soft_joint_pos_limits)[0].clone() + self._pos_ranges = self._asset.data.soft_joint_pos_limits.torch[0].clone() # parse joint position ranges pos_joint_ids = [] for joint_name, joint_range in cfg.params["position_range"].items(): @@ -114,7 +113,7 @@ def __init__(self, cfg: EventTermCfg, env: ManagerBasedEnv): self._pos_ranges = self._pos_ranges[self._pos_joint_ids] # create buffers to store the joint velocity range - soft_joint_vel_limits_torch = wp.to_torch(self._asset.data.soft_joint_vel_limits)[0] + soft_joint_vel_limits_torch = self._asset.data.soft_joint_vel_limits.torch[0] self._vel_ranges = torch.stack([-soft_joint_vel_limits_torch, soft_joint_vel_limits_torch], dim=1) # parse joint velocity ranges vel_joint_ids = [] @@ -157,8 +156,8 @@ def __call__( operation: Literal["abs", "scale"] = "abs", ): # get default joint state - joint_pos = wp.to_torch(self._asset.data.default_joint_pos)[env_ids].clone() - joint_vel = wp.to_torch(self._asset.data.default_joint_vel)[env_ids].clone() + joint_pos = self._asset.data.default_joint_pos.torch[env_ids].clone() + joint_vel = self._asset.data.default_joint_vel.torch[env_ids].clone() # sample random joint positions for each joint if len(self._pos_joint_ids) > 0: @@ -167,7 +166,7 @@ def __call__( self._pos_ranges[:, 0], self._pos_ranges[:, 1], joint_pos_shape, device=joint_pos.device ) # clip the joint positions to the joint limits - joint_pos_limits = wp.to_torch(self._asset.data.soft_joint_pos_limits)[0, self._pos_joint_ids] + joint_pos_limits = self._asset.data.soft_joint_pos_limits.torch[0, self._pos_joint_ids] joint_pos = joint_pos.clamp(joint_pos_limits[:, 0], joint_pos_limits[:, 1]) # sample random joint velocities for each joint @@ -177,7 +176,7 @@ def __call__( self._vel_ranges[:, 0], self._vel_ranges[:, 1], joint_vel_shape, device=joint_vel.device ) # clip the joint velocities to the joint limits - joint_vel_limits = wp.to_torch(self._asset.data.soft_joint_vel_limits)[0, self._vel_joint_ids] + joint_vel_limits = self._asset.data.soft_joint_vel_limits.torch[0, self._vel_joint_ids] joint_vel = joint_vel.clamp(-joint_vel_limits, joint_vel_limits) # set into the physics simulation diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/inhand/mdp/observations.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/inhand/mdp/observations.py index 61f6d2543d39..57620602b6fd 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/inhand/mdp/observations.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/inhand/mdp/observations.py @@ -10,7 +10,6 @@ from typing import TYPE_CHECKING import torch -import warp as wp import isaaclab.utils.math as math_utils from isaaclab.managers import SceneEntityCfg @@ -35,7 +34,7 @@ def goal_quat_diff( # obtain the orientations goal_quat_w = command_term.command[:, 3:7] - asset_quat_w = wp.to_torch(asset.data.root_quat_w) + asset_quat_w = asset.data.root_quat_w.torch # compute quaternion difference quat = math_utils.quat_mul(asset_quat_w, math_utils.quat_conjugate(goal_quat_w)) diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/inhand/mdp/rewards.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/inhand/mdp/rewards.py index da02a20c5aa3..f89b2f613b51 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/inhand/mdp/rewards.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/inhand/mdp/rewards.py @@ -10,7 +10,6 @@ from typing import TYPE_CHECKING import torch -import warp as wp import isaaclab.utils.math as math_utils from isaaclab.managers import SceneEntityCfg @@ -44,7 +43,7 @@ def success_bonus( # obtain the threshold for the orientation error threshold = command_term.cfg.orientation_success_threshold # calculate the orientation error - dtheta = math_utils.quat_error_magnitude(wp.to_torch(asset.data.root_quat_w), goal_quat_w) + dtheta = math_utils.quat_error_magnitude(asset.data.root_quat_w.torch, goal_quat_w) return dtheta <= threshold @@ -68,7 +67,7 @@ def track_pos_l2( # obtain the goal position goal_pos_e = command_term.command[:, 0:3] # obtain the object position in the environment frame - object_pos_e = wp.to_torch(asset.data.root_pos_w) - env.scene.env_origins + object_pos_e = asset.data.root_pos_w.torch - env.scene.env_origins return torch.linalg.norm(goal_pos_e - object_pos_e, ord=2, dim=-1) @@ -96,6 +95,6 @@ def track_orientation_inv_l2( # obtain the goal orientation goal_quat_w = command_term.command[:, 3:7] # calculate the orientation error - dtheta = math_utils.quat_error_magnitude(wp.to_torch(asset.data.root_quat_w), goal_quat_w) + dtheta = math_utils.quat_error_magnitude(asset.data.root_quat_w.torch, goal_quat_w) return 1.0 / (dtheta + rot_eps) diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/inhand/mdp/terminations.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/inhand/mdp/terminations.py index 895e09581bd3..c2c7a02f6797 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/inhand/mdp/terminations.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/inhand/mdp/terminations.py @@ -10,7 +10,6 @@ from typing import TYPE_CHECKING import torch -import warp as wp from isaaclab.managers import SceneEntityCfg @@ -55,7 +54,7 @@ def object_away_from_goal( asset = env.scene[object_cfg.name] # object pos - asset_pos_e = wp.to_torch(asset.data.root_pos_w) - env.scene.env_origins + asset_pos_e = asset.data.root_pos_w.torch - env.scene.env_origins goal_pos_e = command_term.command[:, :3] return torch.linalg.norm(asset_pos_e - goal_pos_e, ord=2, dim=1) > threshold @@ -83,6 +82,6 @@ def object_away_from_robot( object = env.scene[object_cfg.name] # compute distance - dist = torch.linalg.norm(wp.to_torch(robot.data.root_pos_w) - wp.to_torch(object.data.root_pos_w), dim=1) + dist = torch.linalg.norm(robot.data.root_pos_w.torch - object.data.root_pos_w.torch, dim=1) return dist > threshold diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/lift/lift_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/lift/lift_env_cfg.py index b54b6114ee77..e347a0840a33 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/lift/lift_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/lift/lift_env_cfg.py @@ -144,7 +144,7 @@ class RewardsCfg: object_goal_tracking = RewTerm( func=mdp.object_goal_distance, - params={"std": 0.3, "minimal_height": 0.04, "command_name": "object_pose"}, + params={"std": 0.3, "minimal_height": 0.04, "command_name": "object_pose", "success_threshold": 0.05}, weight=16.0, ) diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/lift/mdp/observations.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/lift/mdp/observations.py index 1ccf60969814..06659683d770 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/lift/mdp/observations.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/lift/mdp/observations.py @@ -8,7 +8,6 @@ from typing import TYPE_CHECKING import torch -import warp as wp from isaaclab.managers import SceneEntityCfg from isaaclab.utils.math import subtract_frame_transforms @@ -26,8 +25,6 @@ def object_position_in_robot_root_frame( """The position of the object in the robot's root frame.""" robot: RigidObject = env.scene[robot_cfg.name] object: RigidObject = env.scene[object_cfg.name] - object_pos_w = wp.to_torch(object.data.root_pos_w)[:, :3] - object_pos_b, _ = subtract_frame_transforms( - wp.to_torch(robot.data.root_pos_w), wp.to_torch(robot.data.root_quat_w), object_pos_w - ) + object_pos_w = object.data.root_pos_w.torch[:, :3] + object_pos_b, _ = subtract_frame_transforms(robot.data.root_pos_w.torch, robot.data.root_quat_w.torch, object_pos_w) return object_pos_b diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/lift/mdp/rewards.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/lift/mdp/rewards.py index 2f1ccaf0287e..77517708c053 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/lift/mdp/rewards.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/lift/mdp/rewards.py @@ -8,9 +8,8 @@ from typing import TYPE_CHECKING import torch -import warp as wp -from isaaclab.managers import SceneEntityCfg +from isaaclab.managers import ManagerTermBase, RewardTermCfg, SceneEntityCfg from isaaclab.utils.math import combine_frame_transforms if TYPE_CHECKING: @@ -24,7 +23,7 @@ def object_is_lifted( ) -> torch.Tensor: """Reward the agent for lifting the object above the minimal height.""" object: RigidObject = env.scene[object_cfg.name] - return torch.where(wp.to_torch(object.data.root_pos_w)[:, 2] > minimal_height, 1.0, 0.0) + return torch.where(object.data.root_pos_w.torch[:, 2] > minimal_height, 1.0, 0.0) def object_ee_distance( @@ -38,35 +37,56 @@ def object_ee_distance( object: RigidObject = env.scene[object_cfg.name] ee_frame: FrameTransformer = env.scene[ee_frame_cfg.name] # Target object position: (num_envs, 3) - cube_pos_w = wp.to_torch(object.data.root_pos_w) + cube_pos_w = object.data.root_pos_w.torch # End-effector position: (num_envs, 3) - ee_w = wp.to_torch(ee_frame.data.target_pos_w)[..., 0, :] + ee_w = ee_frame.data.target_pos_w.torch[..., 0, :] # Distance of the end-effector to the object: (num_envs,) object_ee_distance = torch.linalg.norm(cube_pos_w - ee_w, dim=1) return 1 - torch.tanh(object_ee_distance / std) -def object_goal_distance( - env: ManagerBasedRLEnv, - std: float, - minimal_height: float, - command_name: str, - robot_cfg: SceneEntityCfg = SceneEntityCfg("robot"), - object_cfg: SceneEntityCfg = SceneEntityCfg("object"), -) -> torch.Tensor: - """Reward the agent for tracking the goal pose using tanh-kernel.""" - # extract the used quantities (to enable type-hinting) - robot: RigidObject = env.scene[robot_cfg.name] - object: RigidObject = env.scene[object_cfg.name] - command = env.command_manager.get_command(command_name) - # compute the desired position in the world frame - des_pos_b = command[:, :3] - des_pos_w, _ = combine_frame_transforms( - wp.to_torch(robot.data.root_pos_w), wp.to_torch(robot.data.root_quat_w), des_pos_b - ) - # distance of the end-effector to the object: (num_envs,) - object_pos_w = wp.to_torch(object.data.root_pos_w) - distance = torch.linalg.norm(des_pos_w - object_pos_w, dim=1) - # rewarded if the object is lifted above the threshold - return (object_pos_w[:, 2] > minimal_height) * (1 - torch.tanh(distance / std)) +class object_goal_distance(ManagerTermBase): + """Reward the agent for tracking the object-to-goal pose using a tanh kernel. + + If ``success_threshold`` is provided in the term params, this also tracks per-episode + success (sticky binary: object ever within ``success_threshold`` of the commanded goal + while lifted above ``minimal_height``) and logs the mean across environments under + ``Metrics/success_rate`` on reset. + """ + + def __init__(self, cfg: RewardTermCfg, env: ManagerBasedRLEnv): + super().__init__(cfg, env) + self._track_success = cfg.params.get("success_threshold") is not None + if self._track_success: + self._succeeded = torch.zeros(env.num_envs, dtype=torch.bool, device=env.device) + + def reset(self, env_ids: torch.Tensor): + if self._track_success: + self._env.extras.setdefault("log", {})["Metrics/success_rate"] = ( + self._succeeded[env_ids].float().mean().item() + ) + self._succeeded[env_ids] = False + + def __call__( + self, + env: ManagerBasedRLEnv, + std: float, + minimal_height: float, + command_name: str, + robot_cfg: SceneEntityCfg = SceneEntityCfg("robot"), + object_cfg: SceneEntityCfg = SceneEntityCfg("object"), + success_threshold: float | None = None, + ) -> torch.Tensor: + robot: RigidObject = env.scene[robot_cfg.name] + obj: RigidObject = env.scene[object_cfg.name] + command = env.command_manager.get_command(command_name) + des_pos_w, _ = combine_frame_transforms( + robot.data.root_pos_w.torch, robot.data.root_quat_w.torch, command[:, :3] + ) + object_pos_w = obj.data.root_pos_w.torch + distance = torch.linalg.norm(des_pos_w - object_pos_w, dim=1) + is_lifted = object_pos_w[:, 2] > minimal_height + if success_threshold is not None: + self._succeeded |= is_lifted & (distance < success_threshold) + return is_lifted.float() * (1 - torch.tanh(distance / std)) diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/lift/mdp/terminations.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/lift/mdp/terminations.py index 0f1a392fe5a0..5342ab669758 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/lift/mdp/terminations.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/lift/mdp/terminations.py @@ -14,7 +14,6 @@ from typing import TYPE_CHECKING import torch -import warp as wp from isaaclab.managers import SceneEntityCfg from isaaclab.utils.math import combine_frame_transforms @@ -48,11 +47,11 @@ def object_reached_goal( # compute the desired position in the world frame des_pos_b = command[:, :3] # Convert to torch for combine_frame_transforms (robot data may be Warp arrays under Newton) - root_pos_w = wp.to_torch(robot.data.root_pos_w) - root_quat_w = wp.to_torch(robot.data.root_quat_w) + root_pos_w = robot.data.root_pos_w.torch + root_quat_w = robot.data.root_quat_w.torch des_pos_w, _ = combine_frame_transforms(root_pos_w, root_quat_w, des_pos_b) # distance of the end-effector to the object: (num_envs,) - object_pos_w = wp.to_torch(object.data.root_pos_w) + object_pos_w = object.data.root_pos_w.torch distance = torch.linalg.norm(des_pos_w - object_pos_w[:, :3], dim=1) # rewarded if the object is lifted above the threshold diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/pick_place/exhaustpipe_gr1t2_base_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/pick_place/exhaustpipe_gr1t2_base_env_cfg.py index f1254479886b..98c5aca681d8 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/pick_place/exhaustpipe_gr1t2_base_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/pick_place/exhaustpipe_gr1t2_base_env_cfg.py @@ -7,8 +7,6 @@ import tempfile from dataclasses import MISSING -import torch - try: from isaaclab_teleop import XrCfg @@ -275,48 +273,44 @@ class ExhaustPipeGR1T2BaseEnvCfg(ManagerBasedRLEnvCfg): # Idle action to hold robot in default pose # Action format: [left arm pos (3), left arm quat (4), right arm pos (3), # right arm quat (4), left/right hand joint pos (22)] - idle_action = torch.tensor( - [ - [ - -0.2909, - 0.2778, - 1.1247, - 0.5747, - -0.4160, - 0.4699, - 0.5253, - 0.22878, - 0.2536, - 1.0953, - 0.5, - -0.5, - 0.5, - 0.5, - 0.0, - 0.0, - 0.0, - 0.0, - 0.0, - 0.0, - 0.0, - 0.0, - 0.0, - 0.0, - 0.0, - 0.0, - 0.0, - 0.0, - 0.0, - 0.0, - 0.0, - 0.0, - 0.0, - 0.0, - 0.0, - 0.0, - ] - ] - ) + idle_action = [ + -0.2909, + 0.2778, + 1.1247, + 0.5747, + -0.4160, + 0.4699, + 0.5253, + 0.22878, + 0.2536, + 1.0953, + 0.5, + -0.5, + 0.5, + 0.5, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + ] def __post_init__(self): """Post initialization.""" diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/pick_place/mdp/observations.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/pick_place/mdp/observations.py index 87c699bcec56..c3e030b33ec0 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/pick_place/mdp/observations.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/pick_place/mdp/observations.py @@ -8,7 +8,6 @@ from typing import TYPE_CHECKING import torch -import warp as wp if TYPE_CHECKING: from isaaclab.envs import ManagerBasedRLEnv @@ -27,14 +26,14 @@ def object_obs( right_eef_to object, """ - body_pos_w = wp.to_torch(env.scene["robot"].data.body_pos_w) + body_pos_w = env.scene["robot"].data.body_pos_w.torch left_eef_idx = env.scene["robot"].data.body_names.index(left_eef_link_name) right_eef_idx = env.scene["robot"].data.body_names.index(right_eef_link_name) left_eef_pos = body_pos_w[:, left_eef_idx] - env.scene.env_origins right_eef_pos = body_pos_w[:, right_eef_idx] - env.scene.env_origins - object_pos = wp.to_torch(env.scene["object"].data.root_pos_w) - env.scene.env_origins - object_quat = wp.to_torch(env.scene["object"].data.root_quat_w) + object_pos = env.scene["object"].data.root_pos_w.torch - env.scene.env_origins + object_quat = env.scene["object"].data.root_quat_w.torch left_eef_to_object = object_pos - left_eef_pos right_eef_to_object = object_pos - right_eef_pos @@ -51,7 +50,7 @@ def object_obs( def get_eef_pos(env: ManagerBasedRLEnv, link_name: str) -> torch.Tensor: - body_pos_w = wp.to_torch(env.scene["robot"].data.body_pos_w) + body_pos_w = env.scene["robot"].data.body_pos_w.torch left_eef_idx = env.scene["robot"].data.body_names.index(link_name) left_eef_pos = body_pos_w[:, left_eef_idx] - env.scene.env_origins @@ -59,7 +58,7 @@ def get_eef_pos(env: ManagerBasedRLEnv, link_name: str) -> torch.Tensor: def get_eef_quat(env: ManagerBasedRLEnv, link_name: str) -> torch.Tensor: - body_quat_w = wp.to_torch(env.scene["robot"].data.body_quat_w) + body_quat_w = env.scene["robot"].data.body_quat_w.torch left_eef_idx = env.scene["robot"].data.body_names.index(link_name) left_eef_quat = body_quat_w[:, left_eef_idx] @@ -73,7 +72,7 @@ def get_robot_joint_state( # hand_joint_names is a list of regex, use find_joints indexes, _ = env.scene["robot"].find_joints(joint_names) indexes = torch.tensor(indexes, dtype=torch.long) - robot_joint_states = wp.to_torch(env.scene["robot"].data.joint_pos)[:, indexes] + robot_joint_states = env.scene["robot"].data.joint_pos.torch[:, indexes] return robot_joint_states @@ -81,7 +80,7 @@ def get_robot_joint_state( def get_all_robot_link_state( env: ManagerBasedRLEnv, ) -> torch.Tensor: - body_pos_w = wp.to_torch(env.scene["robot"].data.body_link_state_w)[:, :, :] + body_pos_w = env.scene["robot"].data.body_link_state_w.torch[:, :, :] all_robot_link_pos = body_pos_w return all_robot_link_pos diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/pick_place/mdp/pick_place_events.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/pick_place/mdp/pick_place_events.py index e091087bc8af..f1b4bd15de97 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/pick_place/mdp/pick_place_events.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/pick_place/mdp/pick_place_events.py @@ -8,7 +8,6 @@ from typing import TYPE_CHECKING import torch -import warp as wp import isaaclab.utils.math as math_utils from isaaclab.managers import SceneEntityCfg @@ -45,10 +44,10 @@ def reset_object_poses_nut_pour( sorting_scale = env.scene[sorting_scale_cfg.name] # get default root state - sorting_beaker_root_poses = wp.to_torch(sorting_beaker.data.default_root_pose)[env_ids].clone() - factory_nut_root_poses = wp.to_torch(factory_nut.data.default_root_pose)[env_ids].clone() - sorting_bowl_root_poses = wp.to_torch(sorting_bowl.data.default_root_pose)[env_ids].clone() - sorting_scale_root_poses = wp.to_torch(sorting_scale.data.default_root_pose)[env_ids].clone() + sorting_beaker_root_poses = sorting_beaker.data.default_root_pose.torch[env_ids].clone() + factory_nut_root_poses = factory_nut.data.default_root_pose.torch[env_ids].clone() + sorting_bowl_root_poses = sorting_bowl.data.default_root_pose.torch[env_ids].clone() + sorting_scale_root_poses = sorting_scale.data.default_root_pose.torch[env_ids].clone() # get pose ranges range_list = [pose_range.get(key, (0.0, 0.0)) for key in ["x", "y", "z", "roll", "pitch", "yaw"]] diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/pick_place/mdp/terminations.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/pick_place/mdp/terminations.py index 6c1f9161042d..7ff4732f2640 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/pick_place/mdp/terminations.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/pick_place/mdp/terminations.py @@ -14,7 +14,6 @@ from typing import TYPE_CHECKING import torch -import warp as wp from isaaclab.managers import SceneEntityCfg @@ -64,13 +63,13 @@ def task_done_pick_place( object: RigidObject = env.scene[object_cfg.name] # Extract wheel position relative to environment origin - object_x = wp.to_torch(object.data.root_pos_w)[:, 0] - env.scene.env_origins[:, 0] - object_y = wp.to_torch(object.data.root_pos_w)[:, 1] - env.scene.env_origins[:, 1] - object_height = wp.to_torch(object.data.root_pos_w)[:, 2] - env.scene.env_origins[:, 2] - object_vel = torch.abs(wp.to_torch(object.data.root_vel_w)) + object_x = object.data.root_pos_w.torch[:, 0] - env.scene.env_origins[:, 0] + object_y = object.data.root_pos_w.torch[:, 1] - env.scene.env_origins[:, 1] + object_height = object.data.root_pos_w.torch[:, 2] - env.scene.env_origins[:, 2] + object_vel = torch.abs(object.data.root_vel_w.torch) # Get right wrist position relative to environment origin - robot_body_pos_w = wp.to_torch(env.scene["robot"].data.body_pos_w) + robot_body_pos_w = env.scene["robot"].data.body_pos_w.torch right_eef_idx = env.scene["robot"].data.body_names.index(task_link_name) right_wrist_x = robot_body_pos_w[:, right_eef_idx, 0] - env.scene.env_origins[:, 0] @@ -140,11 +139,11 @@ def task_done_nut_pour( sorting_bin: RigidObject = env.scene[sorting_bin_cfg.name] # Get positions relative to environment origin - scale_pos = wp.to_torch(sorting_scale.data.root_pos_w) - env.scene.env_origins - bowl_pos = wp.to_torch(sorting_bowl.data.root_pos_w) - env.scene.env_origins - sorting_beaker_pos = wp.to_torch(sorting_beaker.data.root_pos_w) - env.scene.env_origins - nut_pos = wp.to_torch(factory_nut.data.root_pos_w) - env.scene.env_origins - bin_pos = wp.to_torch(sorting_bin.data.root_pos_w) - env.scene.env_origins + scale_pos = sorting_scale.data.root_pos_w.torch - env.scene.env_origins + bowl_pos = sorting_bowl.data.root_pos_w.torch - env.scene.env_origins + sorting_beaker_pos = sorting_beaker.data.root_pos_w.torch - env.scene.env_origins + nut_pos = factory_nut.data.root_pos_w.torch - env.scene.env_origins + bin_pos = sorting_bin.data.root_pos_w.torch - env.scene.env_origins # nut to bowl nut_to_bowl_x = torch.abs(nut_pos[:, 0] - bowl_pos[:, 0]) @@ -207,8 +206,8 @@ def task_done_exhaust_pipe( blue_sorting_bin: RigidObject = env.scene[blue_sorting_bin_cfg.name] # Get positions relative to environment origin - blue_exhaust_pipe_pos = wp.to_torch(blue_exhaust_pipe.data.root_pos_w) - env.scene.env_origins - blue_sorting_bin_pos = wp.to_torch(blue_sorting_bin.data.root_pos_w) - env.scene.env_origins + blue_exhaust_pipe_pos = blue_exhaust_pipe.data.root_pos_w.torch - env.scene.env_origins + blue_sorting_bin_pos = blue_sorting_bin.data.root_pos_w.torch - env.scene.env_origins # blue exhaust to bin blue_exhaust_to_bin_x = torch.abs(blue_exhaust_pipe_pos[:, 0] - blue_sorting_bin_pos[:, 0]) diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/pick_place/nutpour_gr1t2_base_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/pick_place/nutpour_gr1t2_base_env_cfg.py index 1fb2250b542a..ea2980d53b0a 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/pick_place/nutpour_gr1t2_base_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/pick_place/nutpour_gr1t2_base_env_cfg.py @@ -7,8 +7,6 @@ import tempfile from dataclasses import MISSING -import torch - try: from isaaclab_teleop import XrCfg @@ -310,48 +308,44 @@ class NutPourGR1T2BaseEnvCfg(ManagerBasedRLEnvCfg): # Idle action to hold robot in default pose # Action format: [left arm pos (3), left arm quat (4), right arm pos (3), # right arm quat (4), left/right hand joint pos (22)] - idle_action = torch.tensor( - [ - [ - -0.22878, - 0.2536, - 1.0953, - 0.5, - -0.5, - 0.5, - 0.5, - 0.22878, - 0.2536, - 1.0953, - 0.5, - -0.5, - 0.5, - 0.5, - 0.0, - 0.0, - 0.0, - 0.0, - 0.0, - 0.0, - 0.0, - 0.0, - 0.0, - 0.0, - 0.0, - 0.0, - 0.0, - 0.0, - 0.0, - 0.0, - 0.0, - 0.0, - 0.0, - 0.0, - 0.0, - 0.0, - ] - ] - ) + idle_action = [ + -0.22878, + 0.2536, + 1.0953, + 0.5, + -0.5, + 0.5, + 0.5, + 0.22878, + 0.2536, + 1.0953, + 0.5, + -0.5, + 0.5, + 0.5, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + ] def __post_init__(self): """Post initialization.""" diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/pick_place/pickplace_gr1t2_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/pick_place/pickplace_gr1t2_env_cfg.py index bd224e3ecfa1..8c95df1041eb 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/pick_place/pickplace_gr1t2_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/pick_place/pickplace_gr1t2_env_cfg.py @@ -6,8 +6,6 @@ import os import tempfile -import torch - import isaaclab.envs.mdp as base_mdp import isaaclab.sim as sim_utils from isaaclab.assets import ArticulationCfg, AssetBaseCfg, RigidObjectCfg @@ -547,46 +545,44 @@ class PickPlaceGR1T2EnvCfg(ManagerBasedRLEnvCfg): # Idle action to hold robot in default pose # Action format: [left arm pos (3), left arm quat (4), right arm pos (3), right arm quat (4), # left hand joint pos (11), right hand joint pos (11)] - idle_action = torch.tensor( - [ - -0.22878, - 0.2536, - 1.0953, - 0.5, - -0.5, - 0.5, - 0.5, - 0.22878, - 0.2536, - 1.0953, - 0.5, - -0.5, - 0.5, - 0.5, - 0.0, - 0.0, - 0.0, - 0.0, - 0.0, - 0.0, - 0.0, - 0.0, - 0.0, - 0.0, - 0.0, - 0.0, - 0.0, - 0.0, - 0.0, - 0.0, - 0.0, - 0.0, - 0.0, - 0.0, - 0.0, - 0.0, - ] - ) + idle_action = [ + -0.22878, + 0.2536, + 1.0953, + 0.5, + -0.5, + 0.5, + 0.5, + 0.22878, + 0.2536, + 1.0953, + 0.5, + -0.5, + 0.5, + 0.5, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + ] def __post_init__(self): """Post initialization.""" @@ -611,3 +607,46 @@ def __post_init__(self): sim_device=self.sim.device, xr_cfg=self.xr, ) + + # Legacy teleop devices are built lazily via __getattr__ to avoid + # importing runtime-only modules (carb, pxr) at config-load time. + del self.teleop_devices + + def __getattr__(self, name: str): + if name == "teleop_devices": + from isaaclab.devices.device_base import DevicesCfg # noqa: PLC0415 + from isaaclab.devices.openxr import ManusViveCfg, OpenXRDeviceCfg # noqa: PLC0415 + from isaaclab.devices.openxr.retargeters.humanoid.fourier.gr1t2_retargeter import ( # noqa: PLC0415 + GR1T2RetargeterCfg, + ) + + self.teleop_devices = DevicesCfg( + devices={ + "handtracking": OpenXRDeviceCfg( + retargeters=[ + GR1T2RetargeterCfg( + enable_visualization=True, + num_open_xr_hand_joints=2 * 26, + sim_device=self.sim.device, + hand_joint_names=self.actions.upper_body_ik.hand_joint_names, + ), + ], + sim_device=self.sim.device, + xr_cfg=self.xr, + ), + "manusvive": ManusViveCfg( + retargeters=[ + GR1T2RetargeterCfg( + enable_visualization=True, + num_open_xr_hand_joints=2 * 26, + sim_device=self.sim.device, + hand_joint_names=self.actions.upper_body_ik.hand_joint_names, + ), + ], + sim_device=self.sim.device, + xr_cfg=self.xr, + ), + } + ) + return self.teleop_devices + raise AttributeError(f"'{type(self).__name__}' object has no attribute '{name}'") diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/pick_place/pickplace_unitree_g1_inspire_hand_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/pick_place/pickplace_unitree_g1_inspire_hand_env_cfg.py index f302ad22dd20..e223e3649894 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/pick_place/pickplace_unitree_g1_inspire_hand_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/pick_place/pickplace_unitree_g1_inspire_hand_env_cfg.py @@ -5,7 +5,6 @@ import os import tempfile -import torch from isaaclab_physx.physics import PhysxCfg from isaaclab_teleop.isaac_teleop_cfg import IsaacTeleopCfg from isaaclab_teleop.xr_cfg import XrCfg @@ -534,49 +533,47 @@ class PickPlaceG1InspireFTPEnvCfg(ManagerBasedRLEnvCfg): # Idle action to hold robot in default pose # Action format: [left arm pos (3), left arm quat (4), right arm pos (3), right arm quat (4), # left hand joint pos (12), right hand joint pos (12)] - idle_action = torch.tensor( - [ - # 14 hand joints for EEF control - -0.1487, - 0.2038, - 1.0952, - 0.0, - 0.0, - 0.707, - 0.707, - 0.1487, - 0.2038, - 1.0952, - 0.0, - 0.0, - 0.707, - 0.707, - 0.0, - 0.0, - 0.0, - 0.0, - 0.0, - 0.0, - 0.0, - 0.0, - 0.0, - 0.0, - 0.0, - 0.0, - 0.0, - 0.0, - 0.0, - 0.0, - 0.0, - 0.0, - 0.0, - 0.0, - 0.0, - 0.0, - 0.0, - 0.0, - ] - ) + idle_action = [ + # 14 hand joints for EEF control + -0.1487, + 0.2038, + 1.0952, + 0.0, + 0.0, + 0.707, + 0.707, + 0.1487, + 0.2038, + 1.0952, + 0.0, + 0.0, + 0.707, + 0.707, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + ] def __post_init__(self): """Post initialization.""" diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/place/mdp/observations.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/place/mdp/observations.py index 70c4e9391ad1..0c144db467eb 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/place/mdp/observations.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/place/mdp/observations.py @@ -28,13 +28,13 @@ def object_poses_in_base_frame( """The pose of the object in the robot base frame.""" object: RigidObject = env.scene[object_cfg.name] - pos_object_world = wp.to_torch(object.data.root_pos_w) - quat_object_world = wp.to_torch(object.data.root_quat_w) + pos_object_world = object.data.root_pos_w.torch + quat_object_world = object.data.root_quat_w.torch """The position of the robot in the world frame.""" robot: Articulation = env.scene[robot_cfg.name] - root_pos_w = wp.to_torch(robot.data.root_pos_w) - root_quat_w = wp.to_torch(robot.data.root_quat_w) + root_pos_w = robot.data.root_pos_w.torch + root_quat_w = robot.data.root_quat_w.torch pos_object_base, quat_object_base = math_utils.subtract_frame_transforms( root_pos_w, root_quat_w, pos_object_world, quat_object_world @@ -65,14 +65,12 @@ def object_grasped( ee_frame: FrameTransformer = env.scene[ee_frame_cfg.name] object: RigidObject = env.scene[object_cfg.name] - object_pos = wp.to_torch(object.data.root_pos_w) - end_effector_pos = wp.to_torch(ee_frame.data.target_pos_w)[:, 0, :] + object_pos = object.data.root_pos_w.torch + end_effector_pos = ee_frame.data.target_pos_w.torch[:, 0, :] pose_diff = torch.linalg.vector_norm(object_pos - end_effector_pos, dim=1) if "contact_grasp" in env.scene.keys() and env.scene["contact_grasp"] is not None: - contact_force_grasp = wp.to_torch( - env.scene["contact_grasp"].data.net_forces_w - ) # shape:(N, 2, 3) for two fingers + contact_force_grasp = env.scene["contact_grasp"].data.net_forces_w.torch # shape:(N, 2, 3) for two fingers contact_force_norm = torch.linalg.vector_norm( contact_force_grasp, dim=2 ) # shape:(N, 2) - force magnitude per finger @@ -84,9 +82,9 @@ def object_grasped( f"contact_grasp_{object_cfg.name}" in env.scene.keys() and env.scene[f"contact_grasp_{object_cfg.name}"] is not None ): - contact_force_object = wp.to_torch( - env.scene[f"contact_grasp_{object_cfg.name}"].data.net_forces_w - ) # shape:(N, 2, 3) for two fingers + contact_force_object = env.scene[ + f"contact_grasp_{object_cfg.name}" + ].data.net_forces_w.torch # shape:(N, 2, 3) for two fingers contact_force_norm = torch.linalg.vector_norm( contact_force_object, dim=2 ) # shape:(N, 2) - force magnitude per finger @@ -108,16 +106,12 @@ def object_grasped( gripper_joint_ids, _ = robot.find_joints(env.cfg.gripper_joint_names) grasped = torch.logical_and( grasped, - torch.abs( - torch.abs(wp.to_torch(robot.data.joint_pos)[:, gripper_joint_ids[0]]) - env.cfg.gripper_open_val - ) + torch.abs(torch.abs(robot.data.joint_pos.torch[:, gripper_joint_ids[0]]) - env.cfg.gripper_open_val) > env.cfg.gripper_threshold, ) grasped = torch.logical_and( grasped, - torch.abs( - torch.abs(wp.to_torch(robot.data.joint_pos)[:, gripper_joint_ids[1]]) - env.cfg.gripper_open_val - ) + torch.abs(torch.abs(robot.data.joint_pos.torch[:, gripper_joint_ids[1]]) - env.cfg.gripper_open_val) > env.cfg.gripper_threshold, ) else: diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/place/mdp/terminations.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/place/mdp/terminations.py index 139617d3050f..11368e935181 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/place/mdp/terminations.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/place/mdp/terminations.py @@ -37,9 +37,7 @@ def object_placed_upright( object: RigidObject = env.scene[object_cfg.name] # Compute mug euler angles of X, Y axis, to check if it is placed upright - object_euler_x, object_euler_y, _ = math_utils.euler_xyz_from_quat( - wp.to_torch(object.data.root_quat_w) - ) # (N,4) [0, 2*pi] + object_euler_x, object_euler_y, _ = math_utils.euler_xyz_from_quat(object.data.root_quat_w.torch) # (N,4) [0, 2*pi] object_euler_x_err = torch.abs(math_utils.wrap_to_pi(object_euler_x)) # (N,) object_euler_y_err = torch.abs(math_utils.wrap_to_pi(object_euler_y)) # (N,) @@ -47,7 +45,7 @@ def object_placed_upright( success = torch.logical_and(object_euler_x_err < euler_xy_threshold, object_euler_y_err < euler_xy_threshold) # Check if current mug height is greater than target height - height_success = wp.to_torch(object.data.root_pos_w)[:, 2] > target_height + height_success = object.data.root_pos_w.torch[:, 2] > target_height success = torch.logical_and(height_success, success) @@ -62,16 +60,12 @@ def object_placed_upright( gripper_joint_ids, _ = robot.find_joints(env.cfg.gripper_joint_names) success = torch.logical_and( success, - torch.abs( - torch.abs(wp.to_torch(robot.data.joint_pos)[:, gripper_joint_ids[0]]) - env.cfg.gripper_open_val - ) + torch.abs(torch.abs(robot.data.joint_pos.torch[:, gripper_joint_ids[0]]) - env.cfg.gripper_open_val) < env.cfg.gripper_threshold, ) success = torch.logical_and( success, - torch.abs( - torch.abs(wp.to_torch(robot.data.joint_pos)[:, gripper_joint_ids[1]]) - env.cfg.gripper_open_val - ) + torch.abs(torch.abs(robot.data.joint_pos.torch[:, gripper_joint_ids[1]]) - env.cfg.gripper_open_val) < env.cfg.gripper_threshold, ) else: @@ -96,7 +90,7 @@ def object_a_is_into_b( object_b: RigidObject = env.scene[object_b_cfg.name] # check object a is into object b - pos_diff = wp.to_torch(object_a.data.root_pos_w) - wp.to_torch(object_b.data.root_pos_w) + pos_diff = object_a.data.root_pos_w.torch - object_b.data.root_pos_w.torch height_dist = torch.linalg.vector_norm(pos_diff[:, 2:], dim=1) xy_dist = torch.linalg.vector_norm(pos_diff[:, :2], dim=1) @@ -116,16 +110,12 @@ def object_a_is_into_b( success = torch.logical_and( success, - torch.abs( - torch.abs(wp.to_torch(robot.data.joint_pos)[:, gripper_joint_ids[0]]) - env.cfg.gripper_open_val - ) + torch.abs(torch.abs(robot.data.joint_pos.torch[:, gripper_joint_ids[0]]) - env.cfg.gripper_open_val) < env.cfg.gripper_threshold, ) success = torch.logical_and( success, - torch.abs( - torch.abs(wp.to_torch(robot.data.joint_pos)[:, gripper_joint_ids[1]]) - env.cfg.gripper_open_val - ) + torch.abs(torch.abs(robot.data.joint_pos.torch[:, gripper_joint_ids[1]]) - env.cfg.gripper_open_val) < env.cfg.gripper_threshold, ) else: diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/reach/mdp/rewards.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/reach/mdp/rewards.py index 6ba3176b535c..3238523134d5 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/reach/mdp/rewards.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/reach/mdp/rewards.py @@ -8,7 +8,6 @@ from typing import TYPE_CHECKING import torch -import warp as wp from isaaclab.managers import SceneEntityCfg from isaaclab.utils.math import combine_frame_transforms, quat_error_magnitude, quat_mul @@ -30,10 +29,8 @@ def position_command_error(env: ManagerBasedRLEnv, command_name: str, asset_cfg: command = env.command_manager.get_command(command_name) # obtain the desired and current positions des_pos_b = command[:, :3] - des_pos_w, _ = combine_frame_transforms( - wp.to_torch(asset.data.root_pos_w), wp.to_torch(asset.data.root_quat_w), des_pos_b - ) - curr_pos_w = wp.to_torch(asset.data.body_pos_w)[:, asset_cfg.body_ids[0]] # type: ignore + des_pos_w, _ = combine_frame_transforms(asset.data.root_pos_w.torch, asset.data.root_quat_w.torch, des_pos_b) + curr_pos_w = asset.data.body_pos_w.torch[:, asset_cfg.body_ids[0]] # type: ignore return torch.linalg.norm(curr_pos_w - des_pos_w, dim=1) @@ -50,10 +47,8 @@ def position_command_error_tanh( command = env.command_manager.get_command(command_name) # obtain the desired and current positions des_pos_b = command[:, :3] - des_pos_w, _ = combine_frame_transforms( - wp.to_torch(asset.data.root_pos_w), wp.to_torch(asset.data.root_quat_w), des_pos_b - ) - curr_pos_w = wp.to_torch(asset.data.body_pos_w)[:, asset_cfg.body_ids[0]] # type: ignore + des_pos_w, _ = combine_frame_transforms(asset.data.root_pos_w.torch, asset.data.root_quat_w.torch, des_pos_b) + curr_pos_w = asset.data.body_pos_w.torch[:, asset_cfg.body_ids[0]] # type: ignore distance = torch.linalg.norm(curr_pos_w - des_pos_w, dim=1) return 1 - torch.tanh(distance / std) @@ -70,6 +65,6 @@ def orientation_command_error(env: ManagerBasedRLEnv, command_name: str, asset_c command = env.command_manager.get_command(command_name) # obtain the desired and current orientations des_quat_b = command[:, 3:7] - des_quat_w = quat_mul(wp.to_torch(asset.data.root_quat_w), des_quat_b) - curr_quat_w = wp.to_torch(asset.data.body_quat_w)[:, asset_cfg.body_ids[0]] # type: ignore + des_quat_w = quat_mul(asset.data.root_quat_w.torch, des_quat_b) + curr_quat_w = asset.data.body_quat_w.torch[:, asset_cfg.body_ids[0]] # type: ignore return quat_error_magnitude(curr_quat_w, des_quat_w) diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/reach/reach_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/reach/reach_env_cfg.py index 3bf9cc0443fc..d859e786cf61 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/reach/reach_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/reach/reach_env_cfg.py @@ -38,7 +38,7 @@ class ReachPhysicsCfg(PresetCfg): default: PhysxCfg = PhysxCfg(bounce_threshold_velocity=0.2) physx: PhysxCfg = PhysxCfg(bounce_threshold_velocity=0.2) - newton: NewtonCfg = NewtonCfg( + newton_mjwarp: NewtonCfg = NewtonCfg( solver_cfg=MJWarpSolverCfg( njmax=50, nconmax=20, @@ -66,7 +66,7 @@ class TableCfg(PresetCfg): ), ) - newton: ArticulationCfg = ArticulationCfg( + newton_mjwarp: ArticulationCfg = ArticulationCfg( prim_path="/World/envs/env_.*/Table", init_state=ArticulationCfg.InitialStateCfg( pos=(0.5, 0.15, -0.5), rot=(0, 0, 0.707, 0.707), joint_pos={}, joint_vel={} @@ -120,6 +120,7 @@ class CommandsCfg: body_name=MISSING, resampling_time_range=(4.0, 4.0), debug_vis=True, + position_success_threshold=0.05, ranges=mdp.UniformPoseCommandCfg.Ranges( pos_x=(0.35, 0.65), pos_y=(-0.2, 0.2), diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/stack/config/franka/stack_ik_rel_blueprint_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/stack/config/franka/stack_ik_rel_blueprint_env_cfg.py index ead320d8442f..e123a25604bb 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/stack/config/franka/stack_ik_rel_blueprint_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/stack/config/franka/stack_ik_rel_blueprint_env_cfg.py @@ -26,7 +26,7 @@ if TYPE_CHECKING: from isaaclab.envs import ManagerBasedEnv - from isaaclab.sensors import Camera, RayCasterCamera, TiledCamera + from isaaclab.sensors import Camera, RayCasterCamera ## # Pre-defined configs ## @@ -63,7 +63,7 @@ def image( The images produced at the last time-step """ # extract the used quantities (to enable type-hinting) - sensor: TiledCamera | Camera | RayCasterCamera = env.scene.sensors[sensor_cfg.name] + sensor: Camera | RayCasterCamera = env.scene.sensors[sensor_cfg.name] # obtain the input image images = sensor.data.output[data_type] diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/stack/config/franka/stack_ik_rel_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/stack/config/franka/stack_ik_rel_env_cfg.py index 0b74bc5a682b..1d32adc3426e 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/stack/config/franka/stack_ik_rel_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/stack/config/franka/stack_ik_rel_env_cfg.py @@ -4,31 +4,90 @@ # SPDX-License-Identifier: BSD-3-Clause +from isaaclab.assets import ArticulationCfg, RigidObjectCfg from isaaclab.controllers.differential_ik_cfg import DifferentialIKControllerCfg from isaaclab.envs.mdp.actions.actions_cfg import DifferentialInverseKinematicsActionCfg +from isaaclab.managers import EventTermCfg as EventTerm from isaaclab.managers import SceneEntityCfg from isaaclab.managers import TerminationTermCfg as DoneTerm +from isaaclab.sensors import FrameTransformerCfg +from isaaclab.sensors.frame_transformer.frame_transformer_cfg import OffsetCfg +from isaaclab.sim.schemas.schemas_cfg import RigidBodyPropertiesCfg +from isaaclab.sim.spawners.from_files.from_files_cfg import UsdFileCfg from isaaclab.utils import configclass +from isaaclab.utils.assets import ISAAC_NUCLEUS_DIR -from isaaclab_tasks.manager_based.manipulation.stack.stack_env_cfg import mdp - -from . import stack_joint_pos_env_cfg +from isaaclab_tasks.manager_based.manipulation.stack.mdp import franka_stack_events +from isaaclab_tasks.manager_based.manipulation.stack.stack_env_cfg import StackEnvCfg, mdp ## # Pre-defined configs ## +from isaaclab.markers.config import FRAME_MARKER_CFG # isort: skip from isaaclab_assets.robots.franka import FRANKA_PANDA_HIGH_PD_CFG # isort: skip +# Default arm + gripper joint pose +_FRANKA_STACK_IK_REL_INIT_JOINT_POS: dict[str, float] = { + "panda_joint1": 0.0444, + "panda_joint2": -0.1894, + "panda_joint3": -0.1107, + "panda_joint4": -2.5148, + "panda_joint5": 0.0044, + "panda_joint6": 2.3775, + "panda_joint7": 0.6952, + "panda_finger_joint.*": 0.0400, +} + + +@configclass +class EventCfg: + """Configuration for events.""" + + randomize_franka_joint_state = EventTerm( + func=franka_stack_events.randomize_joint_by_gaussian_offset, + mode="reset", + params={ + "mean": 0.0, + "std": 0.02, + "asset_cfg": SceneEntityCfg("robot"), + }, + ) + + randomize_cube_positions = EventTerm( + func=franka_stack_events.randomize_object_pose, + mode="reset", + params={ + "pose_range": {"x": (0.4, 0.6), "y": (-0.10, 0.10), "z": (0.0203, 0.0203), "yaw": (-1.0, 1, 0)}, + "min_separation": 0.1, + "asset_cfgs": [SceneEntityCfg("cube_1"), SceneEntityCfg("cube_2"), SceneEntityCfg("cube_3")], + }, + ) + @configclass -class FrankaCubeStackEnvCfg(stack_joint_pos_env_cfg.FrankaCubeStackEnvCfg): +class FrankaCubeStackEnvCfg(StackEnvCfg): def __post_init__(self): # post init of parent super().__post_init__() + # Set events + self.events = EventCfg() + # Set Franka as robot # We switch here to a stiffer PD controller for IK tracking to be better. - self.scene.robot = FRANKA_PANDA_HIGH_PD_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") + self.scene.robot = FRANKA_PANDA_HIGH_PD_CFG.replace( + prim_path="{ENV_REGEX_NS}/Robot", + init_state=ArticulationCfg.InitialStateCfg(joint_pos=_FRANKA_STACK_IK_REL_INIT_JOINT_POS), + ) + + # Add semantics to table + self.scene.table.spawn.semantic_tags = [("class", "table")] + + # Add semantics to ground + self.scene.plane.semantic_tags = [("class", "ground")] + + # Add semantics to robot + self.scene.robot.spawn.semantic_tags = [("class", "robot")] # Set actions for the specific robot type (franka) self.actions.arm_action = DifferentialInverseKinematicsActionCfg( @@ -39,6 +98,91 @@ def __post_init__(self): scale=0.5, body_offset=DifferentialInverseKinematicsActionCfg.OffsetCfg(pos=[0.0, 0.0, 0.107]), ) + self.actions.gripper_action = mdp.BinaryJointPositionActionCfg( + asset_name="robot", + joint_names=["panda_finger.*"], + open_command_expr={"panda_finger_.*": 0.04}, + close_command_expr={"panda_finger_.*": 0.0}, + ) + # utilities for gripper status check + self.gripper_joint_names = ["panda_finger_.*"] + self.gripper_open_val = 0.04 + self.gripper_threshold = 0.005 + + # Rigid body properties of each cube + cube_properties = RigidBodyPropertiesCfg( + solver_position_iteration_count=16, + solver_velocity_iteration_count=1, + max_angular_velocity=1000.0, + max_linear_velocity=1000.0, + max_depenetration_velocity=5.0, + disable_gravity=False, + ) + + # Set each stacking cube deterministically + self.scene.cube_1 = RigidObjectCfg( + prim_path="{ENV_REGEX_NS}/Cube_1", + init_state=RigidObjectCfg.InitialStateCfg(pos=[0.4, 0.0, 0.0203], rot=[0, 0, 0, 1]), + spawn=UsdFileCfg( + usd_path=f"{ISAAC_NUCLEUS_DIR}/Props/Blocks/blue_block.usd", + scale=(1.0, 1.0, 1.0), + rigid_props=cube_properties, + semantic_tags=[("class", "cube_1")], + ), + ) + self.scene.cube_2 = RigidObjectCfg( + prim_path="{ENV_REGEX_NS}/Cube_2", + init_state=RigidObjectCfg.InitialStateCfg(pos=[0.55, 0.05, 0.0203], rot=[0, 0, 0, 1]), + spawn=UsdFileCfg( + usd_path=f"{ISAAC_NUCLEUS_DIR}/Props/Blocks/red_block.usd", + scale=(1.0, 1.0, 1.0), + rigid_props=cube_properties, + semantic_tags=[("class", "cube_2")], + ), + ) + self.scene.cube_3 = RigidObjectCfg( + prim_path="{ENV_REGEX_NS}/Cube_3", + init_state=RigidObjectCfg.InitialStateCfg(pos=[0.60, -0.1, 0.0203], rot=[0, 0, 0, 1]), + spawn=UsdFileCfg( + usd_path=f"{ISAAC_NUCLEUS_DIR}/Props/Blocks/green_block.usd", + scale=(1.0, 1.0, 1.0), + rigid_props=cube_properties, + semantic_tags=[("class", "cube_3")], + ), + ) + + # Listens to the required transforms + marker_cfg = FRAME_MARKER_CFG.copy() + marker_cfg.markers["frame"].scale = (0.1, 0.1, 0.1) + marker_cfg.prim_path = "/Visuals/FrameTransformer" + self.scene.ee_frame = FrameTransformerCfg( + prim_path="{ENV_REGEX_NS}/Robot/panda_link0", + debug_vis=False, + visualizer_cfg=marker_cfg, + target_frames=[ + FrameTransformerCfg.FrameCfg( + prim_path="{ENV_REGEX_NS}/Robot/panda_hand", + name="end_effector", + offset=OffsetCfg( + pos=[0.0, 0.0, 0.1034], + ), + ), + FrameTransformerCfg.FrameCfg( + prim_path="{ENV_REGEX_NS}/Robot/panda_rightfinger", + name="tool_rightfinger", + offset=OffsetCfg( + pos=(0.0, 0.0, 0.046), + ), + ), + FrameTransformerCfg.FrameCfg( + prim_path="{ENV_REGEX_NS}/Robot/panda_leftfinger", + name="tool_leftfinger", + offset=OffsetCfg( + pos=(0.0, 0.0, 0.046), + ), + ), + ], + ) @configclass diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/stack/config/franka/stack_ik_rel_visuomotor_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/stack/config/franka/stack_ik_rel_visuomotor_env_cfg.py index 3cfe4616aa33..624df7a8dc1d 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/stack/config/franka/stack_ik_rel_visuomotor_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/stack/config/franka/stack_ik_rel_visuomotor_env_cfg.py @@ -4,31 +4,67 @@ # SPDX-License-Identifier: BSD-3-Clause import isaaclab.sim as sim_utils +from isaaclab.assets import ArticulationCfg, RigidObjectCfg from isaaclab.controllers.differential_ik_cfg import DifferentialIKControllerCfg from isaaclab.envs.mdp.actions.actions_cfg import DifferentialInverseKinematicsActionCfg 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 SceneEntityCfg -from isaaclab.sensors import CameraCfg +from isaaclab.sensors import CameraCfg, FrameTransformerCfg +from isaaclab.sensors.frame_transformer.frame_transformer_cfg import OffsetCfg +from isaaclab.sim.schemas.schemas_cfg import RigidBodyPropertiesCfg +from isaaclab.sim.spawners.from_files.from_files_cfg import UsdFileCfg from isaaclab.utils import configclass from isaaclab.utils.assets import ISAAC_NUCLEUS_DIR, NVIDIA_NUCLEUS_DIR from isaaclab_tasks.manager_based.manipulation.stack import mdp from isaaclab_tasks.manager_based.manipulation.stack.mdp import franka_stack_events - -from . import stack_joint_pos_env_cfg +from isaaclab_tasks.manager_based.manipulation.stack.stack_env_cfg import StackEnvCfg ## # Pre-defined configs ## +from isaaclab.markers.config import FRAME_MARKER_CFG # isort: skip from isaaclab_assets.robots.franka import FRANKA_PANDA_HIGH_PD_CFG # isort: skip +# Default arm + gripper joint pose +_FRANKA_STACK_IK_REL_INIT_JOINT_POS: dict[str, float] = { + "panda_joint1": 0.0444, + "panda_joint2": -0.1894, + "panda_joint3": -0.1107, + "panda_joint4": -2.5148, + "panda_joint5": 0.0044, + "panda_joint6": 2.3775, + "panda_joint7": 0.6952, + "panda_finger_joint.*": 0.0400, +} + @configclass -class EventCfg(stack_joint_pos_env_cfg.EventCfg): +class EventCfg: """Configuration for events.""" + randomize_franka_joint_state = EventTerm( + func=franka_stack_events.randomize_joint_by_gaussian_offset, + mode="reset", + params={ + "mean": 0.0, + "std": 0.02, + "asset_cfg": SceneEntityCfg("robot"), + }, + ) + + randomize_cube_positions = EventTerm( + func=franka_stack_events.randomize_object_pose, + mode="reset", + params={ + "pose_range": {"x": (0.4, 0.6), "y": (-0.10, 0.10), "z": (0.0203, 0.0203), "yaw": (-1.0, 1, 0)}, + "min_separation": 0.1, + "asset_cfgs": [SceneEntityCfg("cube_1"), SceneEntityCfg("cube_2"), SceneEntityCfg("cube_3")], + }, + ) + randomize_light = EventTerm( func=franka_stack_events.randomize_scene_lighting_domelight, mode="reset", @@ -170,7 +206,7 @@ def __post_init__(self): @configclass -class FrankaCubeStackVisuomotorEnvCfg(stack_joint_pos_env_cfg.FrankaCubeStackEnvCfg): +class FrankaCubeStackVisuomotorEnvCfg(StackEnvCfg): observations: ObservationsCfg = ObservationsCfg() # Evaluation settings @@ -186,7 +222,18 @@ def __post_init__(self): # Set Franka as robot # We switch here to a stiffer PD controller for IK tracking to be better. - self.scene.robot = FRANKA_PANDA_HIGH_PD_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") + self.scene.robot = FRANKA_PANDA_HIGH_PD_CFG.replace( + prim_path="{ENV_REGEX_NS}/Robot", + init_state=ArticulationCfg.InitialStateCfg(joint_pos=_FRANKA_STACK_IK_REL_INIT_JOINT_POS), + ) + + # Add semantics to table + self.scene.table.spawn.semantic_tags = [("class", "table")] + + # Add semantics to ground + self.scene.plane.semantic_tags = [("class", "ground")] + + # Add semantics to robot self.scene.robot.spawn.semantic_tags = [("class", "robot")] # Set actions for the specific robot type (franka) @@ -198,6 +245,91 @@ def __post_init__(self): scale=0.5, body_offset=DifferentialInverseKinematicsActionCfg.OffsetCfg(pos=[0.0, 0.0, 0.107]), ) + self.actions.gripper_action = mdp.BinaryJointPositionActionCfg( + asset_name="robot", + joint_names=["panda_finger.*"], + open_command_expr={"panda_finger_.*": 0.04}, + close_command_expr={"panda_finger_.*": 0.0}, + ) + # utilities for gripper status check + self.gripper_joint_names = ["panda_finger_.*"] + self.gripper_open_val = 0.04 + self.gripper_threshold = 0.005 + + # Rigid body properties of each cube + cube_properties = RigidBodyPropertiesCfg( + solver_position_iteration_count=16, + solver_velocity_iteration_count=1, + max_angular_velocity=1000.0, + max_linear_velocity=1000.0, + max_depenetration_velocity=5.0, + disable_gravity=False, + ) + + # Set each stacking cube deterministically + self.scene.cube_1 = RigidObjectCfg( + prim_path="{ENV_REGEX_NS}/Cube_1", + init_state=RigidObjectCfg.InitialStateCfg(pos=[0.4, 0.0, 0.0203], rot=[0, 0, 0, 1]), + spawn=UsdFileCfg( + usd_path=f"{ISAAC_NUCLEUS_DIR}/Props/Blocks/blue_block.usd", + scale=(1.0, 1.0, 1.0), + rigid_props=cube_properties, + semantic_tags=[("class", "cube_1")], + ), + ) + self.scene.cube_2 = RigidObjectCfg( + prim_path="{ENV_REGEX_NS}/Cube_2", + init_state=RigidObjectCfg.InitialStateCfg(pos=[0.55, 0.05, 0.0203], rot=[0, 0, 0, 1]), + spawn=UsdFileCfg( + usd_path=f"{ISAAC_NUCLEUS_DIR}/Props/Blocks/red_block.usd", + scale=(1.0, 1.0, 1.0), + rigid_props=cube_properties, + semantic_tags=[("class", "cube_2")], + ), + ) + self.scene.cube_3 = RigidObjectCfg( + prim_path="{ENV_REGEX_NS}/Cube_3", + init_state=RigidObjectCfg.InitialStateCfg(pos=[0.60, -0.1, 0.0203], rot=[0, 0, 0, 1]), + spawn=UsdFileCfg( + usd_path=f"{ISAAC_NUCLEUS_DIR}/Props/Blocks/green_block.usd", + scale=(1.0, 1.0, 1.0), + rigid_props=cube_properties, + semantic_tags=[("class", "cube_3")], + ), + ) + + # Listens to the required transforms + marker_cfg = FRAME_MARKER_CFG.copy() + marker_cfg.markers["frame"].scale = (0.1, 0.1, 0.1) + marker_cfg.prim_path = "/Visuals/FrameTransformer" + self.scene.ee_frame = FrameTransformerCfg( + prim_path="{ENV_REGEX_NS}/Robot/panda_link0", + debug_vis=False, + visualizer_cfg=marker_cfg, + target_frames=[ + FrameTransformerCfg.FrameCfg( + prim_path="{ENV_REGEX_NS}/Robot/panda_hand", + name="end_effector", + offset=OffsetCfg( + pos=[0.0, 0.0, 0.1034], + ), + ), + FrameTransformerCfg.FrameCfg( + prim_path="{ENV_REGEX_NS}/Robot/panda_rightfinger", + name="tool_rightfinger", + offset=OffsetCfg( + pos=(0.0, 0.0, 0.046), + ), + ), + FrameTransformerCfg.FrameCfg( + prim_path="{ENV_REGEX_NS}/Robot/panda_leftfinger", + name="tool_leftfinger", + offset=OffsetCfg( + pos=(0.0, 0.0, 0.046), + ), + ), + ], + ) # Set cameras # Set wrist camera diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/stack/config/franka/stack_joint_pos_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/stack/config/franka/stack_joint_pos_env_cfg.py index da9c783eca93..83f05e0497df 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/stack/config/franka/stack_joint_pos_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/stack/config/franka/stack_joint_pos_env_cfg.py @@ -3,7 +3,7 @@ # # SPDX-License-Identifier: BSD-3-Clause -from isaaclab.assets import RigidObjectCfg +from isaaclab.assets import ArticulationCfg, RigidObjectCfg from isaaclab.managers import EventTermCfg as EventTerm from isaaclab.managers import SceneEntityCfg from isaaclab.sensors import FrameTransformerCfg @@ -23,20 +23,23 @@ from isaaclab.markers.config import FRAME_MARKER_CFG # isort: skip from isaaclab_assets.robots.franka import FRANKA_PANDA_CFG # isort: skip +# Default arm + gripper joint pose +_FRANKA_STACK_IK_REL_INIT_JOINT_POS: dict[str, float] = { + "panda_joint1": 0.0444, + "panda_joint2": -0.1894, + "panda_joint3": -0.1107, + "panda_joint4": -2.5148, + "panda_joint5": 0.0044, + "panda_joint6": 2.3775, + "panda_joint7": 0.6952, + "panda_finger_joint.*": 0.0400, +} + @configclass class EventCfg: """Configuration for events.""" - # FIXME: Let's not do that and initialize the arm pose correctly in the environment constructor instead. - init_franka_arm_pose = EventTerm( - func=franka_stack_events.set_default_joint_pose, - mode="reset", - params={ - "default_pose": [0.0444, -0.1894, -0.1107, -2.5148, 0.0044, 2.3775, 0.6952, 0.0400, 0.0400], - }, - ) - randomize_franka_joint_state = EventTerm( func=franka_stack_events.randomize_joint_by_gaussian_offset, mode="reset", @@ -70,8 +73,10 @@ def __post_init__(self): self.events = EventCfg() # Set Franka as robot - self.scene.robot = FRANKA_PANDA_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") - self.scene.robot.spawn.semantic_tags = [("class", "robot")] + self.scene.robot = FRANKA_PANDA_CFG.replace( + prim_path="{ENV_REGEX_NS}/Robot", + init_state=ArticulationCfg.InitialStateCfg(joint_pos=_FRANKA_STACK_IK_REL_INIT_JOINT_POS), + ) # Add semantics to table self.scene.table.spawn.semantic_tags = [("class", "table")] @@ -79,6 +84,9 @@ def __post_init__(self): # Add semantics to ground self.scene.plane.semantic_tags = [("class", "ground")] + # Add semantics to robot + self.scene.robot.spawn.semantic_tags = [("class", "robot")] + # Set actions for the specific robot type (franka) self.actions.arm_action = mdp.JointPositionActionCfg( asset_name="robot", joint_names=["panda_joint.*"], scale=0.5, use_default_offset=True diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/stack/mdp/franka_stack_events.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/stack/mdp/franka_stack_events.py index ada7f2fc259c..4d148d6ba216 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/stack/mdp/franka_stack_events.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/stack/mdp/franka_stack_events.py @@ -58,16 +58,16 @@ def randomize_joint_by_gaussian_offset( asset: Articulation = env.scene[asset_cfg.name] # Add gaussian noise to joint states - joint_pos = wp.to_torch(asset.data.default_joint_pos)[env_ids].clone() - joint_vel = wp.to_torch(asset.data.default_joint_vel)[env_ids].clone() + joint_pos = asset.data.default_joint_pos.torch[env_ids].clone() + joint_vel = asset.data.default_joint_vel.torch[env_ids].clone() joint_pos += math_utils.sample_gaussian(mean, std, joint_pos.shape, joint_pos.device) # Clamp joint pos to limits - joint_pos_limits = wp.to_torch(asset.data.soft_joint_pos_limits)[env_ids] + joint_pos_limits = asset.data.soft_joint_pos_limits.torch[env_ids] joint_pos = joint_pos.clamp_(joint_pos_limits[..., 0], joint_pos_limits[..., 1]) # Don't noise the gripper poses - joint_pos[:, -2:] = wp.to_torch(asset.data.default_joint_pos)[env_ids, -2:] + joint_pos[:, -2:] = asset.data.default_joint_pos.torch[env_ids, -2:] # Set into the physics simulation asset.set_joint_position_target_index(target=joint_pos, env_ids=env_ids) @@ -296,7 +296,7 @@ def randomize_visual_texture_material( # textures = [default_texture] # enable replicator extension if not already enabled - from isaacsim.core.utils.extensions import enable_extension + from isaacsim.core.experimental.utils.app import enable_extension enable_extension("omni.replicator.core") # we import the module here since we may not always need the replicator diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/stack/mdp/observations.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/stack/mdp/observations.py index 2378276602d5..1269ef260ff5 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/stack/mdp/observations.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/stack/mdp/observations.py @@ -31,7 +31,7 @@ def cube_positions_in_world_frame( cube_3: RigidObject = env.scene[cube_3_cfg.name] return torch.cat( - (wp.to_torch(cube_1.data.root_pos_w), wp.to_torch(cube_2.data.root_pos_w), wp.to_torch(cube_3.data.root_pos_w)), + (cube_1.data.root_pos_w.torch, cube_2.data.root_pos_w.torch, cube_3.data.root_pos_w.torch), dim=1, ) @@ -54,9 +54,9 @@ def instance_randomize_cube_positions_in_world_frame( cube_2_pos_w = [] cube_3_pos_w = [] for env_id in range(env.num_envs): - cube_1_pos_w.append(wp.to_torch(cube_1.data.body_link_pos_w)[env_id, env.rigid_objects_in_focus[env_id][0], :3]) - cube_2_pos_w.append(wp.to_torch(cube_2.data.body_link_pos_w)[env_id, env.rigid_objects_in_focus[env_id][1], :3]) - cube_3_pos_w.append(wp.to_torch(cube_3.data.body_link_pos_w)[env_id, env.rigid_objects_in_focus[env_id][2], :3]) + cube_1_pos_w.append(cube_1.data.body_link_pos_w.torch[env_id, env.rigid_objects_in_focus[env_id][0], :3]) + cube_2_pos_w.append(cube_2.data.body_link_pos_w.torch[env_id, env.rigid_objects_in_focus[env_id][1], :3]) + cube_3_pos_w.append(cube_3.data.body_link_pos_w.torch[env_id, env.rigid_objects_in_focus[env_id][2], :3]) cube_1_pos_w = torch.stack(cube_1_pos_w) cube_2_pos_w = torch.stack(cube_2_pos_w) cube_3_pos_w = torch.stack(cube_3_pos_w) @@ -77,9 +77,9 @@ def cube_orientations_in_world_frame( return torch.cat( ( - wp.to_torch(cube_1.data.root_quat_w), - wp.to_torch(cube_2.data.root_quat_w), - wp.to_torch(cube_3.data.root_quat_w), + cube_1.data.root_quat_w.torch, + cube_2.data.root_quat_w.torch, + cube_3.data.root_quat_w.torch, ), dim=1, ) @@ -103,15 +103,9 @@ def instance_randomize_cube_orientations_in_world_frame( cube_2_quat_w = [] cube_3_quat_w = [] for env_id in range(env.num_envs): - cube_1_quat_w.append( - wp.to_torch(cube_1.data.body_link_quat_w)[env_id, env.rigid_objects_in_focus[env_id][0], :4] - ) - cube_2_quat_w.append( - wp.to_torch(cube_2.data.body_link_quat_w)[env_id, env.rigid_objects_in_focus[env_id][1], :4] - ) - cube_3_quat_w.append( - wp.to_torch(cube_3.data.body_link_quat_w)[env_id, env.rigid_objects_in_focus[env_id][2], :4] - ) + cube_1_quat_w.append(cube_1.data.body_link_quat_w.torch[env_id, env.rigid_objects_in_focus[env_id][0], :4]) + cube_2_quat_w.append(cube_2.data.body_link_quat_w.torch[env_id, env.rigid_objects_in_focus[env_id][1], :4]) + cube_3_quat_w.append(cube_3.data.body_link_quat_w.torch[env_id, env.rigid_objects_in_focus[env_id][2], :4]) cube_1_quat_w = torch.stack(cube_1_quat_w) cube_2_quat_w = torch.stack(cube_2_quat_w) cube_3_quat_w = torch.stack(cube_3_quat_w) @@ -146,16 +140,16 @@ def object_obs( cube_3: RigidObject = env.scene[cube_3_cfg.name] ee_frame: FrameTransformer = env.scene[ee_frame_cfg.name] - cube_1_pos_w = wp.to_torch(cube_1.data.root_pos_w) - cube_1_quat_w = wp.to_torch(cube_1.data.root_quat_w) + cube_1_pos_w = cube_1.data.root_pos_w.torch + cube_1_quat_w = cube_1.data.root_quat_w.torch - cube_2_pos_w = wp.to_torch(cube_2.data.root_pos_w) - cube_2_quat_w = wp.to_torch(cube_2.data.root_quat_w) + cube_2_pos_w = cube_2.data.root_pos_w.torch + cube_2_quat_w = cube_2.data.root_quat_w.torch - cube_3_pos_w = wp.to_torch(cube_3.data.root_pos_w) - cube_3_quat_w = wp.to_torch(cube_3.data.root_quat_w) + cube_3_pos_w = cube_3.data.root_pos_w.torch + cube_3_quat_w = cube_3.data.root_quat_w.torch - ee_pos_w = wp.to_torch(ee_frame.data.target_pos_w)[:, 0, :] + ee_pos_w = ee_frame.data.target_pos_w.torch[:, 0, :] gripper_to_cube_1 = cube_1_pos_w - ee_pos_w gripper_to_cube_2 = cube_2_pos_w - ee_pos_w gripper_to_cube_3 = cube_3_pos_w - ee_pos_w @@ -220,18 +214,12 @@ def instance_randomize_object_obs( cube_2_quat_w = [] cube_3_quat_w = [] for env_id in range(env.num_envs): - cube_1_pos_w.append(wp.to_torch(cube_1.data.body_link_pos_w)[env_id, env.rigid_objects_in_focus[env_id][0], :3]) - cube_2_pos_w.append(wp.to_torch(cube_2.data.body_link_pos_w)[env_id, env.rigid_objects_in_focus[env_id][1], :3]) - cube_3_pos_w.append(wp.to_torch(cube_3.data.body_link_pos_w)[env_id, env.rigid_objects_in_focus[env_id][2], :3]) - cube_1_quat_w.append( - wp.to_torch(cube_1.data.body_link_quat_w)[env_id, env.rigid_objects_in_focus[env_id][0], :4] - ) - cube_2_quat_w.append( - wp.to_torch(cube_2.data.body_link_quat_w)[env_id, env.rigid_objects_in_focus[env_id][1], :4] - ) - cube_3_quat_w.append( - wp.to_torch(cube_3.data.body_link_quat_w)[env_id, env.rigid_objects_in_focus[env_id][2], :4] - ) + cube_1_pos_w.append(cube_1.data.body_link_pos_w.torch[env_id, env.rigid_objects_in_focus[env_id][0], :3]) + cube_2_pos_w.append(cube_2.data.body_link_pos_w.torch[env_id, env.rigid_objects_in_focus[env_id][1], :3]) + cube_3_pos_w.append(cube_3.data.body_link_pos_w.torch[env_id, env.rigid_objects_in_focus[env_id][2], :3]) + cube_1_quat_w.append(cube_1.data.body_link_quat_w.torch[env_id, env.rigid_objects_in_focus[env_id][0], :4]) + cube_2_quat_w.append(cube_2.data.body_link_quat_w.torch[env_id, env.rigid_objects_in_focus[env_id][1], :4]) + cube_3_quat_w.append(cube_3.data.body_link_quat_w.torch[env_id, env.rigid_objects_in_focus[env_id][2], :4]) cube_1_pos_w = torch.stack(cube_1_pos_w) cube_2_pos_w = torch.stack(cube_2_pos_w) cube_3_pos_w = torch.stack(cube_3_pos_w) @@ -239,7 +227,7 @@ def instance_randomize_object_obs( cube_2_quat_w = torch.stack(cube_2_quat_w) cube_3_quat_w = torch.stack(cube_3_quat_w) - ee_pos_w = wp.to_torch(ee_frame.data.target_pos_w)[:, 0, :] + ee_pos_w = ee_frame.data.target_pos_w.torch[:, 0, :] gripper_to_cube_1 = cube_1_pos_w - ee_pos_w gripper_to_cube_2 = cube_2_pos_w - ee_pos_w gripper_to_cube_3 = cube_3_pos_w - ee_pos_w @@ -269,14 +257,14 @@ def instance_randomize_object_obs( def ee_frame_pos(env: ManagerBasedRLEnv, ee_frame_cfg: SceneEntityCfg = SceneEntityCfg("ee_frame")) -> torch.Tensor: ee_frame: FrameTransformer = env.scene[ee_frame_cfg.name] - ee_frame_pos = wp.to_torch(ee_frame.data.target_pos_w)[:, 0, :] - env.scene.env_origins[:, 0:3] + ee_frame_pos = ee_frame.data.target_pos_w.torch[:, 0, :] - env.scene.env_origins[:, 0:3] return ee_frame_pos def ee_frame_quat(env: ManagerBasedRLEnv, ee_frame_cfg: SceneEntityCfg = SceneEntityCfg("ee_frame")) -> torch.Tensor: ee_frame: FrameTransformer = env.scene[ee_frame_cfg.name] - ee_frame_quat = wp.to_torch(ee_frame.data.target_quat_w)[:, 0, :] + ee_frame_quat = ee_frame.data.target_quat_w.torch[:, 0, :] return ee_frame_quat @@ -305,8 +293,8 @@ def gripper_pos( if hasattr(env.cfg, "gripper_joint_names"): gripper_joint_ids, _ = robot.find_joints(env.cfg.gripper_joint_names) assert len(gripper_joint_ids) == 2, "Observation gripper_pos only support parallel gripper for now" - finger_joint_1 = wp.to_torch(robot.data.joint_pos)[:, gripper_joint_ids[0]].clone().unsqueeze(1) - finger_joint_2 = -1 * wp.to_torch(robot.data.joint_pos)[:, gripper_joint_ids[1]].clone().unsqueeze(1) + finger_joint_1 = robot.data.joint_pos.torch[:, gripper_joint_ids[0]].clone().unsqueeze(1) + finger_joint_2 = -1 * robot.data.joint_pos.torch[:, gripper_joint_ids[1]].clone().unsqueeze(1) return torch.cat((finger_joint_1, finger_joint_2), dim=1) else: raise NotImplementedError("[Error] Cannot find gripper_joint_names in the environment config") @@ -325,8 +313,8 @@ def object_grasped( ee_frame: FrameTransformer = env.scene[ee_frame_cfg.name] object: RigidObject = env.scene[object_cfg.name] - object_pos = wp.to_torch(object.data.root_pos_w) - end_effector_pos = wp.to_torch(ee_frame.data.target_pos_w)[:, 0, :] + object_pos = object.data.root_pos_w.torch + end_effector_pos = ee_frame.data.target_pos_w.torch[:, 0, :] pose_diff = torch.linalg.vector_norm(object_pos - end_effector_pos, dim=1) if hasattr(env.scene, "surface_grippers") and len(env.scene.surface_grippers) > 0: @@ -343,7 +331,7 @@ def object_grasped( grasped = torch.logical_and( pose_diff < diff_threshold, torch.abs( - wp.to_torch(robot.data.joint_pos)[:, gripper_joint_ids[0]] + robot.data.joint_pos.torch[:, gripper_joint_ids[0]] - torch.tensor(env.cfg.gripper_open_val, dtype=torch.float32).to(env.device) ) > env.cfg.gripper_threshold, @@ -351,7 +339,7 @@ def object_grasped( grasped = torch.logical_and( grasped, torch.abs( - wp.to_torch(robot.data.joint_pos)[:, gripper_joint_ids[1]] + robot.data.joint_pos.torch[:, gripper_joint_ids[1]] - torch.tensor(env.cfg.gripper_open_val, dtype=torch.float32).to(env.device) ) > env.cfg.gripper_threshold, @@ -375,7 +363,7 @@ def object_stacked( upper_object: RigidObject = env.scene[upper_object_cfg.name] lower_object: RigidObject = env.scene[lower_object_cfg.name] - pos_diff = wp.to_torch(upper_object.data.root_pos_w) - wp.to_torch(lower_object.data.root_pos_w) + pos_diff = upper_object.data.root_pos_w.torch - lower_object.data.root_pos_w.torch height_dist = torch.linalg.vector_norm(pos_diff[:, 2:], dim=1) xy_dist = torch.linalg.vector_norm(pos_diff[:, :2], dim=1) @@ -393,7 +381,7 @@ def object_stacked( assert len(gripper_joint_ids) == 2, "Observations only support parallel gripper for now" stacked = torch.logical_and( torch.isclose( - wp.to_torch(robot.data.joint_pos)[:, gripper_joint_ids[0]], + robot.data.joint_pos.torch[:, gripper_joint_ids[0]], torch.tensor(env.cfg.gripper_open_val, dtype=torch.float32).to(env.device), atol=1e-4, rtol=1e-4, @@ -402,7 +390,7 @@ def object_stacked( ) stacked = torch.logical_and( torch.isclose( - wp.to_torch(robot.data.joint_pos)[:, gripper_joint_ids[1]], + robot.data.joint_pos.torch[:, gripper_joint_ids[1]], torch.tensor(env.cfg.gripper_open_val, dtype=torch.float32).to(env.device), atol=1e-4, rtol=1e-4, @@ -429,17 +417,17 @@ def cube_poses_in_base_frame( cube_2: RigidObject = env.scene[cube_2_cfg.name] cube_3: RigidObject = env.scene[cube_3_cfg.name] - pos_cube_1_world = wp.to_torch(cube_1.data.root_pos_w) - pos_cube_2_world = wp.to_torch(cube_2.data.root_pos_w) - pos_cube_3_world = wp.to_torch(cube_3.data.root_pos_w) + pos_cube_1_world = cube_1.data.root_pos_w.torch + pos_cube_2_world = cube_2.data.root_pos_w.torch + pos_cube_3_world = cube_3.data.root_pos_w.torch - quat_cube_1_world = wp.to_torch(cube_1.data.root_quat_w) - quat_cube_2_world = wp.to_torch(cube_2.data.root_quat_w) - quat_cube_3_world = wp.to_torch(cube_3.data.root_quat_w) + quat_cube_1_world = cube_1.data.root_quat_w.torch + quat_cube_2_world = cube_2.data.root_quat_w.torch + quat_cube_3_world = cube_3.data.root_quat_w.torch robot: Articulation = env.scene[robot_cfg.name] - root_pos_w = wp.to_torch(robot.data.root_pos_w) - root_quat_w = wp.to_torch(robot.data.root_quat_w) + root_pos_w = robot.data.root_pos_w.torch + root_quat_w = robot.data.root_quat_w.torch pos_cube_1_base, quat_cube_1_base = math_utils.subtract_frame_transforms( root_pos_w, root_quat_w, pos_cube_1_world, quat_cube_1_world @@ -488,17 +476,17 @@ def object_abs_obs_in_base_frame( ee_frame: FrameTransformer = env.scene[ee_frame_cfg.name] robot: Articulation = env.scene[robot_cfg.name] - root_pos_w = wp.to_torch(robot.data.root_pos_w) - root_quat_w = wp.to_torch(robot.data.root_quat_w) + root_pos_w = robot.data.root_pos_w.torch + root_quat_w = robot.data.root_quat_w.torch - cube_1_pos_w = wp.to_torch(cube_1.data.root_pos_w) - cube_1_quat_w = wp.to_torch(cube_1.data.root_quat_w) + cube_1_pos_w = cube_1.data.root_pos_w.torch + cube_1_quat_w = cube_1.data.root_quat_w.torch - cube_2_pos_w = wp.to_torch(cube_2.data.root_pos_w) - cube_2_quat_w = wp.to_torch(cube_2.data.root_quat_w) + cube_2_pos_w = cube_2.data.root_pos_w.torch + cube_2_quat_w = cube_2.data.root_quat_w.torch - cube_3_pos_w = wp.to_torch(cube_3.data.root_pos_w) - cube_3_quat_w = wp.to_torch(cube_3.data.root_quat_w) + cube_3_pos_w = cube_3.data.root_pos_w.torch + cube_3_quat_w = cube_3.data.root_quat_w.torch pos_cube_1_base, quat_cube_1_base = math_utils.subtract_frame_transforms( root_pos_w, root_quat_w, cube_1_pos_w, cube_1_quat_w @@ -510,8 +498,8 @@ def object_abs_obs_in_base_frame( root_pos_w, root_quat_w, cube_3_pos_w, cube_3_quat_w ) - ee_pos_w = wp.to_torch(ee_frame.data.target_pos_w)[:, 0, :] - ee_quat_w = wp.to_torch(ee_frame.data.target_quat_w)[:, 0, :] + ee_pos_w = ee_frame.data.target_pos_w.torch[:, 0, :] + ee_quat_w = ee_frame.data.target_quat_w.torch[:, 0, :] ee_pos_base, ee_quat_base = math_utils.subtract_frame_transforms(root_pos_w, root_quat_w, ee_pos_w, ee_quat_w) return torch.cat( @@ -539,12 +527,12 @@ def ee_frame_pose_in_base_frame( The end effector pose in the robot base frame. """ ee_frame: FrameTransformer = env.scene[ee_frame_cfg.name] - ee_frame_pos_w = wp.to_torch(ee_frame.data.target_pos_w)[:, 0, :] - ee_frame_quat_w = wp.to_torch(ee_frame.data.target_quat_w)[:, 0, :] + ee_frame_pos_w = ee_frame.data.target_pos_w.torch[:, 0, :] + ee_frame_quat_w = ee_frame.data.target_quat_w.torch[:, 0, :] robot: Articulation = env.scene[robot_cfg.name] - root_pos_w = wp.to_torch(robot.data.root_pos_w) - root_quat_w = wp.to_torch(robot.data.root_quat_w) + root_pos_w = robot.data.root_pos_w.torch + root_quat_w = robot.data.root_quat_w.torch ee_pos_in_base, ee_quat_in_base = math_utils.subtract_frame_transforms( root_pos_w, root_quat_w, ee_frame_pos_w, ee_frame_quat_w ) diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/stack/mdp/terminations.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/stack/mdp/terminations.py index d8781b0367a7..e709821972cf 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/stack/mdp/terminations.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/stack/mdp/terminations.py @@ -39,7 +39,7 @@ def cubes_stacked( cube_1: RigidObject = env.scene[cube_1_cfg.name] cube_2: RigidObject = env.scene[cube_2_cfg.name] - pos_diff_c12 = wp.to_torch(cube_1.data.root_pos_w) - wp.to_torch(cube_2.data.root_pos_w) + pos_diff_c12 = cube_1.data.root_pos_w.torch - cube_2.data.root_pos_w.torch # Compute cube position difference in x-y plane xy_dist_c12 = torch.linalg.norm(pos_diff_c12[:, :2], dim=1) @@ -54,7 +54,7 @@ def cubes_stacked( if cube_3_cfg is not None: cube_3: RigidObject = env.scene[cube_3_cfg.name] - pos_diff_c23 = wp.to_torch(cube_2.data.root_pos_w) - wp.to_torch(cube_3.data.root_pos_w) + pos_diff_c23 = cube_2.data.root_pos_w.torch - cube_3.data.root_pos_w.torch # Compute cube position difference in x-y plane xy_dist_c23 = torch.linalg.norm(pos_diff_c23[:, :2], dim=1) @@ -81,7 +81,7 @@ def cubes_stacked( stacked = torch.logical_and( torch.isclose( - wp.to_torch(robot.data.joint_pos)[:, gripper_joint_ids[0]], + robot.data.joint_pos.torch[:, gripper_joint_ids[0]], torch.tensor(env.cfg.gripper_open_val, dtype=torch.float32).to(env.device), atol=atol, rtol=rtol, @@ -90,7 +90,7 @@ def cubes_stacked( ) stacked = torch.logical_and( torch.isclose( - wp.to_torch(robot.data.joint_pos)[:, gripper_joint_ids[1]], + robot.data.joint_pos.torch[:, gripper_joint_ids[1]], torch.tensor(env.cfg.gripper_open_val, dtype=torch.float32).to(env.device), atol=atol, rtol=rtol, diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/stack/stack_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/stack/stack_env_cfg.py index a7f3e560edb5..7706fa3923e3 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/stack/stack_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/stack/stack_env_cfg.py @@ -29,7 +29,7 @@ ## @configclass class ObjectTableSceneCfg(InteractiveSceneCfg): - """Configuration for the lift scene with a robot and a object. + """Configuration for the stacking scene with a robot and objects. This is the abstract base implementation, the exact scene is defined in the derived classes which need to set the target object, robot and end-effector frames """ @@ -197,6 +197,6 @@ def __post_init__(self): self.sim.physics = PhysxCfg( bounce_threshold_velocity=0.01, gpu_found_lost_aggregate_pairs_capacity=1024 * 1024 * 4, - gpu_total_aggregate_pairs_capacity=16 * 1024, + gpu_total_aggregate_pairs_capacity=2**21, friction_correlation_distance=0.00625, ) diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/navigation/config/anymal_c/navigation_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/navigation/config/anymal_c/navigation_env_cfg.py index 96b60705bb50..4d4ad67e9305 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/navigation/config/anymal_c/navigation_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/navigation/config/anymal_c/navigation_env_cfg.py @@ -103,6 +103,7 @@ class CommandsCfg: simple_heading=False, resampling_time_range=(8.0, 8.0), debug_vis=True, + position_success_threshold=0.5, ranges=mdp.UniformPose2dCommandCfg.Ranges(pos_x=(-3.0, 3.0), pos_y=(-3.0, 3.0), heading=(-math.pi, math.pi)), ) diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/navigation/mdp/pre_trained_policy_action.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/navigation/mdp/pre_trained_policy_action.py index 43de222a506d..4857d63711e1 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/navigation/mdp/pre_trained_policy_action.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/navigation/mdp/pre_trained_policy_action.py @@ -8,7 +8,6 @@ from typing import TYPE_CHECKING import torch -import warp as wp import isaaclab.utils.math as math_utils from isaaclab.managers import ActionTerm, ObservationManager @@ -138,12 +137,12 @@ def _debug_vis_callback(self, event): return # get marker location # -- base state - base_pos_w = wp.to_torch(self.robot.data.root_pos_w).clone() + base_pos_w = self.robot.data.root_pos_w.torch.clone() base_pos_w[:, 2] += 0.5 # -- resolve the scales and quaternions vel_des_arrow_scale, vel_des_arrow_quat = self._resolve_xy_velocity_to_arrow(self.raw_actions[:, :2]) vel_arrow_scale, vel_arrow_quat = self._resolve_xy_velocity_to_arrow( - wp.to_torch(self.robot.data.root_lin_vel_b)[:, :2] + self.robot.data.root_lin_vel_b.torch[:, :2] ) # display markers self.base_vel_goal_visualizer.visualize(base_pos_w, vel_des_arrow_quat, vel_des_arrow_scale) @@ -165,7 +164,7 @@ def _resolve_xy_velocity_to_arrow(self, xy_velocity: torch.Tensor) -> tuple[torc zeros = torch.zeros_like(heading_angle) arrow_quat = math_utils.quat_from_euler_xyz(zeros, zeros, heading_angle) # convert everything back from base to world frame - base_quat_w = wp.to_torch(self.robot.data.root_quat_w) + base_quat_w = self.robot.data.root_quat_w.torch arrow_quat = math_utils.quat_mul(base_quat_w, arrow_quat) return arrow_scale, arrow_quat diff --git a/source/isaaclab_tasks/isaaclab_tasks/utils/__init__.pyi b/source/isaaclab_tasks/isaaclab_tasks/utils/__init__.pyi index e960be9e290e..6a0ba23b9429 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/utils/__init__.pyi +++ b/source/isaaclab_tasks/isaaclab_tasks/utils/__init__.pyi @@ -12,14 +12,13 @@ __all__ = [ "preset", "resolve_task_config", "hydra_task_config", - "resolve_preset_defaults", + "resolve_presets", "add_launcher_args", "launch_simulation", "compute_kit_requirements", ] -from .hydra import PresetCfg, preset, hydra_task_config, resolve_task_config +from .hydra import PresetCfg, preset, hydra_task_config, resolve_task_config, resolve_presets from .importer import import_packages from .parse_cfg import get_checkpoint_path, load_cfg_from_registry, parse_env_cfg -from .hydra import resolve_task_config, hydra_task_config, resolve_preset_defaults from .sim_launcher import add_launcher_args, launch_simulation, compute_kit_requirements diff --git a/source/isaaclab_tasks/isaaclab_tasks/utils/hydra.py b/source/isaaclab_tasks/isaaclab_tasks/utils/hydra.py index c5feca37d40c..320632705852 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/utils/hydra.py +++ b/source/isaaclab_tasks/isaaclab_tasks/utils/hydra.py @@ -14,31 +14,84 @@ presets and their paths automatically, including inside dict-valued fields. Override categories (applied in order): - 1. Global presets: ``presets=inference,newton`` -- apply everywhere matching - 2. Path presets: ``env.backend=newton`` -- REPLACE specific section + 1. Global presets: ``presets=inference,newton_mjwarp`` -- apply everywhere matching + 2. Path presets: ``env.backend=newton_mjwarp`` -- REPLACE specific section 3. Preset-path scalars: ``env.backend.dt=0.001`` -- handled by us 4. Global scalars: ``env.decimation=10`` -- handled by Hydra Example usage:: - presets=newton env.backend.dt=0.001 env.decimation=10 + presets=newton_mjwarp env.backend.dt=0.001 env.decimation=10 """ import functools import sys +import warnings from collections.abc import Callable, Mapping -try: - import hydra - from hydra.core.config_store import ConfigStore - from omegaconf import OmegaConf -except ImportError: - raise ImportError("Hydra not installed. Run: pip install hydra-core") +import hydra +from hydra.core.config_store import ConfigStore +from omegaconf import OmegaConf from isaaclab.envs.utils.spaces import replace_env_cfg_spaces_with_strings, replace_strings_with_env_cfg_spaces from isaaclab.utils import configclass, replace_slices_with_strings, replace_strings_with_slices -from isaaclab_tasks.utils.parse_cfg import load_cfg_from_registry +_LITERAL_MAP = {"true": True, "false": False, "none": None, "null": None} + +# Map of deprecated preset name -> current name. Newton-backend solver presets are +# now prefixed with ``newton_`` so they group together in autocomplete and read +# distinctly from backend/package/visualizer names that also use the word +# ``newton``. Aliases keep legacy CLI invocations and ``PresetCfg`` field accesses +# working with a :class:`FutureWarning`; they will be removed in a future release. +_LEGACY_PRESET_ALIASES = {"newton": "newton_mjwarp", "kamino": "newton_kamino"} + + +def _user_stacklevel() -> int: + """Compute a ``warnings.warn`` stacklevel that lands on the first frame + outside this module, so deprecation messages cite user code rather than + internal hydra-utility frames. + + Walks at most a small bounded number of frames; if no non-hydra frame is + found within the bound (frozen modules, exec'd contexts, or oddly named + ``__file__`` globals), falls back to ``stacklevel=2`` so the warning at + least jumps out of the helper that called it. + """ + max_walk = 16 + level = 1 + frame = sys._getframe(1) + while frame is not None and frame.f_globals.get("__file__") == __file__: + level += 1 + frame = frame.f_back + if level > max_walk: + return 2 + return level + + +def _known_preset_names(presets: dict) -> set[str]: + """Return all preset names declared in a collected preset dictionary.""" + return {name for section in presets.values() for fields in section.values() for name in fields} + + +def _normalize_preset_name(name: str, known_names: set[str]) -> str: + """Map a deprecated preset name to its replacement and emit a warning. + + Returns ``name`` unchanged when: + * ``name`` is not a deprecated alias, or + * the replacement is not declared in ``known_names`` (so the user-supplied + value can flow into the standard "unknown preset" error path, where + :func:`_format_unknown_presets_error` will surface the rename), or + * ``name`` is itself a real field in ``known_names`` (a user-defined preset + legitimately reusing the deprecated spelling shadows the alias). + """ + replacement = _LEGACY_PRESET_ALIASES.get(name) + if replacement is None or replacement not in known_names or name in known_names: + return name + warnings.warn( + f"Preset '{name}' is deprecated. Use '{replacement}' instead.", + FutureWarning, + stacklevel=_user_stacklevel(), + ) + return replacement @configclass @@ -55,10 +108,32 @@ class PresetCfg: @configclass class PhysicsCfg(PresetCfg): default: PhysxCfg = PhysxCfg() - newton: NewtonCfg = NewtonCfg() + newton_mjwarp: NewtonCfg = NewtonCfg() + + The preset *name* (``newton_mjwarp``) is decoupled from the config class + (``NewtonCfg``): the class describes the Newton backend, while the field + name labels which solver variant this entry selects. """ - pass + def __getattr__(self, name: str): + """Alias a deprecated preset name to its replacement field. + + Raises ``AttributeError`` for any other missing attribute so that + ``hasattr`` and standard introspection keep working unchanged. The + replacement is only returned when the deprecated name is *not* itself a + real field on the subclass, so a user redefining the deprecated name + shadows the alias. + """ + replacement = _LEGACY_PRESET_ALIASES.get(name) + fields = getattr(type(self), "__dataclass_fields__", {}) + if replacement is not None and replacement in fields and name not in fields: + warnings.warn( + f"Preset '{name}' is deprecated. Use '{replacement}' instead.", + FutureWarning, + stacklevel=_user_stacklevel(), + ) + return getattr(self, replacement) + raise AttributeError(f"{type(self).__name__!s} object has no attribute {name!r}") def preset(**options) -> PresetCfg: @@ -70,12 +145,12 @@ def preset(**options) -> PresetCfg: Example:: - armature = preset(default=0.0, newton=0.01) + armature = preset(default=0.0, newton_mjwarp=0.01) # Equivalent to: # @configclass # class _Preset(PresetCfg): # default: float = 0.0 - # newton: float = 0.01 + # newton_mjwarp: float = 0.01 # armature = _Preset() Args: @@ -142,7 +217,7 @@ def collect_presets(cfg, path: str = "") -> dict: Returns: Dict mapping dotted paths to preset dicts, e.g.: - ``{"backend": {"default": PhysxCfg(), "newton": NewtonCfg()}}`` + ``{"backend": {"default": PhysxCfg(), "newton_mjwarp": NewtonCfg()}}`` """ result = {} @@ -152,6 +227,10 @@ def _record(preset_obj, preset_path): for alt in fields.values(): if hasattr(alt, "__dataclass_fields__"): result.update(collect_presets(alt, preset_path)) + elif isinstance(alt, dict): + for v in alt.values(): + if hasattr(v, "__dataclass_fields__"): + result.update(collect_presets(v, preset_path)) if isinstance(cfg, PresetCfg): _record(cfg, path) @@ -161,6 +240,91 @@ def _record(preset_obj, preset_path): return result +# ============================================================================ +# Preset resolution +# ============================================================================ + + +def _pick_alternative(preset_obj: PresetCfg, selected: set[str], path: str = ""): + """Choose the best alternative from a PresetCfg. + + Priority: first match in ``selected``, then ``default`` (preferring + class-level over instance-level). + + Raises: + ValueError: If no matching name and no ``default`` field exists. + """ + fields = _preset_fields(preset_obj) + field_names = set(fields) + for name in selected: + name = _normalize_preset_name(name, field_names) + if name in fields: + return fields[name] + if "default" in fields: + return fields["default"] + raise ValueError( + f"PresetCfg {type(preset_obj).__name__} at '{path}' has no 'default' field " + f"and none of the selected presets {selected} match its fields {set(fields.keys())}." + ) + + +def resolve_presets(cfg, selected: set[str] = frozenset()): + """Replace every :class:`PresetCfg` in the tree with the best alternative. + + For each ``PresetCfg`` found during a depth-first walk: + + 1. Pick the first name from *selected* that exists as a field on the + preset, otherwise fall back to ``default``. + 2. Replace the preset in its parent (dict key or dataclass attr). + 3. Continue walking the replacement (which may contain more presets). + + Args: + cfg: A configclass, dict, or PresetCfg to resolve in-place. + selected: Set of preset names chosen by the user (e.g. from CLI + ``presets=peg_insert_4mm,eval``). + + Returns: + The resolved ``cfg`` (possibly a different object if the root itself + was a PresetCfg). + """ + if isinstance(cfg, PresetCfg): + seen: set[int] = {id(cfg)} + replacement = _pick_alternative(cfg, selected, path="") + while isinstance(replacement, PresetCfg): + if id(replacement) in seen: + raise ValueError( + f"Cyclic PresetCfg chain detected at '': {type(replacement).__name__} was already visited." + ) + seen.add(id(replacement)) + replacement = _pick_alternative(replacement, selected, path="") + return resolve_presets(replacement, selected) + + def _resolve(parent, key, preset_obj, _path): + seen: set[int] = {id(preset_obj)} + val = _pick_alternative(preset_obj, selected, path=_path) + while isinstance(val, PresetCfg): + if id(val) in seen: + raise ValueError( + f"Cyclic PresetCfg chain detected at '{_path}': {type(val).__name__} was already visited." + ) + seen.add(id(val)) + val = _pick_alternative(val, selected, path=_path) + if isinstance(parent, dict): + parent[key] = val + else: + setattr(parent, key, val) + if hasattr(val, "__dataclass_fields__") or isinstance(val, dict): + _walk_cfg(val, _path, _resolve) + + _walk_cfg(cfg, "", _resolve) + return cfg + + +# ============================================================================ +# CLI / Hydra integration +# ============================================================================ + + def _run_hydra(task, env_cfg, agent_cfg, presets, callback): """Shared Hydra entry point for :func:`resolve_task_config` and :func:`hydra_task_config`.""" global_presets, preset_sel, preset_scalar, global_scalar = parse_overrides(sys.argv[1:], presets) @@ -189,7 +353,7 @@ def hydra_main(hydra_cfg, env_cfg=env_cfg, agent_cfg=agent_cfg): def resolve_task_config(task_name: str, agent_cfg_entry_point: str): """Resolve env and agent configs with Hydra overrides, presets, and scalars fully applied. - Safe to call before Kit is launched — callable config values are stored as + Safe to call before Kit is launched -- callable config values are stored as :class:`~isaaclab.utils.string.ResolvableString` and resolved lazily on first use, so no implementation modules are imported eagerly. @@ -230,30 +394,42 @@ def wrapper(*args, **kwargs): return decorator -def resolve_preset_defaults(cfg): - """Replace PresetCfg fields with their ``default`` value, recursively. +def _format_unknown_presets_error(unknown: set[str], name_to_paths: dict[str, list[str]], max_paths: int = 5) -> str: + """Build a readable error message grouping presets by identical path fingerprints. - Must be called before ``to_dict()`` so the Hydra dict contains only the - resolved config rather than the raw PresetCfg with all alternatives. - Returns the (possibly replaced) cfg if the root itself is a PresetCfg. + When an unknown name matches a deprecated alias (e.g. ``newton``), the + message explicitly calls out the rename so users updating from older + tutorials or scripts get an actionable hint instead of a bare "unknown". """ - if isinstance(cfg, PresetCfg): - default = getattr(cfg, "default", None) - return resolve_preset_defaults(default) if default is not None else cfg - - def _on_preset(parent, key, preset_obj, _path): - default = getattr(preset_obj, "default", None) - if default is None: - return - if isinstance(parent, dict): - parent[key] = default + fingerprint_to_names: dict[tuple[str, ...], list[str]] = {} + for name, paths in name_to_paths.items(): + key = tuple(sorted(paths)) + fingerprint_to_names.setdefault(key, []).append(name) + + lines = [f"Unknown preset(s): {', '.join(sorted(unknown))}"] + deprecated_hits = sorted(name for name in unknown if name in _LEGACY_PRESET_ALIASES) + for legacy in deprecated_hits: + replacement = _LEGACY_PRESET_ALIASES[legacy] + lines.append(f" '{legacy}' was renamed to '{replacement}'; this task does not declare '{replacement}' either.") + lines += [ + "", + "Available presets (grouped by affected paths):", + "", + ] + for paths_tuple in sorted(fingerprint_to_names, key=lambda k: fingerprint_to_names[k][0]): + names = sorted(fingerprint_to_names[paths_tuple]) + if len(names) <= 30: + lines.append(f" {', '.join(names)}") else: - setattr(parent, key, default) - if hasattr(default, "__dataclass_fields__"): - resolve_preset_defaults(default) - - _walk_cfg(cfg, "", _on_preset) - return cfg + lines.append(f" {', '.join(names[:25])}, ... ({len(names)} total)") + shown = list(paths_tuple[:max_paths]) + for p in shown: + lines.append(f" -> {p}") + remaining = len(paths_tuple) - len(shown) + if remaining > 0: + lines.append(f" ... ({remaining} more)") + lines.append("") + return "\n".join(lines) def register_task(task_name: str, agent_entry: str) -> tuple: @@ -266,29 +442,54 @@ def register_task(task_name: str, agent_entry: str) -> tuple: (env_cfg, agent_cfg, presets) where presets = {"env": {"path": {"name": cfg}}, "agent": {...}} """ + from isaaclab_tasks.utils.parse_cfg import load_cfg_from_registry + env_cfg = load_cfg_from_registry(task_name, "env_cfg_entry_point") - agent_cfg = None - if agent_entry: - agent_cfg = load_cfg_from_registry(task_name, agent_entry) + agent_cfg = load_cfg_from_registry(task_name, agent_entry) if agent_entry else None - # Collect presets recursively from the config tree + # Collect presets before resolution (needed for path-based overrides) presets = { "env": collect_presets(env_cfg), "agent": collect_presets(agent_cfg) if agent_cfg else {}, } - # Resolve PresetCfg defaults before serialization so to_dict() doesn't - # include all preset alternatives in the hydra dict. - env_cfg = resolve_preset_defaults(env_cfg) + known_names = _known_preset_names(presets) + selected = { + _normalize_preset_name(v.strip(), known_names) + for arg in sys.argv[1:] + if "=" in arg + for key, val in [arg.split("=", 1)] + if key.lstrip("-") == "presets" + for v in val.split(",") + if v.strip() + } + + if selected: + name_to_paths: dict[str, list[str]] = {} + for sec, sec_presets in presets.items(): + for path, fields in sec_presets.items(): + full = f"{sec}.{path}" if path else sec + for name in fields: + name_to_paths.setdefault(name, []).append(full) + unknown = selected - set(name_to_paths) + if unknown: + display = {n: p for n, p in name_to_paths.items() if n != "default"} + raise ValueError(_format_unknown_presets_error(unknown, display)) + + env_cfg = resolve_presets(env_cfg, selected) if agent_cfg is not None: - agent_cfg = resolve_preset_defaults(agent_cfg) + agent_cfg = resolve_presets(agent_cfg, selected) + + # Also resolve presets inside collected alternatives so that apply_overrides + # never re-introduces unresolved PresetCfg objects when applying a selection. + for section_presets in presets.values(): + for path_presets in section_presets.values(): + for name, alt in path_presets.items(): + resolve_presets(alt, selected) # Convert to dict for Hydra (handle gym spaces and slices) env_cfg = replace_env_cfg_spaces_with_strings(env_cfg) - if agent_cfg is not None and hasattr(agent_cfg, "to_dict"): - agent_dict = agent_cfg.to_dict() - else: - agent_dict = agent_cfg + agent_dict = agent_cfg.to_dict() if agent_cfg is not None and hasattr(agent_cfg, "to_dict") else agent_cfg env_dict = env_cfg.to_dict() # type: ignore[union-attr] cfg_dict = replace_slices_with_strings({"env": env_dict, "agent": agent_dict}) @@ -311,8 +512,6 @@ def parse_overrides(args: list[str], presets: dict) -> tuple: - preset_scalar: [(full_path, value), ...] - scalars in preset paths - global_scalar: [arg, ...] - pass to Hydra """ - # Build lookup of preset group paths (e.g., "env.actions"). - # Root-level PresetCfg has path="" -> bare "env" or "agent" key. preset_paths = {f"{s}.{p}" if p else s for s, v in presets.items() for p in v} global_presets, preset_sel, preset_scalar, global_scalar = [], [], [], [] @@ -322,10 +521,12 @@ def parse_overrides(args: list[str], presets: dict) -> tuple: continue key, val = arg.split("=", 1) if key == "presets": - global_presets.extend(v.strip() for v in val.split(",") if v.strip()) + known_names = _known_preset_names(presets) + global_presets.extend(_normalize_preset_name(v.strip(), known_names) for v in val.split(",") if v.strip()) elif key in preset_paths: sec, path = key.split(".", 1) if "." in key else (key, "") - preset_sel.append((sec, path, val)) + known_names = set(presets[sec][path]) + preset_sel.append((sec, path, _normalize_preset_name(val, known_names))) elif any(key.startswith(pp + ".") for pp in preset_paths): preset_scalar.append((key, val)) else: @@ -346,13 +547,14 @@ def apply_overrides( ): """Apply preset selections and scalar overrides with REPLACE semantics. - Phase 1: Determine the selected preset name for every path (explicit - selections, then global broadcasts, then ``default`` fallback). - Phase 2: Apply in depth order, pruning children whose parent is None. - Phase 3: Apply scalar overrides on top. + Global presets are already applied by :func:`resolve_presets` in + :func:`register_task`. This function handles: + + 1. Path-based selections (``env.backend=newton_mjwarp``) + 2. Scalar overrides within preset paths (``env.backend.dt=0.001``) Returns: - (env_cfg, agent_cfg) — possibly replaced if root-level PresetCfg was resolved. + (env_cfg, agent_cfg) -- possibly replaced if root-level PresetCfg was resolved. Raises: ValueError: If multiple global presets conflict on the same path. @@ -372,29 +574,26 @@ def _path_reachable(sec: str, path: str) -> bool: return False return True - def _apply_node(sec: str, path: str, node): - node_dict = node.to_dict() if hasattr(node, "to_dict") else dict(node) if isinstance(node, Mapping) else node - if path == "": - cfgs[sec] = node - hydra_cfg[sec] = node_dict - else: - _setattr(cfgs[sec], path, node) - _setattr(hydra_cfg, f"{sec}.{path}", node_dict) - - # --- Phase 1: Determine selected preset name for every path --------------- + # --- Phase 1: path-based selections + global broadcast for reachable paths resolved: dict[str, tuple[str, str, str]] = {} for sec, path, name in preset_sel: if path not in presets.get(sec, {}): raise ValueError(f"Unknown preset group: {sec}.{path}") + name = _normalize_preset_name(name, set(presets[sec][path])) if name not in presets[sec][path]: avail = list(presets[sec][path].keys()) - raise ValueError(f"Unknown preset '{name}' for {sec}.{path}. Available: {avail}") + hint = "" + if name in _LEGACY_PRESET_ALIASES: + replacement = _LEGACY_PRESET_ALIASES[name] + hint = f" '{name}' was renamed to '{replacement}'; this path does not declare '{replacement}' either." + raise ValueError(f"Unknown preset '{name}' for {sec}.{path}. Available: {avail}.{hint}") full_path = f"{sec}.{path}" if path else sec resolved[full_path] = (sec, path, name) - # Apply global presets (error on real conflict — same path, different value) applied_by: dict[str, str] = {} + known_names = _known_preset_names(presets) for name in global_presets: + name = _normalize_preset_name(name, known_names) for sec in ("env", "agent"): for path, path_presets in presets.get(sec, {}).items(): if name in path_presets: @@ -410,30 +609,34 @@ def _apply_node(sec: str, path: str, node): ) else: applied_by[full_path] = name - if full_path not in resolved: - resolved[full_path] = (sec, path, name) + resolved.setdefault(full_path, (sec, path, name)) - # Fill remaining paths with "default" (if available) for sec in ("env", "agent"): for path, path_presets in presets.get(sec, {}).items(): - full_path = f"{sec}.{path}" if path else sec - if full_path not in resolved and "default" in path_presets: - resolved[full_path] = (sec, path, "default") + if "default" in path_presets: + full_path = f"{sec}.{path}" if path else sec + resolved.setdefault(full_path, (sec, path, "default")) - # --- Phase 2: Apply in depth order, pruning unreachable children ---------- + # --- Phase 2: apply in depth order, pruning unreachable children for full_path in sorted(resolved, key=lambda fp: fp.count(".")): sec, path, name = resolved[full_path] if cfgs[sec] is not None and _path_reachable(sec, path): - _apply_node(sec, path, presets[sec][path][name]) - - # 3. Apply scalar overrides within preset paths + node = presets[sec][path][name] + node_dict = ( + node.to_dict() if hasattr(node, "to_dict") else dict(node) if isinstance(node, Mapping) else node + ) + if not path: + cfgs[sec], hydra_cfg[sec] = node, node_dict + else: + _setattr(cfgs[sec], path, node) + _setattr(hydra_cfg, f"{sec}.{path}", node_dict) + + # --- Phase 3: scalar overrides within preset paths for full_path, val_str in preset_scalar: - if full_path.startswith("env."): - sec, path = "env", full_path[4:] - elif full_path.startswith("agent."): - sec, path = "agent", full_path[6:] - else: + sec = full_path.split(".", 1)[0] + if sec not in cfgs: continue + path = full_path[len(sec) + 1 :] if cfgs[sec] is not None: val = _parse_val(val_str) _setattr(cfgs[sec], path, val) @@ -455,17 +658,9 @@ def _setattr(obj, path: str, val): def _parse_val(s: str): """Parse string to Python value (bool, None, int, float, or str).""" - low = s.lower() - if low == "true": - return True - if low == "false": - return False - if low in ("none", "null"): - return None + if s.lower() in _LITERAL_MAP: + return _LITERAL_MAP[s.lower()] try: return float(s) if "." in s else int(s) except ValueError: - # Strip quotes if present - if s[0] in "\"'" and s[-1] in "\"'": - return s[1:-1] - return s + return s[1:-1] if len(s) >= 2 and s[0] in "\"'" and s[-1] in "\"'" else s diff --git a/source/isaaclab_tasks/isaaclab_tasks/utils/parse_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/utils/parse_cfg.py index 2c7b39fe90b9..e5e71fa06f8c 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/utils/parse_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/utils/parse_cfg.py @@ -17,6 +17,8 @@ import gymnasium as gym import yaml +from isaaclab_tasks.utils.hydra import resolve_presets + if TYPE_CHECKING: from isaaclab.envs import DirectRLEnvCfg, ManagerBasedRLEnvCfg @@ -141,8 +143,6 @@ def parse_env_cfg( RuntimeError: If the configuration for the task is not a class. We assume users always use a class for the environment configuration. """ - from isaaclab_tasks.utils.hydra import resolve_preset_defaults - # load the default configuration cfg = load_cfg_from_registry(task_name.split(":")[-1], "env_cfg_entry_point") @@ -156,7 +156,7 @@ def parse_env_cfg( # Must happen BEFORE attribute overrides, otherwise overrides on PresetCfg wrapper # fields (e.g. cfg.scene when scene is a PresetCfg) get discarded when the wrapper # is replaced by its .default. - cfg = resolve_preset_defaults(cfg) + cfg = resolve_presets(cfg) # simulation device cfg.sim.device = device diff --git a/source/isaaclab_tasks/isaaclab_tasks/utils/sim_launcher.py b/source/isaaclab_tasks/isaaclab_tasks/utils/sim_launcher.py index 1296873b1537..3030bda1c4b7 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/utils/sim_launcher.py +++ b/source/isaaclab_tasks/isaaclab_tasks/utils/sim_launcher.py @@ -66,9 +66,9 @@ def _visit(node): return results -def _is_newton_physics(node) -> bool: - """True when the node is a Newton physics config (Kit is not required).""" - return isinstance(node, PhysicsCfg) and type(node).__name__ == "NewtonCfg" +def _is_kitless_physics(node) -> bool: + """True when the node is a kitless physics config (Newton or OvPhysX).""" + return isinstance(node, PhysicsCfg) and type(node).__name__ in ("NewtonCfg", "OvPhysxCfg") def _get_visualizer_types(launcher_args: argparse.Namespace | dict | None) -> set[str]: @@ -122,6 +122,15 @@ def _is_kit_camera(node) -> bool: return True if isinstance(renderer_cfg, RendererCfg): return renderer_cfg.renderer_type in ("default", "isaac_rtx") + # PresetCfg renderers (e.g. MultiBackendRendererCfg) are resolved during + # environment construction when the physics backend is known (see + # resolve_task_config and preset resolution in presets.py). At this + # stage we assume they will match the physics backend, so not + # necessarily Kit. + from isaaclab_tasks.utils import PresetCfg + + if isinstance(renderer_cfg, PresetCfg): + return False return True @@ -141,14 +150,72 @@ def compute_kit_requirements( Returns: (needs_kit, has_kit_cameras, visualizer_types) """ - is_newton, has_kit_cameras = _scan_config(env_cfg, [_is_newton_physics, _is_kit_camera]) - needs_kit = has_kit_cameras or not is_newton + is_kitless, has_kit_cameras = _scan_config(env_cfg, [_is_kitless_physics, _is_kit_camera]) + needs_kit = has_kit_cameras or not is_kitless visualizer_types = _get_visualizer_types(launcher_args) if "kit" in visualizer_types: needs_kit = True return needs_kit, has_kit_cameras, visualizer_types +def _resolve_distributed_device( + env_cfg, + launcher_args: argparse.Namespace | dict | None, +) -> None: + """Set ``env_cfg.sim.device`` for distributed training. + + When ``--distributed`` is active and CUDA_VISIBLE_DEVICES restricts each + process to a single GPU, ``local_rank`` may exceed the visible device count. + This helper applies the same fallback logic used by :class:`AppLauncher` so + that **training scripts do not need their own device-resolution code**. + + For the Kit path, :func:`launch_simulation` additionally propagates + ``AppLauncher.device`` after creation; this function handles the early + (pre-AppLauncher) and kitless cases. + """ + distributed = False + if isinstance(launcher_args, argparse.Namespace): + distributed = getattr(launcher_args, "distributed", False) + elif isinstance(launcher_args, dict): + distributed = launcher_args.get("distributed", False) + + if not distributed: + return + + import os + + import torch + + local_rank = int(os.getenv("LOCAL_RANK", "0")) + int(os.getenv("JAX_LOCAL_RANK", "0")) + num_visible_gpus = torch.cuda.device_count() + + # Compare local_rank against device_count (not WORLD_SIZE) so that + # multi-node setups work correctly: WORLD_SIZE is global across all + # nodes, but device_count is local. + if local_rank < num_visible_gpus: + device_str = f"cuda:{local_rank}" + else: + device_str = "cuda:0" + + sim_cfg = getattr(env_cfg, "sim", None) + if sim_cfg is not None: + sim_cfg.device = device_str + + # Set CUDA device early so physics backends that allocate on the + # "current" device during init get the correct GPU. For the Kit path, + # AppLauncher._resolve_device_settings will call set_device again with + # the same value, which is harmless. For the kitless Newton path, this + # is the only place it gets set. + torch.cuda.set_device(device_str) + + logger.info( + "Distributed device resolved to %s (local_rank=%d, visible_gpus=%d)", + device_str, + local_rank, + num_visible_gpus, + ) + + @contextmanager def launch_simulation( env_cfg, @@ -169,6 +236,24 @@ def launch_simulation( with launch_simulation(env_cfg, args_cli): main() """ + # When --visualizer kit is explicitly requested alongside an ovrtx preset, fail early. + # ovrtx and Kit ship the same RTX hydra libraries under conflicting USD namespaces; + # loading both in the same process causes a dynamic-linker crash. Use + # --visualizer newton instead, which is compatible with ovrtx presets. + early_visualizer_types = _get_visualizer_types(launcher_args) + if "kit" in early_visualizer_types: + has_ovrtx = _scan_config( + env_cfg, [lambda node: isinstance(node, RendererCfg) and getattr(node, "renderer_type", None) == "ovrtx"] + )[0] + if has_ovrtx: + raise ValueError( + "[launch_simulation] '--visualizer kit' is incompatible with 'ovrtx_renderer'. " + "Both Kit (Isaac Sim) and ovrtx ship conflicting RTX hydra libraries " + "(librtx.hydra.so, liblegacy.hydra.so) compiled against different USD namespaces, " + "which causes a dynamic-linker crash when loaded into the same process. " + "Use '--visualizer newton' instead, which is fully compatible with ovrtx presets." + ) + needs_kit, has_kit_cameras, visualizer_types = compute_kit_requirements(env_cfg, launcher_args) visualizer_intent = _compute_visualizer_intent(env_cfg) _set_visualizer_intent_on_launcher_args(launcher_args, visualizer_intent) @@ -185,17 +270,46 @@ def launch_simulation( close_fn: Any = None + # Resolve distributed device early, before AppLauncher or physics init. + _resolve_distributed_device(env_cfg, launcher_args) + if needs_kit: # check if Isaac Sim is installed import importlib.util if importlib.util.find_spec("omni.kit") is None: + # Print a more obvious hint when a local _isaac_sim symlink + # exists but its env wasn't sourced (typical on Win11 + conda + # when activate.d hooks didn't fire, e.g. under `conda run`). + import os + import sys + + isaaclab_path = os.environ.get("ISAACLAB_PATH") + local_sim = os.path.join(isaaclab_path, "_isaac_sim") if isaaclab_path else None + extra_hint = "" + if local_sim and os.path.isdir(local_sim): + if sys.platform == "win32": + extra_hint = ( + f" Found a local Isaac Sim at {local_sim} but its environment is not active.\n" + f" Either run via `isaaclab.bat ...` (which now sources setup_conda_env.bat\n" + f" automatically), or in your current shell run:\n" + f' call "{local_sim}\\setup_conda_env.bat"\n' + ) + else: + extra_hint = ( + f" Found a local Isaac Sim at {local_sim} but its environment is not active.\n" + f" Either run via `./isaaclab.sh ...` (which now sources setup_conda_env.sh\n" + f" automatically), or in your current shell run:\n" + f' source "{local_sim}/setup_conda_env.sh"\n' + ) + logger.error( "\n[ERROR] Isaac Sim is not installed or not found on PYTHONPATH.\n" "\n" " This environment requires Isaac Sim and Omniverse Kit.\n" " PhysX backend and Kit visualizer currently requires Isaac Sim.\n" "\n" + f"{extra_hint}" " To fix this, ensure Isaac Sim is installed and available in the current environment.\n" "\n" " See https://isaac-sim.github.io/IsaacLab/main/source/setup/installation for details.\n" @@ -209,20 +323,29 @@ def launch_simulation( from isaaclab.app import AppLauncher app_launcher = AppLauncher(launcher_args) + # AppLauncher may refine the device choice (e.g. Kit-specific + # overrides), so propagate its final value to env_cfg. This + # intentionally overwrites the earlier value set by + # _resolve_distributed_device. + sim_cfg = getattr(env_cfg, "sim", None) + if sim_cfg is not None and hasattr(app_launcher, "device"): + sim_cfg.device = app_launcher.device close_fn = app_launcher.app.close elif visualizer_types: # Newton path without Kit: AppLauncher is skipped, so manually store the visualizer # selection in SettingsManager (works in standalone mode via plain dict) so that # SimulationContext._get_cli_visualizer_types() can find it. - from isaaclab.app.settings_manager import get_settings_manager + from isaaclab.app import AppLauncher disable_all = "none" in visualizer_types - active_types = [] if disable_all else sorted(visualizer_types) - visualizer_str = " ".join(active_types) - settings = get_settings_manager() - settings.set_string("/isaaclab/visualizer/types", visualizer_str) - settings.set_bool("/isaaclab/visualizer/explicit", True) - settings.set_bool("/isaaclab/visualizer/disable_all", disable_all) + if isinstance(launcher_args, argparse.Namespace): + AppLauncher.sync_visualizer_cli_settings_to_carb( + {**vars(launcher_args), "visualizer_explicit": True, "visualizer_disable_all": disable_all} + ) + elif isinstance(launcher_args, dict): + AppLauncher.sync_visualizer_cli_settings_to_carb( + {**launcher_args, "visualizer_explicit": True, "visualizer_disable_all": disable_all} + ) try: yield diff --git a/source/isaaclab_tasks/setup.py b/source/isaaclab_tasks/setup.py index bf552926d857..a719231ca986 100644 --- a/source/isaaclab_tasks/setup.py +++ b/source/isaaclab_tasks/setup.py @@ -40,16 +40,13 @@ keywords=EXTENSION_TOML_DATA["package"]["keywords"], include_package_data=True, package_data={"": ["*.pyi"]}, - python_requires=">=3.10", + python_requires=">=3.12", install_requires=INSTALL_REQUIRES, dependency_links=PYTORCH_INDEX_URL, packages=["isaaclab_tasks"], classifiers=[ "Natural Language :: English", - "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", - "Isaac Sim :: 5.0.0", - "Isaac Sim :: 5.1.0", "Isaac Sim :: 6.0.0", ], zip_safe=False, diff --git a/source/isaaclab_tasks/test/benchmarking/test_environments_training.py b/source/isaaclab_tasks/test/benchmarking/test_environments_training.py index 51df662d7ec2..988cc0336789 100644 --- a/source/isaaclab_tasks/test/benchmarking/test_environments_training.py +++ b/source/isaaclab_tasks/test/benchmarking/test_environments_training.py @@ -76,6 +76,7 @@ def train_job(workflow, task, env_config, num_gpus): return duration +@pytest.mark.skip(reason="Temporarily disabled due to long running time.") @pytest.mark.parametrize("task_spec", setup_environment()) def test_train_environments(workflow, task_spec, config_path, mode, num_gpus, kpi_store): """Train environments provided in the config file, save KPIs, and evaluate against thresholds""" diff --git a/source/isaaclab_tasks/test/env_test_utils.py b/source/isaaclab_tasks/test/env_test_utils.py index 302051aaa538..cde4db9a3693 100644 --- a/source/isaaclab_tasks/test/env_test_utils.py +++ b/source/isaaclab_tasks/test/env_test_utils.py @@ -23,6 +23,11 @@ from isaaclab_tasks.utils.hydra import apply_overrides, collect_presets from isaaclab_tasks.utils.parse_cfg import load_cfg_from_registry, parse_env_cfg +# Map of task IDs to the reason for marking the corresponding parametrized +# test cases as expected failures. Tests that consume :func:`setup_environment` +# automatically pick up these marks via :class:`pytest.param`. +XFAIL_TASKS: dict[str, str] = {} + def _is_teleop_env(task_spec) -> bool: """Check if a task's environment config has teleop dependencies. @@ -63,7 +68,7 @@ def _has_physics_preset(raw_cfg, preset_name: str) -> bool: Args: raw_cfg: Raw env config from :func:`load_cfg_from_registry`. - preset_name: Name of the preset to check for (e.g., 'newton'). + preset_name: Name of the preset to check for (e.g., 'newton_mjwarp'). Returns: True if ``raw_cfg.sim.physics`` is a PresetCfg with the given preset field. @@ -89,7 +94,7 @@ def setup_environment( teleop_envs: bool | None = None, cartpole_showcase_envs: bool | None = None, pickplace_stack_envs: bool | None = None, - newton_envs: bool | None = None, + newton_mjwarp_envs: bool | None = None, ) -> list[str]: """ Acquire all registered Isaac environment task IDs with optional filters. @@ -116,10 +121,10 @@ def setup_environment( - True: include only PickPlace/Stack environments - False: exclude PickPlace/Stack environments - None: include all environments regardless of pick-place/stack type - newton_envs: - - True: include only environments that have a newton physics preset - - False: exclude environments that have a newton physics preset - - None: include all environments regardless of newton preset availability + newton_mjwarp_envs: + - True: include only environments that have an MJWarp physics preset. + - False: exclude environments that have an MJWarp physics preset. + - None: include all environments regardless of MJWarp preset availability. Returns: A sorted list of task IDs matching the selected filters. @@ -180,13 +185,15 @@ def setup_environment( continue # if None: no filter - # apply newton preset filter - if newton_envs is not None: + # apply MJWarp preset filter + if newton_mjwarp_envs is not None: # Use load_cfg_from_registry (not parse_env_cfg) so that the PresetCfg # wrapper on sim.physics is not yet resolved to its default. raw_cfg = load_cfg_from_registry(task_spec.id, "env_cfg_entry_point") - has_newton = _has_physics_preset(raw_cfg, "newton") - if (newton_envs is True and not has_newton) or (newton_envs is False and has_newton): + has_newton_mjwarp = _has_physics_preset(raw_cfg, "newton_mjwarp") + if (newton_mjwarp_envs is True and not has_newton_mjwarp) or ( + newton_mjwarp_envs is False and has_newton_mjwarp + ): continue # if None: no filter @@ -200,7 +207,14 @@ def setup_environment( print(">>> All registered environments:", registered_tasks) - return registered_tasks + # Wrap tasks listed in XFAIL_TASKS in pytest.param so the corresponding + # parametrized test cases are reported as xfailed instead of failed. + return [ + pytest.param(task_id, marks=pytest.mark.xfail(reason=XFAIL_TASKS[task_id], strict=False)) + if task_id in XFAIL_TASKS + else task_id + for task_id in registered_tasks + ] def _run_environments( @@ -223,7 +237,7 @@ def _run_environments( multi_agent: Whether the environment is multi-agent. create_stage_in_memory: Whether to create stage in memory. disable_clone_in_fabric: Whether to disable fabric cloning. - physics_preset_name: Name of the physics preset to apply (e.g., 'newton'). + physics_preset_name: Name of the physics preset to apply (e.g., 'newton_mjwarp'). If None, uses the environment's default physics. """ @@ -311,7 +325,7 @@ def _check_random_actions( multi_agent: Whether the environment is multi-agent. create_stage_in_memory: Whether to create stage in memory. disable_clone_in_fabric: Whether to disable fabric cloning. - physics_preset_name: Name of the physics preset to apply (e.g., 'newton'). + physics_preset_name: Name of the physics preset to apply (e.g., 'newton_mjwarp'). If None, uses the environment's default physics. """ # create a new context stage, if stage in memory is not enabled @@ -351,10 +365,11 @@ def _check_random_actions( print(f"[INFO]: Skipping {task_name} as it is a multi-agent task") return - # TODO: Some Newton preset + multi-asset spawning combinations fail config validation - # here with a ValueError. Consider filtering invalid combinations in setup_environment() - # rather than forgiving them at runtime. See PR #5097 commit fb2c74a3862 for a workaround - # that caught the error and called pytest.skip(). + # TODO: Selecting the MJWarp preset routes through the Newton backend, which does not yet + # support multi-asset spawning; some combinations fail config validation here with a + # ValueError. Consider filtering invalid combinations in setup_environment() rather than + # forgiving them at runtime. See PR #5097 commit fb2c74a3862 for a workaround that caught + # the error and called pytest.skip(). env = gym.make(task_name, cfg=env_cfg) # disable control on stop diff --git a/source/isaaclab_tasks/test/golden_images/cartpole/newton-isaacsim_rtx_renderer-albedo.png b/source/isaaclab_tasks/test/golden_images/cartpole/newton-isaacsim_rtx_renderer-albedo.png index 69cd9439c305..d44cd9a9f6a8 100644 Binary files a/source/isaaclab_tasks/test/golden_images/cartpole/newton-isaacsim_rtx_renderer-albedo.png and b/source/isaaclab_tasks/test/golden_images/cartpole/newton-isaacsim_rtx_renderer-albedo.png differ diff --git a/source/isaaclab_tasks/test/golden_images/cartpole/newton-isaacsim_rtx_renderer-depth.png b/source/isaaclab_tasks/test/golden_images/cartpole/newton-isaacsim_rtx_renderer-depth.png index d62d599245cf..0387686a7a78 100644 Binary files a/source/isaaclab_tasks/test/golden_images/cartpole/newton-isaacsim_rtx_renderer-depth.png and b/source/isaaclab_tasks/test/golden_images/cartpole/newton-isaacsim_rtx_renderer-depth.png differ diff --git a/source/isaaclab_tasks/test/golden_images/cartpole/newton-isaacsim_rtx_renderer-rgb.png b/source/isaaclab_tasks/test/golden_images/cartpole/newton-isaacsim_rtx_renderer-rgb.png old mode 100755 new mode 100644 index cfd8f750494f..4c01a0c9d17c Binary files a/source/isaaclab_tasks/test/golden_images/cartpole/newton-isaacsim_rtx_renderer-rgb.png and b/source/isaaclab_tasks/test/golden_images/cartpole/newton-isaacsim_rtx_renderer-rgb.png differ diff --git a/source/isaaclab_tasks/test/golden_images/cartpole/newton-isaacsim_rtx_renderer-rgba.png b/source/isaaclab_tasks/test/golden_images/cartpole/newton-isaacsim_rtx_renderer-rgba.png old mode 100755 new mode 100644 index d39fca42cbee..7eae5eb40345 Binary files a/source/isaaclab_tasks/test/golden_images/cartpole/newton-isaacsim_rtx_renderer-rgba.png and b/source/isaaclab_tasks/test/golden_images/cartpole/newton-isaacsim_rtx_renderer-rgba.png differ diff --git a/source/isaaclab_tasks/test/golden_images/cartpole/newton-isaacsim_rtx_renderer-semantic_segmentation.png b/source/isaaclab_tasks/test/golden_images/cartpole/newton-isaacsim_rtx_renderer-semantic_segmentation.png index 4d66b87eb642..21926715b7f6 100644 Binary files a/source/isaaclab_tasks/test/golden_images/cartpole/newton-isaacsim_rtx_renderer-semantic_segmentation.png and b/source/isaaclab_tasks/test/golden_images/cartpole/newton-isaacsim_rtx_renderer-semantic_segmentation.png differ diff --git a/source/isaaclab_tasks/test/golden_images/cartpole/newton-isaacsim_rtx_renderer-simple_shading_constant_diffuse.png b/source/isaaclab_tasks/test/golden_images/cartpole/newton-isaacsim_rtx_renderer-simple_shading_constant_diffuse.png old mode 100755 new mode 100644 index 59d444a9566d..276f96e72e30 Binary files a/source/isaaclab_tasks/test/golden_images/cartpole/newton-isaacsim_rtx_renderer-simple_shading_constant_diffuse.png and b/source/isaaclab_tasks/test/golden_images/cartpole/newton-isaacsim_rtx_renderer-simple_shading_constant_diffuse.png differ diff --git a/source/isaaclab_tasks/test/golden_images/cartpole/newton-isaacsim_rtx_renderer-simple_shading_diffuse_mdl.png b/source/isaaclab_tasks/test/golden_images/cartpole/newton-isaacsim_rtx_renderer-simple_shading_diffuse_mdl.png old mode 100755 new mode 100644 index 59d444a9566d..cd3b20dfd5fe Binary files a/source/isaaclab_tasks/test/golden_images/cartpole/newton-isaacsim_rtx_renderer-simple_shading_diffuse_mdl.png and b/source/isaaclab_tasks/test/golden_images/cartpole/newton-isaacsim_rtx_renderer-simple_shading_diffuse_mdl.png differ diff --git a/source/isaaclab_tasks/test/golden_images/cartpole/newton-isaacsim_rtx_renderer-simple_shading_full_mdl.png b/source/isaaclab_tasks/test/golden_images/cartpole/newton-isaacsim_rtx_renderer-simple_shading_full_mdl.png old mode 100755 new mode 100644 index 59d444a9566d..dbf8793d8e8e Binary files a/source/isaaclab_tasks/test/golden_images/cartpole/newton-isaacsim_rtx_renderer-simple_shading_full_mdl.png and b/source/isaaclab_tasks/test/golden_images/cartpole/newton-isaacsim_rtx_renderer-simple_shading_full_mdl.png differ diff --git a/source/isaaclab_tasks/test/golden_images/cartpole/newton-newton_renderer-depth.png b/source/isaaclab_tasks/test/golden_images/cartpole/newton-newton_renderer-depth.png index 33b6033f2b51..0a26486d7f85 100644 Binary files a/source/isaaclab_tasks/test/golden_images/cartpole/newton-newton_renderer-depth.png and b/source/isaaclab_tasks/test/golden_images/cartpole/newton-newton_renderer-depth.png differ diff --git a/source/isaaclab_tasks/test/golden_images/cartpole/newton-newton_renderer-rgb.png b/source/isaaclab_tasks/test/golden_images/cartpole/newton-newton_renderer-rgb.png index 9ee032f0de1c..ff94c25572dc 100644 Binary files a/source/isaaclab_tasks/test/golden_images/cartpole/newton-newton_renderer-rgb.png and b/source/isaaclab_tasks/test/golden_images/cartpole/newton-newton_renderer-rgb.png differ diff --git a/source/isaaclab_tasks/test/golden_images/cartpole/newton-newton_renderer-rgba.png b/source/isaaclab_tasks/test/golden_images/cartpole/newton-newton_renderer-rgba.png index abd37549a9d8..aa6a47e561fb 100644 Binary files a/source/isaaclab_tasks/test/golden_images/cartpole/newton-newton_renderer-rgba.png and b/source/isaaclab_tasks/test/golden_images/cartpole/newton-newton_renderer-rgba.png differ diff --git a/source/isaaclab_tasks/test/golden_images/cartpole/newton-ovrtx_renderer-albedo.png b/source/isaaclab_tasks/test/golden_images/cartpole/newton-ovrtx_renderer-albedo.png new file mode 100644 index 000000000000..d44cd9a9f6a8 --- /dev/null +++ b/source/isaaclab_tasks/test/golden_images/cartpole/newton-ovrtx_renderer-albedo.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:88da57e08497b308d47c3e606d40142291adde3c0fe2df46ab0a924d39b6847b +size 435 diff --git a/source/isaaclab_tasks/test/golden_images/cartpole/newton-ovrtx_renderer-depth.png b/source/isaaclab_tasks/test/golden_images/cartpole/newton-ovrtx_renderer-depth.png new file mode 100644 index 000000000000..0387686a7a78 --- /dev/null +++ b/source/isaaclab_tasks/test/golden_images/cartpole/newton-ovrtx_renderer-depth.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ea4e6ba2251666e4df0c937fbd123489f2a06939bda9e674d5f84eb5c8831f7d +size 422 diff --git a/source/isaaclab_tasks/test/golden_images/cartpole/newton-ovrtx_renderer-rgb.png b/source/isaaclab_tasks/test/golden_images/cartpole/newton-ovrtx_renderer-rgb.png new file mode 100644 index 000000000000..e47c06e2ca7c --- /dev/null +++ b/source/isaaclab_tasks/test/golden_images/cartpole/newton-ovrtx_renderer-rgb.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4029eb71d2361c9fa12d255415bb9edcf1caaeb9d230ca2e6c4e67596c037dd1 +size 2580 diff --git a/source/isaaclab_tasks/test/golden_images/cartpole/newton-ovrtx_renderer-rgba.png b/source/isaaclab_tasks/test/golden_images/cartpole/newton-ovrtx_renderer-rgba.png new file mode 100644 index 000000000000..791497af827c --- /dev/null +++ b/source/isaaclab_tasks/test/golden_images/cartpole/newton-ovrtx_renderer-rgba.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4e1fed2c618875f9f9b4520c52308b0831cf637835e7a62e7a84e96f914c1e83 +size 2882 diff --git a/source/isaaclab_tasks/test/golden_images/cartpole/newton-ovrtx_renderer-semantic_segmentation.png b/source/isaaclab_tasks/test/golden_images/cartpole/newton-ovrtx_renderer-semantic_segmentation.png new file mode 100644 index 000000000000..21926715b7f6 --- /dev/null +++ b/source/isaaclab_tasks/test/golden_images/cartpole/newton-ovrtx_renderer-semantic_segmentation.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1fbe8833cefa8b037cb80538ff73ec9c503253cfe410282f3b9acdea12e7a017 +size 427 diff --git a/source/isaaclab_tasks/test/golden_images/cartpole/newton-ovrtx_renderer-simple_shading_constant_diffuse.png b/source/isaaclab_tasks/test/golden_images/cartpole/newton-ovrtx_renderer-simple_shading_constant_diffuse.png new file mode 100644 index 000000000000..87104cb87161 --- /dev/null +++ b/source/isaaclab_tasks/test/golden_images/cartpole/newton-ovrtx_renderer-simple_shading_constant_diffuse.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:47b5b15d79d0b61d00c0538caa0012172753a481ad6efb45df2888402be2f407 +size 391 diff --git a/source/isaaclab_tasks/test/golden_images/cartpole/newton-ovrtx_renderer-simple_shading_diffuse_mdl.png b/source/isaaclab_tasks/test/golden_images/cartpole/newton-ovrtx_renderer-simple_shading_diffuse_mdl.png new file mode 100644 index 000000000000..7d05e4a7adbd --- /dev/null +++ b/source/isaaclab_tasks/test/golden_images/cartpole/newton-ovrtx_renderer-simple_shading_diffuse_mdl.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f2ba382c0804ea49b55fc5216c9f1e28c34d5cae95b33d9982fd55763df178cc +size 435 diff --git a/source/isaaclab_tasks/test/golden_images/cartpole/newton-ovrtx_renderer-simple_shading_full_mdl.png b/source/isaaclab_tasks/test/golden_images/cartpole/newton-ovrtx_renderer-simple_shading_full_mdl.png new file mode 100644 index 000000000000..6b4f8389da06 --- /dev/null +++ b/source/isaaclab_tasks/test/golden_images/cartpole/newton-ovrtx_renderer-simple_shading_full_mdl.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d7af4ef2afca01d0bf4f9c069c5c3778fa07050bcd8091486541ab11f14e8227 +size 742 diff --git a/source/isaaclab_tasks/test/golden_images/cartpole/physx-isaacsim_rtx_renderer-albedo.png b/source/isaaclab_tasks/test/golden_images/cartpole/physx-isaacsim_rtx_renderer-albedo.png index aa8ca166fa5c..d44cd9a9f6a8 100644 Binary files a/source/isaaclab_tasks/test/golden_images/cartpole/physx-isaacsim_rtx_renderer-albedo.png and b/source/isaaclab_tasks/test/golden_images/cartpole/physx-isaacsim_rtx_renderer-albedo.png differ diff --git a/source/isaaclab_tasks/test/golden_images/cartpole/physx-isaacsim_rtx_renderer-depth.png b/source/isaaclab_tasks/test/golden_images/cartpole/physx-isaacsim_rtx_renderer-depth.png index 627a7ceb96cf..0387686a7a78 100644 Binary files a/source/isaaclab_tasks/test/golden_images/cartpole/physx-isaacsim_rtx_renderer-depth.png and b/source/isaaclab_tasks/test/golden_images/cartpole/physx-isaacsim_rtx_renderer-depth.png differ diff --git a/source/isaaclab_tasks/test/golden_images/cartpole/physx-isaacsim_rtx_renderer-rgb.png b/source/isaaclab_tasks/test/golden_images/cartpole/physx-isaacsim_rtx_renderer-rgb.png old mode 100755 new mode 100644 index fcc142662956..0397969c1af1 Binary files a/source/isaaclab_tasks/test/golden_images/cartpole/physx-isaacsim_rtx_renderer-rgb.png and b/source/isaaclab_tasks/test/golden_images/cartpole/physx-isaacsim_rtx_renderer-rgb.png differ diff --git a/source/isaaclab_tasks/test/golden_images/cartpole/physx-isaacsim_rtx_renderer-rgba.png b/source/isaaclab_tasks/test/golden_images/cartpole/physx-isaacsim_rtx_renderer-rgba.png old mode 100755 new mode 100644 index 1a2a34e7184e..74a8d4f725c8 Binary files a/source/isaaclab_tasks/test/golden_images/cartpole/physx-isaacsim_rtx_renderer-rgba.png and b/source/isaaclab_tasks/test/golden_images/cartpole/physx-isaacsim_rtx_renderer-rgba.png differ diff --git a/source/isaaclab_tasks/test/golden_images/cartpole/physx-isaacsim_rtx_renderer-semantic_segmentation.png b/source/isaaclab_tasks/test/golden_images/cartpole/physx-isaacsim_rtx_renderer-semantic_segmentation.png index ec2cf5c0d2f6..21926715b7f6 100644 Binary files a/source/isaaclab_tasks/test/golden_images/cartpole/physx-isaacsim_rtx_renderer-semantic_segmentation.png and b/source/isaaclab_tasks/test/golden_images/cartpole/physx-isaacsim_rtx_renderer-semantic_segmentation.png differ diff --git a/source/isaaclab_tasks/test/golden_images/cartpole/physx-isaacsim_rtx_renderer-simple_shading_constant_diffuse.png b/source/isaaclab_tasks/test/golden_images/cartpole/physx-isaacsim_rtx_renderer-simple_shading_constant_diffuse.png old mode 100755 new mode 100644 index a9e04d2c4cf5..276f96e72e30 Binary files a/source/isaaclab_tasks/test/golden_images/cartpole/physx-isaacsim_rtx_renderer-simple_shading_constant_diffuse.png and b/source/isaaclab_tasks/test/golden_images/cartpole/physx-isaacsim_rtx_renderer-simple_shading_constant_diffuse.png differ diff --git a/source/isaaclab_tasks/test/golden_images/cartpole/physx-isaacsim_rtx_renderer-simple_shading_diffuse_mdl.png b/source/isaaclab_tasks/test/golden_images/cartpole/physx-isaacsim_rtx_renderer-simple_shading_diffuse_mdl.png old mode 100755 new mode 100644 index a9e04d2c4cf5..cd3b20dfd5fe Binary files a/source/isaaclab_tasks/test/golden_images/cartpole/physx-isaacsim_rtx_renderer-simple_shading_diffuse_mdl.png and b/source/isaaclab_tasks/test/golden_images/cartpole/physx-isaacsim_rtx_renderer-simple_shading_diffuse_mdl.png differ diff --git a/source/isaaclab_tasks/test/golden_images/cartpole/physx-isaacsim_rtx_renderer-simple_shading_full_mdl.png b/source/isaaclab_tasks/test/golden_images/cartpole/physx-isaacsim_rtx_renderer-simple_shading_full_mdl.png old mode 100755 new mode 100644 index a9e04d2c4cf5..dbf8793d8e8e Binary files a/source/isaaclab_tasks/test/golden_images/cartpole/physx-isaacsim_rtx_renderer-simple_shading_full_mdl.png and b/source/isaaclab_tasks/test/golden_images/cartpole/physx-isaacsim_rtx_renderer-simple_shading_full_mdl.png differ diff --git a/source/isaaclab_tasks/test/golden_images/cartpole/physx-newton_renderer-depth.png b/source/isaaclab_tasks/test/golden_images/cartpole/physx-newton_renderer-depth.png index 33b6033f2b51..0a26486d7f85 100644 Binary files a/source/isaaclab_tasks/test/golden_images/cartpole/physx-newton_renderer-depth.png and b/source/isaaclab_tasks/test/golden_images/cartpole/physx-newton_renderer-depth.png differ diff --git a/source/isaaclab_tasks/test/golden_images/cartpole/physx-newton_renderer-rgb.png b/source/isaaclab_tasks/test/golden_images/cartpole/physx-newton_renderer-rgb.png index 767572f5f508..ff94c25572dc 100644 Binary files a/source/isaaclab_tasks/test/golden_images/cartpole/physx-newton_renderer-rgb.png and b/source/isaaclab_tasks/test/golden_images/cartpole/physx-newton_renderer-rgb.png differ diff --git a/source/isaaclab_tasks/test/golden_images/cartpole/physx-newton_renderer-rgba.png b/source/isaaclab_tasks/test/golden_images/cartpole/physx-newton_renderer-rgba.png index e6953c50ef1f..aa6a47e561fb 100644 Binary files a/source/isaaclab_tasks/test/golden_images/cartpole/physx-newton_renderer-rgba.png and b/source/isaaclab_tasks/test/golden_images/cartpole/physx-newton_renderer-rgba.png differ diff --git a/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-isaacsim_rtx_renderer-albedo.png b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-isaacsim_rtx_renderer-albedo.png old mode 100755 new mode 100644 index 45b171e2756b..a49e526d4eee Binary files a/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-isaacsim_rtx_renderer-albedo.png and b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-isaacsim_rtx_renderer-albedo.png differ diff --git a/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-isaacsim_rtx_renderer-depth.png b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-isaacsim_rtx_renderer-depth.png old mode 100755 new mode 100644 index facd5b400a4a..bf4b0e0290dd Binary files a/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-isaacsim_rtx_renderer-depth.png and b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-isaacsim_rtx_renderer-depth.png differ diff --git a/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-isaacsim_rtx_renderer-rgb.png b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-isaacsim_rtx_renderer-rgb.png index aedccbb16056..6d21415e1650 100644 Binary files a/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-isaacsim_rtx_renderer-rgb.png and b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-isaacsim_rtx_renderer-rgb.png differ diff --git a/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-isaacsim_rtx_renderer-rgba.png b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-isaacsim_rtx_renderer-rgba.png index 104e15d3abf2..525aa5b2776e 100644 Binary files a/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-isaacsim_rtx_renderer-rgba.png and b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-isaacsim_rtx_renderer-rgba.png differ diff --git a/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-isaacsim_rtx_renderer-semantic_segmentation.png b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-isaacsim_rtx_renderer-semantic_segmentation.png index 89d1489f2d8f..762a23184316 100644 Binary files a/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-isaacsim_rtx_renderer-semantic_segmentation.png and b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-isaacsim_rtx_renderer-semantic_segmentation.png differ diff --git a/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-isaacsim_rtx_renderer-simple_shading_constant_diffuse.png b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-isaacsim_rtx_renderer-simple_shading_constant_diffuse.png old mode 100755 new mode 100644 index 6c21c2da6195..46ce5933fb8b Binary files a/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-isaacsim_rtx_renderer-simple_shading_constant_diffuse.png and b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-isaacsim_rtx_renderer-simple_shading_constant_diffuse.png differ diff --git a/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-isaacsim_rtx_renderer-simple_shading_diffuse_mdl.png b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-isaacsim_rtx_renderer-simple_shading_diffuse_mdl.png old mode 100755 new mode 100644 index cf24e0114464..e591d31c5df9 Binary files a/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-isaacsim_rtx_renderer-simple_shading_diffuse_mdl.png and b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-isaacsim_rtx_renderer-simple_shading_diffuse_mdl.png differ diff --git a/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-isaacsim_rtx_renderer-simple_shading_full_mdl.png b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-isaacsim_rtx_renderer-simple_shading_full_mdl.png old mode 100755 new mode 100644 index cf24e0114464..2cdfe790a7df Binary files a/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-isaacsim_rtx_renderer-simple_shading_full_mdl.png and b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-isaacsim_rtx_renderer-simple_shading_full_mdl.png differ diff --git a/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-newton_renderer-depth.png b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-newton_renderer-depth.png index 2e8934284fcf..39ea590f59aa 100644 Binary files a/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-newton_renderer-depth.png and b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-newton_renderer-depth.png differ diff --git a/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-newton_renderer-rgb.png b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-newton_renderer-rgb.png index 817175a65069..04f5ba9e9614 100644 Binary files a/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-newton_renderer-rgb.png and b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-newton_renderer-rgb.png differ diff --git a/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-newton_renderer-rgba.png b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-newton_renderer-rgba.png index 139d1666d6dc..9a7493e9cdc8 100644 Binary files a/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-newton_renderer-rgba.png and b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-newton_renderer-rgba.png differ diff --git a/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-ovrtx_renderer-albedo.png b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-ovrtx_renderer-albedo.png new file mode 100644 index 000000000000..5199099a7587 --- /dev/null +++ b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-ovrtx_renderer-albedo.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7cf76622f5f5cc7e7889fe6032ba4cda22516248fa7bb5e957f181c92c86b42b +size 3054 diff --git a/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-ovrtx_renderer-depth.png b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-ovrtx_renderer-depth.png new file mode 100644 index 000000000000..bf4b0e0290dd --- /dev/null +++ b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-ovrtx_renderer-depth.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c003b10810539f538464992860c74ee3bf531b8b4e9b6e0ebe84041d42dba643 +size 532 diff --git a/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-ovrtx_renderer-rgb.png b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-ovrtx_renderer-rgb.png new file mode 100644 index 000000000000..544e2ffd450b --- /dev/null +++ b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-ovrtx_renderer-rgb.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3445142682c88dc5ce11c5d749c7754bf2d54bf0f1aab6420513a733bf3cf645 +size 14919 diff --git a/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-ovrtx_renderer-rgba.png b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-ovrtx_renderer-rgba.png new file mode 100644 index 000000000000..c3b229d34871 --- /dev/null +++ b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-ovrtx_renderer-rgba.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:179a5acba0a763fcc2317cd784f8c347ef48f0d81f8028a1a64996ade67f8706 +size 17836 diff --git a/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-ovrtx_renderer-semantic_segmentation.png b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-ovrtx_renderer-semantic_segmentation.png new file mode 100644 index 000000000000..762a23184316 --- /dev/null +++ b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-ovrtx_renderer-semantic_segmentation.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0b8729d722d1780272b24f0804e517ea024ec2b93f4a0fa3e26c82f222f5c9eb +size 700 diff --git a/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-ovrtx_renderer-simple_shading_constant_diffuse.png b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-ovrtx_renderer-simple_shading_constant_diffuse.png new file mode 100644 index 000000000000..46ce5933fb8b --- /dev/null +++ b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-ovrtx_renderer-simple_shading_constant_diffuse.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8e1d94f0c6ae2e40a1b0ff9cf27a0f2f9b756ebcebd9ddf27b0da31c89e3a57f +size 1485 diff --git a/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-ovrtx_renderer-simple_shading_diffuse_mdl.png b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-ovrtx_renderer-simple_shading_diffuse_mdl.png new file mode 100644 index 000000000000..2e2f6cb257a7 --- /dev/null +++ b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-ovrtx_renderer-simple_shading_diffuse_mdl.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:83ca3d8f55f971d473409c73e77582175906670f3962b56723cccd28d062a868 +size 3513 diff --git a/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-ovrtx_renderer-simple_shading_full_mdl.png b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-ovrtx_renderer-simple_shading_full_mdl.png new file mode 100644 index 000000000000..16b6b73ec7f4 --- /dev/null +++ b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-ovrtx_renderer-simple_shading_full_mdl.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3afc4f214e51a1ccc1b0341448f64b82773bcc4bba3d913ad4f3052dcf497032 +size 4513 diff --git a/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/physx-isaacsim_rtx_renderer-albedo.png b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/physx-isaacsim_rtx_renderer-albedo.png old mode 100755 new mode 100644 index e02f546f8ed2..266c129cbf86 Binary files a/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/physx-isaacsim_rtx_renderer-albedo.png and b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/physx-isaacsim_rtx_renderer-albedo.png differ diff --git a/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/physx-isaacsim_rtx_renderer-depth.png b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/physx-isaacsim_rtx_renderer-depth.png old mode 100755 new mode 100644 index a3e3ed8d7458..56fa75793780 Binary files a/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/physx-isaacsim_rtx_renderer-depth.png and b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/physx-isaacsim_rtx_renderer-depth.png differ diff --git a/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/physx-isaacsim_rtx_renderer-rgb.png b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/physx-isaacsim_rtx_renderer-rgb.png index d1ea4fe5e781..d36460128aae 100644 Binary files a/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/physx-isaacsim_rtx_renderer-rgb.png and b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/physx-isaacsim_rtx_renderer-rgb.png differ diff --git a/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/physx-isaacsim_rtx_renderer-rgba.png b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/physx-isaacsim_rtx_renderer-rgba.png old mode 100755 new mode 100644 index dfe59520b408..c666fa628df2 Binary files a/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/physx-isaacsim_rtx_renderer-rgba.png and b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/physx-isaacsim_rtx_renderer-rgba.png differ diff --git a/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/physx-isaacsim_rtx_renderer-semantic_segmentation.png b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/physx-isaacsim_rtx_renderer-semantic_segmentation.png old mode 100755 new mode 100644 index 3af37ecc08bc..fcc9576e7e95 Binary files a/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/physx-isaacsim_rtx_renderer-semantic_segmentation.png and b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/physx-isaacsim_rtx_renderer-semantic_segmentation.png differ diff --git a/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/physx-isaacsim_rtx_renderer-simple_shading_constant_diffuse.png b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/physx-isaacsim_rtx_renderer-simple_shading_constant_diffuse.png old mode 100755 new mode 100644 index 784b4b983f7d..38f0a4d9d7e3 Binary files a/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/physx-isaacsim_rtx_renderer-simple_shading_constant_diffuse.png and b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/physx-isaacsim_rtx_renderer-simple_shading_constant_diffuse.png differ diff --git a/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/physx-isaacsim_rtx_renderer-simple_shading_diffuse_mdl.png b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/physx-isaacsim_rtx_renderer-simple_shading_diffuse_mdl.png old mode 100755 new mode 100644 index 784b4b983f7d..1b833d0f65d6 Binary files a/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/physx-isaacsim_rtx_renderer-simple_shading_diffuse_mdl.png and b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/physx-isaacsim_rtx_renderer-simple_shading_diffuse_mdl.png differ diff --git a/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/physx-isaacsim_rtx_renderer-simple_shading_full_mdl.png b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/physx-isaacsim_rtx_renderer-simple_shading_full_mdl.png old mode 100755 new mode 100644 index 417534e7f1c4..28122c3bc3c2 Binary files a/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/physx-isaacsim_rtx_renderer-simple_shading_full_mdl.png and b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/physx-isaacsim_rtx_renderer-simple_shading_full_mdl.png differ diff --git a/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/physx-newton_renderer-depth.png b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/physx-newton_renderer-depth.png index 795098c6f2ea..2b296ef399b7 100644 Binary files a/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/physx-newton_renderer-depth.png and b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/physx-newton_renderer-depth.png differ diff --git a/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/physx-newton_renderer-rgb.png b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/physx-newton_renderer-rgb.png index d3dc1df35f8c..a8365cfc8297 100644 Binary files a/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/physx-newton_renderer-rgb.png and b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/physx-newton_renderer-rgb.png differ diff --git a/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/physx-newton_renderer-rgba.png b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/physx-newton_renderer-rgba.png index 757ca3fd19a1..c6d72a99eba2 100644 Binary files a/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/physx-newton_renderer-rgba.png and b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/physx-newton_renderer-rgba.png differ diff --git a/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Albedo-Camera-Direct-v0/default_physics-default_renderer-albedo.png b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Albedo-Camera-Direct-v0/default_physics-default_renderer-albedo.png index 5722d9a21c8c..fc6cb99a4aab 100644 Binary files a/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Albedo-Camera-Direct-v0/default_physics-default_renderer-albedo.png and b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Albedo-Camera-Direct-v0/default_physics-default_renderer-albedo.png differ diff --git a/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Camera-Presets-Direct-v0/default_physics-default_renderer-rgb.png b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Camera-Presets-Direct-v0/default_physics-default_renderer-rgb.png index fcc142662956..fbfa3e28851a 100644 Binary files a/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Camera-Presets-Direct-v0/default_physics-default_renderer-rgb.png and b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Camera-Presets-Direct-v0/default_physics-default_renderer-rgb.png differ diff --git a/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Camera-Presets-Direct-v0/default_physics-default_renderer-rgba.png b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Camera-Presets-Direct-v0/default_physics-default_renderer-rgba.png index 1a2a34e7184e..0791c1063cae 100644 Binary files a/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Camera-Presets-Direct-v0/default_physics-default_renderer-rgba.png and b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Camera-Presets-Direct-v0/default_physics-default_renderer-rgba.png differ diff --git a/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Depth-Camera-Direct-v0/default_physics-default_renderer-depth.png b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Depth-Camera-Direct-v0/default_physics-default_renderer-depth.png index 627a7ceb96cf..0387686a7a78 100644 Binary files a/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Depth-Camera-Direct-v0/default_physics-default_renderer-depth.png and b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Depth-Camera-Direct-v0/default_physics-default_renderer-depth.png differ diff --git a/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-RGB-Camera-Direct-v0/default_physics-default_renderer-rgb.png b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-RGB-Camera-Direct-v0/default_physics-default_renderer-rgb.png index fcc142662956..fbfa3e28851a 100644 Binary files a/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-RGB-Camera-Direct-v0/default_physics-default_renderer-rgb.png and b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-RGB-Camera-Direct-v0/default_physics-default_renderer-rgb.png differ diff --git a/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-RGB-Camera-Direct-v0/default_physics-default_renderer-rgba.png b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-RGB-Camera-Direct-v0/default_physics-default_renderer-rgba.png index 1a2a34e7184e..0791c1063cae 100644 Binary files a/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-RGB-Camera-Direct-v0/default_physics-default_renderer-rgba.png and b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-RGB-Camera-Direct-v0/default_physics-default_renderer-rgba.png differ diff --git a/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-SimpleShading-Constant-Camera-Direct-v0/default_physics-default_renderer-simple_shading_constant_diffuse.png b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-SimpleShading-Constant-Camera-Direct-v0/default_physics-default_renderer-simple_shading_constant_diffuse.png index e68b0539ea01..72930cd6f398 100644 Binary files a/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-SimpleShading-Constant-Camera-Direct-v0/default_physics-default_renderer-simple_shading_constant_diffuse.png and b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-SimpleShading-Constant-Camera-Direct-v0/default_physics-default_renderer-simple_shading_constant_diffuse.png differ diff --git a/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-SimpleShading-Diffuse-Camera-Direct-v0/default_physics-default_renderer-simple_shading_diffuse_mdl.png b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-SimpleShading-Diffuse-Camera-Direct-v0/default_physics-default_renderer-simple_shading_diffuse_mdl.png index e68b0539ea01..1ec3dad3f087 100644 Binary files a/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-SimpleShading-Diffuse-Camera-Direct-v0/default_physics-default_renderer-simple_shading_diffuse_mdl.png and b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-SimpleShading-Diffuse-Camera-Direct-v0/default_physics-default_renderer-simple_shading_diffuse_mdl.png differ diff --git a/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-SimpleShading-Full-Camera-Direct-v0/default_physics-default_renderer-simple_shading_full_mdl.png b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-SimpleShading-Full-Camera-Direct-v0/default_physics-default_renderer-simple_shading_full_mdl.png index e68b0539ea01..4399230afd8a 100644 Binary files a/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-SimpleShading-Full-Camera-Direct-v0/default_physics-default_renderer-simple_shading_full_mdl.png and b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-SimpleShading-Full-Camera-Direct-v0/default_physics-default_renderer-simple_shading_full_mdl.png differ diff --git a/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Repose-Cube-Shadow-Vision-Direct-v0/default_physics-default_renderer-depth.png b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Repose-Cube-Shadow-Vision-Direct-v0/default_physics-default_renderer-depth.png index fb52a8e18211..df186c373970 100644 Binary files a/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Repose-Cube-Shadow-Vision-Direct-v0/default_physics-default_renderer-depth.png and b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Repose-Cube-Shadow-Vision-Direct-v0/default_physics-default_renderer-depth.png differ diff --git a/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Repose-Cube-Shadow-Vision-Direct-v0/default_physics-default_renderer-rgb.png b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Repose-Cube-Shadow-Vision-Direct-v0/default_physics-default_renderer-rgb.png index 1936f5b32056..1197faa87f8d 100644 Binary files a/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Repose-Cube-Shadow-Vision-Direct-v0/default_physics-default_renderer-rgb.png and b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Repose-Cube-Shadow-Vision-Direct-v0/default_physics-default_renderer-rgb.png differ diff --git a/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Repose-Cube-Shadow-Vision-Direct-v0/default_physics-default_renderer-rgba.png b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Repose-Cube-Shadow-Vision-Direct-v0/default_physics-default_renderer-rgba.png index 54057a527807..96989870a197 100644 Binary files a/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Repose-Cube-Shadow-Vision-Direct-v0/default_physics-default_renderer-rgba.png and b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Repose-Cube-Shadow-Vision-Direct-v0/default_physics-default_renderer-rgba.png differ diff --git a/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Repose-Cube-Shadow-Vision-Direct-v0/default_physics-default_renderer-semantic_segmentation.png b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Repose-Cube-Shadow-Vision-Direct-v0/default_physics-default_renderer-semantic_segmentation.png index 2d34c534c973..4bad29d72ce6 100644 Binary files a/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Repose-Cube-Shadow-Vision-Direct-v0/default_physics-default_renderer-semantic_segmentation.png and b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Repose-Cube-Shadow-Vision-Direct-v0/default_physics-default_renderer-semantic_segmentation.png differ diff --git a/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-isaacsim_rtx_renderer-albedo.png b/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-isaacsim_rtx_renderer-albedo.png old mode 100755 new mode 100644 index 43459a6d4767..34d8b8867cb1 Binary files a/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-isaacsim_rtx_renderer-albedo.png and b/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-isaacsim_rtx_renderer-albedo.png differ diff --git a/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-isaacsim_rtx_renderer-depth.png b/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-isaacsim_rtx_renderer-depth.png index 29232f5c37c1..5cad962b3ac0 100644 Binary files a/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-isaacsim_rtx_renderer-depth.png and b/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-isaacsim_rtx_renderer-depth.png differ diff --git a/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-isaacsim_rtx_renderer-rgb.png b/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-isaacsim_rtx_renderer-rgb.png index 756b7791329e..4d7c5c0081fb 100644 Binary files a/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-isaacsim_rtx_renderer-rgb.png and b/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-isaacsim_rtx_renderer-rgb.png differ diff --git a/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-isaacsim_rtx_renderer-rgba.png b/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-isaacsim_rtx_renderer-rgba.png old mode 100755 new mode 100644 index 5575d93246cf..108b5c2bbad3 Binary files a/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-isaacsim_rtx_renderer-rgba.png and b/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-isaacsim_rtx_renderer-rgba.png differ diff --git a/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-isaacsim_rtx_renderer-semantic_segmentation.png b/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-isaacsim_rtx_renderer-semantic_segmentation.png index f3e2cdedae07..7aa704e6243b 100644 Binary files a/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-isaacsim_rtx_renderer-semantic_segmentation.png and b/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-isaacsim_rtx_renderer-semantic_segmentation.png differ diff --git a/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-isaacsim_rtx_renderer-simple_shading_constant_diffuse.png b/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-isaacsim_rtx_renderer-simple_shading_constant_diffuse.png old mode 100755 new mode 100644 index 7146c2359400..d5e537ddc82d Binary files a/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-isaacsim_rtx_renderer-simple_shading_constant_diffuse.png and b/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-isaacsim_rtx_renderer-simple_shading_constant_diffuse.png differ diff --git a/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-isaacsim_rtx_renderer-simple_shading_diffuse_mdl.png b/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-isaacsim_rtx_renderer-simple_shading_diffuse_mdl.png index 7146c2359400..4c4dc0b7383c 100755 Binary files a/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-isaacsim_rtx_renderer-simple_shading_diffuse_mdl.png and b/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-isaacsim_rtx_renderer-simple_shading_diffuse_mdl.png differ diff --git a/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-isaacsim_rtx_renderer-simple_shading_full_mdl.png b/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-isaacsim_rtx_renderer-simple_shading_full_mdl.png old mode 100755 new mode 100644 index 7146c2359400..bb230deaf25d Binary files a/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-isaacsim_rtx_renderer-simple_shading_full_mdl.png and b/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-isaacsim_rtx_renderer-simple_shading_full_mdl.png differ diff --git a/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-newton_renderer-depth.png b/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-newton_renderer-depth.png index cdc12e1ce228..f13af97768c5 100644 Binary files a/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-newton_renderer-depth.png and b/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-newton_renderer-depth.png differ diff --git a/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-newton_renderer-rgb.png b/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-newton_renderer-rgb.png index 06cdc808a402..7844802a4698 100644 Binary files a/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-newton_renderer-rgb.png and b/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-newton_renderer-rgb.png differ diff --git a/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-newton_renderer-rgba.png b/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-newton_renderer-rgba.png index 731ef98ebfaa..33e87b8be324 100644 Binary files a/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-newton_renderer-rgba.png and b/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-newton_renderer-rgba.png differ diff --git a/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-ovrtx_renderer-albedo.png b/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-ovrtx_renderer-albedo.png new file mode 100644 index 000000000000..b0a81304d1b4 --- /dev/null +++ b/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-ovrtx_renderer-albedo.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d6ea478eb0b63ac6e9b19c66fabc9944a9cdd1d3131aa0d480ba645151765f41 +size 2150 diff --git a/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-ovrtx_renderer-depth.png b/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-ovrtx_renderer-depth.png new file mode 100644 index 000000000000..5cad962b3ac0 --- /dev/null +++ b/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-ovrtx_renderer-depth.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cbc51bc91ac202857ec3648475f25e58e921aa927ec1d0814f63862462877e3f +size 3661 diff --git a/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-ovrtx_renderer-rgb.png b/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-ovrtx_renderer-rgb.png new file mode 100644 index 000000000000..d6e87b16a116 --- /dev/null +++ b/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-ovrtx_renderer-rgb.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:87b927816b29714d92113b2fcab01569c60372f017119b37ced9a12f72b01cd7 +size 19717 diff --git a/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-ovrtx_renderer-rgba.png b/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-ovrtx_renderer-rgba.png new file mode 100644 index 000000000000..ddffaebf0722 --- /dev/null +++ b/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-ovrtx_renderer-rgba.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7fb6696c895cb07a86897002e434be6c8c67a9d50f15615c2fd16f5038eee209 +size 21761 diff --git a/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-ovrtx_renderer-semantic_segmentation.png b/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-ovrtx_renderer-semantic_segmentation.png new file mode 100644 index 000000000000..c1d11cc65f5c --- /dev/null +++ b/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-ovrtx_renderer-semantic_segmentation.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8edbd9b2c8131d659d36ed3f6f07040eba5428d0e6e888bb8d97bb67d9001917 +size 1477 diff --git a/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-ovrtx_renderer-simple_shading_constant_diffuse.png b/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-ovrtx_renderer-simple_shading_constant_diffuse.png new file mode 100644 index 000000000000..a25340e96b0f --- /dev/null +++ b/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-ovrtx_renderer-simple_shading_constant_diffuse.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3122340f40be0b24e9d7f2d262bc7285607536c9cf82151750d2691f05d8950d +size 6840 diff --git a/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-ovrtx_renderer-simple_shading_diffuse_mdl.png b/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-ovrtx_renderer-simple_shading_diffuse_mdl.png new file mode 100644 index 000000000000..572a1759a30c --- /dev/null +++ b/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-ovrtx_renderer-simple_shading_diffuse_mdl.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3f0ececab1b4b385c54352d02c9b07d6572f8a4f4069eea1afe2089343a164d6 +size 7429 diff --git a/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-ovrtx_renderer-simple_shading_full_mdl.png b/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-ovrtx_renderer-simple_shading_full_mdl.png new file mode 100644 index 000000000000..687917f13e3b --- /dev/null +++ b/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-ovrtx_renderer-simple_shading_full_mdl.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:88ca19937bbf54a87c40f476c395f678a39d443df3899eb3c74b4e3e854866fc +size 9192 diff --git a/source/isaaclab_tasks/test/golden_images/shadow_hand/physx-isaacsim_rtx_renderer-albedo.png b/source/isaaclab_tasks/test/golden_images/shadow_hand/physx-isaacsim_rtx_renderer-albedo.png old mode 100755 new mode 100644 index c45e91b12616..4f1b5fda96b4 Binary files a/source/isaaclab_tasks/test/golden_images/shadow_hand/physx-isaacsim_rtx_renderer-albedo.png and b/source/isaaclab_tasks/test/golden_images/shadow_hand/physx-isaacsim_rtx_renderer-albedo.png differ diff --git a/source/isaaclab_tasks/test/golden_images/shadow_hand/physx-isaacsim_rtx_renderer-depth.png b/source/isaaclab_tasks/test/golden_images/shadow_hand/physx-isaacsim_rtx_renderer-depth.png index fb52a8e18211..df186c373970 100644 Binary files a/source/isaaclab_tasks/test/golden_images/shadow_hand/physx-isaacsim_rtx_renderer-depth.png and b/source/isaaclab_tasks/test/golden_images/shadow_hand/physx-isaacsim_rtx_renderer-depth.png differ diff --git a/source/isaaclab_tasks/test/golden_images/shadow_hand/physx-isaacsim_rtx_renderer-rgb.png b/source/isaaclab_tasks/test/golden_images/shadow_hand/physx-isaacsim_rtx_renderer-rgb.png index 8803719c8afd..6e64fac3cb3e 100644 Binary files a/source/isaaclab_tasks/test/golden_images/shadow_hand/physx-isaacsim_rtx_renderer-rgb.png and b/source/isaaclab_tasks/test/golden_images/shadow_hand/physx-isaacsim_rtx_renderer-rgb.png differ diff --git a/source/isaaclab_tasks/test/golden_images/shadow_hand/physx-isaacsim_rtx_renderer-rgba.png b/source/isaaclab_tasks/test/golden_images/shadow_hand/physx-isaacsim_rtx_renderer-rgba.png old mode 100755 new mode 100644 index 7b7a92e5832b..b05baaca49c9 Binary files a/source/isaaclab_tasks/test/golden_images/shadow_hand/physx-isaacsim_rtx_renderer-rgba.png and b/source/isaaclab_tasks/test/golden_images/shadow_hand/physx-isaacsim_rtx_renderer-rgba.png differ diff --git a/source/isaaclab_tasks/test/golden_images/shadow_hand/physx-isaacsim_rtx_renderer-semantic_segmentation.png b/source/isaaclab_tasks/test/golden_images/shadow_hand/physx-isaacsim_rtx_renderer-semantic_segmentation.png old mode 100755 new mode 100644 index fc09a2e3eb62..4bad29d72ce6 Binary files a/source/isaaclab_tasks/test/golden_images/shadow_hand/physx-isaacsim_rtx_renderer-semantic_segmentation.png and b/source/isaaclab_tasks/test/golden_images/shadow_hand/physx-isaacsim_rtx_renderer-semantic_segmentation.png differ diff --git a/source/isaaclab_tasks/test/golden_images/shadow_hand/physx-isaacsim_rtx_renderer-simple_shading_constant_diffuse.png b/source/isaaclab_tasks/test/golden_images/shadow_hand/physx-isaacsim_rtx_renderer-simple_shading_constant_diffuse.png old mode 100755 new mode 100644 index d4f6aa7b4ce0..830b7ab5464b Binary files a/source/isaaclab_tasks/test/golden_images/shadow_hand/physx-isaacsim_rtx_renderer-simple_shading_constant_diffuse.png and b/source/isaaclab_tasks/test/golden_images/shadow_hand/physx-isaacsim_rtx_renderer-simple_shading_constant_diffuse.png differ diff --git a/source/isaaclab_tasks/test/golden_images/shadow_hand/physx-isaacsim_rtx_renderer-simple_shading_diffuse_mdl.png b/source/isaaclab_tasks/test/golden_images/shadow_hand/physx-isaacsim_rtx_renderer-simple_shading_diffuse_mdl.png index d4f6aa7b4ce0..357f1231be34 100755 Binary files a/source/isaaclab_tasks/test/golden_images/shadow_hand/physx-isaacsim_rtx_renderer-simple_shading_diffuse_mdl.png and b/source/isaaclab_tasks/test/golden_images/shadow_hand/physx-isaacsim_rtx_renderer-simple_shading_diffuse_mdl.png differ diff --git a/source/isaaclab_tasks/test/golden_images/shadow_hand/physx-isaacsim_rtx_renderer-simple_shading_full_mdl.png b/source/isaaclab_tasks/test/golden_images/shadow_hand/physx-isaacsim_rtx_renderer-simple_shading_full_mdl.png old mode 100755 new mode 100644 index d4f6aa7b4ce0..bc0da8969fff Binary files a/source/isaaclab_tasks/test/golden_images/shadow_hand/physx-isaacsim_rtx_renderer-simple_shading_full_mdl.png and b/source/isaaclab_tasks/test/golden_images/shadow_hand/physx-isaacsim_rtx_renderer-simple_shading_full_mdl.png differ diff --git a/source/isaaclab_tasks/test/golden_images/shadow_hand/physx-newton_renderer-depth.png b/source/isaaclab_tasks/test/golden_images/shadow_hand/physx-newton_renderer-depth.png index 99b3685ba904..1da91b1c4b0b 100644 Binary files a/source/isaaclab_tasks/test/golden_images/shadow_hand/physx-newton_renderer-depth.png and b/source/isaaclab_tasks/test/golden_images/shadow_hand/physx-newton_renderer-depth.png differ diff --git a/source/isaaclab_tasks/test/golden_images/shadow_hand/physx-newton_renderer-rgb.png b/source/isaaclab_tasks/test/golden_images/shadow_hand/physx-newton_renderer-rgb.png index 03f1ebe3c5b4..05fa5d11e83d 100644 Binary files a/source/isaaclab_tasks/test/golden_images/shadow_hand/physx-newton_renderer-rgb.png and b/source/isaaclab_tasks/test/golden_images/shadow_hand/physx-newton_renderer-rgb.png differ diff --git a/source/isaaclab_tasks/test/golden_images/shadow_hand/physx-newton_renderer-rgba.png b/source/isaaclab_tasks/test/golden_images/shadow_hand/physx-newton_renderer-rgba.png index 4073fd393382..59c5d30efda6 100644 Binary files a/source/isaaclab_tasks/test/golden_images/shadow_hand/physx-newton_renderer-rgba.png and b/source/isaaclab_tasks/test/golden_images/shadow_hand/physx-newton_renderer-rgba.png differ diff --git a/source/isaaclab_tasks/test/rendering_test_utils.py b/source/isaaclab_tasks/test/rendering_test_utils.py new file mode 100644 index 000000000000..788064900f85 --- /dev/null +++ b/source/isaaclab_tasks/test/rendering_test_utils.py @@ -0,0 +1,798 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Shared helpers for rendering correctness tests.""" + +import os +from datetime import datetime +from typing import Any + +import numpy as np +import pytest +import torch +from PIL import Image, ImageChops + +# Directory containing golden images. +_GOLDEN_IMAGES_DIRECTORY = os.path.join(os.path.dirname(os.path.abspath(__file__)), "golden_images") + +# Pixel L2 norm difference threshold. L2 norm difference is the Euclidean distance between two pixels: +# +# d = sqrt((R1 - R2)^2 + (G1 - G2)^2 + (B1 - B2)^2) +# +# If the difference between two pixels is less than this threshold, consider them "equal" (i.e. within the tolerance). +# +_PIXEL_L2_NORM_DIFFERENCE_THRESHOLD = 10.0 + +# The max percentage of pixels allowed to differ. If the percentage exceeds this value, the test will fail. +# The value is set case by case based on the screen space taken up by the env in camera output images. It +# needs to be large enough to tolerate minor rendering noise while small enough to catch unexpected changes. +MAX_DIFFERENT_PIXELS_PERCENTAGE_BY_ENV_NAME = { + "cartpole": 1.0, + # Shadow-hand renderings (incl. ``Isaac-Repose-Cube-Shadow-Vision-Direct-v0``) show up to + # ~3.28 % per-pixel diff from anti-aliasing noise along the many finger/cube edges. 5.0 gives + # headroom above that without masking real regressions, which the SSIM gate still catches. + "shadow_hand": 5.0, + # Texture aliasing artifacts on the ground (NVBUG#6116767) + "dexsuite_kuka": 8.0, +} + +# Minimum SSIM score below which two images are considered structurally different. SSIM is a perceptual metric +# robust to uniform per-pixel noise that penalises structural changes (geometry shifts, swapped colours, missing +# materials, etc.), so it complements the per-pixel L2 gate by catching regressions that survive a loosened pixel +# threshold. +_SSIM_THRESHOLD = 0.985 + +# Per-env SSIM overrides. Envs not listed fall back to ``_SSIM_THRESHOLD``. Loosened individually +# (not globally) to keep the strict gate active everywhere it already passes. +_SSIM_THRESHOLD_BY_ENV_NAME = { + # Texture aliasing artifacts on the ground (NVBUG#6116767) + "dexsuite_kuka": 0.95, +} + +# Data types for which the SSIM gate is not enforced. SSIM assumes natural-image statistics and is unreliable on +# outputs where the per-pixel value distribution is highly non-uniform after normalisation (e.g. depth, where we +# divide by the max value so tiny absolute differences near the far plane dominate windowed variance). For these +# data types we still compute SSIM for reporting, but only the per-pixel L2 gate is used to decide pass/fail. +_SSIM_DISABLED_DATA_TYPES: set[str] = {"depth", "distance_to_camera", "distance_to_image_plane"} + +# Directory for comparison images saved during the test session. +# Located under the pytest output root so it gets copied alongside test reports. +_COMPARISON_IMAGES_DIR = os.path.join(os.getcwd(), "tests", "comparison-images") +_COMPARISON_IMAGE_SUBDIR = "images" + +# --------------------------------------------------------------------------- +# Parametrization: (physics_backend, renderer, data_type) +# --------------------------------------------------------------------------- + +# OVRTX kitless paths can segfault on GitHub Actions runners; keep warp/Kit paths in CI. +_SKIP_ON_GITHUB_ACTIONS = os.environ.get("GITHUB_ACTIONS") == "true" +_SKIP_ON_GITHUB_ACTIONS_MARK = pytest.mark.skipif( + _SKIP_ON_GITHUB_ACTIONS, + reason="Skipped on GitHub Actions until the test can run on GitHub Actions.", +) + +PHYSICS_RENDERER_AOV_COMBINATIONS = [ + # physx + isaacsim_rtx_renderer + pytest.param( + "physx", + "isaacsim_rtx_renderer", + "rgb", + id="physx-isaacsim_rtx-rgb", + ), + pytest.param( + "physx", + "isaacsim_rtx_renderer", + "albedo", + id="physx-isaacsim_rtx-albedo", + ), + pytest.param( + "physx", + "isaacsim_rtx_renderer", + "depth", + id="physx-isaacsim_rtx-depth", + ), + pytest.param( + "physx", + "isaacsim_rtx_renderer", + "simple_shading_constant_diffuse", + id="physx-isaacsim_rtx-simple_shading_constant_diffuse", + ), + pytest.param( + "physx", + "isaacsim_rtx_renderer", + "simple_shading_diffuse_mdl", + id="physx-isaacsim_rtx-simple_shading_diffuse_mdl", + ), + pytest.param( + "physx", + "isaacsim_rtx_renderer", + "simple_shading_full_mdl", + id="physx-isaacsim_rtx-simple_shading_full_mdl", + ), + pytest.param( + "physx", + "isaacsim_rtx_renderer", + "semantic_segmentation", + id="physx-isaacsim_rtx-semantic_segmentation", + ), + # newton + isaacsim_rtx_renderer + pytest.param( + "newton", + "isaacsim_rtx_renderer", + "rgb", + id="newton-isaacsim_rtx-rgb", + ), + pytest.param( + "newton", + "isaacsim_rtx_renderer", + "albedo", + id="newton-isaacsim_rtx-albedo", + ), + pytest.param( + "newton", + "isaacsim_rtx_renderer", + "depth", + id="newton-isaacsim_rtx-depth", + ), + pytest.param( + "newton", + "isaacsim_rtx_renderer", + "simple_shading_constant_diffuse", + id="newton-isaacsim_rtx-simple_shading_constant_diffuse", + ), + pytest.param( + "newton", + "isaacsim_rtx_renderer", + "simple_shading_diffuse_mdl", + id="newton-isaacsim_rtx-simple_shading_diffuse_mdl", + ), + pytest.param( + "newton", + "isaacsim_rtx_renderer", + "simple_shading_full_mdl", + id="newton-isaacsim_rtx-simple_shading_full_mdl", + ), + pytest.param( + "newton", + "isaacsim_rtx_renderer", + "semantic_segmentation", + id="newton-isaacsim_rtx-semantic_segmentation", + ), + # physx + newton_renderer (warp) + pytest.param( + "physx", + "newton_renderer", + "rgb", + id="physx-newton_warp-rgb", + ), + pytest.param( + "physx", + "newton_renderer", + "depth", + id="physx-newton_warp-depth", + ), +] + +KITLESS_PHYSICS_RENDERER_AOV_COMBINATIONS = [ + # newton + ovrtx_renderer + pytest.param( + "newton", + "ovrtx_renderer", + "rgb", + id="newton-ovrtx-rgb", + marks=_SKIP_ON_GITHUB_ACTIONS_MARK, + ), + pytest.param( + "newton", + "ovrtx_renderer", + "albedo", + id="newton-ovrtx-albedo", + marks=_SKIP_ON_GITHUB_ACTIONS_MARK, + ), + pytest.param( + "newton", + "ovrtx_renderer", + "depth", + id="newton-ovrtx-depth", + marks=_SKIP_ON_GITHUB_ACTIONS_MARK, + ), + pytest.param( + "newton", + "ovrtx_renderer", + "simple_shading_constant_diffuse", + id="newton-ovrtx-simple_shading_constant_diffuse", + marks=_SKIP_ON_GITHUB_ACTIONS_MARK, + ), + pytest.param( + "newton", + "ovrtx_renderer", + "simple_shading_diffuse_mdl", + id="newton-ovrtx-simple_shading_diffuse_mdl", + marks=_SKIP_ON_GITHUB_ACTIONS_MARK, + ), + pytest.param( + "newton", + "ovrtx_renderer", + "simple_shading_full_mdl", + id="newton-ovrtx-simple_shading_full_mdl", + marks=_SKIP_ON_GITHUB_ACTIONS_MARK, + ), + pytest.param( + "newton", + "ovrtx_renderer", + "semantic_segmentation", + id="newton-ovrtx-semantic_segmentation", + marks=_SKIP_ON_GITHUB_ACTIONS_MARK, + ), + # newton + newton_renderer (warp) + pytest.param( + "newton", + "newton_renderer", + "rgb", + id="newton-newton_warp-rgb", + ), + pytest.param( + "newton", + "newton_renderer", + "depth", + id="newton-newton_warp-depth", + ), +] + + +def maybe_save_stage(test_name: str, physics_backend: str, renderer: str, data_type: str) -> None: + """If ``ISAAC_LAB_SAVE_STAGES`` is set, dump the current USD stage to that directory.""" + out_dir = os.environ.get("ISAAC_LAB_SAVE_STAGES") + if not out_dir: + return + + import isaaclab.sim as sim_utils + + os.makedirs(out_dir, exist_ok=True) + safe_test_name = test_name.replace("/", "_") + stage_path = os.path.join(out_dir, f"{safe_test_name}-{physics_backend}-{renderer}-{data_type}.usda") + sim_utils.save_stage(stage_path, save_and_reload_in_place=False) + print(f"[ISAAC_LAB_SAVE_STAGES] wrote {stage_path}") + + +def _apply_overrides_to_env_cfg(env_cfg: Any, override_args: list[str]) -> Any: + """Apply override args to env_cfg using parse_overrides and apply_overrides.""" + from isaaclab_tasks.utils.hydra import apply_overrides, collect_presets, parse_overrides + + presets = {"env": collect_presets(env_cfg)} + global_presets, preset_sel, preset_scalar, _ = parse_overrides(override_args, presets) + hydra_cfg = {"env": env_cfg.to_dict()} + env_cfg, _ = apply_overrides(env_cfg, None, hydra_cfg, global_presets, preset_sel, preset_scalar, presets) + return env_cfg + + +def _physics_preset_name(physics_backend: str) -> str: + """Translate the historical ``"newton"`` backend label (still used by golden-image + filenames and ``pytest.param`` IDs) to the renamed Hydra preset + ``"newton_mjwarp"``. Other labels (``"physx"`` etc.) pass through unchanged. + """ + return "newton_mjwarp" if physics_backend == "newton" else physics_backend + + +def _normalize_tensor(tensor: torch.Tensor, data_type: str) -> torch.Tensor: + """Convert camera output tensor to [0, 1] float32 for conversion to image.""" + normalized = tensor.float() + + if data_type in ["depth", "distance_to_camera", "distance_to_image_plane"]: + max_val = normalized.max() + if max_val > 0: + normalized = normalized / max_val + elif data_type in {"albedo"}: + normalized = normalized[..., :3] / 255.0 + else: + normalized = normalized / 255.0 + + return normalized + + +def _save_comparison_image(img: Image.Image, filename: str) -> str: + """Save a PIL image under the comparison images directory.""" + path = os.path.join(_COMPARISON_IMAGES_DIR, _COMPARISON_IMAGE_SUBDIR, filename) + os.makedirs(os.path.dirname(path), exist_ok=True) + img.save(path, format="PNG") + return path + + +def generate_html_report(comparison_scores: list[dict], report_filename: str) -> None: + """Generate and save an HTML report of comparison scores.""" + if not comparison_scores: + return + + os.makedirs(_COMPARISON_IMAGES_DIR, exist_ok=True) + report_path = os.path.join(_COMPARISON_IMAGES_DIR, report_filename) + sorted_scores = sorted(comparison_scores, key=lambda e: -e["diff_pct"]) + + rows = [] + for entry in sorted_scores: + status_class = "pass" if entry["passed"] else "fail" + status_text = status_class.upper() + + actual_img_html = "" + golden_img_html = "" + if entry.get("img_result_path"): + actual_fname = os.path.relpath(entry["img_result_path"], _COMPARISON_IMAGES_DIR) + golden_fname = os.path.relpath(entry["img_golden_path"], _COMPARISON_IMAGES_DIR) + actual_img_html = f'' + golden_img_html = f'' + + ssim_checked = entry.get("ssim_checked", True) + ssim_cell_class = "" if ssim_checked else ' class="ssim-disabled"' + entry_ssim_threshold = entry.get("ssim_threshold", _SSIM_THRESHOLD) + ssim_threshold_cell = f"{entry_ssim_threshold:.4f}" if ssim_checked else "N/A" + ssim_title = "" if ssim_checked else ' title="SSIM gate disabled for this data type; score is informational."' + + rows.append( + f'' + f"{entry['test']}" + f"{entry['backend']}" + f"{entry['renderer']}" + f"{entry['aov']}" + f"{entry['diff_pct']:.2f}" + f"{entry['threshold']:.1f}" + f"{entry['ssim']:.4f}" + f"{ssim_threshold_cell}" + f'{status_text}' + f"{actual_img_html}" + f"{golden_img_html}" + "" + ) + + html = ( + "\n" + "\n" + "\n" + '\n' + "Rendering Correctness - Image Comparison Report\n" + "\n" + "\n" + "\n" + "

Rendering Correctness - Image Comparison Report

\n" + f"

Sorted by PixelDiff % (desc) - {len(sorted_scores)}  total.

\n" + "\n" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "\n" + "\n" + "\n".join(rows) + "\n\n
TestBackendRendererAOVPixelDiff %PixelDiff Threshold %SSIMSSIM ThresholdStatusACTUALGOLDEN
\n" + f"

Generated: {datetime.now().astimezone().isoformat(timespec='seconds')}.

\n" + "\n" + "\n" + ) + + with open(report_path, "w", encoding="utf-8") as file: + file.write(html) + + +def attach_comparison_properties( + request: pytest.FixtureRequest, comparison_scores: list[dict], initial_count: int +) -> None: + """Attach pixel-diff, SSIM scores, and failure images as JUnit XML properties.""" + for entry in comparison_scores[initial_count:]: + label = f"{entry['backend']}-{entry['renderer']}-{entry['aov']}" + request.node.user_properties.append((f"diff_pct:{label}", f"{entry['diff_pct']:.2f}")) + ssim_value = f"{entry['ssim']:.4f}" if entry.get("ssim_checked", True) else f"{entry['ssim']:.4f} (N/A)" + request.node.user_properties.append((f"ssim:{label}", ssim_value)) + request.node.user_properties.append((f"threshold:{label}", f"{entry['threshold']:.1f}")) + if entry.get("img_result_path"): + request.node.user_properties.append((f"img_result:{label}", entry["img_result_path"])) + request.node.user_properties.append((f"img_golden:{label}", entry["img_golden_path"])) + + +def make_determinism_fixture(): + """Create an autouse fixture that enables determinism for each test.""" + + @pytest.fixture(autouse=True) + def _determinism_fixture(): + """Enable determinism for each test.""" + from isaaclab.utils.seed import configure_seed + + configure_seed(42, torch_deterministic=True) + + yield + + from isaaclab.sim import SimulationContext + + SimulationContext.clear_instance() + + return _determinism_fixture + + +def make_generate_html_report_fixture(comparison_scores: list[dict], report_filename: str): + """Create a session fixture that writes the HTML report for one module. + + Args: + comparison_scores: Module-local comparison score storage. + report_filename: Output report filename. + """ + + @pytest.fixture(scope="session", autouse=True) + def _generate_html_report(): + """Generate an HTML comparison report after all tests in the session complete.""" + yield + generate_html_report(comparison_scores, report_filename) + + return _generate_html_report + + +def make_attach_comparison_properties_fixture(comparison_scores: list[dict]): + """Create an autouse fixture that attaches JUnit properties for one module. + + Args: + comparison_scores: Module-local comparison score storage. + """ + + @pytest.fixture(autouse=True) + def _attach_comparison_properties(request): + """Attach pixel-diff, SSIM scores, and failure images as JUnit XML properties.""" + initial_count = len(comparison_scores) + yield + attach_comparison_properties(request, comparison_scores, initial_count) + + return _attach_comparison_properties + + +def make_require_ovrtx_install_fixture(): + """Create an autouse fixture that fails fast when OVRTX is required but not installed. + + Only parametrized cases with ``renderer == "ovrtx_renderer"`` are checked (Newton + Warp kitless cases do not need ``ov[ovrtx]``). Install with + ``./isaaclab.sh -i 'ov[ovrtx]'`` (or the equivalent in your environment). + """ + + @pytest.fixture(autouse=True) + def _require_ovrtx_install(request): + callspec = getattr(request.node, "callspec", None) + if callspec is None: + return + + if callspec.params.get("renderer") != "ovrtx_renderer": + return + + try: + import ovrtx + + print(f"ovrtx version: {ovrtx.__version__}") + except ImportError as exc: + pytest.fail( + "Kitless OVRTX rendering tests require the optional dependency ov[ovrtx]. " + "Install with: ./isaaclab.sh -i 'ov[ovrtx]'\n" + f"ImportError: {exc}" + ) + + return _require_ovrtx_install + + +def _make_grid(images: torch.Tensor) -> torch.Tensor: + """Make a grid of images from a tensor of shape (B, H, W, C).""" + from torchvision.utils import make_grid + + return make_grid(torch.swapaxes(images.unsqueeze(1), 1, -1).squeeze(-1), nrow=round(images.shape[0] ** 0.5)) + + +def _ssim(img1: torch.Tensor, img2: torch.Tensor, window_size: int = 11) -> float: + """Compute mean SSIM between two (1, C, H, W) float tensors in [0, 1].""" + c1 = 0.01**2 + c2 = 0.03**2 + channels = img1.shape[1] + pad = window_size // 2 + + kernel = torch.ones(channels, 1, window_size, window_size, device=img1.device, dtype=img1.dtype) / ( + window_size * window_size + ) + + mu1 = torch.nn.functional.conv2d(img1, kernel, padding=pad, groups=channels) + mu2 = torch.nn.functional.conv2d(img2, kernel, padding=pad, groups=channels) + + mu1_sq = mu1 * mu1 + mu2_sq = mu2 * mu2 + mu1_mu2 = mu1 * mu2 + + sigma1_sq = torch.nn.functional.conv2d(img1 * img1, kernel, padding=pad, groups=channels) - mu1_sq + sigma2_sq = torch.nn.functional.conv2d(img2 * img2, kernel, padding=pad, groups=channels) - mu2_sq + sigma12 = torch.nn.functional.conv2d(img1 * img2, kernel, padding=pad, groups=channels) - mu1_mu2 + + ssim_map = ((2 * mu1_mu2 + c1) * (2 * sigma12 + c2)) / ((mu1_sq + mu2_sq + c1) * (sigma1_sq + sigma2_sq + c2)) + return ssim_map.mean().item() + + +def _pixel_diff_percentage( + result_image: Image.Image, + golden_image: Image.Image, + pixel_diff_threshold: float = _PIXEL_L2_NORM_DIFFERENCE_THRESHOLD, +) -> float: + """Compute the percentage of pixels whose L2 norm difference exceeds a threshold.""" + diff_array = np.array(ImageChops.difference(result_image, golden_image)) + l2_norm_array = np.linalg.norm(diff_array, axis=2) + num_different_pixels = np.sum(l2_norm_array > pixel_diff_threshold) + return 100.0 * num_different_pixels / l2_norm_array.size + + +def _compare_images( + result_image: Image.Image, + golden_image: Image.Image, + max_different_pixels_percentage: float, + check_ssim: bool = True, + ssim_threshold: float = _SSIM_THRESHOLD, +) -> tuple[bool, str | None, float, float]: + """Compare result and golden images against pixel and SSIM thresholds.""" + if result_image.size != golden_image.size: + return False, f"Size mismatch: expected {golden_image.size}, got {result_image.size}.", 0.0, 0.0 + + if result_image.mode != golden_image.mode: + return False, f"Mode mismatch: expected {golden_image.mode}, got {result_image.mode}.", 0.0, 0.0 + + diff_pct = _pixel_diff_percentage(result_image, golden_image) + + result_tensor = torch.from_numpy(np.array(result_image, dtype=np.float32) / 255.0).permute(2, 0, 1).unsqueeze(0) + golden_tensor = torch.from_numpy(np.array(golden_image, dtype=np.float32) / 255.0).permute(2, 0, 1).unsqueeze(0) + ssim_score = _ssim(result_tensor, golden_tensor) + + if diff_pct > max_different_pixels_percentage: + return ( + False, + f"The percentage of different pixels ({diff_pct:.2f}%) exceeds the threshold of" + f" {max_different_pixels_percentage:.2f}%. SSIM={ssim_score:.4f}.", + diff_pct, + ssim_score, + ) + + if check_ssim and ssim_score < ssim_threshold: + return ( + False, + f"SSIM ({ssim_score:.4f}) is below the threshold of {ssim_threshold:.4f}." + f" Different pixels: {diff_pct:.2f}%.", + diff_pct, + ssim_score, + ) + + return True, None, diff_pct, ssim_score + + +def validate_camera_outputs( + test_name: str, + physics_backend: str, + renderer: str, + camera_outputs: dict[str, torch.Tensor], + max_different_pixels_percentage: float, + comparison_scores: list[dict], +) -> None: + """Validate correctness and consistency of camera outputs.""" + assert len(camera_outputs) > 0, f"[{test_name}] No camera outputs produced by {physics_backend} + {renderer}." + + golden_image_dir = os.path.join(_GOLDEN_IMAGES_DIRECTORY, test_name) + os.makedirs(golden_image_dir, exist_ok=True) + + ssim_threshold = _SSIM_THRESHOLD_BY_ENV_NAME.get(test_name, _SSIM_THRESHOLD) + failed_data_types = {} + + for data_type, tensor in camera_outputs.items(): + condition = torch.logical_or(torch.isinf(tensor), torch.isnan(tensor)) + corrected = torch.where(condition, torch.zeros_like(tensor), tensor) + max_val = corrected.max() + if max_val <= 0: + failed_data_types[data_type] = f"Camera output '{data_type}' has no non-zero pixels." + continue + + normalized = _normalize_tensor(corrected, data_type) + grid = _make_grid(normalized) + ndarr = grid.mul(255).add_(0.5).clamp_(0, 255).permute(1, 2, 0).to("cpu", torch.uint8).numpy() + result_image = Image.fromarray(ndarr) + + golden_path = os.path.join(golden_image_dir, f"{physics_backend}-{renderer}-{data_type}.png") + if not os.path.exists(golden_path): + failed_data_types[data_type] = f"Golden image not found at {golden_path}." + result_image.save(golden_path) + continue + + try: + golden_image = Image.open(golden_path) + except Exception as error: # noqa: BLE001 + failed_data_types[data_type] = f"Error opening golden image: {error}" + continue + + check_ssim = data_type not in _SSIM_DISABLED_DATA_TYPES + succeeded, error_message, diff_pct, ssim_score = _compare_images( + result_image, + golden_image, + max_different_pixels_percentage, + check_ssim=check_ssim, + ssim_threshold=ssim_threshold, + ) + + entry = { + "test": test_name, + "backend": physics_backend, + "renderer": renderer, + "aov": data_type, + "diff_pct": diff_pct, + "ssim": ssim_score, + "ssim_checked": check_ssim, + "threshold": max_different_pixels_percentage, + "ssim_threshold": ssim_threshold, + "passed": succeeded, + "img_result_path": None, + "img_golden_path": None, + } + + if diff_pct > 0: + prefix = f"{test_name}-{physics_backend}-{renderer}-{data_type}" + entry["img_result_path"] = _save_comparison_image(result_image, f"{prefix}-actual.png") + entry["img_golden_path"] = _save_comparison_image(golden_image, f"{prefix}-golden.png") + + comparison_scores.append(entry) + + if not succeeded: + failed_data_types[data_type] = error_message + + if failed_data_types: + reason = f"{test_name} (physics={physics_backend}, renderer={renderer}) failed for the following data types:\n" + for data_type, error_message in failed_data_types.items(): + reason += f"- {data_type}: {error_message}\n" + reason += f"Comparison images were written to {_COMPARISON_IMAGES_DIR}." + pytest.fail(reason) + + +def rendering_test_shadow_hand( + physics_backend: str, + renderer: str, + data_type: str, + comparison_scores: list[dict], +) -> None: + from isaaclab_tasks.direct.shadow_hand.shadow_hand_vision_env import ShadowHandVisionEnv + from isaaclab_tasks.direct.shadow_hand.shadow_hand_vision_env_cfg import ShadowHandVisionEnvCfg + + override_args = [f"presets={_physics_preset_name(physics_backend)},{renderer},{data_type}"] + + env_cfg = ShadowHandVisionEnvCfg() + env_cfg = _apply_overrides_to_env_cfg(env_cfg, override_args) + + env_cfg.scene.num_envs = 4 + + if data_type == "depth": + # Disable CNN forward pass as it cannot be meaningfully trained from depth alone and will raise a ValueError. + env_cfg.feature_extractor.enabled = False + + env = None + + try: + env = ShadowHandVisionEnv(env_cfg) + maybe_save_stage("shadow_hand", physics_backend, renderer, data_type) + + validate_camera_outputs( + "shadow_hand", + physics_backend, + renderer, + env._tiled_camera.data.output, + max_different_pixels_percentage=MAX_DIFFERENT_PIXELS_PERCENTAGE_BY_ENV_NAME["shadow_hand"], + comparison_scores=comparison_scores, + ) + finally: + if env is not None: + env.close() + + # This invokes camera sensor and renderer cleanup explicitly before pytest teardown, otherwise OV + # native code could probably complain about leaks and trigger segmentation fault. + env = None + + +def rendering_test_cartpole( + physics_backend: str, + renderer: str, + data_type: str, + comparison_scores: list[dict], +) -> None: + from isaaclab_tasks.direct.cartpole.cartpole_camera_env import CartpoleCameraEnv + from isaaclab_tasks.direct.cartpole.cartpole_camera_presets_env_cfg import CartpoleCameraPresetsEnvCfg + + env_cfg = CartpoleCameraPresetsEnvCfg() + env_cfg = _apply_overrides_to_env_cfg( + env_cfg, [f"presets={_physics_preset_name(physics_backend)},{renderer},{data_type}"] + ) + + env_cfg.scene.num_envs = 4 + + env = None + + try: + env = CartpoleCameraEnv(env_cfg) + maybe_save_stage("cartpole", physics_backend, renderer, data_type) + validate_camera_outputs( + "cartpole", + physics_backend, + renderer, + env._tiled_camera.data.output, + max_different_pixels_percentage=MAX_DIFFERENT_PIXELS_PERCENTAGE_BY_ENV_NAME["cartpole"], + comparison_scores=comparison_scores, + ) + finally: + if env is not None: + env.close() + + # This invokes camera sensor and renderer cleanup explicitly before pytest teardown, otherwise OV + # native code could probably complain about leaks and trigger segmentation fault. + env = None + + +def rendering_test_dexsuite_kuka( + physics_backend: str, + renderer: str, + data_type: str, + comparison_scores: list[dict], +) -> None: + from isaaclab.envs import ManagerBasedRLEnv + + from isaaclab_tasks.manager_based.manipulation.dexsuite.config.kuka_allegro.dexsuite_kuka_allegro_env_cfg import ( + DexsuiteKukaAllegroLiftEnvCfg, + ) + + override_args = [f"presets={_physics_preset_name(physics_backend)},{renderer},{data_type}64,single_camera,cube"] + + env_cfg = DexsuiteKukaAllegroLiftEnvCfg() + env_cfg = _apply_overrides_to_env_cfg(env_cfg, override_args) + + env_cfg.scene.num_envs = 4 + + # Disable the observation point-cloud visualisation markers (/Visuals/ObservationPointCloud). + # The underlying point sampling uses the global numpy/torch RNG, so marker positions shift + # across processes and show up as random red dots in the rendered camera output. Since this + # test only cares about rendering correctness of the scene itself, we hide the markers here + # rather than making the sampler deterministic globally. + point_cloud_term = getattr(env_cfg.observations.perception, "object_point_cloud", None) + if point_cloud_term is not None: + point_cloud_term.params["visualize"] = False + + # The success and failure markers are placed exactly at the same location. If both markers are + # visible, the rendering order will determine which one is visible in the camera output. Hide + # both markers to avoid this nondeterministic behavior. + for marker_cfg in env_cfg.commands.object_pose.success_visualizer_cfg.markers.values(): + marker_cfg.visible = False + + env = None + + try: + env = ManagerBasedRLEnv(env_cfg) + maybe_save_stage("dexsuite_kuka", physics_backend, renderer, data_type) + validate_camera_outputs( + "dexsuite_kuka", + physics_backend, + renderer, + env.scene.sensors["base_camera"].data.output, + max_different_pixels_percentage=MAX_DIFFERENT_PIXELS_PERCENTAGE_BY_ENV_NAME["dexsuite_kuka"], + comparison_scores=comparison_scores, + ) + finally: + if env is not None: + env.close() + + # This invokes camera sensor and renderer cleanup explicitly before pytest teardown, otherwise OV + # native code could probably complain about leaks and trigger segmentation fault. + env = None diff --git a/source/isaaclab_tasks/test/test_distributed_device_resolution.py b/source/isaaclab_tasks/test/test_distributed_device_resolution.py new file mode 100644 index 000000000000..ec592c2b1342 --- /dev/null +++ b/source/isaaclab_tasks/test/test_distributed_device_resolution.py @@ -0,0 +1,479 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Tests for distributed multi-GPU device resolution logic. + +These tests verify that ``_resolve_distributed_device`` (in sim_launcher) +correctly handles: + +- Normal multi-GPU: each rank sees all GPUs (local_rank maps directly) +- CUDA_VISIBLE_DEVICES restricted: each rank sees 1 GPU (fallback to cuda:0) +- Multi-node: WORLD_SIZE > local GPU count (local_rank still maps correctly) +- JAX_LOCAL_RANK: added to local_rank for JAX distributed training +- Non-distributed: no device override applied +- launch_simulation device propagation from AppLauncher + +No actual GPUs required — ``torch.cuda.device_count`` and +``torch.cuda.set_device`` are mocked throughout. +""" + +from __future__ import annotations + +import argparse +import os +import sys +import types +from unittest.mock import patch + +import isaaclab_tasks.utils.sim_launcher as sim_launcher + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + + +class _DummySimCfg: + """Minimal sim config stub with a mutable ``device`` attribute.""" + + def __init__(self, device: str = "cuda:0"): + self.device = device + + +class _DummyEnvCfg: + """Minimal env config stub wrapping a sim config.""" + + def __init__(self, device: str = "cuda:0"): + self.sim = _DummySimCfg(device) + + +def _make_distributed_args(**overrides) -> argparse.Namespace: + """Create an argparse.Namespace with ``distributed=True`` plus any overrides.""" + defaults = {"distributed": True} + defaults.update(overrides) + return argparse.Namespace(**defaults) + + +def _make_env_vars( + local_rank: int = 0, + world_size: int = 2, + rank: int = 0, + jax_local_rank: int | None = None, + jax_rank: int | None = None, +) -> dict[str, str]: + """Build a dict of environment variables for distributed training.""" + env = { + "LOCAL_RANK": str(local_rank), + "WORLD_SIZE": str(world_size), + "RANK": str(rank), + } + if jax_local_rank is not None: + env["JAX_LOCAL_RANK"] = str(jax_local_rank) + if jax_rank is not None: + env["JAX_RANK"] = str(jax_rank) + return env + + +# --------------------------------------------------------------------------- +# _resolve_distributed_device — Namespace launcher_args +# --------------------------------------------------------------------------- + + +class TestResolveDistributedDeviceNamespace: + """Tests for _resolve_distributed_device with argparse.Namespace args.""" + + @patch("torch.cuda.set_device") + @patch("torch.cuda.device_count", return_value=4) + def test_normal_multi_gpu_rank0(self, mock_count, mock_set_device): + """4 visible GPUs, world_size=4, rank 0 → cuda:0.""" + env_cfg = _DummyEnvCfg() + args = _make_distributed_args() + env = _make_env_vars(local_rank=0, world_size=4) + + with patch.dict(os.environ, env, clear=False): + sim_launcher._resolve_distributed_device(env_cfg, args) + + assert env_cfg.sim.device == "cuda:0" + mock_set_device.assert_called_once_with("cuda:0") + + @patch("torch.cuda.set_device") + @patch("torch.cuda.device_count", return_value=4) + def test_normal_multi_gpu_rank3(self, mock_count, mock_set_device): + """4 visible GPUs, world_size=4, rank 3 → cuda:3.""" + env_cfg = _DummyEnvCfg() + args = _make_distributed_args() + env = _make_env_vars(local_rank=3, world_size=4) + + with patch.dict(os.environ, env, clear=False): + sim_launcher._resolve_distributed_device(env_cfg, args) + + assert env_cfg.sim.device == "cuda:3" + mock_set_device.assert_called_once_with("cuda:3") + + @patch("torch.cuda.set_device") + @patch("torch.cuda.device_count", return_value=1) + def test_cuda_visible_devices_restricted_rank0(self, mock_count, mock_set_device): + """1 visible GPU (CUDA_VISIBLE_DEVICES set), world_size=2, rank 0 → cuda:0.""" + env_cfg = _DummyEnvCfg() + args = _make_distributed_args() + env = _make_env_vars(local_rank=0, world_size=2) + + with patch.dict(os.environ, env, clear=False): + sim_launcher._resolve_distributed_device(env_cfg, args) + + assert env_cfg.sim.device == "cuda:0" + mock_set_device.assert_called_once_with("cuda:0") + + @patch("torch.cuda.set_device") + @patch("torch.cuda.device_count", return_value=1) + def test_cuda_visible_devices_restricted_rank1(self, mock_count, mock_set_device): + """1 visible GPU, world_size=2, rank 1 → falls back to cuda:0 (not cuda:1).""" + env_cfg = _DummyEnvCfg() + args = _make_distributed_args() + env = _make_env_vars(local_rank=1, world_size=2) + + with patch.dict(os.environ, env, clear=False): + sim_launcher._resolve_distributed_device(env_cfg, args) + + assert env_cfg.sim.device == "cuda:0" + mock_set_device.assert_called_once_with("cuda:0") + + @patch("torch.cuda.set_device") + @patch("torch.cuda.device_count", return_value=2) + def test_jax_local_rank_added(self, mock_count, mock_set_device): + """JAX_LOCAL_RANK is added to LOCAL_RANK for correct device mapping.""" + env_cfg = _DummyEnvCfg() + args = _make_distributed_args() + # LOCAL_RANK=0, JAX_LOCAL_RANK=1 → effective local_rank=1 + env = _make_env_vars(local_rank=0, world_size=2, jax_local_rank=1) + + with patch.dict(os.environ, env, clear=False): + sim_launcher._resolve_distributed_device(env_cfg, args) + + assert env_cfg.sim.device == "cuda:1" + mock_set_device.assert_called_once_with("cuda:1") + + @patch("torch.cuda.set_device") + @patch("torch.cuda.device_count", return_value=1) + def test_jax_local_rank_with_restricted_gpus(self, mock_count, mock_set_device): + """JAX_LOCAL_RANK + restricted GPUs → fallback to cuda:0.""" + env_cfg = _DummyEnvCfg() + args = _make_distributed_args() + env = _make_env_vars(local_rank=0, world_size=2, jax_local_rank=1) + + with patch.dict(os.environ, env, clear=False): + sim_launcher._resolve_distributed_device(env_cfg, args) + + assert env_cfg.sim.device == "cuda:0" + mock_set_device.assert_called_once_with("cuda:0") + + +# --------------------------------------------------------------------------- +# _resolve_distributed_device — dict launcher_args +# --------------------------------------------------------------------------- + + +class TestResolveDistributedDeviceDict: + """Tests for _resolve_distributed_device with dict-style args.""" + + @patch("torch.cuda.set_device") + @patch("torch.cuda.device_count", return_value=4) + def test_dict_args_distributed(self, mock_count, mock_set_device): + """Dict launcher_args with distributed=True should work identically.""" + env_cfg = _DummyEnvCfg() + args = {"distributed": True} + env = _make_env_vars(local_rank=2, world_size=4) + + with patch.dict(os.environ, env, clear=False): + sim_launcher._resolve_distributed_device(env_cfg, args) + + assert env_cfg.sim.device == "cuda:2" + mock_set_device.assert_called_once_with("cuda:2") + + @patch("torch.cuda.set_device") + @patch("torch.cuda.device_count", return_value=1) + def test_dict_args_restricted(self, mock_count, mock_set_device): + """Dict args with restricted GPUs should fall back to cuda:0.""" + env_cfg = _DummyEnvCfg() + args = {"distributed": True} + env = _make_env_vars(local_rank=3, world_size=4) + + with patch.dict(os.environ, env, clear=False): + sim_launcher._resolve_distributed_device(env_cfg, args) + + assert env_cfg.sim.device == "cuda:0" + mock_set_device.assert_called_once_with("cuda:0") + + +# --------------------------------------------------------------------------- +# _resolve_distributed_device — non-distributed (no-op) +# --------------------------------------------------------------------------- + + +class TestResolveDistributedDeviceNoop: + """Tests that non-distributed runs skip device resolution.""" + + @patch("torch.cuda.set_device") + def test_not_distributed_namespace(self, mock_set_device): + """distributed=False → device unchanged, set_device not called.""" + env_cfg = _DummyEnvCfg(device="cuda:0") + args = argparse.Namespace(distributed=False) + + sim_launcher._resolve_distributed_device(env_cfg, args) + + assert env_cfg.sim.device == "cuda:0" + mock_set_device.assert_not_called() + + @patch("torch.cuda.set_device") + def test_not_distributed_dict(self, mock_set_device): + """Dict with distributed=False → no-op.""" + env_cfg = _DummyEnvCfg(device="cuda:0") + args = {"distributed": False} + + sim_launcher._resolve_distributed_device(env_cfg, args) + + assert env_cfg.sim.device == "cuda:0" + mock_set_device.assert_not_called() + + @patch("torch.cuda.set_device") + def test_no_distributed_key(self, mock_set_device): + """Dict without 'distributed' key → no-op.""" + env_cfg = _DummyEnvCfg(device="cuda:0") + args = {} + + sim_launcher._resolve_distributed_device(env_cfg, args) + + assert env_cfg.sim.device == "cuda:0" + mock_set_device.assert_not_called() + + @patch("torch.cuda.set_device") + def test_none_launcher_args(self, mock_set_device): + """launcher_args=None → no-op.""" + env_cfg = _DummyEnvCfg(device="cuda:0") + + sim_launcher._resolve_distributed_device(env_cfg, None) + + assert env_cfg.sim.device == "cuda:0" + mock_set_device.assert_not_called() + + +# --------------------------------------------------------------------------- +# _resolve_distributed_device — edge cases +# --------------------------------------------------------------------------- + + +class TestResolveDistributedDeviceEdgeCases: + """Edge cases for device resolution.""" + + @patch("torch.cuda.set_device") + @patch("torch.cuda.device_count", return_value=2) + def test_env_cfg_without_sim(self, mock_count, mock_set_device): + """env_cfg with no 'sim' attribute → set_device still called, no crash.""" + + class _BareEnvCfg: + pass + + env_cfg = _BareEnvCfg() + args = _make_distributed_args() + env = _make_env_vars(local_rank=1, world_size=2) + + with patch.dict(os.environ, env, clear=False): + sim_launcher._resolve_distributed_device(env_cfg, args) + + # Should still call set_device even without sim_cfg + mock_set_device.assert_called_once_with("cuda:1") + + @patch("torch.cuda.set_device") + @patch("torch.cuda.device_count", return_value=2) + def test_world_size_equals_visible_gpus(self, mock_count, mock_set_device): + """Exact match: 2 visible GPUs, world_size=2 → use local_rank directly.""" + env_cfg = _DummyEnvCfg() + args = _make_distributed_args() + env = _make_env_vars(local_rank=1, world_size=2) + + with patch.dict(os.environ, env, clear=False): + sim_launcher._resolve_distributed_device(env_cfg, args) + + assert env_cfg.sim.device == "cuda:1" + + @patch("torch.cuda.set_device") + @patch("torch.cuda.device_count", return_value=8) + def test_more_gpus_than_world_size(self, mock_count, mock_set_device): + """8 visible GPUs but only 2 ranks → use local_rank directly.""" + env_cfg = _DummyEnvCfg() + args = _make_distributed_args() + env = _make_env_vars(local_rank=1, world_size=2) + + with patch.dict(os.environ, env, clear=False): + sim_launcher._resolve_distributed_device(env_cfg, args) + + assert env_cfg.sim.device == "cuda:1" + + @patch("torch.cuda.set_device") + @patch("torch.cuda.device_count", return_value=0) + def test_zero_visible_gpus(self, mock_count, mock_set_device): + """0 visible GPUs → fallback to cuda:0 (will fail later at CUDA init).""" + env_cfg = _DummyEnvCfg() + args = _make_distributed_args() + env = _make_env_vars(local_rank=0, world_size=2) + + with patch.dict(os.environ, env, clear=False): + sim_launcher._resolve_distributed_device(env_cfg, args) + + assert env_cfg.sim.device == "cuda:0" + + @patch("torch.cuda.set_device") + @patch("torch.cuda.device_count", return_value=4) + def test_missing_env_vars_default_to_zero(self, mock_count, mock_set_device): + """Missing LOCAL_RANK/WORLD_SIZE → defaults to 0/1.""" + env_cfg = _DummyEnvCfg() + args = _make_distributed_args() + + # Remove distributed env vars if they exist + clean_env = { + k: v + for k, v in os.environ.items() + if k not in ("LOCAL_RANK", "WORLD_SIZE", "RANK", "JAX_LOCAL_RANK", "JAX_RANK") + } + + with patch.dict(os.environ, clean_env, clear=True): + sim_launcher._resolve_distributed_device(env_cfg, args) + + # local_rank=0, 0 < 4 → cuda:0 + assert env_cfg.sim.device == "cuda:0" + + +# --------------------------------------------------------------------------- +# _resolve_distributed_device — multi-node scenarios +# --------------------------------------------------------------------------- + + +class TestResolveDistributedDeviceMultiNode: + """Tests for multi-node setups where WORLD_SIZE > local GPU count.""" + + @patch("torch.cuda.set_device") + @patch("torch.cuda.device_count", return_value=4) + def test_multi_node_rank3_sees_4_gpus(self, mock_count, mock_set_device): + """2 nodes × 4 GPUs, WORLD_SIZE=8, local_rank=3, 4 visible → cuda:3. + + Previously this would fail because 4 >= 8 is False, falling back to cuda:0. + With the fix (local_rank < num_visible_gpus), 3 < 4 → cuda:3 ✅ + """ + env_cfg = _DummyEnvCfg() + args = _make_distributed_args() + env = _make_env_vars(local_rank=3, world_size=8, rank=7) + + with patch.dict(os.environ, env, clear=False): + sim_launcher._resolve_distributed_device(env_cfg, args) + + assert env_cfg.sim.device == "cuda:3" + mock_set_device.assert_called_once_with("cuda:3") + + @patch("torch.cuda.set_device") + @patch("torch.cuda.device_count", return_value=4) + def test_multi_node_rank0_sees_4_gpus(self, mock_count, mock_set_device): + """2 nodes × 4 GPUs, WORLD_SIZE=8, local_rank=0 → cuda:0.""" + env_cfg = _DummyEnvCfg() + args = _make_distributed_args() + env = _make_env_vars(local_rank=0, world_size=8, rank=4) + + with patch.dict(os.environ, env, clear=False): + sim_launcher._resolve_distributed_device(env_cfg, args) + + assert env_cfg.sim.device == "cuda:0" + mock_set_device.assert_called_once_with("cuda:0") + + @patch("torch.cuda.set_device") + @patch("torch.cuda.device_count", return_value=1) + def test_multi_node_restricted_gpus(self, mock_count, mock_set_device): + """Multi-node with CUDA_VISIBLE_DEVICES=, local_rank=1 → cuda:0.""" + env_cfg = _DummyEnvCfg() + args = _make_distributed_args() + env = _make_env_vars(local_rank=1, world_size=8, rank=5) + + with patch.dict(os.environ, env, clear=False): + sim_launcher._resolve_distributed_device(env_cfg, args) + + assert env_cfg.sim.device == "cuda:0" + mock_set_device.assert_called_once_with("cuda:0") + + +# --------------------------------------------------------------------------- +# launch_simulation integration — verify device propagation from AppLauncher +# --------------------------------------------------------------------------- + + +class TestLaunchSimulationDevicePropagation: + """Verify that launch_simulation propagates AppLauncher.device to env_cfg.""" + + def test_kit_path_propagates_applauncher_device(self, monkeypatch): + """When Kit is needed, AppLauncher.device should be written to env_cfg.sim.device.""" + + class _FakeAppLauncher: + def __init__(self, launcher_args): + self.device = "cuda:3" # Simulate resolved device + self.app = types.SimpleNamespace(close=lambda: None) + + # Mock has_kit to return False so AppLauncher gets created + mock_isaaclab_utils = types.ModuleType("isaaclab.utils") + mock_isaaclab_utils.has_kit = lambda: False + monkeypatch.setitem(sys.modules, "isaaclab.utils", mock_isaaclab_utils) + + monkeypatch.setitem( + sys.modules, + "isaaclab.app", + types.SimpleNamespace(AppLauncher=_FakeAppLauncher), + ) + monkeypatch.setattr( + "importlib.util.find_spec", + lambda name: object() if name == "omni.kit" else None, + ) + # Force needs_kit=True, no cameras + monkeypatch.setattr( + sim_launcher, + "compute_kit_requirements", + lambda env_cfg, launcher_args: (True, False, set()), + ) + # Mock _resolve_distributed_device to avoid torch.cuda calls + monkeypatch.setattr( + sim_launcher, + "_resolve_distributed_device", + lambda env_cfg, launcher_args: None, + ) + + env_cfg = _DummyEnvCfg(device="cuda:0") + args = argparse.Namespace() + + with sim_launcher.launch_simulation(env_cfg, args): + pass + + assert env_cfg.sim.device == "cuda:3" + + def test_kitless_path_uses_resolve_distributed_device(self, monkeypatch): + """When Kit is NOT needed, _resolve_distributed_device sets the device.""" + resolved_devices = [] + + def _fake_resolve(env_cfg, launcher_args): + env_cfg.sim.device = "cuda:1" + resolved_devices.append("cuda:1") + + monkeypatch.setattr( + sim_launcher, + "compute_kit_requirements", + lambda env_cfg, launcher_args: (False, False, set()), + ) + monkeypatch.setattr( + sim_launcher, + "_resolve_distributed_device", + _fake_resolve, + ) + + env_cfg = _DummyEnvCfg(device="cuda:0") + args = _make_distributed_args() + + with sim_launcher.launch_simulation(env_cfg, args): + pass + + assert env_cfg.sim.device == "cuda:1" + assert len(resolved_devices) == 1 diff --git a/source/isaaclab_tasks/test/test_environments_newton.py b/source/isaaclab_tasks/test/test_environments_newton.py index 8f0ae09e3496..23456946a689 100644 --- a/source/isaaclab_tasks/test/test_environments_newton.py +++ b/source/isaaclab_tasks/test/test_environments_newton.py @@ -32,18 +32,18 @@ teleop_envs=False, cartpole_showcase_envs=False, pickplace_stack_envs=False, - newton_envs=True, + newton_mjwarp_envs=True, ), ) @pytest.mark.newton_ci @pytest.mark.xfail( reason=( - "TODO: Nested PresetCfg resolution for named presets (e.g. 'newton') is not yet supported. " + "TODO: Nested PresetCfg resolution for named presets (e.g. 'newton_mjwarp') is not yet supported. " "The logic in parse_cfg.apply_named_preset should be unified with the deep-nesting " "fixes in https://github.com/isaac-sim/IsaacLab/pull/5029 (isaaclab_tasks.utils.hydra)." ), strict=False, ) def test_environments_newton(task_name, num_envs, device): - # run environments with newton physics preset - _run_environments(task_name, device, num_envs, physics_preset_name="newton", create_stage_in_memory=False) + # run environments with MJWarp physics preset + _run_environments(task_name, device, num_envs, physics_preset_name="newton_mjwarp", create_stage_in_memory=False) diff --git a/source/isaaclab_tasks/test/test_hydra.py b/source/isaaclab_tasks/test/test_hydra.py index 20e79bac54a8..738884874899 100644 --- a/source/isaaclab_tasks/test/test_hydra.py +++ b/source/isaaclab_tasks/test/test_hydra.py @@ -9,17 +9,21 @@ external environment configurations. """ +import warnings + import pytest from isaaclab.utils import configclass +from isaaclab_tasks.utils import hydra as hydra_mod from isaaclab_tasks.utils.hydra import ( PresetCfg, + _format_unknown_presets_error, apply_overrides, collect_presets, parse_overrides, preset, - resolve_preset_defaults, + resolve_presets, ) # ============================================================================= @@ -86,7 +90,7 @@ class SampleAgentCfg: @configclass class SimBackendCfg(PresetCfg): default: PhysxCfg = PhysxCfg() - newton: NewtonCfg = NewtonCfg() + newton_mjwarp: NewtonCfg = NewtonCfg() @configclass @@ -116,7 +120,7 @@ class PresetCfgAgentCfg: @configclass class RootAgentCfg(PresetCfg): - """Root-level PresetCfg — the agent config itself is a PresetCfg.""" + """Root-level PresetCfg -- the agent config itself is a PresetCfg.""" default: SampleAgentCfg = SampleAgentCfg() fast: SampleAgentCfg = SampleAgentCfg(max_iterations=100, learning_rate=1e-3) @@ -162,6 +166,147 @@ class NestedPresetEnvCfg: scene: ScenePresetCfg = ScenePresetCfg() +# -- Scalar PresetCfg and actuator configs (shared by scalar + dict sections) -- + + +@configclass +class ScalarPresetCfg(PresetCfg): + default: float = 0.0 + newton_mjwarp: float = 0.01 + + +@configclass +class ActuatorWithPresetCfg: + joint_names: list = [".*"] + stiffness: float = 40.0 + damping: float = 5.0 + armature: ScalarPresetCfg = ScalarPresetCfg() + + +# -- Deep-nested dict configs (event term params pattern) -- + + +@configclass +class OffsetCfg(PresetCfg): + """Mimics task-specific offset presets (e.g., AssembledOffsetCfg).""" + + task_a: tuple = (0.0, 0.0, 0.01) + task_b: tuple = (0.02, 0.0, 0.005) + default: tuple = task_a + + +@configclass +class FractionCfg(PresetCfg): + task_a: tuple = (0.05, 0.5) + task_b: tuple = (0.3, 1.0) + default: tuple = task_a + + +@configclass +class JointNamesCfg(PresetCfg): + default: list[str] | None = None + robot_a: list[str] = None + robot_b: list[str] = None + + +@configclass +class EntityCfg: + """Mimics SceneEntityCfg with a preset-valued field.""" + + name: str = "robot" + joint_names: list[str] | None = None + + +@configclass +class InnerTermCfg: + """Mimics an EventTermCfg with params containing presets.""" + + func: str = "reset_fn" + params: dict = None + + def __post_init__(self): + if self.params is None: + self.params = { + "offset": OffsetCfg(), + "fraction": FractionCfg(), + "robot_cfg": EntityCfg(name="robot", joint_names=JointNamesCfg()), + } + + +@configclass +class OuterTermCfg: + """Mimics a chained reset term with nested terms dict.""" + + func: str = "chain_fn" + params: dict = None + + def __post_init__(self): + if self.params is None: + self.params = { + "terms": { + "step_one": InnerTermCfg(), + } + } + + +@configclass +class DeepDictEnvCfg: + decimation: int = 4 + events: OuterTermCfg = OuterTermCfg() + + +@configclass +class DictPresetTermCfg: + """Outer term where the terms dict is itself a preset (resolves to a dict).""" + + func: str = "term_choice" + params: dict = None + + def __post_init__(self): + if self.params is None: + self.params = { + "terms": preset( + default={ + "strategy_a": InnerTermCfg(), + "strategy_b": InnerTermCfg(), + }, + alt={ + "strategy_a": InnerTermCfg(), + }, + ), + } + + +@configclass +class PresetResolvesToDictEnvCfg: + decimation: int = 4 + events: DictPresetTermCfg = DictPresetTermCfg() + + +# ============================================================================= +# Helpers +# ============================================================================= + + +def _apply(env_cfg, agent_cfg=None, global_presets=None, preset_sel=None, preset_scalar=None): + """Collect presets, resolve defaults, build hydra dict, and apply overrides.""" + if agent_cfg is None: + agent_cfg = PresetCfgAgentCfg() + presets = {"env": collect_presets(env_cfg), "agent": collect_presets(agent_cfg)} + env_cfg = resolve_presets(env_cfg) + agent_cfg = resolve_presets(agent_cfg) + hydra_cfg = {"env": env_cfg.to_dict(), "agent": agent_cfg.to_dict()} + return apply_overrides( + env_cfg, + agent_cfg, + hydra_cfg, + global_presets or [], + preset_sel or [], + preset_scalar or [], + presets, + ) + + # ============================================================================= # Fixtures # ============================================================================= @@ -185,9 +330,74 @@ def test_collect_presets_class_style(): """PresetCfg fields discovered at correct paths.""" presets = collect_presets(PresetCfgEnvCfg()) assert "backend" in presets - assert set(presets["backend"].keys()) == {"default", "newton"} + assert set(presets["backend"].keys()) == {"default", "newton_mjwarp"} assert isinstance(presets["backend"]["default"], PhysxCfg) - assert isinstance(presets["backend"]["newton"], NewtonCfg) + assert isinstance(presets["backend"]["newton_mjwarp"], NewtonCfg) + + +def test_legacy_newton_attribute_alias_warns(): + """Python access to the legacy ``newton`` preset aliases to ``newton_mjwarp`` during deprecation.""" + cfg = SimBackendCfg() + with pytest.warns(FutureWarning, match="Preset 'newton' is deprecated"): + assert cfg.newton is cfg.newton_mjwarp + + +def test_legacy_kamino_attribute_alias_warns(): + """Python access to the legacy ``kamino`` preset aliases to ``newton_kamino`` during deprecation.""" + + @configclass + class _SolverPresetsCfg(PresetCfg): + default: PhysxCfg = PhysxCfg() + newton_kamino: NewtonCfg = NewtonCfg() + + cfg = _SolverPresetsCfg() + with pytest.warns(FutureWarning, match="Preset 'kamino' is deprecated"): + assert cfg.kamino is cfg.newton_kamino + + +def test_legacy_alias_suppressed_when_legacy_name_is_real_field(): + """An env that legitimately defines ``newton`` should not warn or be remapped.""" + + @configclass + class _ShadowingCfg(PresetCfg): + default: PhysxCfg = PhysxCfg() + newton: PhysxCfg = PhysxCfg() + newton_mjwarp: NewtonCfg = NewtonCfg() + + cfg = _ShadowingCfg() + with warnings.catch_warnings(): + warnings.simplefilter("error", FutureWarning) + assert cfg.newton is not cfg.newton_mjwarp + assert isinstance(cfg.newton, PhysxCfg) + + +def test_presetcfg_attribute_error_for_unknown_attribute(): + """Plain missing attributes should raise ``AttributeError`` (not warn or alias).""" + cfg = SimBackendCfg() + assert not hasattr(cfg, "completely_unknown") + with pytest.raises(AttributeError, match="completely_unknown"): + _ = cfg.completely_unknown + + +def test_format_unknown_presets_error_calls_out_legacy_aliases(): + """The unknown-preset error should explicitly mention the rename for legacy aliases.""" + msg = _format_unknown_presets_error({"newton", "typo"}, {"fast": ["env"]}) + assert "newton' was renamed to 'newton_mjwarp'" in msg + assert "typo" in msg + + +def test_user_stacklevel_warning_origin_is_outside_hydra_module(): + """``_normalize_preset_name`` warnings should not be attributed to hydra.py itself.""" + presets_arg = {"env": {"backend": {"default": None, "newton_mjwarp": None}}, "agent": {}} + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always", FutureWarning) + parse_overrides(["presets=newton"], presets_arg) + deprecations = [w for w in caught if issubclass(w.category, FutureWarning)] + assert deprecations, "expected a FutureWarning from the legacy alias" + assert deprecations[0].filename != hydra_mod.__file__, ( + f"warning was attributed to hydra.py ({deprecations[0].filename}); _user_stacklevel should " + f"point outside the module" + ) def test_collect_presets_root_level(): @@ -211,12 +421,12 @@ def test_parse_overrides_mixed(): args = [ "presets=fast", "env.decimation=10", - "env.backend=newton", + "env.backend=newton_mjwarp", "env.backend.dt=0.001", ] global_p, sel, scalar, glob = parse_overrides(args, presets) assert global_p == ["fast"] - assert ("env", "backend", "newton") in sel + assert ("env", "backend", "newton_mjwarp") in sel assert ("env.backend.dt", "0.001") in scalar assert "env.decimation=10" in glob @@ -229,7 +439,7 @@ def test_parse_overrides_root_preset(): # ============================================================================= -# Tests: apply_overrides — PresetCfg (nested + broadcast + root) +# Tests: apply_overrides -- PresetCfg (nested + broadcast + root) # ============================================================================= @@ -247,7 +457,7 @@ def test_presetcfg_cli_selection(class_presets): """Path selection replaces with chosen preset.""" env_cfg, agent_cfg, presets = class_presets hydra_cfg = {"env": env_cfg.to_dict(), "agent": agent_cfg.to_dict()} - apply_overrides(env_cfg, agent_cfg, hydra_cfg, [], [("env", "backend", "newton")], [], presets) + apply_overrides(env_cfg, agent_cfg, hydra_cfg, [], [("env", "backend", "newton_mjwarp")], [], presets) assert isinstance(env_cfg.backend, NewtonCfg) assert env_cfg.backend.dt == 0.002 @@ -265,7 +475,7 @@ def test_presetcfg_path_selection_others_default(class_presets): """Path preset on one field, others get auto-default.""" env_cfg, agent_cfg, presets = class_presets hydra_cfg = {"env": env_cfg.to_dict(), "agent": agent_cfg.to_dict()} - apply_overrides(env_cfg, agent_cfg, hydra_cfg, [], [("env", "backend", "newton")], [], presets) + apply_overrides(env_cfg, agent_cfg, hydra_cfg, [], [("env", "backend", "newton_mjwarp")], [], presets) assert isinstance(env_cfg.backend, NewtonCfg) assert isinstance(env_cfg.observations, NoiselessObservationsCfg) assert isinstance(agent_cfg.policy, SmallPolicyCfg) @@ -273,22 +483,14 @@ def test_presetcfg_path_selection_others_default(class_presets): def test_root_presetcfg_auto_default(): """Root-level PresetCfg auto-applies 'default'.""" - agent_cfg = RootAgentCfg() - env_cfg = SampleEnvCfg() - presets = {"env": collect_presets(env_cfg), "agent": collect_presets(agent_cfg)} - hydra_cfg = {"env": env_cfg.to_dict(), "agent": agent_cfg.to_dict()} - env_cfg, agent_cfg = apply_overrides(env_cfg, agent_cfg, hydra_cfg, [], [], [], presets) + env_cfg, agent_cfg = _apply(SampleEnvCfg(), RootAgentCfg()) assert isinstance(agent_cfg, SampleAgentCfg) assert agent_cfg.max_iterations == 1000 def test_root_presetcfg_cli_selection(): """Root-level PresetCfg resolved via path selection.""" - agent_cfg = RootAgentCfg() - env_cfg = SampleEnvCfg() - presets = {"env": collect_presets(env_cfg), "agent": collect_presets(agent_cfg)} - hydra_cfg = {"env": env_cfg.to_dict(), "agent": agent_cfg.to_dict()} - env_cfg, agent_cfg = apply_overrides(env_cfg, agent_cfg, hydra_cfg, [], [("agent", "", "fast")], [], presets) + env_cfg, agent_cfg = _apply(SampleEnvCfg(), RootAgentCfg(), preset_sel=[("agent", "", "fast")]) assert isinstance(agent_cfg, SampleAgentCfg) assert agent_cfg.max_iterations == 100 assert agent_cfg.learning_rate == 1e-3 @@ -296,11 +498,7 @@ def test_root_presetcfg_cli_selection(): def test_root_presetcfg_global_preset(): """Root-level PresetCfg resolved via global preset.""" - agent_cfg = RootAgentCfg() - env_cfg = SampleEnvCfg() - presets = {"env": collect_presets(env_cfg), "agent": collect_presets(agent_cfg)} - hydra_cfg = {"env": env_cfg.to_dict(), "agent": agent_cfg.to_dict()} - env_cfg, agent_cfg = apply_overrides(env_cfg, agent_cfg, hydra_cfg, ["fast"], [], [], presets) + env_cfg, agent_cfg = _apply(SampleEnvCfg(), RootAgentCfg(), global_presets=["fast"]) assert isinstance(agent_cfg, SampleAgentCfg) assert agent_cfg.max_iterations == 100 @@ -315,7 +513,6 @@ def test_collect_nested_presetcfg(): presets = collect_presets(NestedPresetEnvCfg()) assert "scene" in presets assert set(presets["scene"].keys()) == {"default", "with_camera"} - # camera preset discovered inside with_camera alternative assert "scene.camera" in presets assert set(presets["scene.camera"].keys()) == {"small", "large", "default"} assert isinstance(presets["scene.camera"]["small"], CameraSmallCfg) @@ -324,24 +521,14 @@ def test_collect_nested_presetcfg(): def test_nested_presetcfg_pruned_when_parent_has_none(): """When scene auto-defaults to default (camera=None), nested camera preset is pruned.""" - env_cfg = NestedPresetEnvCfg() - agent_cfg = PresetCfgAgentCfg() - presets = {"env": collect_presets(env_cfg), "agent": collect_presets(agent_cfg)} - hydra_cfg = {"env": env_cfg.to_dict(), "agent": agent_cfg.to_dict()} - # No CLI args → scene resolves to default (camera=None), camera preset must NOT apply - apply_overrides(env_cfg, agent_cfg, hydra_cfg, [], [], [], presets) + env_cfg, _ = _apply(NestedPresetEnvCfg()) assert isinstance(env_cfg.scene, BaseSceneCfg) assert env_cfg.scene.camera is None def test_nested_presetcfg_auto_default_with_camera(): """When with_camera scene is selected, camera auto-defaults to small (the default).""" - env_cfg = NestedPresetEnvCfg() - agent_cfg = PresetCfgAgentCfg() - presets = {"env": collect_presets(env_cfg), "agent": collect_presets(agent_cfg)} - hydra_cfg = {"env": env_cfg.to_dict(), "agent": agent_cfg.to_dict()} - # Only select with_camera scene, camera should auto-default to small - apply_overrides(env_cfg, agent_cfg, hydra_cfg, ["with_camera"], [], [], presets) + env_cfg, _ = _apply(NestedPresetEnvCfg(), global_presets=["with_camera"]) assert isinstance(env_cfg.scene, BaseSceneCfg) assert isinstance(env_cfg.scene.camera, CameraSmallCfg) assert env_cfg.scene.camera.width == 64 @@ -349,12 +536,7 @@ def test_nested_presetcfg_auto_default_with_camera(): def test_nested_presetcfg_global_broadcast(): """Global preset resolves both outer and nested PresetCfg.""" - env_cfg = NestedPresetEnvCfg() - agent_cfg = PresetCfgAgentCfg() - presets = {"env": collect_presets(env_cfg), "agent": collect_presets(agent_cfg)} - hydra_cfg = {"env": env_cfg.to_dict(), "agent": agent_cfg.to_dict()} - # "with_camera" selects the scene, "large" selects the camera - apply_overrides(env_cfg, agent_cfg, hydra_cfg, ["with_camera", "large"], [], [], presets) + env_cfg, _ = _apply(NestedPresetEnvCfg(), global_presets=["with_camera", "large"]) assert isinstance(env_cfg.scene, BaseSceneCfg) assert isinstance(env_cfg.scene.camera, CameraLargeCfg) assert env_cfg.scene.camera.width == 256 @@ -362,12 +544,8 @@ def test_nested_presetcfg_global_broadcast(): def test_nested_presetcfg_path_selection(): """Path selection on nested PresetCfg resolves correctly.""" - env_cfg = NestedPresetEnvCfg() - agent_cfg = PresetCfgAgentCfg() - presets = {"env": collect_presets(env_cfg), "agent": collect_presets(agent_cfg)} - hydra_cfg = {"env": env_cfg.to_dict(), "agent": agent_cfg.to_dict()} sel = [("env", "scene", "with_camera"), ("env", "scene.camera", "large")] - apply_overrides(env_cfg, agent_cfg, hydra_cfg, [], sel, [], presets) + env_cfg, _ = _apply(NestedPresetEnvCfg(), preset_sel=sel) assert isinstance(env_cfg.scene, BaseSceneCfg) assert isinstance(env_cfg.scene.camera, CameraLargeCfg) assert env_cfg.scene.camera.width == 256 @@ -392,7 +570,7 @@ class RendererBCfg: @configclass class RendererPresetCfg(PresetCfg): default: RendererACfg = RendererACfg() - newton: RendererBCfg = RendererBCfg() + newton_renderer: RendererBCfg = RendererBCfg() @configclass @@ -430,12 +608,12 @@ def test_root_presetcfg_with_nested_preset_collect(): assert "sensor" in presets assert set(presets["sensor"].keys()) == {"default", "depth"} assert "sensor.renderer" in presets - assert set(presets["sensor.renderer"].keys()) == {"default", "newton"} + assert set(presets["sensor.renderer"].keys()) == {"default", "newton_renderer"} def test_root_presetcfg_resolve_defaults(): - """resolve_preset_defaults resolves nested PresetCfg inside root.""" - resolved = resolve_preset_defaults(RootPresetEnvCfg()) + """resolve_presets resolves nested PresetCfg inside root.""" + resolved = resolve_presets(RootPresetEnvCfg()) assert isinstance(resolved, RootEnvBaseCfg) assert isinstance(resolved.sensor, SensorBaseCfg) assert resolved.sensor.data_types == ["rgb"] @@ -463,11 +641,7 @@ class EnvWithOptionalFeatureCfg: def test_presetcfg_none_default_auto_applies(): """PresetCfg with default=None auto-applies None without crashing.""" - env_cfg = EnvWithOptionalFeatureCfg() - agent_cfg = PresetCfgAgentCfg() - presets = {"env": collect_presets(env_cfg), "agent": collect_presets(agent_cfg)} - hydra_cfg = {"env": env_cfg.to_dict(), "agent": agent_cfg.to_dict()} - apply_overrides(env_cfg, agent_cfg, hydra_cfg, [], [], [], presets) + env_cfg, _ = _apply(EnvWithOptionalFeatureCfg()) assert env_cfg.optional_feature is None @@ -485,17 +659,7 @@ def test_presetcfg_none_default_cli_selects_enabled(): def test_root_presetcfg_global_depth_resolves_nested(): """Global preset=depth on root PresetCfg also resolves nested sensor and renderer.""" - env_cfg = RootPresetEnvCfg() - agent_cfg = PresetCfgAgentCfg() - presets = {"env": collect_presets(env_cfg), "agent": collect_presets(agent_cfg)} - - env_cfg = resolve_preset_defaults(env_cfg) - agent_cfg_resolved = resolve_preset_defaults(agent_cfg) - - hydra_cfg = {"env": env_cfg.to_dict(), "agent": agent_cfg_resolved.to_dict()} - - env_cfg, agent_cfg = apply_overrides(env_cfg, agent_cfg_resolved, hydra_cfg, ["depth"], [], [], presets) - + env_cfg, _ = _apply(RootPresetEnvCfg(), global_presets=["depth"]) assert isinstance(env_cfg, RootEnvBaseCfg) assert env_cfg.obs_shape == [100, 100, 1] assert isinstance(env_cfg.sensor, SensorBaseCfg), ( @@ -508,28 +672,14 @@ def test_root_presetcfg_global_depth_resolves_nested(): # ============================================================================= -# Tests: scalar PresetCfg (e.g., armature=PresetCfg(default=0.0, newton=0.01)) +# Tests: scalar PresetCfg (e.g., armature=PresetCfg(default=0.0, newton_mjwarp=0.01)) # ============================================================================= -@configclass -class ScalarPresetCfg(PresetCfg): - default: float = 0.0 - newton: float = 0.01 - - -@configclass -class ActuatorWithScalarPresetCfg: - joint_names: list = [".*"] - stiffness: float = 40.0 - damping: float = 5.0 - armature: ScalarPresetCfg = ScalarPresetCfg() - - @configclass class ScalarPresetEnvCfg: decimation: int = 4 - actuator: ActuatorWithScalarPresetCfg = ActuatorWithScalarPresetCfg() + actuator: ActuatorWithPresetCfg = ActuatorWithPresetCfg() def test_scalar_presetcfg_collect(): @@ -537,53 +687,34 @@ def test_scalar_presetcfg_collect(): presets = collect_presets(ScalarPresetEnvCfg()) assert "actuator.armature" in presets assert presets["actuator.armature"]["default"] == 0.0 - assert presets["actuator.armature"]["newton"] == 0.01 + assert presets["actuator.armature"]["newton_mjwarp"] == 0.01 def test_scalar_presetcfg_resolve_default(): - """resolve_preset_defaults replaces scalar PresetCfg with its default value.""" + """resolve_presets replaces scalar PresetCfg with its default value.""" cfg = ScalarPresetEnvCfg() - resolved = resolve_preset_defaults(cfg) + resolved = resolve_presets(cfg) assert resolved.actuator.armature == 0.0 assert not isinstance(resolved.actuator.armature, PresetCfg) def test_scalar_presetcfg_auto_default(): """Scalar PresetCfg auto-applies default=0.0 when no CLI override.""" - env_cfg = ScalarPresetEnvCfg() - agent_cfg = PresetCfgAgentCfg() - presets = {"env": collect_presets(env_cfg), "agent": collect_presets(agent_cfg)} - env_cfg = resolve_preset_defaults(env_cfg) - agent_cfg = resolve_preset_defaults(agent_cfg) - hydra_cfg = {"env": env_cfg.to_dict(), "agent": agent_cfg.to_dict()} - apply_overrides(env_cfg, agent_cfg, hydra_cfg, [], [], [], presets) + env_cfg, _ = _apply(ScalarPresetEnvCfg()) assert env_cfg.actuator.armature == 0.0 -def test_scalar_presetcfg_global_newton(): - """Global preset=newton replaces scalar PresetCfg with newton value.""" - env_cfg = ScalarPresetEnvCfg() - agent_cfg = PresetCfgAgentCfg() - presets = {"env": collect_presets(env_cfg), "agent": collect_presets(agent_cfg)} - env_cfg = resolve_preset_defaults(env_cfg) - agent_cfg = resolve_preset_defaults(agent_cfg) - hydra_cfg = {"env": env_cfg.to_dict(), "agent": agent_cfg.to_dict()} - apply_overrides(env_cfg, agent_cfg, hydra_cfg, ["newton"], [], [], presets) +def test_scalar_presetcfg_global_newton_mjwarp(): + """Global preset=newton_mjwarp replaces scalar PresetCfg with MJWarp value.""" + env_cfg, _ = _apply(ScalarPresetEnvCfg(), global_presets=["newton_mjwarp"]) assert env_cfg.actuator.armature == 0.01 def test_scalar_presetcfg_path_selection(): """Path selection replaces scalar PresetCfg with chosen value.""" - env_cfg = ScalarPresetEnvCfg() - agent_cfg = PresetCfgAgentCfg() - presets = {"env": collect_presets(env_cfg), "agent": collect_presets(agent_cfg)} - env_cfg = resolve_preset_defaults(env_cfg) - agent_cfg = resolve_preset_defaults(agent_cfg) - hydra_cfg = {"env": env_cfg.to_dict(), "agent": agent_cfg.to_dict()} - sel = [("env", "actuator.armature", "newton")] - apply_overrides(env_cfg, agent_cfg, hydra_cfg, [], sel, [], presets) + env_cfg, _ = _apply(ScalarPresetEnvCfg(), preset_sel=[("env", "actuator.armature", "newton_mjwarp")]) assert env_cfg.actuator.armature == 0.01 - assert env_cfg.actuator.stiffness == 40.0 # other fields untouched + assert env_cfg.actuator.stiffness == 40.0 # ============================================================================= @@ -591,14 +722,6 @@ def test_scalar_presetcfg_path_selection(): # ============================================================================= -@configclass -class ActuatorCfgWithPreset: - joint_names: list = [".*"] - stiffness: float = 40.0 - damping: float = 5.0 - armature: ScalarPresetCfg = ScalarPresetCfg() - - @configclass class RobotCfg: prim_path: str = "/World/Robot" @@ -606,7 +729,7 @@ class RobotCfg: def __post_init__(self): if self.actuators is None: - self.actuators = {"legs": ActuatorCfgWithPreset()} + self.actuators = {"legs": ActuatorWithPresetCfg()} @configclass @@ -621,51 +744,32 @@ def test_collect_presets_traverses_dict_values(): presets = collect_presets(cfg) assert "robot.actuators.legs.armature" in presets assert presets["robot.actuators.legs.armature"]["default"] == 0.0 - assert presets["robot.actuators.legs.armature"]["newton"] == 0.01 + assert presets["robot.actuators.legs.armature"]["newton_mjwarp"] == 0.01 -def test_resolve_preset_defaults_traverses_dict_values(): - """resolve_preset_defaults resolves PresetCfg inside dict-held configclass values.""" +def test_resolve_presets_traverses_dict_values(): + """resolve_presets resolves PresetCfg inside dict-held configclass values.""" cfg = DictPresetEnvCfg() - resolved = resolve_preset_defaults(cfg) + resolved = resolve_presets(cfg) assert resolved.robot.actuators["legs"].armature == 0.0 assert not isinstance(resolved.robot.actuators["legs"].armature, PresetCfg) def test_dict_preset_auto_default(): """Dict-held PresetCfg auto-applies default when no CLI override.""" - env_cfg = DictPresetEnvCfg() - agent_cfg = PresetCfgAgentCfg() - presets = {"env": collect_presets(env_cfg), "agent": collect_presets(agent_cfg)} - env_cfg = resolve_preset_defaults(env_cfg) - agent_cfg = resolve_preset_defaults(agent_cfg) - hydra_cfg = {"env": env_cfg.to_dict(), "agent": agent_cfg.to_dict()} - apply_overrides(env_cfg, agent_cfg, hydra_cfg, [], [], [], presets) + env_cfg, _ = _apply(DictPresetEnvCfg()) assert env_cfg.robot.actuators["legs"].armature == 0.0 -def test_dict_preset_global_newton(): - """Global preset=newton replaces dict-held scalar PresetCfg.""" - env_cfg = DictPresetEnvCfg() - agent_cfg = PresetCfgAgentCfg() - presets = {"env": collect_presets(env_cfg), "agent": collect_presets(agent_cfg)} - env_cfg = resolve_preset_defaults(env_cfg) - agent_cfg = resolve_preset_defaults(agent_cfg) - hydra_cfg = {"env": env_cfg.to_dict(), "agent": agent_cfg.to_dict()} - apply_overrides(env_cfg, agent_cfg, hydra_cfg, ["newton"], [], [], presets) +def test_dict_preset_global_newton_mjwarp(): + """Global preset=newton_mjwarp replaces dict-held scalar PresetCfg.""" + env_cfg, _ = _apply(DictPresetEnvCfg(), global_presets=["newton_mjwarp"]) assert env_cfg.robot.actuators["legs"].armature == 0.01 def test_dict_preset_path_selection(): """Path selection replaces dict-held scalar PresetCfg.""" - env_cfg = DictPresetEnvCfg() - agent_cfg = PresetCfgAgentCfg() - presets = {"env": collect_presets(env_cfg), "agent": collect_presets(agent_cfg)} - env_cfg = resolve_preset_defaults(env_cfg) - agent_cfg = resolve_preset_defaults(agent_cfg) - hydra_cfg = {"env": env_cfg.to_dict(), "agent": agent_cfg.to_dict()} - sel = [("env", "robot.actuators.legs.armature", "newton")] - apply_overrides(env_cfg, agent_cfg, hydra_cfg, [], sel, [], presets) + env_cfg, _ = _apply(DictPresetEnvCfg(), preset_sel=[("env", "robot.actuators.legs.armature", "newton_mjwarp")]) assert env_cfg.robot.actuators["legs"].armature == 0.01 assert env_cfg.robot.actuators["legs"].stiffness == 40.0 @@ -680,7 +784,7 @@ class ActuatorCfgFactory: def __post_init__(self): if self.armature is None: - self.armature = preset(default=0.0, newton=0.01, physx=0.0) + self.armature = preset(default=0.0, newton_mjwarp=0.01, physx=0.0) @configclass class RobotCfgFactory: @@ -698,70 +802,42 @@ class EnvCfgFactory: presets = collect_presets(cfg) assert "robot.actuators.legs.armature" in presets assert presets["robot.actuators.legs.armature"]["default"] == 0.0 - assert presets["robot.actuators.legs.armature"]["newton"] == 0.01 + assert presets["robot.actuators.legs.armature"]["newton_mjwarp"] == 0.01 assert presets["robot.actuators.legs.armature"]["physx"] == 0.0 # ============================================================================= -# Tests: PresetCfg inside deeply nested dicts (e.g., event term params) +# Tests: rough terrain config regressions # ============================================================================= -@configclass -class OffsetCfg(PresetCfg): - """Mimics task-specific offset presets (e.g., AssembledOffsetCfg).""" +def test_go1_rough_newton_mjwarp_armature_preset(): + """Go1 rough terrain uses higher MJWarp armature without changing PhysX.""" + from isaaclab_tasks.manager_based.locomotion.velocity.config.go1.rough_env_cfg import UnitreeGo1RoughEnvCfg - task_a: tuple = (0.0, 0.0, 0.01) - task_b: tuple = (0.02, 0.0, 0.005) - default: tuple = task_a - - -@configclass -class FractionCfg(PresetCfg): - task_a: tuple = (0.05, 0.5) - task_b: tuple = (0.3, 1.0) - default: tuple = task_a - - -@configclass -class InnerTermCfg: - """Mimics an EventTermCfg with params containing presets.""" - - func: str = "reset_fn" - params: dict = None - - def __post_init__(self): - if self.params is None: - self.params = { - "offset": OffsetCfg(), - "fraction": FractionCfg(), - } + env_cfg, _ = _apply(UnitreeGo1RoughEnvCfg(), global_presets=["newton_mjwarp"]) + assert env_cfg.scene.robot.actuators["base_legs"].armature == 0.02 + env_cfg, _ = _apply(UnitreeGo1RoughEnvCfg()) + assert env_cfg.scene.robot.actuators["base_legs"].armature == 0.0 -@configclass -class OuterTermCfg: - """Mimics a chained reset term with nested terms dict.""" - func: str = "chain_fn" - params: dict = None +def test_go1_rough_legacy_newton_alias_resolves_to_newton_mjwarp(): + """Real-config alias path: ``presets=newton`` against an actual env cfg resolves to newton_mjwarp.""" + from isaaclab_tasks.manager_based.locomotion.velocity.config.go1.rough_env_cfg import UnitreeGo1RoughEnvCfg - def __post_init__(self): - if self.params is None: - self.params = { - "terms": { - "step_one": InnerTermCfg(), - } - } + with pytest.warns(FutureWarning, match="Preset 'newton' is deprecated"): + env_cfg, _ = _apply(UnitreeGo1RoughEnvCfg(), global_presets=["newton"]) + assert env_cfg.scene.robot.actuators["base_legs"].armature == 0.02 -@configclass -class DeepDictEnvCfg: - decimation: int = 4 - events: OuterTermCfg = OuterTermCfg() +# ============================================================================= +# Tests: PresetCfg inside deeply nested dicts (e.g., event term params) +# ============================================================================= def test_collect_presets_deep_nested_dicts(): - """collect_presets discovers PresetCfg inside dict→dict→configclass→dict chains.""" + """collect_presets discovers PresetCfg inside dict->dict->configclass->dict chains.""" cfg = DeepDictEnvCfg() presets = collect_presets(cfg) offset_path = "events.params.terms.step_one.params.offset" @@ -774,26 +850,22 @@ def test_collect_presets_deep_nested_dicts(): assert presets[fraction_path]["task_b"] == (0.3, 1.0) -def test_resolve_preset_defaults_deep_nested_dicts(): - """resolve_preset_defaults resolves presets inside deeply nested dicts.""" +def test_resolve_presets_deep_nested_dicts(): + """resolve_presets resolves presets inside deeply nested dicts.""" cfg = DeepDictEnvCfg() - resolved = resolve_preset_defaults(cfg) + resolved = resolve_presets(cfg) inner = resolved.events.params["terms"]["step_one"] assert inner.params["offset"] == (0.0, 0.0, 0.01) assert inner.params["fraction"] == (0.05, 0.5) assert not isinstance(inner.params["offset"], PresetCfg) assert not isinstance(inner.params["fraction"], PresetCfg) + assert inner.params["robot_cfg"].joint_names is None + assert not isinstance(inner.params["robot_cfg"].joint_names, PresetCfg) def test_deep_nested_dict_auto_default(): """Deeply nested dict presets auto-apply default when no CLI override.""" - env_cfg = DeepDictEnvCfg() - agent_cfg = PresetCfgAgentCfg() - presets = {"env": collect_presets(env_cfg), "agent": collect_presets(agent_cfg)} - env_cfg = resolve_preset_defaults(env_cfg) - agent_cfg = resolve_preset_defaults(agent_cfg) - hydra_cfg = {"env": env_cfg.to_dict(), "agent": agent_cfg.to_dict()} - apply_overrides(env_cfg, agent_cfg, hydra_cfg, [], [], [], presets) + env_cfg, _ = _apply(DeepDictEnvCfg()) inner = env_cfg.events.params["terms"]["step_one"] assert inner.params["offset"] == (0.0, 0.0, 0.01) assert inner.params["fraction"] == (0.05, 0.5) @@ -801,13 +873,7 @@ def test_deep_nested_dict_auto_default(): def test_deep_nested_dict_global_preset(): """Global preset=task_b replaces deeply nested dict presets.""" - env_cfg = DeepDictEnvCfg() - agent_cfg = PresetCfgAgentCfg() - presets = {"env": collect_presets(env_cfg), "agent": collect_presets(agent_cfg)} - env_cfg = resolve_preset_defaults(env_cfg) - agent_cfg = resolve_preset_defaults(agent_cfg) - hydra_cfg = {"env": env_cfg.to_dict(), "agent": agent_cfg.to_dict()} - apply_overrides(env_cfg, agent_cfg, hydra_cfg, ["task_b"], [], [], presets) + env_cfg, _ = _apply(DeepDictEnvCfg(), global_presets=["task_b"]) inner = env_cfg.events.params["terms"]["step_one"] assert inner.params["offset"] == (0.02, 0.0, 0.005), f"offset should be task_b value, got {inner.params['offset']}" assert inner.params["fraction"] == (0.3, 1.0), f"fraction should be task_b value, got {inner.params['fraction']}" @@ -815,32 +881,111 @@ def test_deep_nested_dict_global_preset(): def test_deep_nested_dict_path_selection(): """Path selection replaces a specific deeply nested dict preset.""" - env_cfg = DeepDictEnvCfg() - agent_cfg = PresetCfgAgentCfg() - presets = {"env": collect_presets(env_cfg), "agent": collect_presets(agent_cfg)} - env_cfg = resolve_preset_defaults(env_cfg) - agent_cfg = resolve_preset_defaults(agent_cfg) - hydra_cfg = {"env": env_cfg.to_dict(), "agent": agent_cfg.to_dict()} sel = [("env", "events.params.terms.step_one.params.offset", "task_b")] - apply_overrides(env_cfg, agent_cfg, hydra_cfg, [], sel, [], presets) + env_cfg, _ = _apply(DeepDictEnvCfg(), preset_sel=sel) inner = env_cfg.events.params["terms"]["step_one"] assert inner.params["offset"] == (0.02, 0.0, 0.005) - assert inner.params["fraction"] == (0.05, 0.5) # untouched + assert inner.params["fraction"] == (0.05, 0.5) def test_deep_nested_dict_mixed_global_and_path(): """Global preset applies to nested dicts, path selection overrides one.""" - env_cfg = DeepDictEnvCfg() - agent_cfg = PresetCfgAgentCfg() - presets = {"env": collect_presets(env_cfg), "agent": collect_presets(agent_cfg)} - env_cfg = resolve_preset_defaults(env_cfg) - agent_cfg = resolve_preset_defaults(agent_cfg) - hydra_cfg = {"env": env_cfg.to_dict(), "agent": agent_cfg.to_dict()} sel = [("env", "events.params.terms.step_one.params.fraction", "task_a")] - apply_overrides(env_cfg, agent_cfg, hydra_cfg, ["task_b"], sel, [], presets) + env_cfg, _ = _apply(DeepDictEnvCfg(), global_presets=["task_b"], preset_sel=sel) inner = env_cfg.events.params["terms"]["step_one"] - assert inner.params["offset"] == (0.02, 0.0, 0.005) # from global task_b - assert inner.params["fraction"] == (0.05, 0.5) # path override keeps task_a + assert inner.params["offset"] == (0.02, 0.0, 0.005) + assert inner.params["fraction"] == (0.05, 0.5) + + +# ============================================================================= +# Tests: preset resolving to dict containing further presets +# ============================================================================= + + +def test_collect_presets_discovers_presets_inside_dict_valued_alternatives(): + """collect_presets must recurse into dict-valued preset alternatives to + discover further PresetCfg nodes nested inside them. + """ + cfg = PresetResolvesToDictEnvCfg() + presets = collect_presets(cfg) + offset_paths = [p for p in presets if "offset" in p] + fraction_paths = [p for p in presets if "fraction" in p] + assert len(offset_paths) > 0, ( + f"OffsetCfg inside dict-valued preset alternative not discovered. Found: {list(presets.keys())}" + ) + assert len(fraction_paths) > 0, ( + f"FractionCfg inside dict-valued preset alternative not discovered. Found: {list(presets.keys())}" + ) + + +def test_resolve_preset_resolving_to_dict_walks_contents(): + """When a preset resolves to a dict, presets inside that dict are also resolved. + + Also verifies that PresetCfg(default=None) nested inside the resolved dict + correctly resolves to None (not skipped). + """ + cfg = PresetResolvesToDictEnvCfg() + resolved = resolve_presets(cfg) + + terms = resolved.events.params["terms"] + assert isinstance(terms, dict), f"Expected dict, got {type(terms)}" + assert not isinstance(terms, PresetCfg), "Top-level preset was not resolved" + + for name, term in terms.items(): + entity = term.params["robot_cfg"] + assert not isinstance(entity.joint_names, PresetCfg), ( + f"PresetCfg leaked into {name}.params.robot_cfg.joint_names" + ) + assert entity.joint_names is None + assert not isinstance(term.params["offset"], PresetCfg) + assert not isinstance(term.params["fraction"], PresetCfg) + + +def test_resolve_preset_uses_class_level_override(): + """When a robot-specific module overrides PresetCfg.default at class level + after instances are created, resolve_presets picks up the override.""" + + @configclass + class BodyNameCfg(PresetCfg): + default: str = "generic_body" + + @configclass + class TermWithBody: + func: str = "some_fn" + params: dict = None + + def __post_init__(self): + if self.params is None: + self.params = {"cfg": EntityCfg(name="robot", joint_names=BodyNameCfg())} + + @configclass + class EnvWithBody: + events: TermWithBody = TermWithBody() + + BodyNameCfg.default = "robot_specific_body" + + cfg = EnvWithBody() + resolved = resolve_presets(cfg) + assert resolved.events.params["cfg"].joint_names == "robot_specific_body" + assert not isinstance(resolved.events.params["cfg"].joint_names, PresetCfg) + + +def test_resolve_presets_with_selected_name_in_deeply_nested_dict(): + """resolve_presets(cfg, {"task_b"}) must select task_b alternatives + for PresetCfg instances nested inside dict-valued preset alternatives. + """ + cfg = PresetResolvesToDictEnvCfg() + resolved = resolve_presets(cfg, {"task_b"}) + + terms = resolved.events.params["terms"] + assert isinstance(terms, dict) + for name, term in terms.items(): + assert term.params["offset"] == (0.02, 0.0, 0.005), ( + f"{name}: offset should be task_b, got {term.params['offset']}" + ) + assert term.params["fraction"] == (0.3, 1.0), ( + f"{name}: fraction should be task_b, got {term.params['fraction']}" + ) # ============================================================================= @@ -986,7 +1131,7 @@ class ConflictEnvCfg: def test_apply_overrides_aliased_globals_no_conflict(): """Two global presets resolving to equal values do not raise. - Mirrors the dexsuite ObjectCfg pattern where ``newton = cube`` creates + Mirrors the dexsuite ObjectCfg pattern where ``newton_mjwarp = cube`` creates separate but equal dataclass instances after @configclass processing. """ @@ -995,13 +1140,13 @@ class SharedCfg: value: int = 42 cube_val = SharedCfg() - newton_val = SharedCfg() + mjwarp_val = SharedCfg() @configclass class AliasedPresetCfg(PresetCfg): default: str = "d" cube: SharedCfg = cube_val - newton: SharedCfg = newton_val + newton_mjwarp: SharedCfg = mjwarp_val @configclass class AliasedEnvCfg: @@ -1010,10 +1155,10 @@ class AliasedEnvCfg: env_cfg = AliasedEnvCfg() agent_cfg = PresetCfgAgentCfg() presets = {"env": collect_presets(env_cfg), "agent": collect_presets(agent_cfg)} - assert presets["env"]["mode"]["cube"] is not presets["env"]["mode"]["newton"] - assert presets["env"]["mode"]["cube"] == presets["env"]["mode"]["newton"] + assert presets["env"]["mode"]["cube"] is not presets["env"]["mode"]["newton_mjwarp"] + assert presets["env"]["mode"]["cube"] == presets["env"]["mode"]["newton_mjwarp"] hydra_cfg = {"env": env_cfg.to_dict(), "agent": agent_cfg.to_dict()} - apply_overrides(env_cfg, agent_cfg, hydra_cfg, ["cube", "newton"], [], [], presets) + apply_overrides(env_cfg, agent_cfg, hydra_cfg, ["cube", "newton_mjwarp"], [], [], presets) assert env_cfg.mode == SharedCfg() @@ -1024,9 +1169,57 @@ class AliasedEnvCfg: def test_parse_overrides_multiple_global_presets(): """Multiple comma-separated global presets are split correctly.""" - presets = {"env": {"backend": {"default": None, "newton": None}}, "agent": {}} - global_p, _, _, _ = parse_overrides(["presets=fast,newton,debug"], presets) - assert global_p == ["fast", "newton", "debug"] + presets = {"env": {"backend": {"default": None, "newton_mjwarp": None}}, "agent": {}} + global_p, _, _, _ = parse_overrides(["presets=fast,newton_mjwarp,debug"], presets) + assert global_p == ["fast", "newton_mjwarp", "debug"] + + +def test_parse_overrides_maps_legacy_newton_preset_to_newton_mjwarp(): + """Legacy ``newton`` preset selections resolve to ``newton_mjwarp`` when available.""" + presets = {"env": {"backend": {"default": None, "newton_mjwarp": None}}, "agent": {}} + legacy_name = "newton" + + global_p, sel, _, _ = parse_overrides(["presets=fast," + legacy_name, f"env.backend={legacy_name}"], presets) + + assert global_p == ["fast", "newton_mjwarp"] + assert sel == [("env", "backend", "newton_mjwarp")] + + +def test_parse_overrides_maps_legacy_kamino_preset_to_newton_kamino(): + """Legacy ``kamino`` preset selections resolve to ``newton_kamino`` when available.""" + presets = {"env": {"solver": {"default": None, "newton_kamino": None}}, "agent": {}} + legacy_name = "kamino" + + global_p, sel, _, _ = parse_overrides(["presets=" + legacy_name, f"env.solver={legacy_name}"], presets) + + assert global_p == ["newton_kamino"] + assert sel == [("env", "solver", "newton_kamino")] + + +def test_apply_overrides_resolves_legacy_alias_in_global_and_path_selection(class_presets): + """``apply_overrides`` resolves legacy names supplied directly (bypassing ``parse_overrides``).""" + env_cfg, agent_cfg, presets = class_presets + hydra_cfg = {"env": env_cfg.to_dict(), "agent": agent_cfg.to_dict()} + with pytest.warns(FutureWarning, match="Preset 'newton' is deprecated"): + apply_overrides( + env_cfg, + agent_cfg, + hydra_cfg, + global_presets=["newton"], + preset_sel=[("env", "backend", "newton")], + preset_scalar=[], + presets=presets, + ) + assert isinstance(env_cfg.backend, NewtonCfg) + + +def test_apply_overrides_legacy_and_current_alias_do_not_conflict(class_presets): + """``presets=newton,newton_mjwarp`` (legacy + current) resolves to one preset, not a conflict.""" + env_cfg, agent_cfg, presets = class_presets + hydra_cfg = {"env": env_cfg.to_dict(), "agent": agent_cfg.to_dict()} + with pytest.warns(FutureWarning, match="Preset 'newton' is deprecated"): + apply_overrides(env_cfg, agent_cfg, hydra_cfg, ["newton", "newton_mjwarp"], [], [], presets) + assert isinstance(env_cfg.backend, NewtonCfg) def test_parse_overrides_no_equals_treated_as_global_scalar(): @@ -1083,33 +1276,124 @@ def test_parse_val_types(): def test_scalar_override_within_preset_path(class_presets): """Scalar overrides within preset paths are applied on top of the preset.""" env_cfg, agent_cfg, presets = class_presets - env_cfg = resolve_preset_defaults(env_cfg) - agent_cfg = resolve_preset_defaults(agent_cfg) + env_cfg = resolve_presets(env_cfg) + agent_cfg = resolve_presets(agent_cfg) hydra_cfg = {"env": env_cfg.to_dict(), "agent": agent_cfg.to_dict()} apply_overrides( env_cfg, agent_cfg, hydra_cfg, [], - [("env", "backend", "newton")], + [("env", "backend", "newton_mjwarp")], [("env.backend.dt", "0.001")], presets, ) assert isinstance(env_cfg.backend, NewtonCfg) - assert env_cfg.backend.dt == 0.001 # overridden from 0.002 - assert env_cfg.backend.substeps == 4 # untouched + assert env_cfg.backend.dt == 0.001 + assert env_cfg.backend.substeps == 4 # ============================================================================= -# Tests: resolve_preset_defaults idempotency +# Tests: resolve_presets idempotency # ============================================================================= -def test_resolve_preset_defaults_idempotent(): - """Calling resolve_preset_defaults twice yields the same result.""" +def test_resolve_presets_idempotent(): + """Calling resolve_presets twice yields the same result.""" cfg = PresetCfgEnvCfg() - first = resolve_preset_defaults(cfg) - second = resolve_preset_defaults(first) + first = resolve_presets(cfg) + second = resolve_presets(first) assert isinstance(second.backend, PhysxCfg) assert isinstance(second.observations, NoiselessObservationsCfg) assert second.backend.dt == first.backend.dt + + +def test_unknown_global_preset_name_detected(): + """A selected preset name that doesn't match any PresetCfg field is detected. + + This catches typos like presets=peg_insrt_4mm (missing 'e'). The validation + in register_task raises ValueError before resolution begins. + """ + cfg = PresetCfgEnvCfg() + presets = {"env": collect_presets(cfg), "agent": {}} + all_known = {name for alts in presets.values() for fields in alts.values() for name in fields if name != "default"} + + assert "newton_mjwarp" in all_known + assert "typo_preset" not in all_known + + +def test_resolve_presets_errors_on_no_default(): + """A PresetCfg with no 'default' field and no matching selected name + must raise ValueError, not silently linger or infinite loop.""" + + @configclass + class NoDefaultPreset(PresetCfg): + option_a: int = 1 + + @configclass + class EnvCfg: + mode: NoDefaultPreset = NoDefaultPreset() + + with pytest.raises(ValueError, match="no 'default' field"): + resolve_presets(EnvCfg()) + + +def test_resolve_presets_errors_on_chained_no_default(): + """A PresetCfg whose default is another PresetCfg with no 'default' + must raise ValueError on the inner preset.""" + + @configclass + class InnerNoDefault(PresetCfg): + option_a: int = 1 + + @configclass + class OuterPreset(PresetCfg): + default: InnerNoDefault = InnerNoDefault() + + @configclass + class EnvCfg: + mode: OuterPreset = OuterPreset() + + with pytest.raises(ValueError, match="no 'default' field"): + resolve_presets(EnvCfg()) + + +def test_resolve_presets_errors_on_cyclic_preset(): + """Cyclic PresetCfg chain (A.default -> B, B.default -> A) must raise + ValueError instead of looping forever.""" + + @configclass + class CyclicB(PresetCfg): + pass + + @configclass + class CyclicA(PresetCfg): + default: CyclicB = CyclicB() + + CyclicA.default = CyclicB() + CyclicB.default = CyclicA() + + @configclass + class EnvCfg: + mode: CyclicA = CyclicA() + + with pytest.raises(ValueError, match="[Cc]ycl"): + resolve_presets(EnvCfg()) + + +def test_resolve_presets_errors_on_cyclic_preset_at_root(): + """Cyclic PresetCfg at root level must raise ValueError, not RecursionError.""" + + @configclass + class RootCyclicB(PresetCfg): + pass + + @configclass + class RootCyclicA(PresetCfg): + default: RootCyclicB = RootCyclicB() + + RootCyclicA.default = RootCyclicB() + RootCyclicB.default = RootCyclicA() + + with pytest.raises(ValueError, match="[Cc]ycl"): + resolve_presets(RootCyclicA()) diff --git a/source/isaaclab_tasks/test/test_newton_solver_preset_names.py b/source/isaaclab_tasks/test/test_newton_solver_preset_names.py new file mode 100644 index 000000000000..a1324273f67d --- /dev/null +++ b/source/isaaclab_tasks/test/test_newton_solver_preset_names.py @@ -0,0 +1,138 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Regression checks for the public Newton-backend solver preset names. + +These tests prevent reintroduction of the legacy preset names ``newton`` and +``kamino``, which were renamed to ``newton_mjwarp`` and ``newton_kamino`` to +disambiguate from the Newton backend label, package, and visualizer (which all +retain the bare ``newton`` spelling). +""" + +from __future__ import annotations + +import re +from pathlib import Path + +_REPO_ROOT = Path(__file__).resolve().parents[3] + +_TEXT_ROOTS = ( + _REPO_ROOT / "docs" / "source", + _REPO_ROOT / "scripts", + _REPO_ROOT / "source" / "isaaclab_tasks", + _REPO_ROOT / "source" / "isaaclab", + _REPO_ROOT / "source" / "isaaclab_visualizers", +) +_TEXT_SUFFIXES = {".py", ".rst", ".md"} + +# Files that intentionally reference the deprecated names (deprecation tests, +# the alias map, and this scanner's own pattern strings). +_SCAN_EXCLUDE_FILES = frozenset( + { + "test_hydra.py", + "test_newton_solver_preset_names.py", + "hydra.py", + } +) + +# Legacy preset names that must not appear as public preset references in +# user-facing surfaces. Word-boundary anchors (``\b``) keep ``newton_mjwarp``, +# ``newton_renderer``, ``newton_kamino`` and similar prefixed names from +# matching, since ``_`` is a Python word character. +_LEGACY_TOKEN = r"(?:newton|kamino)" +_LEGACY_PRESET_PATTERNS = ( + # CLI: ``presets=...,newton`` or ``presets=newton,...`` + re.compile(rf"presets=[^\s`]*\b{_LEGACY_TOKEN}\b"), + # CLI: ``env.=newton`` or ``env.=kamino`` + re.compile(rf"\benv\.[\w.]*={_LEGACY_TOKEN}\b"), + # Dict-literal preset entry, e.g. ``"newton": NewtonCfg(...)`` + re.compile(rf"""[\"']{_LEGACY_TOKEN}[\"']\s*:\s*\w*Cfg\b"""), + # ``PresetCfg`` field declaration, e.g. `` newton: NewtonCfg = ...`` + re.compile(rf"^\s+{_LEGACY_TOKEN}\s*:\s*[A-Za-z_][\w.]*Cfg\b", re.MULTILINE), + # ``PresetCfg`` field assignment, e.g. `` kamino = NewtonCfg(...)`` + re.compile(rf"^\s+{_LEGACY_TOKEN}\s*=\s*[A-Za-z_][\w.]*Cfg\(", re.MULTILINE), +) + +# RST inline literals are caught only for files known to enumerate per-task +# preset choices, where bare ``newton``/``kamino`` literals must refer to the +# (renamed) physics preset rather than the Newton backend, package, or +# visualizer that share the spelling. +_PRESET_TABLE_FILES = ("docs/source/overview/environments.rst",) +_LEGACY_RST_LITERAL_PATTERN = re.compile(rf"``{_LEGACY_TOKEN}``") + +# Field declaration scoped to physics-related Cfg classes only (used by the +# task-level scanner to keep its message focused on env config files). +_LEGACY_PHYSICS_FIELD_PATTERN = re.compile( + rf"^\s+{_LEGACY_TOKEN}\s*(?::\s*(?:NewtonCfg|SimulationCfg)\b|=\s*(?:NewtonCfg|SimulationCfg)\()", + re.MULTILINE, +) + + +def _iter_text_files() -> list[Path]: + files: list[Path] = [] + for root in _TEXT_ROOTS: + files.extend(path for path in root.rglob("*") if path.suffix in _TEXT_SUFFIXES) + return sorted(files) + + +def test_public_examples_use_renamed_preset_names() -> None: + """Public examples should use ``newton_mjwarp``/``newton_kamino``, not the legacy names.""" + files = _iter_text_files() + assert files, f"no text files scanned -- _TEXT_ROOTS likely stale: {_TEXT_ROOTS!r}" + + offenders: list[str] = [] + for path in files: + if "CHANGELOG" in path.name or "changelog.d" in path.parts: + continue + if path.name in _SCAN_EXCLUDE_FILES: + continue + text = path.read_text(encoding="utf-8") + for pattern in _LEGACY_PRESET_PATTERNS: + for match in pattern.finditer(text): + line = text.count("\n", 0, match.start()) + 1 + offenders.append(f"{path.relative_to(_REPO_ROOT)}:{line}: {match.group(0)}") + if path.relative_to(_REPO_ROOT).as_posix() in _PRESET_TABLE_FILES: + for match in _LEGACY_RST_LITERAL_PATTERN.finditer(text): + line = text.count("\n", 0, match.start()) + 1 + offenders.append(f"{path.relative_to(_REPO_ROOT)}:{line}: {match.group(0)}") + + assert not offenders, "Legacy Newton-backend solver preset references found:\n" + "\n".join(offenders) + + +def test_rendering_test_utils_maps_newton_label_to_newton_mjwarp() -> None: + """Golden-image fixtures keep the ``"newton"`` backend label; the helper must + map it to the ``"newton_mjwarp"`` preset so Hydra resolves the right config. + """ + import sys + + import pytest + + pytest.importorskip("torch") # rendering_test_utils imports torch eagerly + + sys.path.insert(0, str(Path(__file__).resolve().parent)) + try: + from rendering_test_utils import _physics_preset_name + finally: + sys.path.pop(0) + + assert _physics_preset_name("newton") == "newton_mjwarp" + assert _physics_preset_name("physx") == "physx" + assert _physics_preset_name("ovphysx") == "ovphysx" + + +def test_task_physics_presets_use_renamed_field_names() -> None: + """Task ``PresetCfg`` field names should use ``newton_mjwarp`` / ``newton_kamino``.""" + tasks_root = _REPO_ROOT / "source" / "isaaclab_tasks" / "isaaclab_tasks" + files = sorted(tasks_root.rglob("*.py")) + assert files, f"no task config files scanned at {tasks_root}" + + offenders: list[str] = [] + for path in files: + text = path.read_text(encoding="utf-8") + for match in _LEGACY_PHYSICS_FIELD_PATTERN.finditer(text): + line = text.count("\n", 0, match.start()) + 1 + offenders.append(f"{path.relative_to(_REPO_ROOT)}:{line}: {match.group(0).strip()}") + + assert not offenders, "Legacy Newton-backend solver field declarations found:\n" + "\n".join(offenders) diff --git a/source/isaaclab_tasks/test/test_preset_kit_decision.py b/source/isaaclab_tasks/test/test_preset_kit_decision.py index 8840ab024d90..62c51caaa73d 100644 --- a/source/isaaclab_tasks/test/test_preset_kit_decision.py +++ b/source/isaaclab_tasks/test/test_preset_kit_decision.py @@ -5,7 +5,7 @@ """Tests for preset resolution and Kit decision logic. -These tests verify that given presets (e.g. ``presets=newton,ovrtx_renderer``), +These tests verify that given presets (e.g. ``presets=newton_mjwarp,ovrtx_renderer``), the config-based logic correctly decides whether Isaac Sim Kit is needed. No Kit/GPU required — safe for CI and beginners. """ @@ -29,16 +29,16 @@ def _resolve_with_presets(presets: str): sys.argv = old_argv -def test_preset_newton_ovrtx_does_not_need_kit(): +def test_preset_mjwarp_ovrtx_does_not_need_kit(): """Newton + OVRTX renderer is kitless — no AppLauncher required.""" - env_cfg = _resolve_with_presets("newton,ovrtx_renderer") + env_cfg = _resolve_with_presets("newton_mjwarp,ovrtx_renderer") needs_kit, _, _ = compute_kit_requirements(env_cfg) assert needs_kit is False -def test_preset_newton_newton_renderer_does_not_need_kit(): +def test_preset_mjwarp_newton_renderer_does_not_need_kit(): """Newton + Newton Warp renderer is kitless.""" - env_cfg = _resolve_with_presets("newton,newton_renderer") + env_cfg = _resolve_with_presets("newton_mjwarp,newton_renderer") needs_kit, _, _ = compute_kit_requirements(env_cfg) assert needs_kit is False @@ -57,8 +57,8 @@ def test_preset_default_needs_kit(): assert needs_kit is True -def test_preset_newton_isaac_rtx_needs_kit(): +def test_preset_mjwarp_isaac_rtx_needs_kit(): """Newton + Isaac RTX renderer requires Kit (RTX runs in Kit).""" - env_cfg = _resolve_with_presets("newton,isaacsim_rtx_renderer") + env_cfg = _resolve_with_presets("newton_mjwarp,isaacsim_rtx_renderer") needs_kit, _, _ = compute_kit_requirements(env_cfg) assert needs_kit is True diff --git a/source/isaaclab_tasks/test/test_record_video.py b/source/isaaclab_tasks/test/test_record_video.py index ee98a587f4ac..bb1d756fcfb7 100644 --- a/source/isaaclab_tasks/test/test_record_video.py +++ b/source/isaaclab_tasks/test/test_record_video.py @@ -28,6 +28,9 @@ from env_test_utils import setup_environment # isort: skip +pytestmark = pytest.mark.isaacsim_ci + + @pytest.fixture(scope="function") def setup_video_params(): # common parameters diff --git a/source/isaaclab_tasks/test/test_rendering_cartpole.py b/source/isaaclab_tasks/test/test_rendering_cartpole.py new file mode 100644 index 000000000000..6f10a80a1d4b --- /dev/null +++ b/source/isaaclab_tasks/test/test_rendering_cartpole.py @@ -0,0 +1,37 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Rendering correctness tests for Cartpole environment backend combinations.""" + +# Launch Isaac Sim Simulator first for kit-based combinations. +from isaaclab.app import AppLauncher + +app_launcher = AppLauncher(headless=True, enable_cameras=True) +simulation_app = app_launcher.app + +from pathlib import Path # noqa: E402 + +import pytest # noqa: E402 +from rendering_test_utils import ( # noqa: E402 + PHYSICS_RENDERER_AOV_COMBINATIONS, + make_attach_comparison_properties_fixture, + make_determinism_fixture, + make_generate_html_report_fixture, + rendering_test_cartpole, +) + +pytestmark = pytest.mark.isaacsim_ci + +_COMPARISON_SCORES: list[dict] = [] + +_determinism_fixture = make_determinism_fixture() +_generate_html_report_fixture = make_generate_html_report_fixture(_COMPARISON_SCORES, Path(__file__).stem + ".html") +_attach_comparison_properties_fixture = make_attach_comparison_properties_fixture(_COMPARISON_SCORES) + + +@pytest.mark.parametrize("physics_backend,renderer,data_type", PHYSICS_RENDERER_AOV_COMBINATIONS) +def test_rendering_cartpole(physics_backend, renderer, data_type): + """Test cartpole environment rendering correctness.""" + rendering_test_cartpole(physics_backend, renderer, data_type, _COMPARISON_SCORES) diff --git a/source/isaaclab_tasks/test/test_rendering_cartpole_kitless.py b/source/isaaclab_tasks/test/test_rendering_cartpole_kitless.py new file mode 100644 index 000000000000..802ecfd32cfc --- /dev/null +++ b/source/isaaclab_tasks/test/test_rendering_cartpole_kitless.py @@ -0,0 +1,33 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Kit-less rendering correctness tests for Cartpole environment backend combinations.""" + +from pathlib import Path + +import pytest +from rendering_test_utils import ( + KITLESS_PHYSICS_RENDERER_AOV_COMBINATIONS, + make_attach_comparison_properties_fixture, + make_determinism_fixture, + make_generate_html_report_fixture, + make_require_ovrtx_install_fixture, + rendering_test_cartpole, +) + +pytestmark = pytest.mark.isaacsim_ci + +_COMPARISON_SCORES: list[dict] = [] + +_determinism_fixture = make_determinism_fixture() +_generate_html_report_fixture = make_generate_html_report_fixture(_COMPARISON_SCORES, Path(__file__).stem + ".html") +_attach_comparison_properties_fixture = make_attach_comparison_properties_fixture(_COMPARISON_SCORES) +_require_ovrtx_install_fixture = make_require_ovrtx_install_fixture() + + +@pytest.mark.parametrize("physics_backend,renderer,data_type", KITLESS_PHYSICS_RENDERER_AOV_COMBINATIONS) +def test_rendering_cartpole_kitless(physics_backend, renderer, data_type): + """Camera output must match golden images (Cartpole camera presets env).""" + rendering_test_cartpole(physics_backend, renderer, data_type, _COMPARISON_SCORES) diff --git a/source/isaaclab_tasks/test/test_rendering_correctness.py b/source/isaaclab_tasks/test/test_rendering_correctness.py deleted file mode 100644 index 02c82fc16dcc..000000000000 --- a/source/isaaclab_tasks/test/test_rendering_correctness.py +++ /dev/null @@ -1,813 +0,0 @@ -# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). -# All rights reserved. -# -# SPDX-License-Identifier: BSD-3-Clause - -"""Tests for rendering correctness. - -Each test builds an environment with a given (physics_backend, renderer, data_type), -steps once, then checks if camera outputs are not blank (at least one non-zero -pixel) and consistent with golden images. Env-specific fixtures use parametrized -combinations; a separate test covers a list of registered task IDs that use -camera-based observations. -""" - -# Launch Isaac Sim Simulator first. -from isaaclab.app import AppLauncher - -app_launcher = AppLauncher(headless=True, enable_cameras=True) -simulation_app = app_launcher.app - -import os # noqa: E402 -from datetime import datetime # noqa: E402 -from typing import Any # noqa: E402 - -import gymnasium as gym # noqa: E402 -import numpy as np # noqa: E402 -import pytest # noqa: E402 -import torch # noqa: E402 -from PIL import Image, ImageChops # noqa: E402 - -from isaaclab.sim import SimulationContext # noqa: E402 - -from isaaclab_tasks.utils.hydra import ( # noqa: E402 - apply_overrides, - collect_presets, - parse_overrides, -) -from isaaclab_tasks.utils.parse_cfg import parse_env_cfg # noqa: E402 - -# --------------------------------------------------------------------------- -# Constants -# --------------------------------------------------------------------------- - -# Directory containing golden images. -_GOLDEN_IMAGES_DIRECTORY = os.path.join(os.path.dirname(os.path.abspath(__file__)), "golden_images") - -# Pixel L2 norm difference threshold. L2 norm difference is the Euclidean distance between two pixels: -# -# d = sqrt((R1 - R2)^2 + (G1 - G2)^2 + (B1 - B2)^2) -# -# If the difference between two pixels is less than this threshold, consider them "equal" (i.e. within the tolerance). -# -_PIXEL_L2_NORM_DIFFERENCE_THRESHOLD = 10.0 - -_OVRTX_DISABLED = pytest.mark.skip( - reason="OVRTX is optional and experimental feature and temporarily is excluded from testing." -) - -# Directory for comparison images saved during the test session. -# Located under the pytest output root so it gets copied alongside test reports. -_COMPARISON_IMAGES_DIR = os.path.join(os.getcwd(), "tests", "comparison-images") - -# Collects comparison scores from all golden-image comparisons during the session. -# Each entry: {"test": str, "backend": str, "renderer": str, "aov": str, -# "ssim": float, "diff_pct": float, "passed": bool, -# "img_result_path": str | None, "img_golden_path": str | None} -_COMPARISON_SCORES: list[dict] = [] - - -# --------------------------------------------------------------------------- -# Fixtures -# --------------------------------------------------------------------------- - - -@pytest.fixture(autouse=True) -def cleanup_simulation_context(): - """Fixture to clear SimulationContext after each test. - - SimulationContext is a singleton; tests that create envs leave it set. Without - cleanup, later tests can see stale context or fail when the instance is - reused. The fixture runs after every test and calls clear_instance() so each - test runs with a clean simulation context and tests stay isolated. - """ - yield - - SimulationContext.clear_instance() - - -@pytest.fixture(scope="session", autouse=True) -def _generate_comparison_html_report(): - """Generate an HTML comparison report after all tests in the session complete.""" - yield - try: - _generate_html_report() - except Exception as exc: # noqa: BLE001 - import warnings - - warnings.warn(f"Failed to generate HTML comparison report: {exc}", stacklevel=1) - - -@pytest.fixture(autouse=True) -def _attach_comparison_properties(request): - """Attach pixel-diff, SSIM scores, and failure images as JUnit XML properties.""" - initial_count = len(_COMPARISON_SCORES) - yield - for entry in _COMPARISON_SCORES[initial_count:]: - label = f"{entry['backend']}-{entry['renderer']}-{entry['aov']}" - request.node.user_properties.append((f"diff_pct:{label}", f"{entry['diff_pct']:.2f}")) - request.node.user_properties.append((f"ssim:{label}", f"{entry['ssim']:.4f}")) - request.node.user_properties.append((f"threshold:{label}", f"{entry['threshold']:.1f}")) - if entry.get("img_result_path"): - request.node.user_properties.append((f"img_result:{label}", entry["img_result_path"])) - request.node.user_properties.append((f"img_golden:{label}", entry["img_golden_path"])) - - -# --------------------------------------------------------------------------- -# Parametrization: (physics_backend, renderer, data_type) -# --------------------------------------------------------------------------- - -_PHYSICS_RENDERER_AOV_COMBINATIONS = [ - # physx + isaacsim_rtx_renderer - pytest.param( - ("physx", "isaacsim_rtx_renderer", "rgb"), - id="physx-isaacsim_rtx-rgb", - ), - pytest.param( - ("physx", "isaacsim_rtx_renderer", "albedo"), - id="physx-isaacsim_rtx-albedo", - ), - pytest.param( - ("physx", "isaacsim_rtx_renderer", "depth"), - id="physx-isaacsim_rtx-depth", - ), - pytest.param( - ("physx", "isaacsim_rtx_renderer", "simple_shading_constant_diffuse"), - id="physx-isaacsim_rtx-simple_shading_constant_diffuse", - ), - pytest.param( - ("physx", "isaacsim_rtx_renderer", "simple_shading_diffuse_mdl"), - id="physx-isaacsim_rtx-simple_shading_diffuse_mdl", - ), - pytest.param( - ("physx", "isaacsim_rtx_renderer", "simple_shading_full_mdl"), - id="physx-isaacsim_rtx-simple_shading_full_mdl", - ), - pytest.param( - ("physx", "isaacsim_rtx_renderer", "semantic_segmentation"), - id="physx-isaacsim_rtx-semantic_segmentation", - ), - # physx + newton_renderer (warp) - pytest.param( - ("physx", "newton_renderer", "rgb"), - id="physx-newton_warp-rgb", - ), - pytest.param( - ("physx", "newton_renderer", "depth"), - id="physx-newton_warp-depth", - ), - # newton + isaacsim_rtx_renderer - pytest.param( - ("newton", "isaacsim_rtx_renderer", "rgb"), - id="newton-isaacsim_rtx-rgb", - ), - pytest.param( - ("newton", "isaacsim_rtx_renderer", "albedo"), - id="newton-isaacsim_rtx-albedo", - ), - pytest.param( - ("newton", "isaacsim_rtx_renderer", "depth"), - id="newton-isaacsim_rtx-depth", - ), - pytest.param( - ("newton", "isaacsim_rtx_renderer", "simple_shading_constant_diffuse"), - id="newton-isaacsim_rtx-simple_shading_constant_diffuse", - ), - pytest.param( - ("newton", "isaacsim_rtx_renderer", "simple_shading_diffuse_mdl"), - id="newton-isaacsim_rtx-simple_shading_diffuse_mdl", - ), - pytest.param( - ("newton", "isaacsim_rtx_renderer", "simple_shading_full_mdl"), - id="newton-isaacsim_rtx-simple_shading_full_mdl", - ), - pytest.param( - ("newton", "isaacsim_rtx_renderer", "semantic_segmentation"), - id="newton-isaacsim_rtx-semantic_segmentation", - ), - # newton + newton_renderer (warp) - pytest.param( - ("newton", "newton_renderer", "rgb"), - id="newton-newton_warp-rgb", - ), - pytest.param( - ("newton", "newton_renderer", "depth"), - id="newton-newton_warp-depth", - ), - # newton + ovrtx_renderer - pytest.param( - ("newton", "ovrtx_renderer", "rgb"), - id="newton-ovrtx-rgb", - marks=_OVRTX_DISABLED, - ), - pytest.param( - ("newton", "ovrtx_renderer", "albedo"), - id="newton-ovrtx-albedo", - marks=_OVRTX_DISABLED, - ), - pytest.param( - ("newton", "ovrtx_renderer", "depth"), - id="newton-ovrtx-depth", - marks=_OVRTX_DISABLED, - ), - pytest.param( - ("newton", "ovrtx_renderer", "simple_shading_constant_diffuse"), - id="newton-ovrtx-simple_shading_constant_diffuse", - marks=_OVRTX_DISABLED, - ), - pytest.param( - ("newton", "ovrtx_renderer", "simple_shading_diffuse_mdl"), - id="newton-ovrtx-simple_shading_diffuse_mdl", - marks=_OVRTX_DISABLED, - ), - pytest.param( - ("newton", "ovrtx_renderer", "simple_shading_full_mdl"), - id="newton-ovrtx-simple_shading_full_mdl", - marks=_OVRTX_DISABLED, - ), - pytest.param( - ("newton", "ovrtx_renderer", "semantic_segmentation"), - id="newton-ovrtx-semantic_segmentation", - marks=_OVRTX_DISABLED, - ), -] - - -# --------------------------------------------------------------------------- -# Helpers -# --------------------------------------------------------------------------- - - -def _apply_overrides_to_env_cfg(env_cfg: Any, override_args: list[str]) -> Any: - """Apply override args to env_cfg using parse_overrides and apply_overrides. - - Args: - env_cfg: Environment config to mutate (supports :meth:`to_dict`). - override_args: List of override strings (e.g. ``["presets=physx,isaacsim_rtx_renderer,rgb"]``). - - Returns: - The resolved env_cfg (possibly a different object if root preset was applied). - """ - presets = {"env": collect_presets(env_cfg)} - global_presets, preset_sel, preset_scalar, _ = parse_overrides(override_args, presets) - hydra_cfg = {"env": env_cfg.to_dict()} - env_cfg, _ = apply_overrides(env_cfg, None, hydra_cfg, global_presets, preset_sel, preset_scalar, presets) - return env_cfg - - -def _normalize_tensor(tensor: torch.Tensor, data_type: str) -> torch.Tensor: - """Convert camera output tensor to [0, 1] float32 for conversion to image. - - Args: - tensor: Camera output tensor. - data_type: Data type of the camera output. - - Returns: - Normalized tensor. - """ - normalized = tensor.float() - - if data_type in ["depth", "distance_to_camera", "distance_to_image_plane"]: - max_val = normalized.max() - if max_val > 0: - normalized = normalized / max_val - elif data_type in {"albedo"}: - normalized = normalized[..., :3] / 255.0 - else: - normalized = normalized / 255.0 - - return normalized - - -def _save_comparison_image(img: Image.Image, filename: str) -> str: - """Save a PIL image to the comparison-images/images directory. - - Args: - img: PIL Image to save. - filename: File name (e.g. ``"test-backend-renderer-aov-result.png"``). - - Returns: - Absolute path to the saved file. - """ - path = os.path.join(_COMPARISON_IMAGES_DIR, "images", filename) - os.makedirs(os.path.dirname(path), exist_ok=True) - img.save(path, format="PNG") - return path - - -def _generate_html_report() -> None: - """Generate an HTML report of all comparison scores and save it alongside the comparison images. - - The report is written to ``<_COMPARISON_IMAGES_DIR>/_report_.html`` and includes a table of - all image comparison results sorted by PixelDiff % descending, with thumbnail links to actual - and golden images where available. - """ - if not _COMPARISON_SCORES: - return - - os.makedirs(_COMPARISON_IMAGES_DIR, exist_ok=True) - report_path = os.path.join(_COMPARISON_IMAGES_DIR, "_report_.html") - - sorted_scores = sorted(_COMPARISON_SCORES, key=lambda e: -e["diff_pct"]) - - rows = [] - for entry in sorted_scores: - status_class = "pass" if entry["passed"] else "fail" - status_text = status_class.upper() - - actual_img_html = "" - golden_img_html = "" - if entry.get("img_result_path"): - actual_fname = os.path.relpath(entry["img_result_path"], _COMPARISON_IMAGES_DIR) - golden_fname = os.path.relpath(entry["img_golden_path"], _COMPARISON_IMAGES_DIR) - actual_img_html = f'' - golden_img_html = f'' - - rows.append( - f'' - f"{entry['test']}" - f"{entry['backend']}" - f"{entry['renderer']}" - f"{entry['aov']}" - f"{entry['diff_pct']:.2f}" - f"{entry['threshold']:.1f}" - f"{entry['ssim']:.4f}" - f'{status_text}' - f"{actual_img_html}" - f"{golden_img_html}" - "" - ) - - html = ( - "\n" - "\n" - "\n" - '\n' - "Rendering Correctness — Image Comparison Report\n" - "\n" - "\n" - "\n" - "

Rendering Correctness — Image Comparison Report

\n" - f"

Sorted by PixelDiff % (desc) — {len(sorted_scores)}  total.

\n" - "\n" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "\n" - "\n" + "\n".join(rows) + "\n\n
TestBackendRendererAOVPixelDiff %Threshold %SSIMStatusACTUALGOLDEN
\n\n\n" - f"

Generated: {datetime.now().astimezone().isoformat(timespec='seconds')}.

\n" - ) - - with open(report_path, "w", encoding="utf-8") as f: - f.write(html) - - -def _make_grid(images: torch.Tensor) -> torch.Tensor: - """Make a grid of images from a tensor of shape (B, H, W, C). - - Args: - images: A tensor of shape (B, H, W, C) containing the images. - - Returns: - A tensor of shape (H, W, C) containing the grid of images. - """ - from torchvision.utils import make_grid - - return make_grid(torch.swapaxes(images.unsqueeze(1), 1, -1).squeeze(-1), nrow=round(images.shape[0] ** 0.5)) - - -def _ssim(img1: torch.Tensor, img2: torch.Tensor, window_size: int = 11) -> float: - """Compute mean SSIM between two (1, C, H, W) float tensors in [0, 1]. - - https://en.wikipedia.org/wiki/Structural_similarity_index_measure - - Uses a uniform averaging window and the standard SSIM constants (K1=0.01, K2=0.03, - data_range=1.0). - - Args: - img1: First image tensor of shape (1, C, H, W) in [0, 1]. - img2: Second image tensor of shape (1, C, H, W) in [0, 1]. - window_size: Side length of the square averaging window. - - Returns: - Mean SSIM score (1.0 = identical). - """ - c1 = 0.01**2 - c2 = 0.03**2 - channels = img1.shape[1] - pad = window_size // 2 - - kernel = torch.ones(channels, 1, window_size, window_size, device=img1.device, dtype=img1.dtype) / ( - window_size * window_size - ) - - mu1 = torch.nn.functional.conv2d(img1, kernel, padding=pad, groups=channels) - mu2 = torch.nn.functional.conv2d(img2, kernel, padding=pad, groups=channels) - - mu1_sq = mu1 * mu1 - mu2_sq = mu2 * mu2 - mu1_mu2 = mu1 * mu2 - - sigma1_sq = torch.nn.functional.conv2d(img1 * img1, kernel, padding=pad, groups=channels) - mu1_sq - sigma2_sq = torch.nn.functional.conv2d(img2 * img2, kernel, padding=pad, groups=channels) - mu2_sq - sigma12 = torch.nn.functional.conv2d(img1 * img2, kernel, padding=pad, groups=channels) - mu1_mu2 - - ssim_map = ((2 * mu1_mu2 + c1) * (2 * sigma12 + c2)) / ((mu1_sq + mu2_sq + c1) * (sigma1_sq + sigma2_sq + c2)) - return ssim_map.mean().item() - - -def _pixel_diff_percentage( - result_image: Image.Image, - golden_image: Image.Image, - pixel_diff_threshold: float = _PIXEL_L2_NORM_DIFFERENCE_THRESHOLD, -) -> float: - """Compute the percentage of pixels whose L2 norm difference exceeds a threshold. - - Args: - result_image: Result image as PIL Image. - golden_image: Golden image as PIL Image (must be same size/mode). - pixel_diff_threshold: Pixel L2 norm difference threshold. - - Returns: - Percentage of pixels that differ beyond the threshold. - """ - diff_array = np.array(ImageChops.difference(result_image, golden_image)) - l2_norm_array = np.linalg.norm(diff_array, axis=2) - num_different_pixels = np.sum(l2_norm_array > pixel_diff_threshold) - return 100.0 * num_different_pixels / l2_norm_array.size - - -def _compare_images( - result_image: Image.Image, - golden_image: Image.Image, - max_different_pixels_percentage: float, -) -> tuple[bool, str | None, float, float]: - """Compare result and golden images using pixel L2 norm (pass/fail) and SSIM (reference). - - Args: - result_image: Result image as PIL Image to compare with golden image. - golden_image: Golden image as PIL Image to compare with result image. - max_different_pixels_percentage: Maximum percentage of pixels allowed to exceed pixel_diff_threshold. - - Returns: - (passed, error_message_or_None, diff_percentage, ssim_score). - Scores are 0.0 / 0.0 when comparison cannot be performed (size/mode mismatch). - """ - if result_image.size != golden_image.size: - return False, f"Size mismatch: expected {golden_image.size}, got {result_image.size}.", 0.0, 0.0 - - if result_image.mode != golden_image.mode: - return False, f"Mode mismatch: expected {golden_image.mode}, got {result_image.mode}.", 0.0, 0.0 - - diff_pct = _pixel_diff_percentage(result_image, golden_image) - - # SSIM (reference only, not used for pass/fail). - result_tensor = torch.from_numpy(np.array(result_image, dtype=np.float32) / 255.0).permute(2, 0, 1).unsqueeze(0) - golden_tensor = torch.from_numpy(np.array(golden_image, dtype=np.float32) / 255.0).permute(2, 0, 1).unsqueeze(0) - ssim_score = _ssim(result_tensor, golden_tensor) - - if diff_pct > max_different_pixels_percentage: - return ( - False, - f"The percentage of different pixels ({diff_pct:.2f}%) exceeds the threshold of" - f" {max_different_pixels_percentage:.2f}%. SSIM={ssim_score:.4f} (reference).", - diff_pct, - ssim_score, - ) - - return True, None, diff_pct, ssim_score - - -def _validate_camera_outputs( - test_name: str, - physics_backend: str, - renderer: str, - camera_outputs: dict[str, torch.Tensor], - max_different_pixels_percentage: float, -) -> None: - """Validate correctness and consistency of camera outputs. - - Args: - test_name: Test name. - physics_backend: Physics backend. - renderer: Renderer. - camera_outputs: {data_type -> tensor}. - max_different_pixels_percentage: Maximum percentage of pixels allowed to exceed pixel_diff_threshold. - """ - assert len(camera_outputs) > 0, f"[{test_name}] No camera outputs produced by {physics_backend} + {renderer}." - - golden_image_dir = os.path.join(_GOLDEN_IMAGES_DIRECTORY, test_name) - os.makedirs(golden_image_dir, exist_ok=True) - - for data_type, tensor in camera_outputs.items(): - # Replace inf/nan with zero so they do not break comparison; ensure the tensor has at least one non-zero value. - condition = torch.logical_or(torch.isinf(tensor), torch.isnan(tensor)) - corrected = torch.where(condition, torch.zeros_like(tensor), tensor) - max_val = corrected.max() - assert max_val > 0, ( - f"[{test_name}] Camera output '{data_type}' has no non-zero pixels. " - f"Shape: {corrected.shape}, dtype: {corrected.dtype}." - ) - - # convert tensors to a tiled image. - normalized = _normalize_tensor(corrected, data_type) - grid = _make_grid(normalized) - - # permute(1, 2, 0) is there to change the tensor layout from channel-first to channel-last so it matches what - # PIL expects. - ndarr = grid.mul(255).add_(0.5).clamp_(0, 255).permute(1, 2, 0).to("cpu", torch.uint8).numpy() - result_image = Image.fromarray(ndarr) - - # first run creates baseline and fails; second run validates. - golden_path = os.path.join(golden_image_dir, f"{physics_backend}-{renderer}-{data_type}.png") - if not os.path.exists(golden_path): - result_image.save(golden_path) - pytest.fail( - f"[{test_name}] Golden image not found at {golden_path}. Saved result image to {golden_path}. " - "Please run the test again to validate the consistency of rendering outputs." - ) - - try: - golden_image = Image.open(golden_path) - except Exception as e: - pytest.fail(f"Error opening golden image: {e}") - - # validate the consistency of rendering outputs. - succeeded, error_message, diff_pct, ssim_score = _compare_images( - result_image, golden_image, max_different_pixels_percentage - ) - - entry = { - "test": test_name, - "backend": physics_backend, - "renderer": renderer, - "aov": data_type, - "diff_pct": diff_pct, - "ssim": ssim_score, - "threshold": max_different_pixels_percentage, - "passed": succeeded, - "img_result_path": None, - "img_golden_path": None, - } - - if diff_pct > 0: - prefix = f"{test_name}-{physics_backend}-{renderer}-{data_type}" - entry["img_result_path"] = _save_comparison_image(result_image, f"{prefix}-actual.png") - entry["img_golden_path"] = _save_comparison_image(golden_image, f"{prefix}-golden.png") - - _COMPARISON_SCORES.append(entry) - - if not succeeded: - timestamp = datetime.now().strftime("%Y-%m-%d-%H-%M-%S") - result_path = os.path.join(golden_image_dir, f"{physics_backend}-{renderer}-{data_type}-{timestamp}.png") - result_image.save(result_path) - pytest.fail( - f"[{test_name}] Inconsistency detected for camera output '{data_type}': {error_message}. " - f"Saved result image to {result_path} for further investigation. " - f"If result image is correct, please replace the golden image at {golden_path} with the result image." - ) - - -def _collect_camera_outputs(env: object) -> dict[str, dict[str, torch.Tensor]]: - """Collect camera outputs from env.scene.sensors. - - Args: - env: Gymnasium env (or any object with optional unwrapped.scene.sensors). - - Returns: - Nested dict: sensor name -> {data_type -> tensor} for non-empty tensor outputs. - """ - base = getattr(env, "unwrapped", env) - out = {} - - scene = getattr(base, "scene", None) - if scene is not None: - sensors = getattr(scene, "sensors", None) - if sensors is not None: - for name, sensor in sensors.items(): - data = getattr(sensor, "data", None) - output = getattr(data, "output", None) if data is not None else None - if not isinstance(output, dict): - continue - - # Collect only tensor entries (ignore empty or lazy-unfilled) - tensor_output = {k: v for k, v in output.items() if isinstance(v, torch.Tensor) and v.numel() > 0} - if tensor_output: - out[name] = tensor_output - - return out - - -# --------------------------------------------------------------------------- -# Shadow Hand vision env -# --------------------------------------------------------------------------- - - -@pytest.fixture(params=_PHYSICS_RENDERER_AOV_COMBINATIONS) -def shadow_hand_env(request): - """Build Shadow Hand vision env for (physics_backend, renderer, data_type); step once, yield, close.""" - from isaaclab_tasks.direct.shadow_hand.shadow_hand_vision_env import ShadowHandVisionEnv - from isaaclab_tasks.direct.shadow_hand.shadow_hand_vision_env_cfg import ShadowHandVisionEnvCfg - - physics_backend, renderer, data_type = request.param - - override_args = [f"presets={physics_backend},{renderer},{data_type}"] - - env_cfg = ShadowHandVisionEnvCfg() - env_cfg = _apply_overrides_to_env_cfg(env_cfg, override_args) - - env_cfg.scene.num_envs = 4 - env_cfg.seed = 42 - - if data_type == "depth": - # Disable CNN forward pass as it cannot be meaningfully trained from depth alone and will raise a ValueError. - env_cfg.feature_extractor.enabled = False - - env = None - try: - env = ShadowHandVisionEnv(env_cfg) - env.reset() - yield physics_backend, renderer, data_type, env - finally: - if env is not None: - env.close() - - -def test_shadow_hand(shadow_hand_env): - """Camera output must contain at least one non-zero pixel (Shadow Hand vision env).""" - physics_backend, renderer, _, env = shadow_hand_env - - _validate_camera_outputs( - "shadow_hand", - physics_backend, - renderer, - env._tiled_camera.data.output, - max_different_pixels_percentage=8.0, - ) - - -# --------------------------------------------------------------------------- -# Cartpole camera env -# --------------------------------------------------------------------------- - - -@pytest.fixture(params=_PHYSICS_RENDERER_AOV_COMBINATIONS) -def cartpole_env(request): - """Build Cartpole camera env for (physics_backend, renderer, data_type); step once, yield, close.""" - from isaaclab_tasks.direct.cartpole.cartpole_camera_env import CartpoleCameraEnv - from isaaclab_tasks.direct.cartpole.cartpole_camera_presets_env_cfg import CartpoleCameraPresetsEnvCfg - - physics_backend, renderer, data_type = request.param - - override_args = [f"presets={physics_backend},{renderer},{data_type}"] - - env_cfg = CartpoleCameraPresetsEnvCfg() - env_cfg = _apply_overrides_to_env_cfg(env_cfg, override_args) - - env_cfg.scene.num_envs = 4 - env_cfg.seed = 42 - - env = None - try: - env = CartpoleCameraEnv(env_cfg) - env.reset() - yield physics_backend, renderer, data_type, env - finally: - if env is not None: - env.close() - - -def test_cartpole(cartpole_env): - """Camera output must contain at least one non-zero pixel (Cartpole camera env).""" - physics_backend, renderer, _, env = cartpole_env - - _validate_camera_outputs( - "cartpole", - physics_backend, - renderer, - env._tiled_camera.data.output, - max_different_pixels_percentage=2.0, - ) - - -# --------------------------------------------------------------------------- -# Dexsuite Kuka-Allegro Lift (single camera) -# --------------------------------------------------------------------------- - - -@pytest.fixture(params=_PHYSICS_RENDERER_AOV_COMBINATIONS) -def dexsuite_kuka_allegro_lift_env(request): - """Build Dexsuite Kuka-Allegro Lift (single camera) for backend/renderer/data_type; step once, yield, close.""" - from isaaclab.envs import ManagerBasedRLEnv - - from isaaclab_tasks.manager_based.manipulation.dexsuite.config.kuka_allegro.dexsuite_kuka_allegro_env_cfg import ( - DexsuiteKukaAllegroLiftEnvCfg, - ) - - physics_backend, renderer, data_type = request.param - - if renderer == "newton_renderer" and data_type == "rgb": - # TODO: re-enable the test case once the issue is resolved. - pytest.skip("Newton Warp produces inconsistent RGB colors run-to-run; skipping test.") - - # Dexsuite data type has explicit resolution suffix (64, 128, 256). We only test 64x64. - override_args = [f"presets={physics_backend},{renderer},{data_type}64,single_camera,cube"] - - env_cfg = DexsuiteKukaAllegroLiftEnvCfg() - env_cfg = _apply_overrides_to_env_cfg(env_cfg, override_args) - - env_cfg.scene.num_envs = 4 - env_cfg.seed = 42 - - env = None - try: - env = ManagerBasedRLEnv(env_cfg) - env.reset() - yield physics_backend, renderer, data_type, env - finally: - if env is not None: - env.close() - - -def test_dexsuite_kuka_allegro_lift(dexsuite_kuka_allegro_lift_env): - """Camera output must contain at least one non-zero pixel (Dexsuite Kuka-Allegro Lift, single camera).""" - physics_backend, renderer, _, env = dexsuite_kuka_allegro_lift_env - - _validate_camera_outputs( - "dexsuite_kuka", - physics_backend, - renderer, - env.scene.sensors["base_camera"].data.output, - max_different_pixels_percentage=10.0, - ) - - -# --------------------------------------------------------------------------- -# Registered tasks (camera-based observations) -# --------------------------------------------------------------------------- - -# Task IDs that expose camera/tiled_camera image observations; each is validated for non-blank rendering. -_RENDER_CORRECTNESS_TASK_IDS = [ - "Isaac-Cartpole-Albedo-Camera-Direct-v0", - "Isaac-Cartpole-Camera-Presets-Direct-v0", - "Isaac-Cartpole-Depth-Camera-Direct-v0", - "Isaac-Cartpole-RGB-Camera-Direct-v0", - "Isaac-Cartpole-SimpleShading-Constant-Camera-Direct-v0", - "Isaac-Cartpole-SimpleShading-Diffuse-Camera-Direct-v0", - "Isaac-Cartpole-SimpleShading-Full-Camera-Direct-v0", - "Isaac-Repose-Cube-Shadow-Vision-Direct-v0", -] - - -@pytest.mark.parametrize("task_id", _RENDER_CORRECTNESS_TASK_IDS) -def test_registered_tasks(task_id): - """Camera output must be non-empty for each registered task with camera-based observations.""" - env = None - try: - env_cfg = parse_env_cfg(task_id, num_envs=4) - env_cfg.seed = 42 - - env = gym.make(task_id, cfg=env_cfg) - unwrapped: Any = env.unwrapped - sim = getattr(unwrapped, "sim", None) - if sim is not None: - sim._app_control_on_stop_handle = None - - env.reset() - - camera_outputs_nested_dict = _collect_camera_outputs(env) - num_camera_outputs = len(camera_outputs_nested_dict) - assert num_camera_outputs == 1, f"[{task_id}] Expected 1 camera output, got {num_camera_outputs}." - - camera_outputs = next(iter(camera_outputs_nested_dict.values())) - - _validate_camera_outputs( - f"registered_tasks/{task_id}", - "default_physics", - "default_renderer", - camera_outputs, - max_different_pixels_percentage=5.0, - ) - finally: - if env is not None: - env.close() diff --git a/source/isaaclab_tasks/test/test_rendering_dexsuite_kuka.py b/source/isaaclab_tasks/test/test_rendering_dexsuite_kuka.py new file mode 100644 index 000000000000..623c1e08c233 --- /dev/null +++ b/source/isaaclab_tasks/test/test_rendering_dexsuite_kuka.py @@ -0,0 +1,38 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Rendering correctness tests for Dexsuite Kuka-Allegro Lift backend combinations.""" + +# Launch Isaac Sim Simulator first for kit-based combinations. +from isaaclab.app import AppLauncher + +app_launcher = AppLauncher(headless=True, enable_cameras=True) +simulation_app = app_launcher.app + +from pathlib import Path # noqa: E402 + +import pytest # noqa: E402 +from rendering_test_utils import ( # noqa: E402 + PHYSICS_RENDERER_AOV_COMBINATIONS, + make_attach_comparison_properties_fixture, + make_determinism_fixture, + make_generate_html_report_fixture, + rendering_test_dexsuite_kuka, +) + +pytestmark = pytest.mark.isaacsim_ci + +_COMPARISON_SCORES: list[dict] = [] + +_determinism_fixture = make_determinism_fixture() +_generate_html_report_fixture = make_generate_html_report_fixture(_COMPARISON_SCORES, Path(__file__).stem + ".html") +_attach_comparison_properties_fixture = make_attach_comparison_properties_fixture(_COMPARISON_SCORES) + + +@pytest.mark.flaky(max_runs=3, min_passes=1) +@pytest.mark.parametrize("physics_backend,renderer,data_type", PHYSICS_RENDERER_AOV_COMBINATIONS) +def test_rendering_dexsuite_kuka(physics_backend, renderer, data_type): + """Test dexsuite kuka allegro lift environment rendering correctness.""" + rendering_test_dexsuite_kuka(physics_backend, renderer, data_type, _COMPARISON_SCORES) diff --git a/source/isaaclab_tasks/test/test_rendering_dexsuite_kuka_kitless.py b/source/isaaclab_tasks/test/test_rendering_dexsuite_kuka_kitless.py new file mode 100644 index 000000000000..f76d43364ab5 --- /dev/null +++ b/source/isaaclab_tasks/test/test_rendering_dexsuite_kuka_kitless.py @@ -0,0 +1,34 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Kit-less rendering correctness tests for Dexsuite Kuka-Allegro Lift backend combinations.""" + +from pathlib import Path + +import pytest +from rendering_test_utils import ( + KITLESS_PHYSICS_RENDERER_AOV_COMBINATIONS, + make_attach_comparison_properties_fixture, + make_determinism_fixture, + make_generate_html_report_fixture, + make_require_ovrtx_install_fixture, + rendering_test_dexsuite_kuka, +) + +pytestmark = pytest.mark.isaacsim_ci + +_COMPARISON_SCORES: list[dict] = [] + +_determinism_fixture = make_determinism_fixture() +_generate_html_report_fixture = make_generate_html_report_fixture(_COMPARISON_SCORES, Path(__file__).stem + ".html") +_attach_comparison_properties_fixture = make_attach_comparison_properties_fixture(_COMPARISON_SCORES) +_require_ovrtx_install_fixture = make_require_ovrtx_install_fixture() + + +@pytest.mark.flaky(max_runs=3, min_passes=1) +@pytest.mark.parametrize("physics_backend,renderer,data_type", KITLESS_PHYSICS_RENDERER_AOV_COMBINATIONS) +def test_rendering_dexsuite_kuka_kitless(physics_backend, renderer, data_type): + """Camera output must match golden images (Dexsuite Kuka-Allegro Lift, single camera).""" + rendering_test_dexsuite_kuka(physics_backend, renderer, data_type, _COMPARISON_SCORES) diff --git a/source/isaaclab_tasks/test/test_rendering_registered_tasks.py b/source/isaaclab_tasks/test/test_rendering_registered_tasks.py new file mode 100644 index 000000000000..f1b208f4d727 --- /dev/null +++ b/source/isaaclab_tasks/test/test_rendering_registered_tasks.py @@ -0,0 +1,119 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Rendering correctness tests for camera-based registered tasks.""" + +# Launch Isaac Sim Simulator first for kit-based combinations. +from isaaclab.app import AppLauncher + +app_launcher = AppLauncher(headless=True, enable_cameras=True) +simulation_app = app_launcher.app + +from pathlib import Path # noqa: E402 +from typing import Any # noqa: E402 + +import gymnasium as gym # noqa: E402 +import pytest # noqa: E402 +import torch # noqa: E402 +from rendering_test_utils import ( # noqa: E402 + MAX_DIFFERENT_PIXELS_PERCENTAGE_BY_ENV_NAME, + make_attach_comparison_properties_fixture, + make_determinism_fixture, + make_generate_html_report_fixture, + maybe_save_stage, + validate_camera_outputs, +) + +pytestmark = pytest.mark.isaacsim_ci + +_COMPARISON_SCORES: list[dict] = [] + +_determinism_fixture = make_determinism_fixture() +_generate_html_report_fixture = make_generate_html_report_fixture(_COMPARISON_SCORES, Path(__file__).stem + ".html") +_attach_comparison_properties_fixture = make_attach_comparison_properties_fixture(_COMPARISON_SCORES) + + +def _collect_camera_outputs(env: object) -> dict[str, dict[str, torch.Tensor]]: + """Collect camera outputs from env.scene.sensors.""" + base = getattr(env, "unwrapped", env) + outputs = {} + + scene = getattr(base, "scene", None) + if scene is not None: + sensors = getattr(scene, "sensors", None) + if sensors is not None: + for name, sensor in sensors.items(): + data = getattr(sensor, "data", None) + output = getattr(data, "output", None) if data is not None else None + if not isinstance(output, dict): + continue + + tensor_output = {k: v for k, v in output.items() if isinstance(v, torch.Tensor) and v.numel() > 0} + if tensor_output: + outputs[name] = tensor_output + + return outputs + + +# Task IDs that expose camera/tiled_camera image observations; each is validated for non-blank rendering. +# The max different pixels percentage is set based on the screen space taken up by the env. +_RENDER_CORRECTNESS_TASK_IDS = [ + ("Isaac-Cartpole-Albedo-Camera-Direct-v0", "cartpole"), + ("Isaac-Cartpole-Camera-Presets-Direct-v0", "cartpole"), + ("Isaac-Cartpole-Depth-Camera-Direct-v0", "cartpole"), + ("Isaac-Cartpole-RGB-Camera-Direct-v0", "cartpole"), + ("Isaac-Cartpole-SimpleShading-Constant-Camera-Direct-v0", "cartpole"), + ("Isaac-Cartpole-SimpleShading-Diffuse-Camera-Direct-v0", "cartpole"), + ("Isaac-Cartpole-SimpleShading-Full-Camera-Direct-v0", "cartpole"), + pytest.param( + "Isaac-Repose-Cube-Shadow-Vision-Direct-v0", + "shadow_hand", + # The Shadow-Vision render is right at the SSIM/diff-pixel tolerance and intermittently + # exceeds the 3% diff threshold by a fraction of a percent. Allow up to 3 attempts and + # require at least one pass while we tighten the validation tolerances for this scene. + marks=pytest.mark.flaky(max_runs=3, min_passes=1), + ), +] + + +@pytest.mark.parametrize("task_id, env_name", _RENDER_CORRECTNESS_TASK_IDS) +def test_rendering_registered_tasks(task_id: str, env_name: str): + """Test registered tasks rendering correctness.""" + env = None + + try: + from isaaclab_tasks.utils.parse_cfg import parse_env_cfg + + env_cfg = parse_env_cfg(task_id, num_envs=4) + + env = gym.make(task_id, cfg=env_cfg) + unwrapped: Any = env.unwrapped + sim = getattr(unwrapped, "sim", None) + if sim is not None: + sim._app_control_on_stop_handle = None + + maybe_save_stage(f"registered_tasks_{task_id}", "default_physics", "default_renderer", "stage") + + camera_outputs_nested_dict = _collect_camera_outputs(env) + num_camera_outputs = len(camera_outputs_nested_dict) + assert num_camera_outputs == 1, f"[{task_id}] Expected 1 camera output, got {num_camera_outputs}." + + camera_outputs = next(iter(camera_outputs_nested_dict.values())) + + validate_camera_outputs( + f"registered_tasks/{task_id}", + "default_physics", + "default_renderer", + camera_outputs, + max_different_pixels_percentage=MAX_DIFFERENT_PIXELS_PERCENTAGE_BY_ENV_NAME[env_name], + comparison_scores=_COMPARISON_SCORES, + ) + finally: + if env is not None: + env.close() + + # This invokes camera sensor and renderer cleanup explicitly before pytest teardown, otherwise OV + # native code could probably complain about leaks and trigger segmentation fault. + env = None diff --git a/source/isaaclab_tasks/test/test_rendering_shadow_hand.py b/source/isaaclab_tasks/test/test_rendering_shadow_hand.py new file mode 100644 index 000000000000..b49bff692170 --- /dev/null +++ b/source/isaaclab_tasks/test/test_rendering_shadow_hand.py @@ -0,0 +1,37 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Rendering correctness tests for Shadow Hand environment backend combinations.""" + +# Launch Isaac Sim Simulator first for kit-based combinations. +from isaaclab.app import AppLauncher + +app_launcher = AppLauncher(headless=True, enable_cameras=True) +simulation_app = app_launcher.app + +from pathlib import Path # noqa: E402 + +import pytest # noqa: E402 +from rendering_test_utils import ( # noqa: E402 + PHYSICS_RENDERER_AOV_COMBINATIONS, + make_attach_comparison_properties_fixture, + make_determinism_fixture, + make_generate_html_report_fixture, + rendering_test_shadow_hand, +) + +pytestmark = pytest.mark.isaacsim_ci + +_COMPARISON_SCORES: list[dict] = [] + +_determinism_fixture = make_determinism_fixture() +_generate_html_report_fixture = make_generate_html_report_fixture(_COMPARISON_SCORES, Path(__file__).stem + ".html") +_attach_comparison_properties_fixture = make_attach_comparison_properties_fixture(_COMPARISON_SCORES) + + +@pytest.mark.parametrize("physics_backend,renderer,data_type", PHYSICS_RENDERER_AOV_COMBINATIONS) +def test_rendering_shadow_hand(physics_backend, renderer, data_type): + """Test shadow hand environment rendering correctness.""" + rendering_test_shadow_hand(physics_backend, renderer, data_type, _COMPARISON_SCORES) diff --git a/source/isaaclab_tasks/test/test_rendering_shadow_hand_kitless.py b/source/isaaclab_tasks/test/test_rendering_shadow_hand_kitless.py new file mode 100644 index 000000000000..2244dcce5fab --- /dev/null +++ b/source/isaaclab_tasks/test/test_rendering_shadow_hand_kitless.py @@ -0,0 +1,33 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Kit-less rendering correctness tests for Shadow Hand environment backend combinations.""" + +from pathlib import Path + +import pytest +from rendering_test_utils import ( + KITLESS_PHYSICS_RENDERER_AOV_COMBINATIONS, + make_attach_comparison_properties_fixture, + make_determinism_fixture, + make_generate_html_report_fixture, + make_require_ovrtx_install_fixture, + rendering_test_shadow_hand, +) + +pytestmark = pytest.mark.isaacsim_ci + +_COMPARISON_SCORES: list[dict] = [] + +_determinism_fixture = make_determinism_fixture() +_generate_html_report_fixture = make_generate_html_report_fixture(_COMPARISON_SCORES, Path(__file__).stem + ".html") +_attach_comparison_properties_fixture = make_attach_comparison_properties_fixture(_COMPARISON_SCORES) +_require_ovrtx_install_fixture = make_require_ovrtx_install_fixture() + + +@pytest.mark.parametrize("physics_backend,renderer,data_type", KITLESS_PHYSICS_RENDERER_AOV_COMBINATIONS) +def test_rendering_shadow_hand_kitless(physics_backend, renderer, data_type): + """Test shadow hand environment rendering correctness.""" + rendering_test_shadow_hand(physics_backend, renderer, data_type, _COMPARISON_SCORES) diff --git a/source/isaaclab_tasks/test/test_shadow_hand_vision_presets.py b/source/isaaclab_tasks/test/test_shadow_hand_vision_presets.py index c4896cd5a316..5faf370f1cdb 100644 --- a/source/isaaclab_tasks/test/test_shadow_hand_vision_presets.py +++ b/source/isaaclab_tasks/test/test_shadow_hand_vision_presets.py @@ -41,7 +41,7 @@ ShadowHandVisionBenchmarkEnvCfg, ShadowHandVisionEnvCfg, ) -from isaaclab_tasks.utils.hydra import collect_presets, resolve_preset_defaults # noqa: E402 +from isaaclab_tasks.utils.hydra import collect_presets, resolve_presets # noqa: E402 # --------------------------------------------------------------------------- # Helpers @@ -308,7 +308,7 @@ def test_warp_with_invalid_camera_preset(shadow_hand_vision_presets, camera_pres # --------------------------------------------------------------------------- _RENDER_CORRECTNESS_CASES = [ - # (renderer_preset, camera_preset, physics) — physics is "physx" or "newton" + # (renderer_preset, camera_preset, physics) - physics is "physx" or "newton" # ── PhysX physics (default) + IsaacRTX: supports all data types ── pytest.param(("isaacsim_rtx_renderer", "rgb", "physx"), id="physx-isaacsim_rtx-rgb"), pytest.param(("isaacsim_rtx_renderer", "depth", "physx"), id="physx-isaacsim_rtx-depth"), @@ -383,16 +383,16 @@ def render_correctness_env(request, shadow_hand_vision_presets): camera_cfg = copy.deepcopy(shadow_hand_vision_presets["tiled_camera"][camera_preset]) camera_cfg.renderer_cfg = copy.deepcopy(shadow_hand_vision_presets["tiled_camera.renderer_cfg"][renderer_preset]) cfg.tiled_camera = camera_cfg - # Apply Newton presets before resolve_preset_defaults so they are not overwritten by defaults. + # Apply MJWarp presets before resolve_presets so they are not overwritten by defaults. # Newton needs a specific solver config, a different robot USD, an articulation-based object, # and a stripped-down event cfg (no PhysX-specific material randomization). if physics == "newton": - cfg.sim.physics = copy.deepcopy(shadow_hand_vision_presets["sim.physics"]["newton"]) - cfg.robot_cfg = copy.deepcopy(shadow_hand_vision_presets["robot_cfg"]["newton"]) - cfg.object_cfg = copy.deepcopy(shadow_hand_vision_presets["object_cfg"]["newton"]) + cfg.sim.physics = copy.deepcopy(shadow_hand_vision_presets["sim.physics"]["newton_mjwarp"]) + cfg.robot_cfg = copy.deepcopy(shadow_hand_vision_presets["robot_cfg"]["newton_mjwarp"]) + cfg.object_cfg = copy.deepcopy(shadow_hand_vision_presets["object_cfg"]["newton_mjwarp"]) if "events" in shadow_hand_vision_presets: - cfg.events = copy.deepcopy(shadow_hand_vision_presets["events"]["newton"]) - cfg = resolve_preset_defaults(cfg) + cfg.events = copy.deepcopy(shadow_hand_vision_presets["events"]["newton_mjwarp"]) + cfg = resolve_presets(cfg) cfg.scene.num_envs = 4 cfg.feature_extractor.write_image_to_file = False env = ShadowHandVisionEnv(cfg) diff --git a/source/isaaclab_tasks/test/test_sim_launcher_visualizer_intent.py b/source/isaaclab_tasks/test/test_sim_launcher_visualizer_intent.py index 853a9fb31a5d..c6bad5c19f1e 100644 --- a/source/isaaclab_tasks/test/test_sim_launcher_visualizer_intent.py +++ b/source/isaaclab_tasks/test/test_sim_launcher_visualizer_intent.py @@ -75,15 +75,18 @@ def set_bool(self, path: str, value: bool) -> None: monkeypatch.setattr( sim_launcher, "compute_kit_requirements", lambda env_cfg, launcher_args: (False, False, {"none"}) ) - monkeypatch.setitem( - sys.modules, - "isaaclab.app.settings_manager", - types.SimpleNamespace(get_settings_manager=lambda: _FakeSettings()), - ) + # `app_launcher` imports both names from settings_manager; provide a full stub module + # so `from isaaclab.app import AppLauncher` succeeds in kitless mode. + _sm = types.ModuleType("isaaclab.app.settings_manager") + _sm.get_settings_manager = lambda: _FakeSettings() + _sm.initialize_carb_settings = lambda: None + monkeypatch.setitem(sys.modules, "isaaclab.app.settings_manager", _sm) env_cfg = _DummyEnvCfg(_DummySimCfg(None)) launcher_args = argparse.Namespace(visualizer=["none"]) with sim_launcher.launch_simulation(env_cfg, launcher_args): pass - assert captured == {"types": "", "explicit": True, "disable_all": True} + # `sync_visualizer_cli_settings_to_carb` uses ``" ".join(visualizer)`` → ``"none"`` for ``["none"]``, + # not an empty string (empty only when *visualizer* is missing/empty). + assert captured == {"types": "none", "explicit": True, "disable_all": True} diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/cartpole/cartpole_warp_env.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/cartpole/cartpole_warp_env.py index a9670c6b8dd4..ff3c87da847e 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/cartpole/cartpole_warp_env.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/cartpole/cartpole_warp_env.py @@ -226,8 +226,8 @@ def __init__(self, cfg: CartpoleWarpEnvCfg, render_mode: str | None = None, **kw # Simulation bindings # Note: these are direct memory views into the Newton simulation data, they should not be modified directly - self.joint_pos = self.cartpole.data.joint_pos - self.joint_vel = self.cartpole.data.joint_vel + self.joint_pos = self.cartpole.data.joint_pos.warp + self.joint_vel = self.cartpole.data.joint_vel.warp # Buffers self.observations = wp.zeros((self.num_envs), dtype=wp.vec4f, device=self.device) @@ -344,8 +344,8 @@ def _reset_idx(self, mask: wp.array | None = None) -> None: reset, dim=self.num_envs, inputs=[ - self.cartpole.data.default_joint_pos, - self.cartpole.data.default_joint_vel, + self.cartpole.data.default_joint_pos.warp, + self.cartpole.data.default_joint_vel.warp, self.joint_pos, self.joint_vel, self._cart_dof_idx[0], diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/inhand_manipulation/inhand_manipulation_warp_env.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/inhand_manipulation/inhand_manipulation_warp_env.py index 8b142cf8e2ee..d5bc6a2ad529 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/inhand_manipulation/inhand_manipulation_warp_env.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/inhand_manipulation/inhand_manipulation_warp_env.py @@ -573,8 +573,8 @@ def __init__(self, cfg: AllegroHandWarpEnvCfg, render_mode: str | None = None, * self.finger_bodies = wp.array(finger_bodies, dtype=wp.int32, device=self.device) # joint limits - self.hand_dof_lower_limits = self.hand.data.joint_pos_limits_lower - self.hand_dof_upper_limits = self.hand.data.joint_pos_limits_upper + self.hand_dof_lower_limits = self.hand.data.joint_pos_limits_lower.warp + self.hand_dof_upper_limits = self.hand.data.joint_pos_limits_upper.warp # unit vectors self.x_unit_vec = wp.vec3f(1.0, 0.0, 0.0) @@ -603,7 +603,7 @@ def __init__(self, cfg: AllegroHandWarpEnvCfg, render_mode: str | None = None, * self.goal_pos_w = wp.zeros(self.num_envs, dtype=wp.vec3f, device=self.device) # Initialize goal constants from Torch (avoid a one-off kernel launch). - default_root_pose = wp.to_torch(self.object.data.default_root_pose).to(self.device) + default_root_pose = self.object.data.default_root_pose.torch.to(self.device) in_hand_pos = default_root_pose[:, 0:3].clone() in_hand_pos[:, 2] -= 0.04 self.in_hand_pos.assign(wp.from_torch(in_hand_pos, dtype=wp.vec3f)) @@ -812,15 +812,15 @@ def _reset_idx(self, mask: wp.array | None = None): reset_object, dim=self.num_envs, inputs=[ - self.object.data.default_root_pose, + self.object.data.default_root_pose.warp, self.env_origins, self.cfg.reset_position_noise, self.x_unit_vec, self.y_unit_vec, mask, self.rng_state, - self.object.data.root_link_pose_w, - self.object.data.root_com_vel_w, + self.object.data.root_link_pose_w.warp, + self.object.data.root_com_vel_w.warp, ], device=self.device, ) @@ -830,8 +830,8 @@ def _reset_idx(self, mask: wp.array | None = None): reset_hand, dim=self.num_envs, inputs=[ - self.hand.data.default_joint_pos, - self.hand.data.default_joint_vel, + self.hand.data.default_joint_pos.warp, + self.hand.data.default_joint_vel.warp, self.hand_dof_lower_limits, self.hand_dof_upper_limits, self.cfg.reset_dof_pos_noise, @@ -839,8 +839,8 @@ def _reset_idx(self, mask: wp.array | None = None): mask, self.num_hand_dofs, self.rng_state, - self.hand.data.joint_pos, - self.hand.data.joint_vel, + self.hand.data.joint_pos.warp, + self.hand.data.joint_vel.warp, self.prev_targets, self.cur_targets, self.hand_dof_targets, @@ -900,13 +900,13 @@ def _compute_intermediate_values(self): compute_intermediate_values, dim=self.num_envs, inputs=[ - self.hand.data.body_pos_w, - self.hand.data.body_quat_w, - self.hand.data.body_vel_w, + self.hand.data.body_pos_w.warp, + self.hand.data.body_quat_w.warp, + self.hand.data.body_vel_w.warp, self.finger_bodies, self.env_origins, - self.object.data.root_link_pose_w, - self.object.data.root_com_vel_w, + self.object.data.root_link_pose_w.warp, + self.object.data.root_com_vel_w.warp, self.num_fingertips, self.fingertip_pos, self.fingertip_rot, @@ -950,8 +950,8 @@ def compute_full_observations(self): compute_full_observations, dim=self.num_envs, inputs=[ - self.hand.data.joint_pos, - self.hand.data.joint_vel, + self.hand.data.joint_pos.warp, + self.hand.data.joint_vel.warp, self.hand_dof_lower_limits, self.hand_dof_upper_limits, self.cfg.vel_obs_scale, diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/locomotion/locomotion_env_warp.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/locomotion/locomotion_env_warp.py index 6a726eb035ef..d8d712a655e9 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/locomotion/locomotion_env_warp.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/locomotion/locomotion_env_warp.py @@ -359,11 +359,11 @@ def __init__(self, cfg: DirectRLEnvCfg, render_mode: str | None = None, **kwargs # Simulation bindings # Note: these are direct memory views into the Newton simulation data, they should not be modified directly - self.joint_pos = self.robot.data.joint_pos - self.joint_vel = self.robot.data.joint_vel - self.root_pose_w = self.robot.data.root_pose_w - self.root_vel_w = self.robot.data.root_vel_w - self.soft_joint_pos_limits = self.robot.data.soft_joint_pos_limits + self.joint_pos = self.robot.data.joint_pos.warp + self.joint_vel = self.robot.data.joint_vel.warp + self.root_pose_w = self.robot.data.root_pose_w.warp + self.root_vel_w = self.robot.data.root_vel_w.warp + self.soft_joint_pos_limits = self.robot.data.soft_joint_pos_limits.warp # Buffers self.observations = wp.zeros( @@ -548,8 +548,8 @@ def _reset_idx(self, mask: wp.array | None = None): reset_root, dim=self.num_envs, inputs=[ - self.robot.data.default_root_pose, - self.robot.data.default_root_vel, + self.robot.data.default_root_pose.warp, + self.robot.data.default_root_vel.warp, self.env_origins, self.cfg.sim.dt, self.targets, @@ -564,8 +564,8 @@ def _reset_idx(self, mask: wp.array | None = None): reset_joints, dim=(self.num_envs, self.robot.num_joints), inputs=[ - self.robot.data.default_joint_pos, - self.robot.data.default_joint_vel, + self.robot.data.default_joint_pos.warp, + self.robot.data.default_joint_vel.warp, self.joint_pos, self.joint_vel, mask, diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/__init__.py new file mode 100644 index 000000000000..7f23883e6332 --- /dev/null +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Experimental registrations for manager-based tasks. + +We intentionally only register new Gym IDs pointing at experimental entry points. +Task definitions (configs/mdp) remain in `isaaclab_tasks` to avoid duplication. +""" diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/__init__.py new file mode 100644 index 000000000000..79c13e2aa8f4 --- /dev/null +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/__init__.py @@ -0,0 +1,12 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Classic environments for control. + +These environments are based on the MuJoCo environments provided by OpenAI. + +Reference: + https://github.com/openai/gym/tree/master/gym/envs/mujoco +""" diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/ant/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/ant/__init__.py new file mode 100644 index 000000000000..5f123abaa756 --- /dev/null +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/ant/__init__.py @@ -0,0 +1,30 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +""" +Ant locomotion environment (experimental manager-based entry point). +""" + +import gymnasium as gym + +# Reuse agent configs from the stable task package. +from isaaclab_tasks.manager_based.classic.ant import agents + +## +# Register Gym environments. +## + +gym.register( + id="Isaac-Ant-Warp-v0", + entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": f"{__name__}.ant_env_cfg:AntEnvCfg", + "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:AntPPORunnerCfg", + "rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_ppo_cfg.yaml", + "skrl_cfg_entry_point": f"{agents.__name__}:skrl_ppo_cfg.yaml", + "sb3_cfg_entry_point": f"{agents.__name__}:sb3_ppo_cfg.yaml", + }, +) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/ant/ant_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/ant/ant_env_cfg.py new file mode 100644 index 000000000000..106d1a78ba09 --- /dev/null +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/ant/ant_env_cfg.py @@ -0,0 +1,198 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +# Ant reuses humanoid's experimental MDP (mirrors stable pattern). +from isaaclab_experimental.managers import ObservationTermCfg as ObsTerm +from isaaclab_experimental.managers import RewardTermCfg as RewTerm +from isaaclab_experimental.managers import TerminationTermCfg as DoneTerm +from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg + +import isaaclab.sim as sim_utils +from isaaclab.assets import AssetBaseCfg +from isaaclab.envs import ManagerBasedRLEnvCfg +from isaaclab.managers import EventTermCfg as EventTerm +from isaaclab.managers import ObservationGroupCfg as ObsGroup +from isaaclab.scene import InteractiveSceneCfg +from isaaclab.sim import SimulationCfg +from isaaclab.terrains import TerrainImporterCfg +from isaaclab.utils import configclass + +import isaaclab_tasks_experimental.manager_based.classic.humanoid.mdp as mdp + +## +# Pre-defined configs +## +from isaaclab_assets.robots.ant import ANT_CFG # isort: skip + + +@configclass +class MySceneCfg(InteractiveSceneCfg): + """Configuration for the terrain scene with an ant robot.""" + + # terrain + terrain = TerrainImporterCfg( + prim_path="/World/ground", + terrain_type="plane", + collision_group=-1, + physics_material=sim_utils.RigidBodyMaterialCfg( + friction_combine_mode="average", + restitution_combine_mode="average", + static_friction=1.0, + dynamic_friction=1.0, + restitution=0.0, + ), + debug_vis=False, + ) + + # robot + robot = ANT_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") + + # lights + light = AssetBaseCfg( + prim_path="/World/light", + spawn=sim_utils.DistantLightCfg(color=(0.75, 0.75, 0.75), intensity=3000.0), + ) + + +## +# MDP settings +## + + +@configclass +class ActionsCfg: + """Action specifications for the MDP.""" + + joint_effort = mdp.JointEffortActionCfg(asset_name="robot", joint_names=[".*"], scale=7.5) + + +@configclass +class ObservationsCfg: + """Observation specifications for the MDP.""" + + @configclass + class PolicyCfg(ObsGroup): + """Observations for the policy.""" + + base_height = ObsTerm(func=mdp.base_pos_z) + base_lin_vel = ObsTerm(func=mdp.base_lin_vel) + base_ang_vel = ObsTerm(func=mdp.base_ang_vel) + base_yaw_roll = ObsTerm(func=mdp.base_yaw_roll) + base_angle_to_target = ObsTerm(func=mdp.base_angle_to_target, params={"target_pos": (1000.0, 0.0, 0.0)}) + base_up_proj = ObsTerm(func=mdp.base_up_proj) + base_heading_proj = ObsTerm(func=mdp.base_heading_proj, params={"target_pos": (1000.0, 0.0, 0.0)}) + joint_pos_norm = ObsTerm(func=mdp.joint_pos_limit_normalized) + joint_vel_rel = ObsTerm(func=mdp.joint_vel_rel, scale=0.2) + actions = ObsTerm(func=mdp.last_action) + + def __post_init__(self): + self.enable_corruption = False + self.concatenate_terms = True + + # observation groups + policy: PolicyCfg = PolicyCfg() + + +@configclass +class EventCfg: + """Configuration for events.""" + + reset_base = EventTerm( + func=mdp.reset_root_state_uniform, + mode="reset", + params={"pose_range": {}, "velocity_range": {}}, + ) + + reset_robot_joints = EventTerm( + func=mdp.reset_joints_by_offset, + mode="reset", + params={ + "position_range": (-0.2, 0.2), + "velocity_range": (-0.1, 0.1), + }, + ) + + +@configclass +class RewardsCfg: + """Reward terms for the MDP.""" + + # (1) Reward for moving forward + progress = RewTerm(func=mdp.progress_reward, weight=1.0, params={"target_pos": (1000.0, 0.0, 0.0)}) + # (2) Stay alive bonus + alive = RewTerm(func=mdp.is_alive, weight=0.5) + # (3) Reward for non-upright posture + upright = RewTerm(func=mdp.upright_posture_bonus, weight=0.1, params={"threshold": 0.93}) + # (4) Reward for moving in the right direction + move_to_target = RewTerm( + func=mdp.move_to_target_bonus, weight=0.5, params={"threshold": 0.8, "target_pos": (1000.0, 0.0, 0.0)} + ) + # (5) Penalty for large action commands + action_l2 = RewTerm(func=mdp.action_l2, weight=-0.005) + # (6) Penalty for energy consumption + energy = RewTerm(func=mdp.power_consumption, weight=-0.05, params={"gear_ratio": {".*": 15.0}}) + # (7) Penalty for reaching close to joint limits + joint_pos_limits = RewTerm( + func=mdp.joint_pos_limits_penalty_ratio, weight=-0.1, params={"threshold": 0.99, "gear_ratio": {".*": 15.0}} + ) + + +@configclass +class TerminationsCfg: + """Termination terms for the MDP.""" + + # (1) Terminate if the episode length is exceeded + time_out = DoneTerm(func=mdp.time_out, time_out=True) + # (2) Terminate if the robot falls + torso_height = DoneTerm(func=mdp.root_height_below_minimum, params={"minimum_height": 0.31}) + + +## +# Environment configuration +## + + +@configclass +class AntEnvCfg(ManagerBasedRLEnvCfg): + """Configuration for the MuJoCo-style Ant walking environment.""" + + # Simulation settings + sim: SimulationCfg = SimulationCfg( + physics=NewtonCfg( + solver_cfg=MJWarpSolverCfg( + njmax=38, + nconmax=15, + ls_iterations=10, + cone="pyramidal", + ls_parallel=True, + impratio=1, + integrator="implicitfast", + ), + num_substeps=1, + debug_mode=False, + ) + ) + + # Scene settings + scene: MySceneCfg = MySceneCfg(num_envs=4096, env_spacing=5.0, clone_in_fabric=True) + # Basic settings + observations: ObservationsCfg = ObservationsCfg() + actions: ActionsCfg = ActionsCfg() + # MDP settings + rewards: RewardsCfg = RewardsCfg() + terminations: TerminationsCfg = TerminationsCfg() + events: EventCfg = EventCfg() + + def __post_init__(self): + """Post initialization.""" + # general settings + self.decimation = 2 + self.episode_length_s = 16.0 + # simulation settings + self.sim.dt = 1 / 120.0 + self.sim.render_interval = self.decimation + # default friction material + self.sim.physics_material.static_friction = 1.0 + self.sim.physics_material.dynamic_friction = 1.0 diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/cartpole/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/cartpole/__init__.py new file mode 100644 index 000000000000..4e3324264949 --- /dev/null +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/cartpole/__init__.py @@ -0,0 +1,30 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +""" +Cartpole balancing environment (experimental manager-based entry point). +""" + +import gymnasium as gym + +# Reuse agent configs from the stable task package. +from isaaclab_tasks.manager_based.classic.cartpole import agents + +## +# Register Gym environments. +## + +gym.register( + id="Isaac-Cartpole-Warp-v0", + entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": f"{__name__}.cartpole_env_cfg:CartpoleEnvCfg", + "rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_ppo_cfg.yaml", + "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:CartpolePPORunnerCfg", + "skrl_cfg_entry_point": f"{agents.__name__}:skrl_ppo_cfg.yaml", + "sb3_cfg_entry_point": f"{agents.__name__}:sb3_ppo_cfg.yaml", + }, +) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/cartpole/cartpole_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/cartpole/cartpole_env_cfg.py new file mode 100644 index 000000000000..898ac8be4fd0 --- /dev/null +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/cartpole/cartpole_env_cfg.py @@ -0,0 +1,199 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +import math + +from isaaclab_experimental.managers import ObservationTermCfg as ObsTerm +from isaaclab_experimental.managers import RewardTermCfg as RewTerm +from isaaclab_experimental.managers import SceneEntityCfg +from isaaclab_experimental.managers import TerminationTermCfg as DoneTerm +from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg + +import isaaclab.sim as sim_utils +from isaaclab.assets import ArticulationCfg, AssetBaseCfg +from isaaclab.envs import ManagerBasedRLEnvCfg +from isaaclab.managers import EventTermCfg as EventTerm +from isaaclab.managers import ObservationGroupCfg as ObsGroup +from isaaclab.scene import InteractiveSceneCfg +from isaaclab.sim import SimulationCfg +from isaaclab.utils import configclass + +import isaaclab_tasks_experimental.manager_based.classic.cartpole.mdp as mdp + +## +# Pre-defined configs +## +from isaaclab_assets.robots.cartpole import CARTPOLE_CFG # isort:skip + + +## +# Scene definition +## + + +@configclass +class CartpoleSceneCfg(InteractiveSceneCfg): + """Configuration for a cart-pole scene.""" + + # ground plane + # ground = AssetBaseCfg( + # prim_path="/World/ground", + # spawn=sim_utils.GroundPlaneCfg(size=(100.0, 100.0)), + # ) + + # cartpole + robot: ArticulationCfg = CARTPOLE_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") + + # lights + dome_light = AssetBaseCfg( + prim_path="/World/DomeLight", + spawn=sim_utils.DomeLightCfg(color=(0.9, 0.9, 0.9), intensity=500.0), + ) + + +## +# MDP settings +## + + +@configclass +class ActionsCfg: + """Action specifications for the MDP.""" + + joint_effort = mdp.JointEffortActionCfg(asset_name="robot", joint_names=["slider_to_cart"], scale=100.0) + + +@configclass +class ObservationsCfg: + """Observation specifications for the MDP.""" + + @configclass + class PolicyCfg(ObsGroup): + """Observations for policy group.""" + + # observation terms (order preserved) + joint_pos_rel = ObsTerm(func=mdp.joint_pos_rel) + joint_vel_rel = ObsTerm(func=mdp.joint_vel_rel) + + def __post_init__(self) -> None: + self.enable_corruption = False + self.concatenate_terms = True + + # observation groups + policy: PolicyCfg = PolicyCfg() + + +@configclass +class EventCfg: + """Configuration for events.""" + + # reset + reset_cart_position = EventTerm( + func=mdp.reset_joints_by_offset, + mode="reset", + params={ + "asset_cfg": SceneEntityCfg("robot", joint_names=["slider_to_cart"]), + "position_range": (-1.0, 1.0), + "velocity_range": (-0.5, 0.5), + }, + ) + + reset_pole_position = EventTerm( + func=mdp.reset_joints_by_offset, + mode="reset", + params={ + "asset_cfg": SceneEntityCfg("robot", joint_names=["cart_to_pole"]), + "position_range": (-0.25 * math.pi, 0.25 * math.pi), + "velocity_range": (-0.25 * math.pi, 0.25 * math.pi), + }, + ) + + +@configclass +class RewardsCfg: + """Reward terms for the MDP.""" + + # (1) Constant running reward + alive = RewTerm(func=mdp.is_alive, weight=1.0) + # (2) Failure penalty + terminating = RewTerm(func=mdp.is_terminated, weight=-2.0) + # (3) Primary task: keep pole upright + pole_pos = RewTerm( + func=mdp.joint_pos_target_l2, + weight=-1.0, + params={"asset_cfg": SceneEntityCfg("robot", joint_names=["cart_to_pole"]), "target": 0.0}, + ) + # (4) Shaping tasks: lower cart velocity + cart_vel = RewTerm( + func=mdp.joint_vel_l1, + weight=-0.01, + params={"asset_cfg": SceneEntityCfg("robot", joint_names=["slider_to_cart"])}, + ) + # (5) Shaping tasks: lower pole angular velocity + pole_vel = RewTerm( + func=mdp.joint_vel_l1, + weight=-0.005, + params={"asset_cfg": SceneEntityCfg("robot", joint_names=["cart_to_pole"])}, + ) + + +@configclass +class TerminationsCfg: + """Termination terms for the MDP.""" + + # (1) Time out + time_out = DoneTerm(func=mdp.time_out, time_out=True) + # (2) Cart out of bounds + cart_out_of_bounds = DoneTerm( + func=mdp.joint_pos_out_of_manual_limit, + params={"asset_cfg": SceneEntityCfg("robot", joint_names=["slider_to_cart"]), "bounds": (-3.0, 3.0)}, + ) + + +## +# Environment configuration +## + + +@configclass +class CartpoleEnvCfg(ManagerBasedRLEnvCfg): + """Configuration for the cartpole environment.""" + + # Scene settings + scene: CartpoleSceneCfg = CartpoleSceneCfg(num_envs=4096, env_spacing=4.0, clone_in_fabric=True) + # Basic settings + observations: ObservationsCfg = ObservationsCfg() + actions: ActionsCfg = ActionsCfg() + events: EventCfg = EventCfg() + # MDP settings + rewards: RewardsCfg = RewardsCfg() + terminations: TerminationsCfg = TerminationsCfg() + # Simulation settings + sim: SimulationCfg = SimulationCfg( + physics=NewtonCfg( + solver_cfg=MJWarpSolverCfg( + njmax=5, + nconmax=3, + cone="pyramidal", + impratio=1, + integrator="implicitfast", + ), + num_substeps=1, + debug_mode=False, + use_cuda_graph=True, + ) + ) + + # Post initialization + def __post_init__(self) -> None: + """Post initialization.""" + # general settings + self.decimation = 2 + self.episode_length_s = 5 + # viewer settings + self.viewer.eye = (8.0, 0.0, 5.0) + # simulation settings + self.sim.dt = 1 / 120 + self.sim.render_interval = self.decimation diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/cartpole/mdp/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/cartpole/mdp/__init__.py new file mode 100644 index 000000000000..73b1cf4fb2c5 --- /dev/null +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/cartpole/mdp/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""This sub-module contains the functions that are specific to the cartpole environments.""" + +from isaaclab_experimental.envs.mdp import * # noqa: F401, F403 + +from .rewards import * # noqa: F401, F403 diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/cartpole/mdp/rewards.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/cartpole/mdp/rewards.py new file mode 100644 index 000000000000..b83d2ea61706 --- /dev/null +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/cartpole/mdp/rewards.py @@ -0,0 +1,46 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from __future__ import annotations + +from typing import TYPE_CHECKING + +import warp as wp +from isaaclab_experimental.managers import SceneEntityCfg +from isaaclab_experimental.utils.warp.utils import wrap_to_pi + +from isaaclab.assets import Articulation + +if TYPE_CHECKING: + from isaaclab.envs import ManagerBasedRLEnv + + +@wp.kernel +def _joint_pos_target_l2_kernel( + joint_pos: wp.array(dtype=wp.float32, ndim=2), + joint_mask: wp.array(dtype=wp.bool), + out: wp.array(dtype=wp.float32), + target: float, +): + i = wp.tid() + s = float(0.0) + for j in range(joint_pos.shape[1]): + if joint_mask[j]: + a = wrap_to_pi(joint_pos[i, j]) + d = a - target + s += d * d + out[i] = s + + +def joint_pos_target_l2(env: ManagerBasedRLEnv, out, target: float, asset_cfg: SceneEntityCfg) -> None: + """Penalize joint position deviation from a target value. Writes into ``out``.""" + asset: Articulation = env.scene[asset_cfg.name] + assert asset.data.joint_pos.warp.shape[1] == asset_cfg.joint_mask.shape[0] + wp.launch( + kernel=_joint_pos_target_l2_kernel, + dim=env.num_envs, + inputs=[asset.data.joint_pos.warp, asset_cfg.joint_mask, out, target], + device=env.device, + ) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/humanoid/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/humanoid/__init__.py new file mode 100644 index 000000000000..c08e5156b926 --- /dev/null +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/humanoid/__init__.py @@ -0,0 +1,30 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +""" +Humanoid locomotion environment (experimental manager-based entry point). +""" + +import gymnasium as gym + +# Reuse agent configs from the stable task package. +from isaaclab_tasks.manager_based.classic.humanoid import agents + +## +# Register Gym environments. +## + +gym.register( + id="Isaac-Humanoid-Warp-v0", + entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": f"{__name__}.humanoid_env_cfg:HumanoidEnvCfg", + "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:HumanoidPPORunnerCfg", + "rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_ppo_cfg.yaml", + "skrl_cfg_entry_point": f"{agents.__name__}:skrl_ppo_cfg.yaml", + "sb3_cfg_entry_point": f"{agents.__name__}:sb3_ppo_cfg.yaml", + }, +) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/humanoid/humanoid_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/humanoid/humanoid_env_cfg.py new file mode 100644 index 000000000000..781541a495e6 --- /dev/null +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/humanoid/humanoid_env_cfg.py @@ -0,0 +1,233 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from isaaclab_experimental.managers import ObservationTermCfg as ObsTerm +from isaaclab_experimental.managers import RewardTermCfg as RewTerm +from isaaclab_experimental.managers import TerminationTermCfg as DoneTerm +from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg + +import isaaclab.sim as sim_utils +from isaaclab.assets import AssetBaseCfg +from isaaclab.envs import ManagerBasedRLEnvCfg +from isaaclab.managers import EventTermCfg as EventTerm +from isaaclab.managers import ObservationGroupCfg as ObsGroup +from isaaclab.scene import InteractiveSceneCfg +from isaaclab.sim import SimulationCfg +from isaaclab.terrains import TerrainImporterCfg +from isaaclab.utils import configclass + +import isaaclab_tasks_experimental.manager_based.classic.humanoid.mdp as mdp + +from isaaclab_assets.robots.humanoid import HUMANOID_CFG # isort:skip + + +## +# Scene definition +## + + +@configclass +class MySceneCfg(InteractiveSceneCfg): + """Configuration for the terrain scene with a humanoid robot.""" + + # terrain + terrain = TerrainImporterCfg( + prim_path="/World/ground", + terrain_type="plane", + collision_group=-1, + physics_material=sim_utils.RigidBodyMaterialCfg(static_friction=1.0, dynamic_friction=1.0, restitution=0.0), + debug_vis=False, + ) + + # robot + robot = HUMANOID_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") + + # lights + light = AssetBaseCfg( + prim_path="/World/light", + spawn=sim_utils.DistantLightCfg(color=(0.75, 0.75, 0.75), intensity=3000.0), + ) + + +## +# MDP settings +## + + +@configclass +class ActionsCfg: + """Action specifications for the MDP.""" + + joint_effort = mdp.JointEffortActionCfg( + asset_name="robot", + joint_names=[".*"], + scale={ + ".*_waist.*": 67.5, + ".*_upper_arm.*": 67.5, + "pelvis": 67.5, + ".*_lower_arm": 45.0, + ".*_thigh:0": 45.0, + ".*_thigh:1": 135.0, + ".*_thigh:2": 45.0, + ".*_shin": 90.0, + ".*_foot.*": 22.5, + }, + ) + + +@configclass +class ObservationsCfg: + """Observation specifications for the MDP.""" + + @configclass + class PolicyCfg(ObsGroup): + """Observations for the policy.""" + + base_height = ObsTerm(func=mdp.base_pos_z) + base_lin_vel = ObsTerm(func=mdp.base_lin_vel) + base_ang_vel = ObsTerm(func=mdp.base_ang_vel, scale=0.25) + base_yaw_roll = ObsTerm(func=mdp.base_yaw_roll) + base_angle_to_target = ObsTerm(func=mdp.base_angle_to_target, params={"target_pos": (1000.0, 0.0, 0.0)}) + base_up_proj = ObsTerm(func=mdp.base_up_proj) + base_heading_proj = ObsTerm(func=mdp.base_heading_proj, params={"target_pos": (1000.0, 0.0, 0.0)}) + joint_pos_norm = ObsTerm(func=mdp.joint_pos_limit_normalized) + joint_vel_rel = ObsTerm(func=mdp.joint_vel_rel, scale=0.1) + actions = ObsTerm(func=mdp.last_action) + + def __post_init__(self): + self.enable_corruption = False + self.concatenate_terms = True + + # observation groups + policy: PolicyCfg = PolicyCfg() + + +@configclass +class EventCfg: + """Configuration for events.""" + + reset_base = EventTerm( + func=mdp.reset_root_state_uniform, + mode="reset", + params={"pose_range": {}, "velocity_range": {}}, + ) + + reset_robot_joints = EventTerm( + func=mdp.reset_joints_by_offset, + mode="reset", + params={ + "position_range": (-0.2, 0.2), + "velocity_range": (-0.1, 0.1), + }, + ) + + +@configclass +class RewardsCfg: + """Reward terms for the MDP.""" + + # (1) Reward for moving forward + progress = RewTerm(func=mdp.progress_reward, weight=1.0, params={"target_pos": (1000.0, 0.0, 0.0)}) + # (2) Stay alive bonus + alive = RewTerm(func=mdp.is_alive, weight=2.0) + # (3) Reward for non-upright posture + upright = RewTerm(func=mdp.upright_posture_bonus, weight=0.1, params={"threshold": 0.93}) + # (4) Reward for moving in the right direction + move_to_target = RewTerm( + func=mdp.move_to_target_bonus, weight=0.5, params={"threshold": 0.8, "target_pos": (1000.0, 0.0, 0.0)} + ) + # (5) Penalty for large action commands + action_l2 = RewTerm(func=mdp.action_l2, weight=-0.01) + # (6) Penalty for energy consumption + energy = RewTerm( + func=mdp.power_consumption, + weight=-0.005, + params={ + "gear_ratio": { + ".*_waist.*": 67.5, + ".*_upper_arm.*": 67.5, + "pelvis": 67.5, + ".*_lower_arm": 45.0, + ".*_thigh:0": 45.0, + ".*_thigh:1": 135.0, + ".*_thigh:2": 45.0, + ".*_shin": 90.0, + ".*_foot.*": 22.5, + } + }, + ) + # (7) Penalty for reaching close to joint limits + joint_pos_limits = RewTerm( + func=mdp.joint_pos_limits_penalty_ratio, + weight=-0.25, + params={ + "threshold": 0.98, + "gear_ratio": { + ".*_waist.*": 67.5, + ".*_upper_arm.*": 67.5, + "pelvis": 67.5, + ".*_lower_arm": 45.0, + ".*_thigh:0": 45.0, + ".*_thigh:1": 135.0, + ".*_thigh:2": 45.0, + ".*_shin": 90.0, + ".*_foot.*": 22.5, + }, + }, + ) + + +@configclass +class TerminationsCfg: + """Termination terms for the MDP.""" + + # (1) Terminate if the episode length is exceeded + time_out = DoneTerm(func=mdp.time_out, time_out=True) + # (2) Terminate if the robot falls + torso_height = DoneTerm(func=mdp.root_height_below_minimum, params={"minimum_height": 0.8}) + + +@configclass +class HumanoidEnvCfg(ManagerBasedRLEnvCfg): + """Configuration for the MuJoCo-style Humanoid walking environment.""" + + # Scene settings + scene: MySceneCfg = MySceneCfg(num_envs=4096, env_spacing=5.0, clone_in_fabric=True) + # Basic settings + observations: ObservationsCfg = ObservationsCfg() + actions: ActionsCfg = ActionsCfg() + # MDP settings + rewards: RewardsCfg = RewardsCfg() + terminations: TerminationsCfg = TerminationsCfg() + events: EventCfg = EventCfg() + + def __post_init__(self): + """Post initialization.""" + # general settings + self.decimation = 2 + self.episode_length_s = 16.0 + # simulation settings + self.sim: SimulationCfg = SimulationCfg( + dt=1 / 120.0, + physics=NewtonCfg( + solver_cfg=MJWarpSolverCfg( + njmax=80, + nconmax=25, + ls_iterations=15, + cone="pyramidal", + ls_parallel=True, + update_data_interval=2, + impratio=1, + integrator="implicitfast", + ), + num_substeps=2, + debug_mode=False, + ), + ) + # self.sim.dt = 1 / 120.0 + self.sim.render_interval = self.decimation + # default friction material + self.sim.physics_material.static_friction = 1.0 + self.sim.physics_material.dynamic_friction = 1.0 diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/humanoid/mdp/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/humanoid/mdp/__init__.py new file mode 100644 index 000000000000..df0802edf058 --- /dev/null +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/humanoid/mdp/__init__.py @@ -0,0 +1,11 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""This sub-module contains the functions that are specific to the humanoid environments.""" + +from isaaclab_experimental.envs.mdp import * # noqa: F401, F403 + +from .observations import * # noqa: F401, F403 +from .rewards import * # noqa: F401, F403 diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/humanoid/mdp/observations.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/humanoid/mdp/observations.py new file mode 100644 index 000000000000..23c3c779eab9 --- /dev/null +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/humanoid/mdp/observations.py @@ -0,0 +1,186 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Warp-first observation terms for the humanoid task. + +All observation functions follow the ``func(env, out, **params) -> None`` signature. +Dimensions are declared via ``out_dim`` on the ``@generic_io_descriptor_warp`` decorator. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +import warp as wp +from isaaclab_experimental.envs.utils.io_descriptors import generic_io_descriptor_warp +from isaaclab_experimental.managers import SceneEntityCfg +from isaaclab_newton.kernels.state_kernels import rotate_vec_to_body_frame + +from isaaclab.assets import Articulation + +if TYPE_CHECKING: + from isaaclab.envs import ManagerBasedEnv + + +@wp.kernel +def _base_yaw_roll_kernel( + root_quat_w: wp.array(dtype=wp.quatf), + out: wp.array(dtype=wp.float32, ndim=2), +): + """Extract yaw and roll angles from root quaternion (x, y, z, w layout).""" + i = wp.tid() + q = root_quat_w[i] + qx = q[0] + qy = q[1] + qz = q[2] + qw = q[3] + # roll = atan2(2*(qw*qx + qy*qz), 1 - 2*(qx^2 + qy^2)) + sin_roll = 2.0 * (qw * qx + qy * qz) + cos_roll = 1.0 - 2.0 * (qx * qx + qy * qy) + roll = wp.atan2(sin_roll, cos_roll) + # yaw = atan2(2*(qw*qz + qx*qy), 1 - 2*(qy^2 + qz^2)) + sin_yaw = 2.0 * (qw * qz + qx * qy) + cos_yaw = 1.0 - 2.0 * (qy * qy + qz * qz) + yaw = wp.atan2(sin_yaw, cos_yaw) + out[i, 0] = yaw + out[i, 1] = roll + + +@generic_io_descriptor_warp(out_dim=2, observation_type="RootState") +def base_yaw_roll(env: ManagerBasedEnv, out, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")) -> None: + """Yaw and roll of the base in the simulation world frame. Shape: (num_envs, 2).""" + asset: Articulation = env.scene[asset_cfg.name] + wp.launch( + kernel=_base_yaw_roll_kernel, + dim=env.num_envs, + inputs=[asset.data.root_quat_w.warp, out], + device=env.device, + ) + + +# Inline Tier 1 access: derives projected gravity directly from root_link_pose_w, +# avoiding the lazy TimestampedWarpBuffer which is not CUDA-graph-capturable. +# See GRAPH_CAPTURE_MIGRATION.md in isaaclab_newton for background. + + +@wp.kernel +def _base_up_proj_kernel( + root_pose_w: wp.array(dtype=wp.transformf), + gravity_w: wp.array(dtype=wp.vec3f), + out: wp.array(dtype=wp.float32, ndim=2), +): + """Project base up vector onto world up: -gravity_b[2].""" + i = wp.tid() + out[i, 0] = -rotate_vec_to_body_frame(gravity_w[0], root_pose_w[i])[2] + + +@generic_io_descriptor_warp(out_dim=1, observation_type="RootState") +def base_up_proj(env: ManagerBasedEnv, out, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")) -> None: + """Projection of the base up vector onto the world up vector. Shape: (num_envs, 1).""" + asset: Articulation = env.scene[asset_cfg.name] + wp.launch( + kernel=_base_up_proj_kernel, + dim=env.num_envs, + inputs=[asset.data.root_link_pose_w.warp, asset.data.GRAVITY_VEC_W.warp, out], + device=env.device, + ) + + +@wp.kernel +def _base_heading_proj_kernel( + root_pos_w: wp.array(dtype=wp.vec3f), + root_quat_w: wp.array(dtype=wp.quatf), + target_x: float, + target_y: float, + target_z: float, + out: wp.array(dtype=wp.float32, ndim=2), +): + """Dot product between robot forward and direction to target.""" + i = wp.tid() + pos = root_pos_w[i] + q = root_quat_w[i] + # compute direction to target (zeroed z) + dx = target_x - pos[0] + dy = target_y - pos[1] + dist = wp.sqrt(dx * dx + dy * dy) + # avoid division by zero + inv_dist = wp.where(dist > 1.0e-6, 1.0 / dist, 0.0) + to_target_x = dx * inv_dist + to_target_y = dy * inv_dist + # compute forward vector via quaternion rotation of (1,0,0) + fwd = wp.quat_rotate(q, wp.vec3f(1.0, 0.0, 0.0)) + # dot product (xy only) + heading_proj = fwd[0] * to_target_x + fwd[1] * to_target_y + out[i, 0] = heading_proj + + +@generic_io_descriptor_warp(out_dim=1, observation_type="RootState") +def base_heading_proj( + env: ManagerBasedEnv, + out, + target_pos: tuple[float, float, float], + asset_cfg: SceneEntityCfg = SceneEntityCfg("robot"), +) -> None: + """Dot product between the base forward direction and direction to target. Shape: (num_envs, 1).""" + asset: Articulation = env.scene[asset_cfg.name] + wp.launch( + kernel=_base_heading_proj_kernel, + dim=env.num_envs, + inputs=[ + asset.data.root_pos_w.warp, + asset.data.root_quat_w.warp, + target_pos[0], + target_pos[1], + target_pos[2], + out, + ], + device=env.device, + ) + + +@wp.kernel +def _base_angle_to_target_kernel( + root_pos_w: wp.array(dtype=wp.vec3f), + root_quat_w: wp.array(dtype=wp.quatf), + target_x: float, + target_y: float, + out: wp.array(dtype=wp.float32, ndim=2), +): + """Angle between base forward and vector to target, normalized to [-pi, pi].""" + i = wp.tid() + pos = root_pos_w[i] + q = root_quat_w[i] + # angle to target in world frame + dx = target_x - pos[0] + dy = target_y - pos[1] + walk_target_angle = wp.atan2(dy, dx) + # extract yaw from quaternion + qx = q[0] + qy = q[1] + qz = q[2] + qw = q[3] + sin_yaw = 2.0 * (qw * qz + qx * qy) + cos_yaw = 1.0 - 2.0 * (qy * qy + qz * qz) + yaw = wp.atan2(sin_yaw, cos_yaw) + # normalize to [-pi, pi] + angle = walk_target_angle - yaw + out[i, 0] = wp.atan2(wp.sin(angle), wp.cos(angle)) + + +@generic_io_descriptor_warp(out_dim=1, observation_type="RootState") +def base_angle_to_target( + env: ManagerBasedEnv, + out, + target_pos: tuple[float, float, float], + asset_cfg: SceneEntityCfg = SceneEntityCfg("robot"), +) -> None: + """Angle between the base forward vector and the vector to the target. Shape: (num_envs, 1).""" + asset: Articulation = env.scene[asset_cfg.name] + wp.launch( + kernel=_base_angle_to_target_kernel, + dim=env.num_envs, + inputs=[asset.data.root_pos_w.warp, asset.data.root_quat_w.warp, target_pos[0], target_pos[1], out], + device=env.device, + ) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/humanoid/mdp/rewards.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/humanoid/mdp/rewards.py new file mode 100644 index 000000000000..f0e47dfbbf05 --- /dev/null +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/humanoid/mdp/rewards.py @@ -0,0 +1,321 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Warp-first reward terms for the humanoid task. + +All reward functions follow the ``func(env, out, **params) -> None`` signature +where ``out`` is a pre-allocated Warp array of shape ``(num_envs,)`` with float32 dtype. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +import torch +import warp as wp +from isaaclab_experimental.managers import SceneEntityCfg +from isaaclab_experimental.managers.manager_base import ManagerTermBase +from isaaclab_newton.kernels.state_kernels import rotate_vec_to_body_frame + +import isaaclab.utils.string as string_utils +from isaaclab.assets import Articulation + +if TYPE_CHECKING: + from isaaclab_experimental.managers.manager_term_cfg import RewardTermCfg + + from isaaclab.envs import ManagerBasedRLEnv + + +# --------------------------------------------------------------------------- +# Function-based reward terms +# --------------------------------------------------------------------------- + + +# Inline Tier 1 access: derives projected gravity directly from root_link_pose_w, +# avoiding the lazy TimestampedWarpBuffer which is not CUDA-graph-capturable. +# See GRAPH_CAPTURE_MIGRATION.md in isaaclab_newton for background. +# If ArticulationData Tier 2 lazy update is made graph-safe, this can revert to +# reading asset.data.projected_gravity_b directly. + + +@wp.kernel +def _upright_posture_bonus_kernel( + root_pose_w: wp.array(dtype=wp.transformf), + gravity_w: wp.array(dtype=wp.vec3f), + threshold: float, + out: wp.array(dtype=wp.float32), +): + i = wp.tid() + up_proj = -rotate_vec_to_body_frame(gravity_w[0], root_pose_w[i])[2] + out[i] = wp.where(up_proj > threshold, 1.0, 0.0) + + +def upright_posture_bonus( + env: ManagerBasedRLEnv, out, threshold: float, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot") +) -> None: + """Reward for maintaining an upright posture. Writes 1.0 if up_proj > threshold, else 0.0.""" + asset: Articulation = env.scene[asset_cfg.name] + wp.launch( + kernel=_upright_posture_bonus_kernel, + dim=env.num_envs, + inputs=[asset.data.root_link_pose_w.warp, asset.data.GRAVITY_VEC_W.warp, threshold, out], + device=env.device, + ) + + +@wp.kernel +def _move_to_target_bonus_kernel( + root_pos_w: wp.array(dtype=wp.vec3f), + root_quat_w: wp.array(dtype=wp.quatf), + target_x: float, + target_y: float, + threshold: float, + out: wp.array(dtype=wp.float32), +): + i = wp.tid() + pos = root_pos_w[i] + q = root_quat_w[i] + # direction to target + dx = target_x - pos[0] + dy = target_y - pos[1] + dist = wp.sqrt(dx * dx + dy * dy) + inv_dist = wp.where(dist > 1.0e-6, 1.0 / dist, 0.0) + to_target_x = dx * inv_dist + to_target_y = dy * inv_dist + # forward vector + fwd = wp.quat_rotate(q, wp.vec3f(1.0, 0.0, 0.0)) + heading_proj = fwd[0] * to_target_x + fwd[1] * to_target_y + out[i] = wp.where(heading_proj > threshold, 1.0, heading_proj / threshold) + + +def move_to_target_bonus( + env: ManagerBasedRLEnv, + out, + threshold: float, + target_pos: tuple[float, float, float], + asset_cfg: SceneEntityCfg = SceneEntityCfg("robot"), +) -> None: + """Reward for heading towards the target.""" + asset: Articulation = env.scene[asset_cfg.name] + wp.launch( + kernel=_move_to_target_bonus_kernel, + dim=env.num_envs, + inputs=[ + asset.data.root_pos_w.warp, + asset.data.root_quat_w.warp, + target_pos[0], + target_pos[1], + threshold, + out, + ], + device=env.device, + ) + + +# --------------------------------------------------------------------------- +# Class-based reward terms +# --------------------------------------------------------------------------- + + +@wp.kernel +def _progress_reward_reset_kernel( + env_mask: wp.array(dtype=wp.bool), + root_pos_w: wp.array(dtype=wp.vec3f), + target_x: float, + target_y: float, + target_z: float, + inv_step_dt: float, + potentials: wp.array(dtype=wp.float32), +): + i = wp.tid() + if env_mask[i]: + pos = root_pos_w[i] + dx = target_x - pos[0] + dy = target_y - pos[1] + dz = target_z - pos[2] + dist = wp.sqrt(dx * dx + dy * dy + dz * dz) + potentials[i] = -dist * inv_step_dt + + +@wp.kernel +def _progress_reward_kernel( + root_pos_w: wp.array(dtype=wp.vec3f), + target_x: float, + target_y: float, + inv_step_dt: float, + potentials: wp.array(dtype=wp.float32), + out: wp.array(dtype=wp.float32), +): + i = wp.tid() + pos = root_pos_w[i] + dx = target_x - pos[0] + dy = target_y - pos[1] + # z component is zeroed (xy distance only, matching stable) + dist = wp.sqrt(dx * dx + dy * dy) + prev = potentials[i] + pot = -dist * inv_step_dt + potentials[i] = pot + out[i] = pot - prev + + +class progress_reward(ManagerTermBase): + """Reward for making progress towards the target (potential-based).""" + + def __init__(self, cfg: RewardTermCfg, env: ManagerBasedRLEnv): + super().__init__(cfg, env) + self.potentials = wp.zeros(env.num_envs, dtype=wp.float32, device=env.device) + self._target_pos = cfg.params["target_pos"] + + def reset(self, env_mask: wp.array | None = None) -> None: + if env_mask is None: + self.potentials.zero_() + return + asset: Articulation = self._env.scene["robot"] + inv_dt = 1.0 / self._env.step_dt + wp.launch( + kernel=_progress_reward_reset_kernel, + dim=self.num_envs, + inputs=[ + env_mask, + asset.data.root_pos_w.warp, + self._target_pos[0], + self._target_pos[1], + self._target_pos[2], + inv_dt, + self.potentials, + ], + device=self.device, + ) + + def __call__( + self, + env: ManagerBasedRLEnv, + out, + target_pos: tuple[float, float, float], + asset_cfg: SceneEntityCfg = SceneEntityCfg("robot"), + ) -> None: + asset: Articulation = env.scene[asset_cfg.name] + inv_dt = 1.0 / env.step_dt + wp.launch( + kernel=_progress_reward_kernel, + dim=env.num_envs, + inputs=[asset.data.root_pos_w.warp, target_pos[0], target_pos[1], inv_dt, self.potentials, out], + device=env.device, + ) + + +@wp.kernel +def _joint_pos_limits_penalty_ratio_kernel( + joint_pos: wp.array(dtype=wp.float32, ndim=2), + soft_limits: wp.array(dtype=wp.vec2f, ndim=2), + gear_ratio_scaled: wp.array(dtype=wp.float32, ndim=2), + threshold: float, + inv_range: float, + out: wp.array(dtype=wp.float32), +): + i = wp.tid() + n_joints = joint_pos.shape[1] + s = float(0.0) + for j in range(n_joints): + lim = soft_limits[i, j] + lower = lim.x + upper = lim.y + mid = (lower + upper) * 0.5 + half_range = (upper - lower) * 0.5 + scaled = float(0.0) + if half_range > 0.0: + scaled = (joint_pos[i, j] - mid) / half_range + abs_scaled = wp.abs(scaled) + if abs_scaled > threshold: + violation = (abs_scaled - threshold) * inv_range + s += violation * gear_ratio_scaled[i, j] + out[i] = s + + +class joint_pos_limits_penalty_ratio(ManagerTermBase): + """Penalty for violating joint position limits weighted by the gear ratio.""" + + def __init__(self, cfg: RewardTermCfg, env: ManagerBasedRLEnv): + asset_cfg = cfg.params.get("asset_cfg", SceneEntityCfg("robot")) + asset: Articulation = env.scene[asset_cfg.name] + + # resolve the gear ratio for each joint (torch in __init__ is fine) + gear_ratio = torch.ones(env.num_envs, asset.num_joints, device=env.device) + index_list, _, value_list = string_utils.resolve_matching_names_values( + cfg.params["gear_ratio"], asset.joint_names + ) + gear_ratio[:, index_list] = torch.tensor(value_list, device=env.device) + gear_ratio_scaled = gear_ratio / torch.max(gear_ratio) + self._gear_ratio_scaled_wp = wp.from_torch(gear_ratio_scaled) + + def __call__( + self, + env: ManagerBasedRLEnv, + out, + threshold: float, + gear_ratio: dict[str, float], + asset_cfg: SceneEntityCfg = SceneEntityCfg("robot"), + ) -> None: + asset: Articulation = env.scene[asset_cfg.name] + wp.launch( + kernel=_joint_pos_limits_penalty_ratio_kernel, + dim=env.num_envs, + inputs=[ + asset.data.joint_pos.warp, + asset.data.soft_joint_pos_limits.warp, + self._gear_ratio_scaled_wp, + threshold, + 1.0 / (1.0 - threshold), + out, + ], + device=env.device, + ) + + +@wp.kernel +def _power_consumption_kernel( + action: wp.array(dtype=wp.float32, ndim=2), + joint_vel: wp.array(dtype=wp.float32, ndim=2), + gear_ratio_scaled: wp.array(dtype=wp.float32, ndim=2), + out: wp.array(dtype=wp.float32), +): + i = wp.tid() + n_joints = action.shape[1] + s = float(0.0) + for j in range(n_joints): + s += wp.abs(action[i, j] * joint_vel[i, j] * gear_ratio_scaled[i, j]) + out[i] = s + + +class power_consumption(ManagerTermBase): + """Penalty for the power consumed by the actions to the environment.""" + + def __init__(self, cfg: RewardTermCfg, env: ManagerBasedRLEnv): + asset_cfg = cfg.params.get("asset_cfg", SceneEntityCfg("robot")) + asset: Articulation = env.scene[asset_cfg.name] + + # resolve the gear ratio for each joint (torch in __init__ is fine) + gear_ratio = torch.ones(env.num_envs, asset.num_joints, device=env.device) + index_list, _, value_list = string_utils.resolve_matching_names_values( + cfg.params["gear_ratio"], asset.joint_names + ) + gear_ratio[:, index_list] = torch.tensor(value_list, device=env.device) + gear_ratio_scaled = gear_ratio / torch.max(gear_ratio) + self._gear_ratio_scaled_wp = wp.from_torch(gear_ratio_scaled) + + def __call__( + self, + env: ManagerBasedRLEnv, + out, + gear_ratio: dict[str, float], + asset_cfg: SceneEntityCfg = SceneEntityCfg("robot"), + ) -> None: + asset: Articulation = env.scene[asset_cfg.name] + wp.launch( + kernel=_power_consumption_kernel, + dim=env.num_envs, + inputs=[env.action_manager.action, asset.data.joint_vel.warp, self._gear_ratio_scaled_wp, out], + device=env.device, + ) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/__init__.py new file mode 100644 index 000000000000..0660d38f0658 --- /dev/null +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/__init__.py @@ -0,0 +1,6 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Locomotion experimental task registrations (manager-based).""" diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/__init__.py new file mode 100644 index 000000000000..0857176a3fc7 --- /dev/null +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/__init__.py @@ -0,0 +1,6 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Velocity locomotion experimental task registrations (manager-based).""" diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/__init__.py new file mode 100644 index 000000000000..26f3257daef4 --- /dev/null +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/__init__.py @@ -0,0 +1,9 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Configurations for velocity-based locomotion environments.""" + +# We leave this file empty since we don't want to expose any configs in this package directly. +# We still need this file to import the "config" module in the parent package. diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/a1/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/a1/__init__.py new file mode 100644 index 000000000000..6c79524e8532 --- /dev/null +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/a1/__init__.py @@ -0,0 +1,37 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +import gymnasium as gym + +# Reuse agent configs from the stable task package. +from isaaclab_tasks.manager_based.locomotion.velocity.config.a1 import agents + +## +# Register Gym environments. +## + +gym.register( + id="Isaac-Velocity-Flat-Unitree-A1-Warp-v0", + entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": f"{__name__}.flat_env_cfg:UnitreeA1FlatEnvCfg", + "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:UnitreeA1FlatPPORunnerCfg", + "skrl_cfg_entry_point": f"{agents.__name__}:skrl_flat_ppo_cfg.yaml", + "sb3_cfg_entry_point": f"{agents.__name__}:sb3_ppo_cfg.yaml", + }, +) + +gym.register( + id="Isaac-Velocity-Flat-Unitree-A1-Warp-Play-v0", + entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": f"{__name__}.flat_env_cfg:UnitreeA1FlatEnvCfg_PLAY", + "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:UnitreeA1FlatPPORunnerCfg", + "skrl_cfg_entry_point": f"{agents.__name__}:skrl_flat_ppo_cfg.yaml", + "sb3_cfg_entry_point": f"{agents.__name__}:sb3_ppo_cfg.yaml", + }, +) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/a1/flat_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/a1/flat_env_cfg.py new file mode 100644 index 000000000000..b27f8098d629 --- /dev/null +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/a1/flat_env_cfg.py @@ -0,0 +1,60 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg + +from isaaclab.sim import SimulationCfg +from isaaclab.utils import configclass + +from .rough_env_cfg import UnitreeA1RoughEnvCfg + + +@configclass +class UnitreeA1FlatEnvCfg(UnitreeA1RoughEnvCfg): + sim: SimulationCfg = SimulationCfg( + physics=NewtonCfg( + solver_cfg=MJWarpSolverCfg( + njmax=60, + nconmax=30, + cone="pyramidal", + impratio=1, + integrator="implicitfast", + ), + num_substeps=1, + debug_mode=False, + ) + ) + + def __post_init__(self): + # post init of parent + super().__post_init__() + + # override rewards + self.rewards.flat_orientation_l2.weight = -2.5 + self.rewards.feet_air_time.weight = 0.25 + + # change terrain to flat + self.scene.terrain.terrain_type = "plane" + self.scene.terrain.terrain_generator = None + # no height scan + # self.scene.height_scanner = None + # self.observations.policy.height_scan = None + # no terrain curriculum + self.curriculum.terrain_levels = None + + +class UnitreeA1FlatEnvCfg_PLAY(UnitreeA1FlatEnvCfg): + def __post_init__(self) -> None: + # post init of parent + super().__post_init__() + + # make a smaller scene for play + self.scene.num_envs = 50 + self.scene.env_spacing = 2.5 + # disable randomization for play + self.observations.policy.enable_corruption = False + # remove random pushing event + self.events.base_external_force_torque = None + self.events.push_robot = None diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/a1/rough_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/a1/rough_env_cfg.py new file mode 100644 index 000000000000..03aec88a4018 --- /dev/null +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/a1/rough_env_cfg.py @@ -0,0 +1,91 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from isaaclab_experimental.managers import TerminationTermCfg as DoneTerm + +from isaaclab.utils import configclass + +import isaaclab_tasks_experimental.manager_based.locomotion.velocity.mdp as mdp +from isaaclab_tasks_experimental.manager_based.locomotion.velocity.velocity_env_cfg import ( + LocomotionVelocityRoughEnvCfg, + TerminationsCfg, +) + +from isaaclab_assets.robots.unitree import UNITREE_A1_CFG # isort: skip + + +class TerminationsCfg_A1(TerminationsCfg): + base_too_low = DoneTerm(func=mdp.root_height_below_minimum, params={"minimum_height": 0.2}) + + +@configclass +class UnitreeA1RoughEnvCfg(LocomotionVelocityRoughEnvCfg): + terminations: TerminationsCfg_A1 = TerminationsCfg_A1() + + def __post_init__(self): + # post init of parent + super().__post_init__() + + self.scene.robot = UNITREE_A1_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") + self.scene.terrain.terrain_generator.sub_terrains["boxes"].grid_height_range = (0.025, 0.1) + self.scene.terrain.terrain_generator.sub_terrains["random_rough"].noise_range = (0.01, 0.06) + self.scene.terrain.terrain_generator.sub_terrains["random_rough"].noise_step = 0.01 + + # reduce action scale + self.actions.joint_pos.scale = 0.25 + + # event + self.events.push_robot = None + # TODO: TEMPORARILY DISABLED - adding this causes NaNs in the simulation + # self.events.add_base_mass.params["mass_distribution_params"] = (-1.0, 3.0) + # self.events.add_base_mass.params["asset_cfg"].body_names = "trunk" + self.events.base_external_force_torque.params["asset_cfg"].body_names = "trunk" + self.events.reset_robot_joints.params["position_range"] = (1.0, 1.0) + self.events.reset_base.params = { + "pose_range": {"x": (-0.5, 0.5), "y": (-0.5, 0.5), "yaw": (-3.14, 3.14)}, + "velocity_range": { + "x": (0.0, 0.0), + "y": (0.0, 0.0), + "z": (0.0, 0.0), + "roll": (0.0, 0.0), + "pitch": (0.0, 0.0), + "yaw": (0.0, 0.0), + }, + } + self.events.base_com = None + + # rewards + self.rewards.feet_air_time.params["sensor_cfg"].body_names = ".*_foot" + self.rewards.feet_air_time.weight = 0.01 + self.rewards.undesired_contacts.params["sensor_cfg"].body_names = ".*thigh" + self.rewards.dof_torques_l2.weight = -0.0002 + self.rewards.track_lin_vel_xy_exp.weight = 1.5 + self.rewards.track_ang_vel_z_exp.weight = 0.75 + self.rewards.dof_acc_l2.weight = -2.5e-7 + self.terminations.base_contact.params["sensor_cfg"].body_names = "trunk" + + +@configclass +class UnitreeA1RoughEnvCfg_PLAY(UnitreeA1RoughEnvCfg): + def __post_init__(self): + # post init of parent + super().__post_init__() + + # make a smaller scene for play + self.scene.num_envs = 50 + self.scene.env_spacing = 2.5 + # spawn the robot randomly in the grid (instead of their terrain levels) + self.scene.terrain.max_init_terrain_level = None + # reduce the number of terrains to save memory + if self.scene.terrain.terrain_generator is not None: + self.scene.terrain.terrain_generator.num_rows = 5 + self.scene.terrain.terrain_generator.num_cols = 5 + self.scene.terrain.terrain_generator.curriculum = False + + # disable randomization for play + self.observations.policy.enable_corruption = False + # remove random pushing event + self.events.base_external_force_torque = None + self.events.push_robot = None diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_b/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_b/__init__.py new file mode 100644 index 000000000000..cbbf5290e82a --- /dev/null +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_b/__init__.py @@ -0,0 +1,37 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +import gymnasium as gym + +# Reuse agent configs from the stable task package. +from isaaclab_tasks.manager_based.locomotion.velocity.config.anymal_b import agents + +## +# Register Gym environments. +## + +gym.register( + id="Isaac-Velocity-Flat-Anymal-B-Warp-v0", + entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": f"{__name__}.flat_env_cfg:AnymalBFlatEnvCfg", + "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:AnymalBFlatPPORunnerCfg", + "rsl_rl_with_symmetry_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:AnymalBFlatPPORunnerWithSymmetryCfg", + "skrl_cfg_entry_point": f"{agents.__name__}:skrl_flat_ppo_cfg.yaml", + }, +) + +gym.register( + id="Isaac-Velocity-Flat-Anymal-B-Warp-Play-v0", + entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": f"{__name__}.flat_env_cfg:AnymalBFlatEnvCfg_PLAY", + "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:AnymalBFlatPPORunnerCfg", + "rsl_rl_with_symmetry_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:AnymalBFlatPPORunnerWithSymmetryCfg", + "skrl_cfg_entry_point": f"{agents.__name__}:skrl_flat_ppo_cfg.yaml", + }, +) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_b/flat_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_b/flat_env_cfg.py new file mode 100644 index 000000000000..28c0dc5c26b6 --- /dev/null +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_b/flat_env_cfg.py @@ -0,0 +1,60 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg + +from isaaclab.sim import SimulationCfg +from isaaclab.utils import configclass + +from .rough_env_cfg import AnymalBRoughEnvCfg + + +@configclass +class AnymalBFlatEnvCfg(AnymalBRoughEnvCfg): + sim: SimulationCfg = SimulationCfg( + physics=NewtonCfg( + solver_cfg=MJWarpSolverCfg( + njmax=75, + nconmax=15, + cone="elliptic", + impratio=100, + integrator="implicitfast", + ), + num_substeps=1, + debug_mode=False, + ) + ) + + def __post_init__(self): + # post init of parent + super().__post_init__() + + # override rewards + self.rewards.flat_orientation_l2.weight = -5.0 + self.rewards.dof_torques_l2.weight = -2.5e-5 + self.rewards.feet_air_time.weight = 0.5 + # change terrain to flat + self.scene.terrain.terrain_type = "plane" + self.scene.terrain.terrain_generator = None + # no height scan + self.scene.height_scanner = None + self.observations.policy.height_scan = None + # no terrain curriculum + self.curriculum.terrain_levels = None + + +class AnymalBFlatEnvCfg_PLAY(AnymalBFlatEnvCfg): + def __post_init__(self) -> None: + # post init of parent + super().__post_init__() + + # make a smaller scene for play + self.scene.num_envs = 50 + self.scene.env_spacing = 2.5 + # disable randomization for play + self.observations.policy.enable_corruption = False + # remove random pushing event + self.events.base_external_force_torque = None + self.events.push_robot = None diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_b/rough_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_b/rough_env_cfg.py new file mode 100644 index 000000000000..9811356ef220 --- /dev/null +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_b/rough_env_cfg.py @@ -0,0 +1,34 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from isaaclab.utils import configclass + +from isaaclab_tasks_experimental.manager_based.locomotion.velocity.velocity_env_cfg import LocomotionVelocityRoughEnvCfg + +from isaaclab_assets import ANYMAL_B_CFG # isort: skip + + +@configclass +class AnymalBRoughEnvCfg(LocomotionVelocityRoughEnvCfg): + def __post_init__(self): + super().__post_init__() + self.scene.robot = ANYMAL_B_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") + self.manager_call_max_mode = {"Scene": 1} + + +@configclass +class AnymalBRoughEnvCfg_PLAY(AnymalBRoughEnvCfg): + def __post_init__(self): + super().__post_init__() + self.scene.num_envs = 50 + self.scene.env_spacing = 2.5 + self.scene.terrain.max_init_terrain_level = None + if self.scene.terrain.terrain_generator is not None: + self.scene.terrain.terrain_generator.num_rows = 5 + self.scene.terrain.terrain_generator.num_cols = 5 + self.scene.terrain.terrain_generator.curriculum = False + self.observations.policy.enable_corruption = False + self.events.base_external_force_torque = None + self.events.push_robot = None diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_c/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_c/__init__.py new file mode 100644 index 000000000000..318b13cc4707 --- /dev/null +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_c/__init__.py @@ -0,0 +1,39 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +import gymnasium as gym + +# Reuse agent configs from the stable task package. +from isaaclab_tasks.manager_based.locomotion.velocity.config.anymal_c import agents + +## +# Register Gym environments. +## + +gym.register( + id="Isaac-Velocity-Flat-Anymal-C-Warp-v0", + entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": f"{__name__}.flat_env_cfg:AnymalCFlatEnvCfg", + "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:AnymalCFlatPPORunnerCfg", + "rsl_rl_with_symmetry_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:AnymalCFlatPPORunnerWithSymmetryCfg", + "rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_flat_ppo_cfg.yaml", + "skrl_cfg_entry_point": f"{agents.__name__}:skrl_flat_ppo_cfg.yaml", + }, +) + +gym.register( + id="Isaac-Velocity-Flat-Anymal-C-Warp-Play-v0", + entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": f"{__name__}.flat_env_cfg:AnymalCFlatEnvCfg_PLAY", + "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:AnymalCFlatPPORunnerCfg", + "rsl_rl_with_symmetry_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:AnymalCFlatPPORunnerWithSymmetryCfg", + "rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_flat_ppo_cfg.yaml", + "skrl_cfg_entry_point": f"{agents.__name__}:skrl_flat_ppo_cfg.yaml", + }, +) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_c/flat_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_c/flat_env_cfg.py new file mode 100644 index 000000000000..e82cf9559d61 --- /dev/null +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_c/flat_env_cfg.py @@ -0,0 +1,52 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg + +from isaaclab.sim import SimulationCfg +from isaaclab.utils import configclass + +from .rough_env_cfg import AnymalCRoughEnvCfg + + +@configclass +class AnymalCFlatEnvCfg(AnymalCRoughEnvCfg): + sim: SimulationCfg = SimulationCfg( + physics=NewtonCfg( + solver_cfg=MJWarpSolverCfg( + njmax=120, + nconmax=15, + cone="elliptic", + impratio=100, + integrator="implicitfast", + ), + num_substeps=1, + debug_mode=False, + ) + ) + + def __post_init__(self): + # post init of parent + super().__post_init__() + + # override rewards + self.rewards.flat_orientation_l2.weight = -5.0 + self.rewards.dof_torques_l2.weight = -2.5e-5 + self.rewards.feet_air_time.weight = 0.5 + # change terrain to flat + self.scene.terrain.terrain_type = "plane" + self.scene.terrain.terrain_generator = None + # no terrain curriculum + self.curriculum.terrain_levels = None + + +class AnymalCFlatEnvCfg_PLAY(AnymalCFlatEnvCfg): + def __post_init__(self) -> None: + super().__post_init__() + self.scene.num_envs = 50 + self.scene.env_spacing = 2.5 + self.observations.policy.enable_corruption = False + self.events.base_external_force_torque = None + self.events.push_robot = None diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_c/rough_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_c/rough_env_cfg.py new file mode 100644 index 000000000000..36af75613c07 --- /dev/null +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_c/rough_env_cfg.py @@ -0,0 +1,40 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from isaaclab.utils import configclass + +from isaaclab_tasks_experimental.manager_based.locomotion.velocity.velocity_env_cfg import LocomotionVelocityRoughEnvCfg + +## +# Pre-defined configs +## +from isaaclab_assets.robots.anymal import ANYMAL_C_CFG # isort: skip + + +@configclass +class AnymalCRoughEnvCfg(LocomotionVelocityRoughEnvCfg): + def __post_init__(self): + # post init of parent + super().__post_init__() + # switch robot to anymal-c + self.scene.robot = ANYMAL_C_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") + self.scene.robot.actuators["legs"].armature = 0.01 + self.manager_call_max_mode = {"Scene": 1} + + +@configclass +class AnymalCRoughEnvCfg_PLAY(AnymalCRoughEnvCfg): + def __post_init__(self): + super().__post_init__() + self.scene.num_envs = 50 + self.scene.env_spacing = 2.5 + self.scene.terrain.max_init_terrain_level = None + if self.scene.terrain.terrain_generator is not None: + self.scene.terrain.terrain_generator.num_rows = 5 + self.scene.terrain.terrain_generator.num_cols = 5 + self.scene.terrain.terrain_generator.curriculum = False + self.observations.policy.enable_corruption = False + self.events.base_external_force_torque = None + self.events.push_robot = None diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_d/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_d/__init__.py new file mode 100644 index 000000000000..e5e75d19dc2d --- /dev/null +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_d/__init__.py @@ -0,0 +1,60 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +import gymnasium as gym + +# Reuse agent configs from the stable task package. +from isaaclab_tasks.manager_based.locomotion.velocity.config.anymal_d import agents + +## +# Register Gym environments. +## + +# Rough env disabled: requires isaaclab_physx which is not yet available on dev/newton. +# The package exists on upstream/develop (commit 308400f1d35) but has not been merged. +# Re-enable once dev/newton picks up isaaclab_physx. +# gym.register( +# id="Isaac-Velocity-Rough-Anymal-D-Warp-v0", +# entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", +# disable_env_checker=True, +# kwargs={ +# "env_cfg_entry_point": f"{__name__}.rough_env_cfg:AnymalDRoughEnvCfg", +# "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:AnymalDRoughPPORunnerCfg", +# "skrl_cfg_entry_point": f"{agents.__name__}:skrl_rough_ppo_cfg.yaml", +# }, +# ) + +# gym.register( +# id="Isaac-Velocity-Rough-Anymal-D-Warp-Play-v0", +# entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", +# disable_env_checker=True, +# kwargs={ +# "env_cfg_entry_point": f"{__name__}.rough_env_cfg:AnymalDRoughEnvCfg_PLAY", +# "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:AnymalDRoughPPORunnerCfg", +# "skrl_cfg_entry_point": f"{agents.__name__}:skrl_rough_ppo_cfg.yaml", +# }, +# ) + +gym.register( + id="Isaac-Velocity-Flat-Anymal-D-Warp-v0", + entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": f"{__name__}.flat_env_cfg:AnymalDFlatEnvCfg", + "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:AnymalDFlatPPORunnerCfg", + "skrl_cfg_entry_point": f"{agents.__name__}:skrl_flat_ppo_cfg.yaml", + }, +) + +gym.register( + id="Isaac-Velocity-Flat-Anymal-D-Warp-Play-v0", + entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": f"{__name__}.flat_env_cfg:AnymalDFlatEnvCfg_PLAY", + "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:AnymalDFlatPPORunnerCfg", + "skrl_cfg_entry_point": f"{agents.__name__}:skrl_flat_ppo_cfg.yaml", + }, +) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_d/flat_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_d/flat_env_cfg.py new file mode 100644 index 000000000000..1f98c1b56120 --- /dev/null +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_d/flat_env_cfg.py @@ -0,0 +1,46 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg + +from isaaclab.sim import SimulationCfg +from isaaclab.utils import configclass + +from .rough_env_cfg import AnymalDRoughEnvCfg + + +@configclass +class AnymalDFlatEnvCfg(AnymalDRoughEnvCfg): + sim: SimulationCfg = SimulationCfg( + physics=NewtonCfg( + solver_cfg=MJWarpSolverCfg( + njmax=60, + nconmax=25, + cone="elliptic", + impratio=100.0, + ), + num_substeps=1, + debug_mode=False, + ) + ) + + def __post_init__(self): + super().__post_init__() + self.rewards.flat_orientation_l2.weight = -5.0 + self.rewards.dof_torques_l2.weight = -2.5e-5 + self.rewards.feet_air_time.weight = 0.5 + self.scene.terrain.terrain_type = "plane" + self.scene.terrain.terrain_generator = None + self.curriculum.terrain_levels = None + + +class AnymalDFlatEnvCfg_PLAY(AnymalDFlatEnvCfg): + def __post_init__(self) -> None: + super().__post_init__() + self.scene.num_envs = 50 + self.scene.env_spacing = 2.5 + self.observations.policy.enable_corruption = False + self.events.base_external_force_torque = None + self.events.push_robot = None diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_d/rough_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_d/rough_env_cfg.py new file mode 100644 index 000000000000..1cafa006ee64 --- /dev/null +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_d/rough_env_cfg.py @@ -0,0 +1,37 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from isaaclab.utils import configclass + +from isaaclab_tasks_experimental.manager_based.locomotion.velocity.velocity_env_cfg import LocomotionVelocityRoughEnvCfg + +## +# Pre-defined configs +## +from isaaclab_assets.robots.anymal import ANYMAL_D_CFG # isort: skip + + +@configclass +class AnymalDRoughEnvCfg(LocomotionVelocityRoughEnvCfg): + def __post_init__(self): + super().__post_init__() + self.scene.robot = ANYMAL_D_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") + self.manager_call_max_mode = {"Scene": 1} + + +@configclass +class AnymalDRoughEnvCfg_PLAY(AnymalDRoughEnvCfg): + def __post_init__(self): + super().__post_init__() + self.scene.num_envs = 50 + self.scene.env_spacing = 2.5 + self.scene.terrain.max_init_terrain_level = None + if self.scene.terrain.terrain_generator is not None: + self.scene.terrain.terrain_generator.num_rows = 5 + self.scene.terrain.terrain_generator.num_cols = 5 + self.scene.terrain.terrain_generator.curriculum = False + self.observations.policy.enable_corruption = False + self.events.base_external_force_torque = None + self.events.push_robot = None diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/cassie/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/cassie/__init__.py new file mode 100644 index 000000000000..4d9d4a77883a --- /dev/null +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/cassie/__init__.py @@ -0,0 +1,35 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +import gymnasium as gym + +# Reuse agent configs from the stable task package. +from isaaclab_tasks.manager_based.locomotion.velocity.config.cassie import agents + +## +# Register Gym environments. +## + +gym.register( + id="Isaac-Velocity-Flat-Cassie-Warp-v0", + entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": f"{__name__}.flat_env_cfg:CassieFlatEnvCfg", + "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:CassieFlatPPORunnerCfg", + "skrl_cfg_entry_point": f"{agents.__name__}:skrl_flat_ppo_cfg.yaml", + }, +) + +gym.register( + id="Isaac-Velocity-Flat-Cassie-Warp-Play-v0", + entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": f"{__name__}.flat_env_cfg:CassieFlatEnvCfg_PLAY", + "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:CassieFlatPPORunnerCfg", + "skrl_cfg_entry_point": f"{agents.__name__}:skrl_flat_ppo_cfg.yaml", + }, +) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/cassie/flat_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/cassie/flat_env_cfg.py new file mode 100644 index 000000000000..bcc670cf3788 --- /dev/null +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/cassie/flat_env_cfg.py @@ -0,0 +1,45 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg + +from isaaclab.sim import SimulationCfg +from isaaclab.utils import configclass + +from .rough_env_cfg import CassieRoughEnvCfg + + +@configclass +class CassieFlatEnvCfg(CassieRoughEnvCfg): + sim: SimulationCfg = SimulationCfg( + physics=NewtonCfg( + solver_cfg=MJWarpSolverCfg( + njmax=52, + nconmax=15, + cone="pyramidal", + impratio=1, + integrator="implicitfast", + ), + num_substeps=1, + debug_mode=False, + ) + ) + + def __post_init__(self): + super().__post_init__() + self.rewards.flat_orientation_l2.weight = -2.5 + self.rewards.feet_air_time.weight = 5.0 + self.rewards.joint_deviation_hip.params["asset_cfg"].joint_names = ["hip_rotation_.*"] + self.scene.terrain.terrain_type = "plane" + self.scene.terrain.terrain_generator = None + self.curriculum.terrain_levels = None + + +class CassieFlatEnvCfg_PLAY(CassieFlatEnvCfg): + def __post_init__(self) -> None: + super().__post_init__() + self.scene.num_envs = 50 + self.scene.env_spacing = 2.5 + self.observations.policy.enable_corruption = False diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/cassie/rough_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/cassie/rough_env_cfg.py new file mode 100644 index 000000000000..43341babeb3d --- /dev/null +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/cassie/rough_env_cfg.py @@ -0,0 +1,96 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from isaaclab_experimental.managers import RewardTermCfg as RewTerm +from isaaclab_experimental.managers import SceneEntityCfg + +from isaaclab.utils import configclass + +import isaaclab_tasks_experimental.manager_based.locomotion.velocity.mdp as mdp +from isaaclab_tasks_experimental.manager_based.locomotion.velocity.velocity_env_cfg import ( + LocomotionVelocityRoughEnvCfg, + RewardsCfg, +) + +from isaaclab_assets.robots.cassie import CASSIE_CFG # isort: skip + + +@configclass +class CassieRewardsCfg(RewardsCfg): + termination_penalty = RewTerm(func=mdp.is_terminated, weight=-200.0) + feet_air_time = RewTerm( + func=mdp.feet_air_time_positive_biped, + weight=2.5, + params={ + "sensor_cfg": SceneEntityCfg("contact_forces", body_names=".*toe"), + "command_name": "base_velocity", + "threshold": 0.3, + }, + ) + joint_deviation_hip = RewTerm( + func=mdp.joint_deviation_l1, + weight=-0.2, + params={"asset_cfg": SceneEntityCfg("robot", joint_names=["hip_abduction_.*", "hip_rotation_.*"])}, + ) + joint_deviation_toes = RewTerm( + func=mdp.joint_deviation_l1, + weight=-0.2, + params={"asset_cfg": SceneEntityCfg("robot", joint_names=["toe_joint_.*"])}, + ) + dof_pos_limits = RewTerm( + func=mdp.joint_pos_limits, + weight=-1.0, + params={"asset_cfg": SceneEntityCfg("robot", joint_names="toe_joint_.*")}, + ) + + +@configclass +class CassieRoughEnvCfg(LocomotionVelocityRoughEnvCfg): + rewards: CassieRewardsCfg = CassieRewardsCfg() + + def __post_init__(self): + super().__post_init__() + self.scene.robot = CASSIE_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") + self.actions.joint_pos.scale = 0.5 + self.events.push_robot = None + # TODO: TEMPORARILY DISABLED - adding this causes NaNs in the simulation + # self.events.add_base_mass = None + self.events.reset_robot_joints.params["position_range"] = (1.0, 1.0) + self.events.base_external_force_torque.params["asset_cfg"].body_names = [".*pelvis"] + self.events.reset_base.params = { + "pose_range": {"x": (-0.5, 0.5), "y": (-0.5, 0.5), "yaw": (-3.14, 3.14)}, + "velocity_range": { + "x": (0.0, 0.0), + "y": (0.0, 0.0), + "z": (0.0, 0.0), + "roll": (0.0, 0.0), + "pitch": (0.0, 0.0), + "yaw": (0.0, 0.0), + }, + } + self.events.base_com = None + self.terminations.base_contact.params["sensor_cfg"].body_names = [".*pelvis"] + self.rewards.undesired_contacts = None + self.rewards.dof_torques_l2.weight = -5.0e-6 + self.rewards.track_lin_vel_xy_exp.weight = 2.0 + self.rewards.track_ang_vel_z_exp.weight = 1.0 + self.rewards.action_rate_l2.weight *= 1.5 + self.rewards.dof_acc_l2.weight *= 1.5 + + +@configclass +class CassieRoughEnvCfg_PLAY(CassieRoughEnvCfg): + def __post_init__(self): + super().__post_init__() + self.scene.num_envs = 50 + self.scene.env_spacing = 2.5 + self.scene.terrain.max_init_terrain_level = None + if self.scene.terrain.terrain_generator is not None: + self.scene.terrain.terrain_generator.num_rows = 5 + self.scene.terrain.terrain_generator.num_cols = 5 + self.scene.terrain.terrain_generator.curriculum = False + self.observations.policy.enable_corruption = False + self.events.base_external_force_torque = None + self.events.push_robot = None diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/g1/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/g1/__init__.py new file mode 100644 index 000000000000..83bdf047a488 --- /dev/null +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/g1/__init__.py @@ -0,0 +1,58 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +import gymnasium as gym + +# Reuse agent configs from the stable task package. +from isaaclab_tasks.manager_based.locomotion.velocity.config.g1 import agents + +## +# Register Gym environments. +## + +# gym.register( +# id="Isaac-Velocity-Rough-G1-Warp-v0", +# entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", +# disable_env_checker=True, +# kwargs={ +# "env_cfg_entry_point": f"{__name__}.rough_env_cfg:G1RoughEnvCfg", +# "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:G1RoughPPORunnerCfg", +# "skrl_cfg_entry_point": f"{agents.__name__}:skrl_rough_ppo_cfg.yaml", +# }, +# ) + + +# gym.register( +# id="Isaac-Velocity-Rough-G1-Warp-Play-v0", +# entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", +# disable_env_checker=True, +# kwargs={ +# "env_cfg_entry_point": f"{__name__}.rough_env_cfg:G1RoughEnvCfg_PLAY", +# "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:G1RoughPPORunnerCfg", +# "skrl_cfg_entry_point": f"{agents.__name__}:skrl_rough_ppo_cfg.yaml", +# }, +# ) + +gym.register( + id="Isaac-Velocity-Flat-G1-Warp-v0", + entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": f"{__name__}.flat_env_cfg:G1FlatEnvCfg", + "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:G1FlatPPORunnerCfg", + "skrl_cfg_entry_point": f"{agents.__name__}:skrl_flat_ppo_cfg.yaml", + }, +) + +gym.register( + id="Isaac-Velocity-Flat-G1-Warp-Play-v0", + entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": f"{__name__}.flat_env_cfg:G1FlatEnvCfg_PLAY", + "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:G1FlatPPORunnerCfg", + "skrl_cfg_entry_point": f"{agents.__name__}:skrl_flat_ppo_cfg.yaml", + }, +) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/g1/flat_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/g1/flat_env_cfg.py new file mode 100644 index 000000000000..3d9047a98506 --- /dev/null +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/g1/flat_env_cfg.py @@ -0,0 +1,58 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from isaaclab_experimental.managers import SceneEntityCfg +from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg + +from isaaclab.sim import SimulationCfg +from isaaclab.utils import configclass + +from .rough_env_cfg import G1RoughEnvCfg + + +@configclass +class G1FlatEnvCfg(G1RoughEnvCfg): + sim: SimulationCfg = SimulationCfg( + physics=NewtonCfg( + solver_cfg=MJWarpSolverCfg( + njmax=95, + nconmax=10, + cone="pyramidal", + impratio=1, + integrator="implicitfast", + ), + num_substeps=1, + debug_mode=False, + ) + ) + + def __post_init__(self): + super().__post_init__() + self.scene.terrain.terrain_type = "plane" + self.scene.terrain.terrain_generator = None + self.curriculum.terrain_levels = None + self.rewards.track_ang_vel_z_exp.weight = 1.0 + self.rewards.lin_vel_z_l2.weight = -0.2 + self.rewards.action_rate_l2.weight = -0.005 + self.rewards.dof_acc_l2.weight = -1.0e-7 + self.rewards.feet_air_time.weight = 0.75 + self.rewards.feet_air_time.params["threshold"] = 0.4 + self.rewards.dof_torques_l2.weight = -2.0e-6 + self.rewards.dof_torques_l2.params["asset_cfg"] = SceneEntityCfg( + "robot", joint_names=[".*_hip_.*", ".*_knee_joint"] + ) + self.commands.base_velocity.ranges.lin_vel_x = (0.0, 1.0) + self.commands.base_velocity.ranges.lin_vel_y = (-0.5, 0.5) + self.commands.base_velocity.ranges.ang_vel_z = (-1.0, 1.0) + + +class G1FlatEnvCfg_PLAY(G1FlatEnvCfg): + def __post_init__(self) -> None: + super().__post_init__() + self.scene.num_envs = 50 + self.scene.env_spacing = 2.5 + self.observations.policy.enable_corruption = False + self.events.base_external_force_torque = None + self.events.push_robot = None diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/g1/rough_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/g1/rough_env_cfg.py new file mode 100644 index 000000000000..db4cc159e4c5 --- /dev/null +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/g1/rough_env_cfg.py @@ -0,0 +1,178 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from isaaclab_experimental.managers import RewardTermCfg as RewTerm +from isaaclab_experimental.managers import SceneEntityCfg + +from isaaclab.utils import configclass + +import isaaclab_tasks_experimental.manager_based.locomotion.velocity.mdp as mdp +from isaaclab_tasks_experimental.manager_based.locomotion.velocity.velocity_env_cfg import ( + LocomotionVelocityRoughEnvCfg, + RewardsCfg, +) + +## +# Pre-defined configs +## +from isaaclab_assets import G1_MINIMAL_CFG # isort: skip + + +@configclass +class G1Rewards(RewardsCfg): + """Reward terms for the MDP.""" + + termination_penalty = RewTerm(func=mdp.is_terminated, weight=-200.0) + track_lin_vel_xy_exp = RewTerm( + func=mdp.track_lin_vel_xy_yaw_frame_exp, + weight=1.0, + params={"command_name": "base_velocity", "std": 0.5}, + ) + track_ang_vel_z_exp = RewTerm( + func=mdp.track_ang_vel_z_world_exp, weight=2.0, params={"command_name": "base_velocity", "std": 0.5} + ) + feet_air_time = RewTerm( + func=mdp.feet_air_time_positive_biped, + weight=0.25, + params={ + "command_name": "base_velocity", + "sensor_cfg": SceneEntityCfg("contact_forces", body_names=".*_ankle_roll_link"), + "threshold": 0.4, + }, + ) + feet_slide = RewTerm( + func=mdp.feet_slide, + weight=-0.1, + params={ + "sensor_cfg": SceneEntityCfg("contact_forces", body_names=".*_ankle_roll_link"), + "asset_cfg": SceneEntityCfg("robot", body_names=".*_ankle_roll_link"), + }, + ) + dof_pos_limits = RewTerm( + func=mdp.joint_pos_limits, + weight=-1.0, + params={"asset_cfg": SceneEntityCfg("robot", joint_names=[".*_ankle_pitch_joint", ".*_ankle_roll_joint"])}, + ) + joint_deviation_hip = RewTerm( + func=mdp.joint_deviation_l1, + weight=-0.1, + params={"asset_cfg": SceneEntityCfg("robot", joint_names=[".*_hip_yaw_joint", ".*_hip_roll_joint"])}, + ) + joint_deviation_arms = RewTerm( + func=mdp.joint_deviation_l1, + weight=-0.1, + params={ + "asset_cfg": SceneEntityCfg( + "robot", + joint_names=[ + ".*_shoulder_pitch_joint", + ".*_shoulder_roll_joint", + ".*_shoulder_yaw_joint", + ".*_elbow_pitch_joint", + ".*_elbow_roll_joint", + ], + ) + }, + ) + joint_deviation_fingers = RewTerm( + func=mdp.joint_deviation_l1, + weight=-0.05, + params={ + "asset_cfg": SceneEntityCfg( + "robot", + joint_names=[ + ".*_five_joint", + ".*_three_joint", + ".*_six_joint", + ".*_four_joint", + ".*_zero_joint", + ".*_one_joint", + ".*_two_joint", + ], + ) + }, + ) + joint_deviation_torso = RewTerm( + func=mdp.joint_deviation_l1, + weight=-0.1, + params={"asset_cfg": SceneEntityCfg("robot", joint_names="torso_joint")}, + ) + + +@configclass +class G1RoughEnvCfg(LocomotionVelocityRoughEnvCfg): + rewards: G1Rewards = G1Rewards() + + def __post_init__(self): + super().__post_init__() + self.scene.robot = G1_MINIMAL_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") + self.events.push_robot = None + # TODO: TEMPORARILY DISABLED - adding this causes NaNs in the simulation + # self.events.add_base_mass = None + self.events.reset_robot_joints.params["position_range"] = (1.0, 1.0) + self.events.base_external_force_torque.params["asset_cfg"].body_names = ["torso_link"] + self.events.reset_base.params = { + "pose_range": {"x": (-0.5, 0.5), "y": (-0.5, 0.5), "yaw": (-3.14, 3.14)}, + "velocity_range": { + "x": (0.0, 0.0), + "y": (0.0, 0.0), + "z": (0.0, 0.0), + "roll": (0.0, 0.0), + "pitch": (0.0, 0.0), + "yaw": (0.0, 0.0), + }, + } + self.events.base_com = None + + # Rewards + self.rewards.lin_vel_z_l2.weight = 0.0 + self.rewards.undesired_contacts = None + self.rewards.flat_orientation_l2.weight = -1.0 + self.rewards.action_rate_l2.weight = -0.005 + self.rewards.dof_acc_l2.weight = -1.25e-7 + self.rewards.dof_acc_l2.params["asset_cfg"] = SceneEntityCfg( + "robot", joint_names=[".*_hip_.*", ".*_knee_joint"] + ) + self.rewards.dof_torques_l2.weight = -1.5e-7 + self.rewards.dof_torques_l2.params["asset_cfg"] = SceneEntityCfg( + "robot", joint_names=[".*_hip_.*", ".*_knee_joint", ".*_ankle_.*"] + ) + + # Commands + self.commands.base_velocity.ranges.lin_vel_x = (0.0, 1.0) + self.commands.base_velocity.ranges.lin_vel_y = (-0.0, 0.0) + self.commands.base_velocity.ranges.ang_vel_z = (-1.0, 1.0) + + # terminations + self.terminations.base_contact.params["sensor_cfg"].body_names = "torso_link" + + +@configclass +class G1RoughEnvCfg_PLAY(G1RoughEnvCfg): + def __post_init__(self): + # post init of parent + super().__post_init__() + + # make a smaller scene for play + self.scene.num_envs = 50 + self.scene.env_spacing = 2.5 + self.episode_length_s = 40.0 + # spawn the robot randomly in the grid (instead of their terrain levels) + self.scene.terrain.max_init_terrain_level = None + # reduce the number of terrains to save memory + if self.scene.terrain.terrain_generator is not None: + self.scene.terrain.terrain_generator.num_rows = 5 + self.scene.terrain.terrain_generator.num_cols = 5 + self.scene.terrain.terrain_generator.curriculum = False + + self.commands.base_velocity.ranges.lin_vel_x = (1.0, 1.0) + self.commands.base_velocity.ranges.lin_vel_y = (0.0, 0.0) + self.commands.base_velocity.ranges.ang_vel_z = (-1.0, 1.0) + self.commands.base_velocity.ranges.heading = (0.0, 0.0) + # disable randomization for play + self.observations.policy.enable_corruption = False + # remove random pushing + self.events.base_external_force_torque = None + self.events.push_robot = None diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/go1/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/go1/__init__.py new file mode 100644 index 000000000000..038f55740728 --- /dev/null +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/go1/__init__.py @@ -0,0 +1,35 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +import gymnasium as gym + +# Reuse agent configs from the stable task package. +from isaaclab_tasks.manager_based.locomotion.velocity.config.go1 import agents + +## +# Register Gym environments. +## + +gym.register( + id="Isaac-Velocity-Flat-Unitree-Go1-Warp-v0", + entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": f"{__name__}.flat_env_cfg:UnitreeGo1FlatEnvCfg", + "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:UnitreeGo1FlatPPORunnerCfg", + "skrl_cfg_entry_point": f"{agents.__name__}:skrl_flat_ppo_cfg.yaml", + }, +) + +gym.register( + id="Isaac-Velocity-Flat-Unitree-Go1-Warp-Play-v0", + entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": f"{__name__}.flat_env_cfg:UnitreeGo1FlatEnvCfg_PLAY", + "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:UnitreeGo1FlatPPORunnerCfg", + "skrl_cfg_entry_point": f"{agents.__name__}:skrl_flat_ppo_cfg.yaml", + }, +) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/go1/flat_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/go1/flat_env_cfg.py new file mode 100644 index 000000000000..e4fbc73e1d08 --- /dev/null +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/go1/flat_env_cfg.py @@ -0,0 +1,46 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg + +from isaaclab.sim import SimulationCfg +from isaaclab.utils import configclass + +from .rough_env_cfg import UnitreeGo1RoughEnvCfg + + +@configclass +class UnitreeGo1FlatEnvCfg(UnitreeGo1RoughEnvCfg): + sim: SimulationCfg = SimulationCfg( + physics=NewtonCfg( + solver_cfg=MJWarpSolverCfg( + njmax=60, + nconmax=25, + cone="pyramidal", + impratio=1, + integrator="implicitfast", + ), + num_substeps=1, + debug_mode=False, + ) + ) + + def __post_init__(self): + super().__post_init__() + self.rewards.flat_orientation_l2.weight = -2.5 + self.rewards.feet_air_time.weight = 0.25 + self.scene.terrain.terrain_type = "plane" + self.scene.terrain.terrain_generator = None + self.curriculum.terrain_levels = None + + +class UnitreeGo1FlatEnvCfg_PLAY(UnitreeGo1FlatEnvCfg): + def __post_init__(self) -> None: + super().__post_init__() + self.scene.num_envs = 50 + self.scene.env_spacing = 2.5 + self.observations.policy.enable_corruption = False + self.events.base_external_force_torque = None + self.events.push_robot = None diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/go1/rough_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/go1/rough_env_cfg.py new file mode 100644 index 000000000000..2864bbba3130 --- /dev/null +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/go1/rough_env_cfg.py @@ -0,0 +1,61 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from isaaclab.utils import configclass + +from isaaclab_tasks_experimental.manager_based.locomotion.velocity.velocity_env_cfg import LocomotionVelocityRoughEnvCfg + +from isaaclab_assets.robots.unitree import UNITREE_GO1_CFG # isort: skip + + +@configclass +class UnitreeGo1RoughEnvCfg(LocomotionVelocityRoughEnvCfg): + def __post_init__(self): + super().__post_init__() + self.scene.robot = UNITREE_GO1_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") + self.manager_call_max_mode = {"Scene": 1} + self.scene.terrain.terrain_generator.sub_terrains["boxes"].grid_height_range = (0.025, 0.1) + self.scene.terrain.terrain_generator.sub_terrains["random_rough"].noise_range = (0.01, 0.06) + self.scene.terrain.terrain_generator.sub_terrains["random_rough"].noise_step = 0.01 + self.actions.joint_pos.scale = 0.25 + self.events.push_robot = None + self.events.base_external_force_torque.params["asset_cfg"].body_names = "trunk" + self.events.reset_robot_joints.params["position_range"] = (1.0, 1.0) + self.events.reset_base.params = { + "pose_range": {"x": (-0.5, 0.5), "y": (-0.5, 0.5), "yaw": (-3.14, 3.14)}, + "velocity_range": { + "x": (0.0, 0.0), + "y": (0.0, 0.0), + "z": (0.0, 0.0), + "roll": (0.0, 0.0), + "pitch": (0.0, 0.0), + "yaw": (0.0, 0.0), + }, + } + self.events.base_com = None + self.rewards.feet_air_time.params["sensor_cfg"].body_names = ".*_foot" + self.rewards.feet_air_time.weight = 0.01 + self.rewards.undesired_contacts = None + self.rewards.dof_torques_l2.weight = -0.0002 + self.rewards.track_lin_vel_xy_exp.weight = 1.5 + self.rewards.track_ang_vel_z_exp.weight = 0.75 + self.rewards.dof_acc_l2.weight = -2.5e-7 + self.terminations.base_contact.params["sensor_cfg"].body_names = "trunk" + + +@configclass +class UnitreeGo1RoughEnvCfg_PLAY(UnitreeGo1RoughEnvCfg): + def __post_init__(self): + super().__post_init__() + self.scene.num_envs = 50 + self.scene.env_spacing = 2.5 + self.scene.terrain.max_init_terrain_level = None + if self.scene.terrain.terrain_generator is not None: + self.scene.terrain.terrain_generator.num_rows = 5 + self.scene.terrain.terrain_generator.num_cols = 5 + self.scene.terrain.terrain_generator.curriculum = False + self.observations.policy.enable_corruption = False + self.events.base_external_force_torque = None + self.events.push_robot = None diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/go2/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/go2/__init__.py new file mode 100644 index 000000000000..7e124029c682 --- /dev/null +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/go2/__init__.py @@ -0,0 +1,35 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +import gymnasium as gym + +# Reuse agent configs from the stable task package. +from isaaclab_tasks.manager_based.locomotion.velocity.config.go2 import agents + +## +# Register Gym environments. +## + +gym.register( + id="Isaac-Velocity-Flat-Unitree-Go2-Warp-v0", + entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": f"{__name__}.flat_env_cfg:UnitreeGo2FlatEnvCfg", + "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:UnitreeGo2FlatPPORunnerCfg", + "skrl_cfg_entry_point": f"{agents.__name__}:skrl_flat_ppo_cfg.yaml", + }, +) + +gym.register( + id="Isaac-Velocity-Flat-Unitree-Go2-Warp-Play-v0", + entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": f"{__name__}.flat_env_cfg:UnitreeGo2FlatEnvCfg_PLAY", + "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:UnitreeGo2FlatPPORunnerCfg", + "skrl_cfg_entry_point": f"{agents.__name__}:skrl_flat_ppo_cfg.yaml", + }, +) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/go2/flat_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/go2/flat_env_cfg.py new file mode 100644 index 000000000000..ad8a8aa862f0 --- /dev/null +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/go2/flat_env_cfg.py @@ -0,0 +1,46 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg + +from isaaclab.sim import SimulationCfg +from isaaclab.utils import configclass + +from .rough_env_cfg import UnitreeGo2RoughEnvCfg + + +@configclass +class UnitreeGo2FlatEnvCfg(UnitreeGo2RoughEnvCfg): + sim: SimulationCfg = SimulationCfg( + physics=NewtonCfg( + solver_cfg=MJWarpSolverCfg( + njmax=65, + nconmax=35, + cone="pyramidal", + impratio=1, + integrator="implicitfast", + ), + num_substeps=1, + debug_mode=False, + ) + ) + + def __post_init__(self): + super().__post_init__() + self.rewards.flat_orientation_l2.weight = -2.5 + self.rewards.feet_air_time.weight = 0.25 + self.scene.terrain.terrain_type = "plane" + self.scene.terrain.terrain_generator = None + self.curriculum.terrain_levels = None + + +class UnitreeGo2FlatEnvCfg_PLAY(UnitreeGo2FlatEnvCfg): + def __post_init__(self) -> None: + super().__post_init__() + self.scene.num_envs = 50 + self.scene.env_spacing = 2.5 + self.observations.policy.enable_corruption = False + self.events.base_external_force_torque = None + self.events.push_robot = None diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/go2/rough_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/go2/rough_env_cfg.py new file mode 100644 index 000000000000..ff13b7e86176 --- /dev/null +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/go2/rough_env_cfg.py @@ -0,0 +1,60 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from isaaclab.utils import configclass + +from isaaclab_tasks_experimental.manager_based.locomotion.velocity.velocity_env_cfg import LocomotionVelocityRoughEnvCfg + +from isaaclab_assets.robots.unitree import UNITREE_GO2_CFG # isort: skip + + +@configclass +class UnitreeGo2RoughEnvCfg(LocomotionVelocityRoughEnvCfg): + def __post_init__(self): + super().__post_init__() + self.scene.robot = UNITREE_GO2_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") + self.scene.terrain.terrain_generator.sub_terrains["boxes"].grid_height_range = (0.025, 0.1) + self.scene.terrain.terrain_generator.sub_terrains["random_rough"].noise_range = (0.01, 0.06) + self.scene.terrain.terrain_generator.sub_terrains["random_rough"].noise_step = 0.01 + self.actions.joint_pos.scale = 0.25 + self.events.push_robot = None + self.events.base_external_force_torque.params["asset_cfg"].body_names = "base" + self.events.reset_robot_joints.params["position_range"] = (1.0, 1.0) + self.events.reset_base.params = { + "pose_range": {"x": (-0.5, 0.5), "y": (-0.5, 0.5), "yaw": (-3.14, 3.14)}, + "velocity_range": { + "x": (0.0, 0.0), + "y": (0.0, 0.0), + "z": (0.0, 0.0), + "roll": (0.0, 0.0), + "pitch": (0.0, 0.0), + "yaw": (0.0, 0.0), + }, + } + self.events.base_com = None + self.rewards.feet_air_time.params["sensor_cfg"].body_names = ".*_foot" + self.rewards.feet_air_time.weight = 0.01 + self.rewards.undesired_contacts = None + self.rewards.dof_torques_l2.weight = -0.0002 + self.rewards.track_lin_vel_xy_exp.weight = 1.5 + self.rewards.track_ang_vel_z_exp.weight = 0.75 + self.rewards.dof_acc_l2.weight = -2.5e-7 + self.terminations.base_contact.params["sensor_cfg"].body_names = "base" + + +@configclass +class UnitreeGo2RoughEnvCfg_PLAY(UnitreeGo2RoughEnvCfg): + def __post_init__(self): + super().__post_init__() + self.scene.num_envs = 50 + self.scene.env_spacing = 2.5 + self.scene.terrain.max_init_terrain_level = None + if self.scene.terrain.terrain_generator is not None: + self.scene.terrain.terrain_generator.num_rows = 5 + self.scene.terrain.terrain_generator.num_cols = 5 + self.scene.terrain.terrain_generator.curriculum = False + self.observations.policy.enable_corruption = False + self.events.base_external_force_torque = None + self.events.push_robot = None diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/h1/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/h1/__init__.py new file mode 100644 index 000000000000..95a1e8f29e3f --- /dev/null +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/h1/__init__.py @@ -0,0 +1,57 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +import gymnasium as gym + +# Reuse agent configs from the stable task package. +from isaaclab_tasks.manager_based.locomotion.velocity.config.h1 import agents + +## +# Register Gym environments. +## + +# gym.register( +# id="Isaac-Velocity-Rough-H1-Warp-v0", +# entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", +# disable_env_checker=True, +# kwargs={ +# "env_cfg_entry_point": f"{__name__}.rough_env_cfg:H1RoughEnvCfg", +# "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:H1RoughPPORunnerCfg", +# "skrl_cfg_entry_point": f"{agents.__name__}:skrl_rough_ppo_cfg.yaml", +# }, +# ) + +# gym.register( +# id="Isaac-Velocity-Rough-H1-Warp-Play-v0", +# entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", +# disable_env_checker=True, +# kwargs={ +# "env_cfg_entry_point": f"{__name__}.rough_env_cfg:H1RoughEnvCfg_PLAY", +# "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:H1RoughPPORunnerCfg", +# "skrl_cfg_entry_point": f"{agents.__name__}:skrl_rough_ppo_cfg.yaml", +# }, +# ) + +gym.register( + id="Isaac-Velocity-Flat-H1-Warp-v0", + entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": f"{__name__}.flat_env_cfg:H1FlatEnvCfg", + "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:H1FlatPPORunnerCfg", + "skrl_cfg_entry_point": f"{agents.__name__}:skrl_flat_ppo_cfg.yaml", + }, +) + +gym.register( + id="Isaac-Velocity-Flat-H1-Warp-Play-v0", + entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": f"{__name__}.flat_env_cfg:H1FlatEnvCfg_PLAY", + "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:H1FlatPPORunnerCfg", + "skrl_cfg_entry_point": f"{agents.__name__}:skrl_flat_ppo_cfg.yaml", + }, +) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/h1/flat_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/h1/flat_env_cfg.py new file mode 100644 index 000000000000..22648c27a2c5 --- /dev/null +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/h1/flat_env_cfg.py @@ -0,0 +1,46 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg + +from isaaclab.sim import SimulationCfg +from isaaclab.utils import configclass + +from .rough_env_cfg import H1RoughEnvCfg + + +@configclass +class H1FlatEnvCfg(H1RoughEnvCfg): + sim: SimulationCfg = SimulationCfg( + physics=NewtonCfg( + solver_cfg=MJWarpSolverCfg( + njmax=65, + nconmax=15, + cone="pyramidal", + impratio=1, + integrator="implicitfast", + ), + num_substeps=1, + debug_mode=False, + ) + ) + + def __post_init__(self): + super().__post_init__() + self.scene.terrain.terrain_type = "plane" + self.scene.terrain.terrain_generator = None + self.curriculum.terrain_levels = None + self.rewards.feet_air_time.weight = 1.0 + self.rewards.feet_air_time.params["threshold"] = 0.6 + + +class H1FlatEnvCfg_PLAY(H1FlatEnvCfg): + def __post_init__(self) -> None: + super().__post_init__() + self.scene.num_envs = 50 + self.scene.env_spacing = 2.5 + self.observations.policy.enable_corruption = False + self.events.base_external_force_torque = None + self.events.push_robot = None diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/h1/rough_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/h1/rough_env_cfg.py new file mode 100644 index 000000000000..edb71956a3fc --- /dev/null +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/h1/rough_env_cfg.py @@ -0,0 +1,131 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from isaaclab_experimental.managers import RewardTermCfg as RewTerm +from isaaclab_experimental.managers import SceneEntityCfg + +from isaaclab.utils import configclass + +import isaaclab_tasks_experimental.manager_based.locomotion.velocity.mdp as mdp +from isaaclab_tasks_experimental.manager_based.locomotion.velocity.velocity_env_cfg import ( + LocomotionVelocityRoughEnvCfg, + RewardsCfg, +) + +## +# Pre-defined configs +## +from isaaclab_assets import H1_MINIMAL_CFG # isort: skip + + +@configclass +class H1Rewards(RewardsCfg): + """Reward terms for the MDP.""" + + termination_penalty = RewTerm(func=mdp.is_terminated, weight=-200.0) + lin_vel_z_l2 = None + track_lin_vel_xy_exp = RewTerm( + func=mdp.track_lin_vel_xy_yaw_frame_exp, + weight=1.0, + params={"command_name": "base_velocity", "std": 0.5}, + ) + track_ang_vel_z_exp = RewTerm( + func=mdp.track_ang_vel_z_world_exp, weight=1.0, params={"command_name": "base_velocity", "std": 0.5} + ) + feet_air_time = RewTerm( + func=mdp.feet_air_time_positive_biped, + weight=0.25, + params={ + "command_name": "base_velocity", + "sensor_cfg": SceneEntityCfg("contact_forces", body_names=".*ankle_link"), + "threshold": 0.4, + }, + ) + feet_slide = RewTerm( + func=mdp.feet_slide, + weight=-0.25, + params={ + "sensor_cfg": SceneEntityCfg("contact_forces", body_names=".*ankle_link"), + "asset_cfg": SceneEntityCfg("robot", body_names=".*ankle_link"), + }, + ) + dof_pos_limits = RewTerm( + func=mdp.joint_pos_limits, weight=-1.0, params={"asset_cfg": SceneEntityCfg("robot", joint_names=".*_ankle")} + ) + joint_deviation_hip = RewTerm( + func=mdp.joint_deviation_l1, + weight=-0.2, + params={"asset_cfg": SceneEntityCfg("robot", joint_names=[".*_hip_yaw", ".*_hip_roll"])}, + ) + joint_deviation_arms = RewTerm( + func=mdp.joint_deviation_l1, + weight=-0.2, + params={"asset_cfg": SceneEntityCfg("robot", joint_names=[".*_shoulder_.*", ".*_elbow"])}, + ) + joint_deviation_torso = RewTerm( + func=mdp.joint_deviation_l1, weight=-0.1, params={"asset_cfg": SceneEntityCfg("robot", joint_names="torso")} + ) + + +@configclass +class H1RoughEnvCfg(LocomotionVelocityRoughEnvCfg): + rewards: H1Rewards = H1Rewards() + + def __post_init__(self): + super().__post_init__() + self.scene.robot = H1_MINIMAL_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") + self.events.push_robot = None + self.events.reset_robot_joints.params["position_range"] = (1.0, 1.0) + self.events.base_external_force_torque.params["asset_cfg"].body_names = [".*torso_link"] + self.events.reset_base.params = { + "pose_range": {"x": (-0.5, 0.5), "y": (-0.5, 0.5), "yaw": (-3.14, 3.14)}, + "velocity_range": { + "x": (0.0, 0.0), + "y": (0.0, 0.0), + "z": (0.0, 0.0), + "roll": (0.0, 0.0), + "pitch": (0.0, 0.0), + "yaw": (0.0, 0.0), + }, + } + self.events.base_com = None + self.rewards.undesired_contacts = None + self.rewards.flat_orientation_l2.weight = -1.0 + self.rewards.dof_torques_l2.weight = 0.0 + self.rewards.action_rate_l2.weight = -0.005 + self.rewards.dof_acc_l2.weight = -1.25e-7 + self.commands.base_velocity.ranges.lin_vel_x = (0.0, 1.0) + self.commands.base_velocity.ranges.lin_vel_y = (0.0, 0.0) + self.commands.base_velocity.ranges.ang_vel_z = (-1.0, 1.0) + self.terminations.base_contact.params["sensor_cfg"].body_names = ".*torso_link" + + +@configclass +class H1RoughEnvCfg_PLAY(H1RoughEnvCfg): + def __post_init__(self): + # post init of parent + super().__post_init__() + + # make a smaller scene for play + self.scene.num_envs = 50 + self.scene.env_spacing = 2.5 + self.episode_length_s = 40.0 + # spawn the robot randomly in the grid (instead of their terrain levels) + self.scene.terrain.max_init_terrain_level = None + # reduce the number of terrains to save memory + if self.scene.terrain.terrain_generator is not None: + self.scene.terrain.terrain_generator.num_rows = 5 + self.scene.terrain.terrain_generator.num_cols = 5 + self.scene.terrain.terrain_generator.curriculum = False + + self.commands.base_velocity.ranges.lin_vel_x = (1.0, 1.0) + self.commands.base_velocity.ranges.lin_vel_y = (0.0, 0.0) + self.commands.base_velocity.ranges.ang_vel_z = (-1.0, 1.0) + self.commands.base_velocity.ranges.heading = (0.0, 0.0) + # disable randomization for play + self.observations.policy.enable_corruption = False + # remove random pushing + self.events.base_external_force_torque = None + self.events.push_robot = None diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/mdp/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/mdp/__init__.py new file mode 100644 index 000000000000..cdc532db4255 --- /dev/null +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/mdp/__init__.py @@ -0,0 +1,12 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""This sub-module contains the functions that are specific to the locomotion environments.""" + +from isaaclab_experimental.envs.mdp import * # noqa: F401, F403 + +from .curriculums import * # noqa: F401, F403 +from .rewards import * # noqa: F401, F403 +from .terminations import * # noqa: F401, F403 diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/mdp/curriculums.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/mdp/curriculums.py new file mode 100644 index 000000000000..01653af7d96b --- /dev/null +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/mdp/curriculums.py @@ -0,0 +1,39 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Curriculum functions for the velocity locomotion environment. + +Curriculum terms are not warp-managed (they run at reset time, not per-step), +so they remain torch-based. +""" + +from __future__ import annotations + +from collections.abc import Sequence +from typing import TYPE_CHECKING + +import torch + +from isaaclab.assets import Articulation +from isaaclab.managers import SceneEntityCfg +from isaaclab.terrains import TerrainImporter + +if TYPE_CHECKING: + from isaaclab.envs import ManagerBasedRLEnv + + +def terrain_levels_vel( + env: ManagerBasedRLEnv, env_ids: Sequence[int], asset_cfg: SceneEntityCfg = SceneEntityCfg("robot") +) -> torch.Tensor: + """Curriculum based on the distance the robot walked when commanded to move at a desired velocity.""" + asset: Articulation = env.scene[asset_cfg.name] + terrain: TerrainImporter = env.scene.terrain + command = env.command_manager.get_command("base_velocity") + distance = torch.norm(asset.data.root_pos_w.torch[env_ids, :2] - env.scene.env_origins[env_ids, :2], dim=1) + move_up = distance > terrain.cfg.terrain_generator.size[0] / 2 + move_down = distance < torch.norm(command[env_ids, :2], dim=1) * env.max_episode_length_s * 0.5 + move_down *= ~move_up + terrain.update_env_origins(env_ids, move_up, move_down) + return torch.mean(terrain.terrain_levels.float()) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/mdp/rewards.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/mdp/rewards.py new file mode 100644 index 000000000000..6daea9d45499 --- /dev/null +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/mdp/rewards.py @@ -0,0 +1,319 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Warp-first reward functions for the velocity locomotion environment. + +All functions follow the ``func(env, out, **params) -> None`` signature. +Cross-manager torch tensors (contact sensor, commands) are cached as zero-copy +warp views on first call via ``wp.from_torch``. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +import warp as wp + +from isaaclab.managers import SceneEntityCfg +from isaaclab.sensors import ContactSensor + +if TYPE_CHECKING: + from isaaclab.envs import ManagerBasedRLEnv + +# --------------------------------------------------------------------------- +# feet_air_time +# --------------------------------------------------------------------------- + + +@wp.kernel +def _feet_air_time_kernel( + last_air_time: wp.array(dtype=wp.float32, ndim=2), + first_contact: wp.array(dtype=wp.float32, ndim=2), + body_ids: wp.array(dtype=wp.int32), + cmd_xy: wp.array(dtype=wp.float32, ndim=2), + threshold: float, + out: wp.array(dtype=wp.float32), +): + i = wp.tid() + s = float(0.0) + for k in range(body_ids.shape[0]): + b = body_ids[k] + s += (last_air_time[i, b] - threshold) * first_contact[i, b] + # gate by command magnitude + cx = cmd_xy[i, 0] + cy = cmd_xy[i, 1] + cmd_norm = wp.sqrt(cx * cx + cy * cy) + out[i] = wp.where(cmd_norm > 0.1, s, 0.0) + + +def feet_air_time(env: ManagerBasedRLEnv, out, command_name: str, sensor_cfg: SceneEntityCfg, threshold: float) -> None: + """Reward long steps taken by the feet using L2-kernel.""" + fn = feet_air_time + contact_sensor: ContactSensor = env.scene.sensors[sensor_cfg.name] + # Cache command bridge (persistent pointer) + if not getattr(fn, "_is_warmed_up", False) or fn._cmd_name != command_name: + cmd = env.command_manager.get_command(command_name) + fn._cmd_wp = cmd if isinstance(cmd, wp.array) else wp.from_torch(cmd) + fn._cmd_name = command_name + fn._is_warmed_up = True + # Newton contact sensor returns persistent wp.arrays — use directly, no wp.from_torch needed + first_contact = contact_sensor.compute_first_contact(env.step_dt) + wp.launch( + kernel=_feet_air_time_kernel, + dim=env.num_envs, + inputs=[ + contact_sensor.data.last_air_time.warp, + first_contact, + sensor_cfg.body_ids_wp, + fn._cmd_wp, + threshold, + out, + ], + device=env.device, + ) + + +# --------------------------------------------------------------------------- +# feet_air_time_positive_biped +# --------------------------------------------------------------------------- + + +@wp.kernel +def _feet_air_time_positive_biped_kernel( + air_time: wp.array(dtype=wp.float32, ndim=2), + contact_time: wp.array(dtype=wp.float32, ndim=2), + body_ids: wp.array(dtype=wp.int32), + cmd_xy: wp.array(dtype=wp.float32, ndim=2), + threshold: float, + out: wp.array(dtype=wp.float32), +): + i = wp.tid() + n_feet = body_ids.shape[0] + # count feet in contact and find single-stance min mode time + n_contact = int(0) + for k in range(n_feet): + b = body_ids[k] + if contact_time[i, b] > 0.0: + n_contact += 1 + single_stance = n_contact == 1 + min_val = threshold # clamp upper bound + for k in range(n_feet): + b = body_ids[k] + in_contact = contact_time[i, b] > 0.0 + mode_time = wp.where(in_contact, contact_time[i, b], air_time[i, b]) + val = wp.where(single_stance, mode_time, 0.0) + min_val = wp.min(min_val, val) + # gate by command magnitude + cx = cmd_xy[i, 0] + cy = cmd_xy[i, 1] + cmd_norm = wp.sqrt(cx * cx + cy * cy) + out[i] = wp.where(cmd_norm > 0.1, min_val, 0.0) + + +def feet_air_time_positive_biped(env, out, command_name: str, threshold: float, sensor_cfg: SceneEntityCfg) -> None: + """Reward long steps taken by the feet for bipeds.""" + fn = feet_air_time_positive_biped + contact_sensor: ContactSensor = env.scene.sensors[sensor_cfg.name] + if not getattr(fn, "_is_warmed_up", False) or fn._cmd_name != command_name: + cmd = env.command_manager.get_command(command_name) + fn._cmd_wp = cmd if isinstance(cmd, wp.array) else wp.from_torch(cmd) + fn._cmd_name = command_name + fn._is_warmed_up = True + wp.launch( + kernel=_feet_air_time_positive_biped_kernel, + dim=env.num_envs, + inputs=[ + contact_sensor.data.current_air_time.warp, + contact_sensor.data.current_contact_time.warp, + sensor_cfg.body_ids_wp, + fn._cmd_wp, + threshold, + out, + ], + device=env.device, + ) + + +# --------------------------------------------------------------------------- +# feet_slide +# --------------------------------------------------------------------------- + + +@wp.kernel +def _feet_slide_kernel( + body_lin_vel_w: wp.array(dtype=wp.vec3f, ndim=2), + net_forces_w: wp.array(dtype=wp.vec3f, ndim=3), + body_ids: wp.array(dtype=wp.int32), + n_history: int, + out: wp.array(dtype=wp.float32), +): + i = wp.tid() + s = float(0.0) + for k in range(body_ids.shape[0]): + b = body_ids[k] + # check if in contact: max force norm over history > 1.0 + max_force = float(0.0) + for h in range(n_history): + f = net_forces_w[i, h, b] + f_norm = wp.sqrt(f[0] * f[0] + f[1] * f[1] + f[2] * f[2]) + max_force = wp.max(max_force, f_norm) + in_contact = wp.where(max_force > 1.0, 1.0, 0.0) + # planar velocity norm + vx = body_lin_vel_w[i, b][0] + vy = body_lin_vel_w[i, b][1] + vel_norm = wp.sqrt(vx * vx + vy * vy) + s += vel_norm * in_contact + out[i] = s + + +def feet_slide(env, out, sensor_cfg: SceneEntityCfg, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")) -> None: + """Penalize feet sliding.""" + contact_sensor: ContactSensor = env.scene.sensors[sensor_cfg.name] + asset = env.scene[asset_cfg.name] + wp.launch( + kernel=_feet_slide_kernel, + dim=env.num_envs, + inputs=[ + asset.data.body_lin_vel_w.warp, + contact_sensor.data.net_forces_w_history.warp, + sensor_cfg.body_ids_wp, + contact_sensor.data.net_forces_w_history.warp.shape[1], + out, + ], + device=env.device, + ) + + +# --------------------------------------------------------------------------- +# track_lin_vel_xy_yaw_frame_exp +# --------------------------------------------------------------------------- + + +@wp.kernel +def _track_lin_vel_xy_yaw_frame_exp_kernel( + root_quat_w: wp.array(dtype=wp.quatf), + root_lin_vel_w: wp.array(dtype=wp.vec3f), + cmd: wp.array(dtype=wp.float32, ndim=2), + inv_std_sq: float, + out: wp.array(dtype=wp.float32), +): + i = wp.tid() + q = root_quat_w[i] + # extract yaw-only quaternion + qx = q[0] + qy = q[1] + qz = q[2] + qw = q[3] + sin_yaw = 2.0 * (qw * qz + qx * qy) + cos_yaw = 1.0 - 2.0 * (qy * qy + qz * qz) + yaw_half = wp.atan2(sin_yaw, cos_yaw) * 0.5 + yaw_q = wp.quatf(0.0, 0.0, wp.sin(yaw_half), wp.cos(yaw_half)) + # rotate world velocity into yaw frame (inverse = conjugate for unit quat) + vel_w = root_lin_vel_w[i] + vel_yaw = wp.quat_rotate(wp.quat_inverse(yaw_q), vel_w) + # error + ex = cmd[i, 0] - vel_yaw[0] + ey = cmd[i, 1] - vel_yaw[1] + err_sq = ex * ex + ey * ey + out[i] = wp.exp(-err_sq * inv_std_sq) + + +def track_lin_vel_xy_yaw_frame_exp( + env, out, std: float, command_name: str, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot") +) -> None: + """Reward tracking of linear velocity commands (xy axes) in the gravity aligned robot frame.""" + fn = track_lin_vel_xy_yaw_frame_exp + asset = env.scene[asset_cfg.name] + if not getattr(fn, "_is_warmed_up", False) or fn._cmd_name != command_name: + cmd = env.command_manager.get_command(command_name) + fn._cmd_wp = cmd if isinstance(cmd, wp.array) else wp.from_torch(cmd) + fn._cmd_name = command_name + fn._is_warmed_up = True + wp.launch( + kernel=_track_lin_vel_xy_yaw_frame_exp_kernel, + dim=env.num_envs, + inputs=[asset.data.root_quat_w.warp, asset.data.root_lin_vel_w.warp, fn._cmd_wp, 1.0 / (std * std), out], + device=env.device, + ) + + +# --------------------------------------------------------------------------- +# track_ang_vel_z_world_exp +# --------------------------------------------------------------------------- + + +@wp.kernel +def _track_ang_vel_z_world_exp_kernel( + root_ang_vel_w: wp.array(dtype=wp.vec3f), + cmd: wp.array(dtype=wp.float32, ndim=2), + inv_std_sq: float, + out: wp.array(dtype=wp.float32), +): + i = wp.tid() + err = cmd[i, 2] - root_ang_vel_w[i][2] + out[i] = wp.exp(-(err * err) * inv_std_sq) + + +def track_ang_vel_z_world_exp( + env, out, command_name: str, std: float, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot") +) -> None: + """Reward tracking of angular velocity commands (yaw) in world frame.""" + fn = track_ang_vel_z_world_exp + asset = env.scene[asset_cfg.name] + if not getattr(fn, "_is_warmed_up", False) or fn._cmd_name != command_name: + cmd = env.command_manager.get_command(command_name) + fn._cmd_wp = cmd if isinstance(cmd, wp.array) else wp.from_torch(cmd) + fn._cmd_name = command_name + fn._is_warmed_up = True + wp.launch( + kernel=_track_ang_vel_z_world_exp_kernel, + dim=env.num_envs, + inputs=[asset.data.root_ang_vel_w.warp, fn._cmd_wp, 1.0 / (std * std), out], + device=env.device, + ) + + +# --------------------------------------------------------------------------- +# stand_still_joint_deviation_l1 +# --------------------------------------------------------------------------- + + +@wp.kernel +def _stand_still_joint_deviation_l1_kernel( + joint_pos: wp.array(dtype=wp.float32, ndim=2), + default_joint_pos: wp.array(dtype=wp.float32, ndim=2), + cmd: wp.array(dtype=wp.float32, ndim=2), + command_threshold: float, + out: wp.array(dtype=wp.float32), +): + i = wp.tid() + n_joints = joint_pos.shape[1] + dev = float(0.0) + for j in range(n_joints): + dev += wp.abs(joint_pos[i, j] - default_joint_pos[i, j]) + # gate: only penalize when command is small + cx = cmd[i, 0] + cy = cmd[i, 1] + cmd_norm = wp.sqrt(cx * cx + cy * cy) + out[i] = wp.where(cmd_norm < command_threshold, dev, 0.0) + + +def stand_still_joint_deviation_l1( + env, out, command_name: str, command_threshold: float = 0.06, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot") +) -> None: + """Penalize offsets from the default joint positions when the command is very small.""" + fn = stand_still_joint_deviation_l1 + asset = env.scene[asset_cfg.name] + if not getattr(fn, "_is_warmed_up", False) or fn._cmd_name != command_name: + cmd = env.command_manager.get_command(command_name) + fn._cmd_wp = cmd if isinstance(cmd, wp.array) else wp.from_torch(cmd) + fn._cmd_name = command_name + fn._is_warmed_up = True + wp.launch( + kernel=_stand_still_joint_deviation_l1_kernel, + dim=env.num_envs, + inputs=[asset.data.joint_pos.warp, asset.data.default_joint_pos.warp, fn._cmd_wp, command_threshold, out], + device=env.device, + ) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/mdp/terminations.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/mdp/terminations.py new file mode 100644 index 000000000000..4b3699e0e0bf --- /dev/null +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/mdp/terminations.py @@ -0,0 +1,66 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Warp-first termination functions for the velocity locomotion environment.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +import warp as wp + +from isaaclab.assets import Articulation +from isaaclab.managers import SceneEntityCfg + +if TYPE_CHECKING: + from isaaclab.envs import ManagerBasedRLEnv + + +@wp.kernel +def _terrain_out_of_bounds_kernel( + root_pos_w: wp.array(dtype=wp.vec3f), + half_width: float, + half_height: float, + distance_buffer: float, + out: wp.array(dtype=wp.bool), +): + i = wp.tid() + px = wp.abs(root_pos_w[i][0]) + py = wp.abs(root_pos_w[i][1]) + out[i] = px > half_width - distance_buffer or py > half_height - distance_buffer + + +def terrain_out_of_bounds( + env: ManagerBasedRLEnv, out, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot"), distance_buffer: float = 3.0 +) -> None: + """Terminate when the actor moves too close to the edge of the terrain.""" + fn = terrain_out_of_bounds + if not getattr(fn, "_is_warmed_up", False): + terrain_type = env.scene.cfg.terrain.terrain_type + if terrain_type == "plane": + fn._is_plane = True + elif terrain_type == "generator": + fn._is_plane = False + terrain_gen_cfg = env.scene.terrain.cfg.terrain_generator + grid_width, grid_length = terrain_gen_cfg.size + n_rows, n_cols = terrain_gen_cfg.num_rows, terrain_gen_cfg.num_cols + border_width = terrain_gen_cfg.border_width + fn._half_width = 0.5 * (n_rows * grid_width + 2 * border_width) + fn._half_height = 0.5 * (n_cols * grid_length + 2 * border_width) + else: + raise ValueError("Received unsupported terrain type, must be either 'plane' or 'generator'.") + fn._is_warmed_up = True + + if fn._is_plane: + out.zero_() + return + + asset: Articulation = env.scene[asset_cfg.name] + wp.launch( + kernel=_terrain_out_of_bounds_kernel, + dim=env.num_envs, + inputs=[asset.data.root_pos_w.warp, fn._half_width, fn._half_height, distance_buffer, out], + device=env.device, + ) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/velocity_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/velocity_env_cfg.py new file mode 100644 index 000000000000..7442d3654ba3 --- /dev/null +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/velocity_env_cfg.py @@ -0,0 +1,296 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +import math +from dataclasses import MISSING + +from isaaclab_experimental.managers import ObservationTermCfg as ObsTerm +from isaaclab_experimental.managers import RewardTermCfg as RewTerm +from isaaclab_experimental.managers import SceneEntityCfg +from isaaclab_experimental.managers import TerminationTermCfg as DoneTerm + +import isaaclab.sim as sim_utils +from isaaclab.assets import ArticulationCfg, AssetBaseCfg +from isaaclab.envs import ManagerBasedRLEnvCfg +from isaaclab.managers import CurriculumTermCfg as CurrTerm +from isaaclab.managers import EventTermCfg as EventTerm +from isaaclab.managers import ObservationGroupCfg as ObsGroup +from isaaclab.scene import InteractiveSceneCfg +from isaaclab.sensors import ContactSensorCfg +from isaaclab.terrains import TerrainImporterCfg +from isaaclab.utils import configclass +from isaaclab.utils.assets import ISAAC_NUCLEUS_DIR, ISAACLAB_NUCLEUS_DIR +from isaaclab.utils.noise import UniformNoiseCfg as Unoise + +import isaaclab_tasks_experimental.manager_based.locomotion.velocity.mdp as mdp + +## +# Pre-defined configs +## +from isaaclab.terrains.config.rough import ROUGH_TERRAINS_CFG # isort: skip + + +## +# Scene definition +## + + +@configclass +class MySceneCfg(InteractiveSceneCfg): + """Configuration for the terrain scene with a legged robot.""" + + # ground terrain + terrain = TerrainImporterCfg( + prim_path="/World/ground", + terrain_type="generator", + terrain_generator=ROUGH_TERRAINS_CFG, + max_init_terrain_level=5, + collision_group=-1, + physics_material=sim_utils.RigidBodyMaterialCfg( + friction_combine_mode="multiply", + restitution_combine_mode="multiply", + static_friction=1.0, + dynamic_friction=1.0, + ), + visual_material=sim_utils.MdlFileCfg( + mdl_path=f"{ISAACLAB_NUCLEUS_DIR}/Materials/TilesMarbleSpiderWhiteBrickBondHoned/TilesMarbleSpiderWhiteBrickBondHoned.mdl", + project_uvw=True, + texture_scale=(0.25, 0.25), + ), + debug_vis=False, + ) + # robots + robot: ArticulationCfg = MISSING + # sensors + contact_forces = ContactSensorCfg( + prim_path="{ENV_REGEX_NS}/Robot/.*", + filter_prim_paths_expr=[], + history_length=3, + track_air_time=True, + ) + # lights + sky_light = AssetBaseCfg( + prim_path="/World/skyLight", + spawn=sim_utils.DomeLightCfg( + intensity=750.0, + texture_file=f"{ISAAC_NUCLEUS_DIR}/Materials/Textures/Skies/PolyHaven/kloofendal_43d_clear_puresky_4k.hdr", + ), + ) + + +## +# MDP settings +## + + +@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=True, + 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=(-math.pi, math.pi) + ), + ) + + +@configclass +class ActionsCfg: + """Action specifications for the MDP.""" + + joint_pos = mdp.JointPositionActionCfg(asset_name="robot", joint_names=[".*"], scale=0.5, use_default_offset=True) + + +@configclass +class PolicyCfg(ObsGroup): + """Observations for policy 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)) + projected_gravity = ObsTerm( + func=mdp.projected_gravity, + noise=Unoise(n_min=-0.05, n_max=0.05), + ) + velocity_commands = ObsTerm(func=mdp.generated_commands, params={"command_name": "base_velocity"}) + joint_pos = ObsTerm(func=mdp.joint_pos_rel, noise=Unoise(n_min=-0.01, n_max=0.01)) + joint_vel = ObsTerm(func=mdp.joint_vel_rel, noise=Unoise(n_min=-1.5, n_max=1.5)) + actions = ObsTerm(func=mdp.last_action) + + def __post_init__(self): + self.enable_corruption = True + self.concatenate_terms = True + + +@configclass +class ObservationsCfg: + """Observation specifications for the MDP.""" + + # observation groups + policy: PolicyCfg = PolicyCfg() + + +@configclass +class EventCfg: + """Configuration for events.""" + + # FIXME(warp-migration): COM randomization in exp manager-based locomotion currently causes + # NaNs and is temporarily disabled. + # base_com = EventTerm( + # func=mdp.randomize_rigid_body_com, + # mode="startup", + # params={ + # "asset_cfg": SceneEntityCfg("robot", body_names="base"), + # "com_range": {"x": (-0.05, 0.05), "y": (-0.05, 0.05), "z": (-0.01, 0.01)}, + # }, + # ) + base_com = None + + # 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_base = EventTerm( + func=mdp.reset_root_state_uniform, + mode="reset", + params={ + "pose_range": {"x": (-0.5, 0.5), "y": (-0.5, 0.5), "yaw": (-3.14, 3.14)}, + "velocity_range": { + "x": (-0.5, 0.5), + "y": (-0.5, 0.5), + "z": (-0.5, 0.5), + "roll": (-0.5, 0.5), + "pitch": (-0.5, 0.5), + "yaw": (-0.5, 0.5), + }, + }, + ) + + 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), + }, + ) + + # interval + push_robot = EventTerm( + func=mdp.push_by_setting_velocity, + mode="interval", + interval_range_s=(10.0, 15.0), + params={"velocity_range": {"x": (-0.5, 0.5), "y": (-0.5, 0.5)}}, + ) + + +@configclass +class RewardsCfg: + """Reward terms for the MDP.""" + + # -- task + track_lin_vel_xy_exp = RewTerm( + func=mdp.track_lin_vel_xy_exp, weight=1.0, params={"command_name": "base_velocity", "std": math.sqrt(0.25)} + ) + track_ang_vel_z_exp = RewTerm( + func=mdp.track_ang_vel_z_exp, weight=0.5, params={"command_name": "base_velocity", "std": math.sqrt(0.25)} + ) + # -- penalties + lin_vel_z_l2 = RewTerm(func=mdp.lin_vel_z_l2, weight=-2.0) + ang_vel_xy_l2 = RewTerm(func=mdp.ang_vel_xy_l2, weight=-0.05) + dof_torques_l2 = RewTerm(func=mdp.joint_torques_l2, weight=-1.0e-5) + dof_acc_l2 = RewTerm(func=mdp.joint_acc_l2, weight=-2.5e-7) + action_rate_l2 = RewTerm(func=mdp.action_rate_l2, weight=-0.01) + feet_air_time = RewTerm( + func=mdp.feet_air_time, + weight=0.125, + params={ + "sensor_cfg": SceneEntityCfg("contact_forces", body_names=".*FOOT"), + "command_name": "base_velocity", + "threshold": 0.5, + }, + ) + undesired_contacts = RewTerm( + func=mdp.undesired_contacts, + weight=-1.0, + params={"sensor_cfg": SceneEntityCfg("contact_forces", body_names=".*THIGH"), "threshold": 1.0}, + ) + # -- optional penalties + flat_orientation_l2 = RewTerm(func=mdp.flat_orientation_l2, weight=0.0) + dof_pos_limits = RewTerm(func=mdp.joint_pos_limits, weight=0.0) + + +@configclass +class TerminationsCfg: + """Termination terms for the MDP.""" + + time_out = DoneTerm(func=mdp.time_out, time_out=True) + base_contact = DoneTerm( + func=mdp.illegal_contact, + params={"sensor_cfg": SceneEntityCfg("contact_forces", body_names="base"), "threshold": 1.0}, + ) + + +@configclass +class CurriculumCfg: + """Curriculum terms for the MDP.""" + + terrain_levels = CurrTerm(func=mdp.terrain_levels_vel) + + +## +# Environment configuration +## + + +@configclass +class LocomotionVelocityRoughEnvCfg(ManagerBasedRLEnvCfg): + """Configuration for the locomotion velocity-tracking environment.""" + + # Scene settings + scene: MySceneCfg = MySceneCfg(num_envs=4096, env_spacing=2.5, replicate_physics=True) + # Basic settings + observations: ObservationsCfg = ObservationsCfg() + actions: ActionsCfg = ActionsCfg() + commands: CommandsCfg = CommandsCfg() + # MDP settings + rewards: RewardsCfg = RewardsCfg() + terminations: TerminationsCfg = TerminationsCfg() + events: EventCfg = EventCfg() + curriculum: CurriculumCfg = CurriculumCfg() + + def __post_init__(self): + """Post initialization.""" + # general settings + self.decimation = 4 + self.episode_length_s = 20.0 + # simulation settings + self.sim.dt = 1.0 / 200.0 + self.sim.render_interval = self.decimation + self.sim.physics_material = self.scene.terrain.physics_material + # update sensor update periods + if self.scene.contact_forces is not None: + self.scene.contact_forces.update_period = self.sim.dt + # check if terrain levels curriculum is enabled + if getattr(self.curriculum, "terrain_levels", None) is not None: + if self.scene.terrain.terrain_generator is not None: + self.scene.terrain.terrain_generator.curriculum = True + else: + if self.scene.terrain.terrain_generator is not None: + self.scene.terrain.terrain_generator.curriculum = False diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/__init__.py new file mode 100644 index 000000000000..6cd56351b6e5 --- /dev/null +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/__init__.py @@ -0,0 +1,6 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from .reach import * diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/__init__.py new file mode 100644 index 000000000000..fe34199f2321 --- /dev/null +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/__init__.py @@ -0,0 +1,6 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Reach experimental task registrations (manager-based).""" diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/config/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/config/__init__.py new file mode 100644 index 000000000000..460a30569089 --- /dev/null +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/config/__init__.py @@ -0,0 +1,4 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/config/franka/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/config/franka/__init__.py new file mode 100644 index 000000000000..b08612ccc741 --- /dev/null +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/config/franka/__init__.py @@ -0,0 +1,41 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +import gymnasium as gym + +# Reuse agent configs from the stable task package. +from isaaclab_tasks.manager_based.manipulation.reach.config.franka import agents + +## +# Register Gym environments. +## + +## +# Joint Position Control +## + +gym.register( + id="Isaac-Reach-Franka-Warp-v0", + entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": f"{__name__}.joint_pos_env_cfg:FrankaReachEnvCfg", + "rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_ppo_cfg.yaml", + "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:FrankaReachPPORunnerCfg", + "skrl_cfg_entry_point": f"{agents.__name__}:skrl_ppo_cfg.yaml", + }, +) + +gym.register( + id="Isaac-Reach-Franka-Warp-Play-v0", + entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": f"{__name__}.joint_pos_env_cfg:FrankaReachEnvCfg_PLAY", + "rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_ppo_cfg.yaml", + "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:FrankaReachPPORunnerCfg", + "skrl_cfg_entry_point": f"{agents.__name__}:skrl_ppo_cfg.yaml", + }, +) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/config/franka/joint_pos_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/config/franka/joint_pos_env_cfg.py new file mode 100644 index 000000000000..5b3c7ec0c2f4 --- /dev/null +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/config/franka/joint_pos_env_cfg.py @@ -0,0 +1,74 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +import math + +from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg + +from isaaclab.sim import SimulationCfg +from isaaclab.utils import configclass + +import isaaclab_tasks_experimental.manager_based.manipulation.reach.mdp as mdp +from isaaclab_tasks_experimental.manager_based.manipulation.reach.reach_env_cfg import ReachEnvCfg + +## +# Pre-defined configs +## +from isaaclab_assets import FRANKA_PANDA_CFG # isort: skip + + +## +# Environment configuration +## + + +@configclass +class FrankaReachEnvCfg(ReachEnvCfg): + sim: SimulationCfg = SimulationCfg( + dt=1 / 60, + physics=NewtonCfg( + solver_cfg=MJWarpSolverCfg( + njmax=50, + nconmax=20, + cone="pyramidal", + impratio=1, + integrator="implicitfast", + ), + num_substeps=1, + debug_mode=False, + ), + ) + + def __post_init__(self): + # post init of parent + super().__post_init__() + + # switch robot to franka + self.scene.robot = FRANKA_PANDA_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") + # override rewards + self.rewards.end_effector_position_tracking.params["asset_cfg"].body_names = ["panda_hand"] + self.rewards.end_effector_position_tracking_fine_grained.params["asset_cfg"].body_names = ["panda_hand"] + self.rewards.end_effector_orientation_tracking.params["asset_cfg"].body_names = ["panda_hand"] + + # override actions + self.actions.arm_action = mdp.JointPositionActionCfg( + asset_name="robot", joint_names=["panda_joint.*"], scale=0.5, use_default_offset=True + ) + # override command generator body + # end-effector is along z-direction + self.commands.ee_pose.body_name = "panda_hand" + self.commands.ee_pose.ranges.pitch = (math.pi, math.pi) + + +@configclass +class FrankaReachEnvCfg_PLAY(FrankaReachEnvCfg): + def __post_init__(self): + # post init of parent + super().__post_init__() + # make a smaller scene for play + self.scene.num_envs = 50 + self.scene.env_spacing = 2.5 + # disable randomization for play + self.observations.policy.enable_corruption = False diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/config/ur_10/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/config/ur_10/__init__.py new file mode 100644 index 000000000000..85908c158052 --- /dev/null +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/config/ur_10/__init__.py @@ -0,0 +1,36 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +# UR10 env disabled: USD asset has composition errors (broken asset file). +# Fails on both torch baseline and warp with: +# RuntimeError: USD stage has composition errors while loading provided stage +# Re-enable once the UR10 USD asset is fixed. + +# import gymnasium as gym +# from isaaclab_tasks.manager_based.manipulation.reach.config.ur_10 import agents + +# gym.register( +# id="Isaac-Reach-UR10-Warp-v0", +# entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", +# disable_env_checker=True, +# kwargs={ +# "env_cfg_entry_point": f"{__name__}.joint_pos_env_cfg:UR10ReachEnvCfg", +# "rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_ppo_cfg.yaml", +# "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:UR10ReachPPORunnerCfg", +# "skrl_cfg_entry_point": f"{agents.__name__}:skrl_ppo_cfg.yaml", +# }, +# ) + +# gym.register( +# id="Isaac-Reach-UR10-Warp-Play-v0", +# entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", +# disable_env_checker=True, +# kwargs={ +# "env_cfg_entry_point": f"{__name__}.joint_pos_env_cfg:UR10ReachEnvCfg_PLAY", +# "rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_ppo_cfg.yaml", +# "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:UR10ReachPPORunnerCfg", +# "skrl_cfg_entry_point": f"{agents.__name__}:skrl_ppo_cfg.yaml", +# }, +# ) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/config/ur_10/joint_pos_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/config/ur_10/joint_pos_env_cfg.py new file mode 100644 index 000000000000..7eddda91f5ac --- /dev/null +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/config/ur_10/joint_pos_env_cfg.py @@ -0,0 +1,74 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +import math + +from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg + +from isaaclab.sim import SimulationCfg +from isaaclab.utils import configclass + +import isaaclab_tasks_experimental.manager_based.manipulation.reach.mdp as mdp +from isaaclab_tasks_experimental.manager_based.manipulation.reach.reach_env_cfg import ReachEnvCfg + +## +# Pre-defined configs +## +from isaaclab_assets import UR10_CFG # isort: skip + + +## +# Environment configuration +## + + +@configclass +class UR10ReachEnvCfg(ReachEnvCfg): + sim: SimulationCfg = SimulationCfg( + physics=NewtonCfg( + solver_cfg=MJWarpSolverCfg( + njmax=50, + nconmax=20, + cone="pyramidal", + impratio=1, + integrator="implicitfast", + ), + num_substeps=1, + debug_mode=False, + ) + ) + + def __post_init__(self): + # post init of parent + super().__post_init__() + + # switch robot to ur10 + self.scene.robot = UR10_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") + # override events + self.events.reset_robot_joints.params["position_range"] = (0.75, 1.25) + # override rewards + self.rewards.end_effector_position_tracking.params["asset_cfg"].body_names = ["ee_link"] + self.rewards.end_effector_position_tracking_fine_grained.params["asset_cfg"].body_names = ["ee_link"] + self.rewards.end_effector_orientation_tracking.params["asset_cfg"].body_names = ["ee_link"] + # override actions + self.actions.arm_action = mdp.JointPositionActionCfg( + asset_name="robot", joint_names=[".*"], scale=0.5, use_default_offset=True + ) + # override command generator body + # end-effector is along x-direction + self.commands.ee_pose.body_name = "ee_link" + self.commands.ee_pose.ranges.pitch = (math.pi / 2, math.pi / 2) + + +@configclass +class UR10ReachEnvCfg_PLAY(UR10ReachEnvCfg): + def __post_init__(self): + # post init of parent + super().__post_init__() + # make a smaller scene for play + self.scene.num_envs = 50 + self.scene.env_spacing = 2.5 + # disable randomization for play + self.observations.policy.enable_corruption = False diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/mdp/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/mdp/__init__.py new file mode 100644 index 000000000000..b0845d6735b6 --- /dev/null +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/mdp/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""This sub-module contains the functions that are specific to the reach environments.""" + +from isaaclab_experimental.envs.mdp import * # noqa: F401, F403 + +from .rewards import * # noqa: F401, F403 diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/mdp/rewards.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/mdp/rewards.py new file mode 100644 index 000000000000..e378bbfcee80 --- /dev/null +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/mdp/rewards.py @@ -0,0 +1,166 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Warp-first reward terms for the reach task. + +All functions follow the ``func(env, out, **params) -> None`` signature. +Command tensors are cached as zero-copy warp views on first call. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +import warp as wp + +from isaaclab.assets import Articulation +from isaaclab.managers import SceneEntityCfg + +if TYPE_CHECKING: + from isaaclab.envs import ManagerBasedRLEnv + + +# --------------------------------------------------------------------------- +# position_command_error +# --------------------------------------------------------------------------- + + +@wp.kernel +def _position_command_error_kernel( + root_pos_w: wp.array(dtype=wp.vec3f), + root_quat_w: wp.array(dtype=wp.quatf), + body_pos_w: wp.array(dtype=wp.vec3f, ndim=2), + cmd: wp.array(dtype=wp.float32, ndim=2), + body_idx: int, + out: wp.array(dtype=wp.float32), +): + i = wp.tid() + # desired position in body frame -> world frame + des_b = wp.vec3f(cmd[i, 0], cmd[i, 1], cmd[i, 2]) + des_w = root_pos_w[i] + wp.quat_rotate(root_quat_w[i], des_b) + # current end-effector position + cur_w = body_pos_w[i, body_idx] + dx = cur_w[0] - des_w[0] + dy = cur_w[1] - des_w[1] + dz = cur_w[2] - des_w[2] + out[i] = wp.sqrt(dx * dx + dy * dy + dz * dz) + + +def position_command_error(env: ManagerBasedRLEnv, out, command_name: str, asset_cfg: SceneEntityCfg) -> None: + """Penalize tracking of the position error using L2-norm.""" + fn = position_command_error + asset: Articulation = env.scene[asset_cfg.name] + if not hasattr(fn, "_cmd_wp") or fn._cmd_name != command_name: + cmd = env.command_manager.get_command(command_name) + fn._cmd_wp = cmd if isinstance(cmd, wp.array) else wp.from_torch(cmd) + fn._cmd_name = command_name + wp.launch( + kernel=_position_command_error_kernel, + dim=env.num_envs, + inputs=[ + asset.data.root_pos_w.warp, + asset.data.root_quat_w.warp, + asset.data.body_pos_w.warp, + fn._cmd_wp, + asset_cfg.body_ids[0], + out, + ], + device=env.device, + ) + + +# --------------------------------------------------------------------------- +# position_command_error_tanh +# --------------------------------------------------------------------------- + + +@wp.kernel +def _position_command_error_tanh_kernel( + root_pos_w: wp.array(dtype=wp.vec3f), + root_quat_w: wp.array(dtype=wp.quatf), + body_pos_w: wp.array(dtype=wp.vec3f, ndim=2), + cmd: wp.array(dtype=wp.float32, ndim=2), + body_idx: int, + inv_std: float, + out: wp.array(dtype=wp.float32), +): + i = wp.tid() + des_b = wp.vec3f(cmd[i, 0], cmd[i, 1], cmd[i, 2]) + des_w = root_pos_w[i] + wp.quat_rotate(root_quat_w[i], des_b) + cur_w = body_pos_w[i, body_idx] + dx = cur_w[0] - des_w[0] + dy = cur_w[1] - des_w[1] + dz = cur_w[2] - des_w[2] + dist = wp.sqrt(dx * dx + dy * dy + dz * dz) + out[i] = 1.0 - wp.tanh(dist * inv_std) + + +def position_command_error_tanh( + env: ManagerBasedRLEnv, out, std: float, command_name: str, asset_cfg: SceneEntityCfg +) -> None: + """Reward tracking of the position using the tanh kernel.""" + fn = position_command_error_tanh + asset: Articulation = env.scene[asset_cfg.name] + if not hasattr(fn, "_cmd_wp") or fn._cmd_name != command_name: + cmd = env.command_manager.get_command(command_name) + fn._cmd_wp = cmd if isinstance(cmd, wp.array) else wp.from_torch(cmd) + fn._cmd_name = command_name + wp.launch( + kernel=_position_command_error_tanh_kernel, + dim=env.num_envs, + inputs=[ + asset.data.root_pos_w.warp, + asset.data.root_quat_w.warp, + asset.data.body_pos_w.warp, + fn._cmd_wp, + asset_cfg.body_ids[0], + 1.0 / std, + out, + ], + device=env.device, + ) + + +# --------------------------------------------------------------------------- +# orientation_command_error +# --------------------------------------------------------------------------- + + +@wp.kernel +def _orientation_command_error_kernel( + root_quat_w: wp.array(dtype=wp.quatf), + body_quat_w: wp.array(dtype=wp.quatf, ndim=2), + cmd: wp.array(dtype=wp.float32, ndim=2), + body_idx: int, + out: wp.array(dtype=wp.float32), +): + i = wp.tid() + # desired quat in body frame -> world frame: q_des_w = q_root * q_des_b + des_b = wp.quatf(cmd[i, 3], cmd[i, 4], cmd[i, 5], cmd[i, 6]) + des_w = root_quat_w[i] * des_b + # current ee orientation + cur_w = body_quat_w[i, body_idx] + # shortest-path error: angle of q_err = cur^-1 * des + q_err = wp.quat_inverse(cur_w) * des_w + # error magnitude = 2 * acos(|w|) (w component of the error quaternion) + qw = wp.abs(q_err[3]) + qw = wp.clamp(qw, 0.0, 1.0) + out[i] = 2.0 * wp.acos(qw) + + +def orientation_command_error(env: ManagerBasedRLEnv, out, command_name: str, asset_cfg: SceneEntityCfg) -> None: + """Penalize tracking orientation error using shortest path.""" + fn = orientation_command_error + asset: Articulation = env.scene[asset_cfg.name] + if not hasattr(fn, "_cmd_wp") or fn._cmd_name != command_name: + cmd = env.command_manager.get_command(command_name) + fn._cmd_wp = cmd if isinstance(cmd, wp.array) else wp.from_torch(cmd) + fn._cmd_name = command_name + wp.launch( + kernel=_orientation_command_error_kernel, + dim=env.num_envs, + inputs=[asset.data.root_quat_w.warp, asset.data.body_quat_w.warp, fn._cmd_wp, asset_cfg.body_ids[0], out], + device=env.device, + ) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/reach_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/reach_env_cfg.py new file mode 100644 index 000000000000..d019b0531402 --- /dev/null +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/reach_env_cfg.py @@ -0,0 +1,206 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +from dataclasses import MISSING + +from isaaclab_experimental.managers import ObservationTermCfg as ObsTerm +from isaaclab_experimental.managers import RewardTermCfg as RewTerm +from isaaclab_experimental.managers import SceneEntityCfg +from isaaclab_experimental.managers import TerminationTermCfg as DoneTerm + +import isaaclab.sim as sim_utils +from isaaclab.assets import ArticulationCfg, AssetBaseCfg +from isaaclab.envs import ManagerBasedRLEnvCfg +from isaaclab.managers import ActionTermCfg as ActionTerm +from isaaclab.managers import CurriculumTermCfg as CurrTerm +from isaaclab.managers import EventTermCfg as EventTerm +from isaaclab.managers import ObservationGroupCfg as ObsGroup +from isaaclab.scene import InteractiveSceneCfg +from isaaclab.utils import configclass +from isaaclab.utils.noise import UniformNoiseCfg as Unoise + +import isaaclab_tasks_experimental.manager_based.manipulation.reach.mdp as mdp + +## +# Scene definition +## + + +@configclass +class ReachSceneCfg(InteractiveSceneCfg): + """Configuration for the scene with a robotic arm.""" + + # world + ground = AssetBaseCfg( + prim_path="/World/ground", + spawn=sim_utils.GroundPlaneCfg(), + init_state=AssetBaseCfg.InitialStateCfg(pos=(0.0, 0.0, -1.05)), + ) + + # robots + robot: ArticulationCfg = MISSING + + # lights + light = AssetBaseCfg( + prim_path="/World/light", + spawn=sim_utils.DomeLightCfg(color=(0.75, 0.75, 0.75), intensity=2500.0), + ) + + +## +# MDP settings +## + + +@configclass +class CommandsCfg: + """Command terms for the MDP.""" + + ee_pose = mdp.UniformPoseCommandCfg( + asset_name="robot", + body_name=MISSING, + resampling_time_range=(4.0, 4.0), + debug_vis=True, + ranges=mdp.UniformPoseCommandCfg.Ranges( + pos_x=(0.35, 0.65), + pos_y=(-0.2, 0.2), + pos_z=(0.15, 0.5), + roll=(0.0, 0.0), + pitch=MISSING, # depends on end-effector axis + yaw=(-3.14, 3.14), + ), + ) + + +@configclass +class ActionsCfg: + """Action specifications for the MDP.""" + + arm_action: ActionTerm = MISSING + gripper_action: ActionTerm | None = None + + +@configclass +class ObservationsCfg: + """Observation specifications for the MDP.""" + + @configclass + class PolicyCfg(ObsGroup): + """Observations for policy group.""" + + # observation terms (order preserved) + joint_pos = ObsTerm(func=mdp.joint_pos_rel, noise=Unoise(n_min=-0.01, n_max=0.01)) + joint_vel = ObsTerm(func=mdp.joint_vel_rel, noise=Unoise(n_min=-0.01, n_max=0.01)) + pose_command = ObsTerm(func=mdp.generated_commands, params={"command_name": "ee_pose"}) + actions = ObsTerm(func=mdp.last_action) + + def __post_init__(self): + self.enable_corruption = True + self.concatenate_terms = True + + # observation groups + policy: PolicyCfg = PolicyCfg() + + +@configclass +class EventCfg: + """Configuration for events.""" + + reset_base = EventTerm( + func=mdp.reset_root_state_uniform, + mode="reset", + params={"pose_range": {}, "velocity_range": {}}, + ) + + 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.""" + + # task terms + end_effector_position_tracking = RewTerm( + func=mdp.position_command_error, + weight=-0.2, + params={"asset_cfg": SceneEntityCfg("robot", body_names=MISSING), "command_name": "ee_pose"}, + ) + end_effector_position_tracking_fine_grained = RewTerm( + func=mdp.position_command_error_tanh, + weight=0.1, + params={"asset_cfg": SceneEntityCfg("robot", body_names=MISSING), "std": 0.1, "command_name": "ee_pose"}, + ) + end_effector_orientation_tracking = RewTerm( + func=mdp.orientation_command_error, + weight=-0.1, + params={"asset_cfg": SceneEntityCfg("robot", body_names=MISSING), "command_name": "ee_pose"}, + ) + + # action penalty + action_rate = RewTerm(func=mdp.action_rate_l2, weight=-0.0001) + joint_vel = RewTerm( + func=mdp.joint_vel_l2, + weight=-0.0001, + params={"asset_cfg": SceneEntityCfg("robot")}, + ) + + +@configclass +class TerminationsCfg: + """Termination terms for the MDP.""" + + time_out = DoneTerm(func=mdp.time_out, time_out=True) + + +@configclass +class CurriculumCfg: + """Curriculum terms for the MDP.""" + + action_rate = CurrTerm( + func=mdp.modify_reward_weight, params={"term_name": "action_rate", "weight": -0.005, "num_steps": 4500} + ) + + joint_vel = CurrTerm( + func=mdp.modify_reward_weight, params={"term_name": "joint_vel", "weight": -0.001, "num_steps": 4500} + ) + + +## +# Environment configuration +## + + +@configclass +class ReachEnvCfg(ManagerBasedRLEnvCfg): + """Configuration for the reach end-effector pose tracking environment.""" + + # Scene settings + scene: ReachSceneCfg = ReachSceneCfg(num_envs=4096, env_spacing=2.5) + # Basic settings + observations: ObservationsCfg = ObservationsCfg() + actions: ActionsCfg = ActionsCfg() + commands: CommandsCfg = CommandsCfg() + # MDP settings + rewards: RewardsCfg = RewardsCfg() + terminations: TerminationsCfg = TerminationsCfg() + events: EventCfg = EventCfg() + curriculum: CurriculumCfg = CurriculumCfg() + + def __post_init__(self): + """Post initialization.""" + # general settings + self.decimation = 2 + self.sim.render_interval = self.decimation + self.episode_length_s = 12.0 + self.viewer.eye = (3.5, 3.5, 3.5) + # simulation settings + self.sim.dt = 1.0 / 60.0 diff --git a/source/isaaclab_tasks_experimental/setup.py b/source/isaaclab_tasks_experimental/setup.py index ae77016f8984..4e6efc076704 100644 --- a/source/isaaclab_tasks_experimental/setup.py +++ b/source/isaaclab_tasks_experimental/setup.py @@ -25,15 +25,12 @@ description=EXTENSION_TOML_DATA["package"]["description"], keywords=EXTENSION_TOML_DATA["package"]["keywords"], include_package_data=True, - python_requires=">=3.10", + python_requires=">=3.12", install_requires=["isaaclab_tasks"], packages=find_packages(), classifiers=[ "Natural Language :: English", - "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", - "Isaac Sim :: 5.0.0", - "Isaac Sim :: 5.1.0", "Isaac Sim :: 6.0.0", ], zip_safe=False, diff --git a/source/isaaclab_teleop/changelog.d/.gitkeep b/source/isaaclab_teleop/changelog.d/.gitkeep new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/source/isaaclab_teleop/changelog.d/rwiltz-restore-legacy-teleop.rst b/source/isaaclab_teleop/changelog.d/rwiltz-restore-legacy-teleop.rst new file mode 100644 index 000000000000..4c534f674c8a --- /dev/null +++ b/source/isaaclab_teleop/changelog.d/rwiltz-restore-legacy-teleop.rst @@ -0,0 +1,11 @@ +Changed +^^^^^^^ + +* Changed ``--teleop_device`` default to ``None`` in ``teleop_se3_agent.py`` + and ``record_demos.py``. When omitted, the IsaacTeleop pipeline is used if + the env configures ``isaac_teleop``; otherwise keyboard is used as fallback. + When explicitly provided, the scripts use the legacy ``teleop_devices`` path + and error out if no matching entry exists. +* Removed automatic ``--xr`` detection from ``--teleop_device`` containing + ``"handtracking"``. Users who need XR with the legacy path should pass + ``--xr`` explicitly. diff --git a/source/isaaclab_teleop/config/extension.toml b/source/isaaclab_teleop/config/extension.toml index 48e59c25e80e..947103618b9a 100644 --- a/source/isaaclab_teleop/config/extension.toml +++ b/source/isaaclab_teleop/config/extension.toml @@ -1,6 +1,6 @@ [package] # Semantic Versioning is used: https://semver.org/ -version = "0.3.4" +version = "0.3.9" # Description title = "Isaac Lab Teleop" diff --git a/source/isaaclab_teleop/docs/CHANGELOG.rst b/source/isaaclab_teleop/docs/CHANGELOG.rst index e9545bd4b894..3856e6ec1346 100644 --- a/source/isaaclab_teleop/docs/CHANGELOG.rst +++ b/source/isaaclab_teleop/docs/CHANGELOG.rst @@ -1,6 +1,108 @@ Changelog --------- +0.3.9 (2026-04-29) +~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed installation failure on Windows by adding ``platform_system == 'Linux'`` + marker to the ``isaacteleop`` dependency, which is only available on Linux. + + +0.3.8 (2026-04-24) +~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Switched :class:`~isaaclab_teleop.xr_anchor_utils.XrAnchorSynchronizer` to import + ``get_current_stage`` from :mod:`isaaclab.sim.utils.stage` instead of + ``isaacsim.core.experimental.utils.stage``, aligning with the Isaac Lab API. + + +0.3.7 (2026-04-22) +~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Updated XR anchor prim creation to use :func:`isaaclab.sim.utils.prims.create_prim` + instead of ``isaacsim.core.experimental.prims.XformPrim``. + + +0.3.6 (2026-04-21) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :attr:`~isaaclab_teleop.IsaacTeleopCfg.control_channel_uuid` for + receiving teleop control commands (start/stop/reset) from the headset via + an OpenXR message channel. The channel is managed by TeleopCore's native + ``teleop_control_pipeline`` mechanism. + +* Added :class:`~isaaclab_teleop.teleop_message_processor.TeleopMessageProcessor` + retargeter that converts raw message-channel payloads into boolean control + signals for :class:`~isaacteleop.teleop_session_manager.DefaultTeleopStateManager`. + +* Added :func:`~isaaclab_teleop.poll_control_events` helper, + :class:`~isaaclab_teleop.ControlEvents` dataclass, and + :class:`~isaaclab_teleop.SupportsControlEvents` protocol for polling + start/stop/reset signals from any teleop device in a single call. + +* Added :attr:`~isaaclab_teleop.IsaacTeleopDevice.last_control_events` + property exposing the most recent control events from the message channel. + Control events are automatically bridged to legacy + :meth:`~isaaclab_teleop.IsaacTeleopDevice.add_callback` callbacks. + +Changed +^^^^^^^ + +* :meth:`~isaaclab_teleop.IsaacTeleopDevice.reset` now injects a + ``reset`` :class:`ExecutionEvents` into TeleopCore's ``ComputeContext`` + on the next pipeline step, resetting retargeter cross-step state. + Previously only the XR anchor was reset. + +Fixed +^^^^^ + +* Fixed ``record_demos.py`` not resetting the teleop device when a + success condition triggers an environment reset. Retargeters now + reinitialize their state on success-triggered resets. + +* Fixed shutdown hang caused by Kit's pre-shutdown callback calling + ``stop()`` while the simulation loop was still running. The callback + now uses the same graceful teardown path as the XR-disabled handler. + +0.3.5 (2026-04-06) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added ``cloudxr_env_file`` and ``auto_launch_cloudxr`` parameters to + :func:`~isaaclab_teleop.create_isaac_teleop_device`, + :class:`~isaaclab_teleop.IsaacTeleopDevice`, and + :class:`~isaaclab_teleop.session_lifecycle.TeleopSessionLifecycle` for + auto-launching the CloudXR runtime and WSS proxy during session startup. + When a ``.env`` file path is provided via ``--cloudxr_env``, users no + longer need to run ``python -m isaacteleop.cloudxr`` in a separate + terminal. +* Added device-specific CloudXR ``.env`` profiles: + :data:`~isaaclab_teleop.CLOUDXR_JS_ENV` (Quest/Pico, ``auto-webrtc``) and + :data:`~isaaclab_teleop.CLOUDXR_AVP_ENV` (Apple Vision Pro, ``auto-native``). +* Added ``dex-retargeting==0.5.0`` as a required dependency on Linux x86_64. + +Changed +^^^^^^^ + +* Made ``isaacteleop[retargeters,ui,cloudxr]~=1.2.0`` a required dependency of + ``isaaclab_teleop`` (previously an optional extra via + ``isaaclab_teleop[teleop]``). + + 0.3.4 (2026-03-17) ~~~~~~~~~~~~~~~~~~~ diff --git a/source/isaaclab_teleop/isaaclab_teleop/__init__.pyi b/source/isaaclab_teleop/isaaclab_teleop/__init__.pyi index e253d899f47a..045f16f0c690 100644 --- a/source/isaaclab_teleop/isaaclab_teleop/__init__.pyi +++ b/source/isaaclab_teleop/isaaclab_teleop/__init__.pyi @@ -4,16 +4,23 @@ # SPDX-License-Identifier: BSD-3-Clause __all__ = [ + "CLOUDXR_AVP_ENV", + "CLOUDXR_JS_ENV", + "ControlEvents", "IsaacTeleopCfg", "IsaacTeleopDevice", - "create_isaac_teleop_device", - "XrAnchorSynchronizer", + "SupportsControlEvents", + "TELEOP_CONTROL_CHANNEL_UUID", "XrAnchorRotationMode", + "XrAnchorSynchronizer", "XrCfg", + "create_isaac_teleop_device", + "poll_control_events", "remove_camera_configs", ] -from .isaac_teleop_cfg import IsaacTeleopCfg +from .control_events import TELEOP_CONTROL_CHANNEL_UUID, ControlEvents, SupportsControlEvents, poll_control_events +from .isaac_teleop_cfg import CLOUDXR_AVP_ENV, CLOUDXR_JS_ENV, IsaacTeleopCfg from .isaac_teleop_device import IsaacTeleopDevice, create_isaac_teleop_device from .xr_anchor_utils import XrAnchorSynchronizer from .xr_cfg import XrAnchorRotationMode, XrCfg, remove_camera_configs diff --git a/source/isaaclab_teleop/isaaclab_teleop/avp-cloudxr.env b/source/isaaclab_teleop/isaaclab_teleop/avp-cloudxr.env new file mode 100644 index 000000000000..df2de8eb3811 --- /dev/null +++ b/source/isaaclab_teleop/isaaclab_teleop/avp-cloudxr.env @@ -0,0 +1,2 @@ +NV_DEVICE_PROFILE=auto-native +NV_CXR_ENABLE_PUSH_DEVICES=0 diff --git a/source/isaaclab_teleop/isaaclab_teleop/cloudxrjs-cloudxr.env b/source/isaaclab_teleop/isaaclab_teleop/cloudxrjs-cloudxr.env new file mode 100644 index 000000000000..55e16229f3fa --- /dev/null +++ b/source/isaaclab_teleop/isaaclab_teleop/cloudxrjs-cloudxr.env @@ -0,0 +1,2 @@ +NV_DEVICE_PROFILE=auto-webrtc +NV_CXR_ENABLE_PUSH_DEVICES=0 diff --git a/source/isaaclab_teleop/isaaclab_teleop/command_handler.py b/source/isaaclab_teleop/isaaclab_teleop/command_handler.py index eb5fb38aeb44..7e999e638f5e 100644 --- a/source/isaaclab_teleop/isaaclab_teleop/command_handler.py +++ b/source/isaaclab_teleop/isaaclab_teleop/command_handler.py @@ -3,57 +3,30 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""Teleop command handling for IsaacTeleop-based teleoperation.""" +"""Teleop command callback registry for IsaacTeleop-based teleoperation.""" from __future__ import annotations -import logging from collections.abc import Callable -from typing import Any - -import carb - -logger = logging.getLogger(__name__) class CommandHandler: - """Handles teleop command callbacks and XR message bus events. - - This class is responsible for: - - 1. Registering callbacks for teleop commands (START, STOP, RESET) - 2. Subscribing to the XR message bus for command events - 3. Dispatching callbacks when commands are received - - Teleop commands can be triggered via XR controller buttons or the - message bus. The handler normalizes command names (e.g. mapping - ``"R"`` to ``"RESET"``) and dispatches to registered callbacks. + """Lightweight callback registry for teleop commands. + + Scripts can register callbacks for ``START``, ``STOP``, and ``RESET`` + commands via :meth:`add_callback`. The callbacks are dispatched by + :meth:`fire` when the corresponding command is received. + + Note: + In the current architecture control signals arrive through + TeleopCore's ``teleop_control_pipeline`` and are consumed via + :func:`~isaaclab_teleop.poll_control_events`. This registry is + retained for backward compatibility with scripts that register + callbacks before the pipeline-based path was introduced. """ - TELEOP_COMMAND_EVENT_TYPE = "teleop_command" - - def __init__(self, xr_core: Any | None = None, on_reset: Callable[[], None] | None = None): - """Initialize the command handler. - - Args: - xr_core: The XRCore singleton, or ``None`` if XR is not available. - When provided, the handler subscribes to the message bus for - teleop command events. - on_reset: Optional hook called whenever a ``"reset"`` message-bus - event is received, *in addition to* the user's RESET callback. - This allows the device to perform internal reset actions (e.g. - resetting the XR anchor) without coupling the handler to the - anchor manager. - """ + def __init__(self) -> None: self._callbacks: dict[str, Callable] = {} - self._on_reset = on_reset - self._xr_core = xr_core - self._vc_subscription = None - - if self._xr_core is not None: - self._vc_subscription = self._xr_core.get_message_bus().create_subscription_to_pop_by_type( - carb.events.type_from_string(self.TELEOP_COMMAND_EVENT_TYPE), self._on_teleop_command - ) @property def callbacks(self) -> dict[str, Callable]: @@ -70,7 +43,6 @@ def add_callback(self, key: str, func: Callable) -> None: func: The function to call when the command is received. Should take no arguments. """ - # Map "R" to "RESET" for compatibility with existing scripts if key == "R": key = "RESET" self._callbacks[key] = func @@ -84,19 +56,5 @@ def fire(self, command: str) -> None: if command in self._callbacks: self._callbacks[command]() - def _on_teleop_command(self, event: carb.events.IEvent) -> None: - """Handle teleop command events from the message bus.""" - msg = event.payload.get("message", "") - - if "start" in msg: - self.fire("START") - elif "stop" in msg: - self.fire("STOP") - elif "reset" in msg: - self.fire("RESET") - if self._on_reset is not None: - self._on_reset() - def cleanup(self) -> None: - """Release event subscriptions.""" - self._vc_subscription = None + """Release resources (no-op; retained for API compatibility).""" diff --git a/source/isaaclab_teleop/isaaclab_teleop/control_events.py b/source/isaaclab_teleop/isaaclab_teleop/control_events.py new file mode 100644 index 000000000000..69ddd7c1ed21 --- /dev/null +++ b/source/isaaclab_teleop/isaaclab_teleop/control_events.py @@ -0,0 +1,78 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Teleop control events dataclass, polling helper, and well-known channel UUID.""" + +from __future__ import annotations + +import dataclasses +import uuid +from typing import Protocol, runtime_checkable + +TELEOP_CONTROL_CHANNEL_UUID: bytes = uuid.uuid5(uuid.NAMESPACE_DNS, "teleop_command").bytes +"""Well-known 16-byte UUID for the teleop control message channel. + +Derived deterministically as ``uuid5(NAMESPACE_DNS, "teleop_command")`` +so that both the Isaac Lab server and the Quest client can independently +compute the same channel identifier from the string ``"teleop_command"``. + +Pass this value as :attr:`~isaaclab_teleop.IsaacTeleopCfg.control_channel_uuid` +when configuring a teleop session with message-channel-based control. +""" + + +@dataclasses.dataclass(frozen=True) +class ControlEvents: + """Result of :func:`poll_control_events`. + + Attributes: + is_active: ``True`` when the teleop state machine is in RUNNING, + ``False`` when PAUSED or STOPPED, or ``None`` when no control + channel is configured (callers should leave their own active + flag unchanged). + should_reset: ``True`` when a reset was triggered this frame. + """ + + is_active: bool | None = None + should_reset: bool = False + + +_NO_OP_EVENTS = ControlEvents() +"""Shared immutable sentinel returned when no control channel is active.""" + + +@runtime_checkable +class SupportsControlEvents(Protocol): + """Duck type for teleop devices that expose control events.""" + + @property + def last_control_events(self) -> ControlEvents: ... + + +def poll_control_events(teleop_interface: SupportsControlEvents | object) -> ControlEvents: + """Poll control events from any teleop interface. + + Safe to call with any device type (keyboard, spacemouse, etc.). + Devices that do not expose the message-channel protocol return + a no-op :class:`ControlEvents`. + + Args: + teleop_interface: The teleop device to poll. Devices implementing + :class:`SupportsControlEvents` provide full type safety; other + devices are handled gracefully via duck typing. + + Returns: + A :class:`ControlEvents` with the latest start/stop and reset + signals. + """ + events = getattr(teleop_interface, "last_control_events", None) + if events is None: + return _NO_OP_EVENTS + if isinstance(events, ControlEvents): + return events + return ControlEvents( + is_active=getattr(events, "is_active", None), + should_reset=getattr(events, "should_reset", False), + ) diff --git a/source/isaaclab_teleop/isaaclab_teleop/deprecated/openxr/manus_vive_utils.py b/source/isaaclab_teleop/isaaclab_teleop/deprecated/openxr/manus_vive_utils.py index 97056b21ac69..a67a738c0c83 100644 --- a/source/isaaclab_teleop/isaaclab_teleop/deprecated/openxr/manus_vive_utils.py +++ b/source/isaaclab_teleop/isaaclab_teleop/deprecated/openxr/manus_vive_utils.py @@ -9,7 +9,7 @@ import numpy as np -from isaacsim.core.utils.extensions import enable_extension +from isaacsim.core.experimental.utils.app import enable_extension # For testing purposes, we need to mock the XRCore XRCore, XRPoseValidityFlags = None, None diff --git a/source/isaaclab_teleop/isaaclab_teleop/deprecated/openxr/openxr_device.py b/source/isaaclab_teleop/isaaclab_teleop/deprecated/openxr/openxr_device.py index cd57ecf2bd3a..3135e8e5bb4d 100644 --- a/source/isaaclab_teleop/isaaclab_teleop/deprecated/openxr/openxr_device.py +++ b/source/isaaclab_teleop/isaaclab_teleop/deprecated/openxr/openxr_device.py @@ -338,8 +338,8 @@ def _calculate_joint_poses( quati = quat.GetImaginary() quatw = quat.GetReal() else: - quatw = previous_joint_poses[joint_name][3] - quati = previous_joint_poses[joint_name][4:] + quati = previous_joint_poses[joint_name][3:6] + quatw = previous_joint_poses[joint_name][6] # Directly update the dictionary with new data previous_joint_poses[joint_name] = np.array( diff --git a/source/isaaclab_teleop/isaaclab_teleop/deprecated/openxr/retargeters/humanoid/fourier/gr1_t2_dex_retargeting_utils.py b/source/isaaclab_teleop/isaaclab_teleop/deprecated/openxr/retargeters/humanoid/fourier/gr1_t2_dex_retargeting_utils.py index aaeb9bda0314..e832f441e403 100644 --- a/source/isaaclab_teleop/isaaclab_teleop/deprecated/openxr/retargeters/humanoid/fourier/gr1_t2_dex_retargeting_utils.py +++ b/source/isaaclab_teleop/isaaclab_teleop/deprecated/openxr/retargeters/humanoid/fourier/gr1_t2_dex_retargeting_utils.py @@ -158,8 +158,8 @@ def convert_hand_joints(self, hand_poses: dict[str, np.ndarray], operator2mano: # Convert hand pose to the canonical frame. joint_position = joint_position - joint_position[0:1, :] xr_wrist_quat = hand_poses.get("wrist")[3:] - # OpenXR hand uses w,x,y,z order for quaternions but scipy uses x,y,z,w order - wrist_rot = R.from_quat([xr_wrist_quat[1], xr_wrist_quat[2], xr_wrist_quat[3], xr_wrist_quat[0]]).as_matrix() + # OpenXR hand data is in xyzw order, matching scipy's convention + wrist_rot = R.from_quat(xr_wrist_quat).as_matrix() return joint_position @ wrist_rot @ operator2mano diff --git a/source/isaaclab_teleop/isaaclab_teleop/isaac_teleop_cfg.py b/source/isaaclab_teleop/isaaclab_teleop/isaac_teleop_cfg.py index 36dfb55a737c..f94a63d57589 100644 --- a/source/isaaclab_teleop/isaaclab_teleop/isaac_teleop_cfg.py +++ b/source/isaaclab_teleop/isaaclab_teleop/isaac_teleop_cfg.py @@ -9,12 +9,22 @@ from collections.abc import Callable from dataclasses import MISSING, field +from pathlib import Path from typing import TYPE_CHECKING from isaaclab.utils import configclass +from .control_events import TELEOP_CONTROL_CHANNEL_UUID from .xr_cfg import XrCfg +_CLOUDXR_ENV_DIR = Path(__file__).resolve().parent + +CLOUDXR_AVP_ENV: str = str(_CLOUDXR_ENV_DIR / "avp-cloudxr.env") +"""Absolute path to the Apple Vision Pro CloudXR ``.env`` profile (``auto-native``).""" + +CLOUDXR_JS_ENV: str = str(_CLOUDXR_ENV_DIR / "cloudxrjs-cloudxr.env") +"""Absolute path to the CloudXR JS (Quest/Pico) ``.env`` profile (``auto-webrtc``).""" + if TYPE_CHECKING: from isaacteleop.retargeting_engine.interface import BaseRetargeter, OutputCombiner from isaacteleop.teleop_session_manager import PluginConfig @@ -108,6 +118,24 @@ def build_pipeline(): If ``None``, the tuning UI will not be opened. """ + control_channel_uuid: bytes | None = TELEOP_CONTROL_CHANNEL_UUID + """16-byte UUID for the teleop control message channel. + + Defaults to :data:`~isaaclab_teleop.TELEOP_CONTROL_CHANNEL_UUID` + (``uuid5(NAMESPACE_DNS, "teleop_command")``), which is the well-known + channel both the Isaac Lab server and CloudXR JS client use to + exchange start/stop/reset commands. + + When set, a ``teleop_control_pipeline`` is created automatically + using :class:`~isaaclab_teleop.teleop_message_processor.TeleopMessageProcessor` + and :class:`~isaacteleop.teleop_session_manager.DefaultTeleopStateManager`. + The remote client sends UTF-8 control commands over the OpenXR opaque + data channel identified by this UUID, and the results are exposed via + :func:`~isaaclab_teleop.poll_control_events`. + + Set to ``None`` to disable the control channel entirely. + """ + target_frame_prim_path: str | None = None """Optional USD prim path whose world frame becomes the target coordinate frame for all output poses. diff --git a/source/isaaclab_teleop/isaaclab_teleop/isaac_teleop_device.py b/source/isaaclab_teleop/isaaclab_teleop/isaac_teleop_device.py index 832f5536b28c..3f8c565a7e21 100644 --- a/source/isaaclab_teleop/isaaclab_teleop/isaac_teleop_device.py +++ b/source/isaaclab_teleop/isaaclab_teleop/isaac_teleop_device.py @@ -15,6 +15,7 @@ import torch from .command_handler import CommandHandler +from .control_events import ControlEvents from .isaac_teleop_cfg import IsaacTeleopCfg from .session_lifecycle import TeleopSessionLifecycle from .xr_anchor_manager import XrAnchorManager @@ -35,8 +36,8 @@ class IsaacTeleopDevice: and coordinate-frame transform computation. * :class:`TeleopSessionLifecycle` -- pipeline building, OpenXR handle acquisition, session creation/destruction, and action-tensor extraction. - * :class:`CommandHandler` -- callback registration and XR message-bus - command dispatch. + * :class:`CommandHandler` -- callback registration for START / STOP / RESET + commands, bridged from the pipeline-based control events. Together they manage: @@ -67,7 +68,8 @@ class IsaacTeleopDevice: Teleop commands: The device supports callbacks for START, STOP, and RESET commands - that can be triggered via XR controller buttons or the message bus. + that can be triggered via the message-channel control pipeline or + registered directly via :meth:`add_callback`. Example: .. code-block:: python @@ -98,24 +100,36 @@ class IsaacTeleopDevice: env.step(action.repeat(num_envs, 1)) """ - def __init__(self, cfg: IsaacTeleopCfg): + def __init__( + self, + cfg: IsaacTeleopCfg, + cloudxr_env_file: str | None = None, + auto_launch_cloudxr: bool = True, + ): """Initialize the IsaacTeleop device. Args: cfg: Configuration object for IsaacTeleop settings. + cloudxr_env_file: Optional path to a CloudXR ``.env`` file. + When provided and *auto_launch_cloudxr* is ``True``, the + CloudXR runtime is launched automatically during session + start. When ``None``, no CloudXR runtime is launched. + auto_launch_cloudxr: Whether to auto-launch the CloudXR runtime + when *cloudxr_env_file* is set. Ignored when + *cloudxr_env_file* is ``None``. """ self._cfg = cfg - # Compose the three collaborators self._anchor_manager = XrAnchorManager(cfg.xr_cfg) - self._session_lifecycle = TeleopSessionLifecycle(cfg) - self._command_handler = CommandHandler( - xr_core=self._anchor_manager.xr_core, - on_reset=self._anchor_manager.reset, + self._command_handler = CommandHandler() + self._session_lifecycle = TeleopSessionLifecycle( + cfg, + cloudxr_env_file=cloudxr_env_file, + auto_launch_cloudxr=auto_launch_cloudxr, ) - # Controller button polling state (edge detection for right 'A') self._prev_right_a_pressed = False + self._prev_control_is_active: bool | None = None def __del__(self): """Clean up resources when the object is destroyed.""" @@ -172,9 +186,23 @@ def __exit__(self, exc_type, exc_val, exc_tb): def reset(self) -> None: """Reset the device state. - Resets the XR anchor synchronizer if present. + Resets the XR anchor synchronizer and schedules a + ``reset`` :class:`~isaacteleop.retargeting_engine.interface.execution_events.ExecutionEvents` + for the next pipeline step so that all retargeters reinitialize + their cross-step state. """ self._anchor_manager.reset() + self._session_lifecycle.request_reset() + + @property + def last_control_events(self) -> ControlEvents: + """Control events from the most recent :meth:`advance`. + + Returns a :class:`ControlEvents` derived from the teleop control + pipeline. When no control channel is configured, returns a + default (no-op) :class:`ControlEvents`. + """ + return self._session_lifecycle.last_control_events def add_callback(self, key: str, func: Callable) -> None: """Add a callback function for teleop commands. @@ -236,8 +264,39 @@ def advance(self, target_T_world: np.ndarray | torch.Tensor | SupportsDLPack | N # Poll controller buttons (e.g. toggle anchor rotation on right 'A' press) self._poll_buttons() + self._dispatch_control_callbacks() + return action + # ------------------------------------------------------------------ + # Control event -> callback bridge + # ------------------------------------------------------------------ + + def _dispatch_control_callbacks(self) -> None: + """Fire legacy callbacks when control events indicate a state change. + + This bridges the pipeline-based :class:`ControlEvents` with the + callback-based :class:`CommandHandler` so that scripts which registered + callbacks via :meth:`add_callback` still receive dispatches. + + Only fires START/STOP when ``is_active`` transitions between ``True`` + and ``False``; initial transitions from ``None`` are ignored to avoid + spurious callbacks during ``DefaultTeleopStateManager``'s + STOPPED -> PAUSED progression. + """ + from .control_events import _NO_OP_EVENTS + + events = self._session_lifecycle.last_control_events + if events is _NO_OP_EVENTS: + return + if events.should_reset: + self._command_handler.fire("RESET") + self._anchor_manager.reset() + if events.is_active is not None: + if self._prev_control_is_active is not None and events.is_active != self._prev_control_is_active: + self._command_handler.fire("START" if events.is_active else "STOP") + self._prev_control_is_active = events.is_active + # ------------------------------------------------------------------ # Target frame transform (config-driven rebase) # ------------------------------------------------------------------ @@ -350,6 +409,8 @@ def create_isaac_teleop_device( cfg: IsaacTeleopCfg, sim_device: str | None = None, callbacks: dict[str, Callable] | None = None, + cloudxr_env_file: str | None = None, + auto_launch_cloudxr: bool = True, ) -> IsaacTeleopDevice: """Create an :class:`IsaacTeleopDevice` with required Omniverse extension setup. @@ -371,6 +432,14 @@ def create_isaac_teleop_device( are placed on the requested torch device (e.g. ``"cuda:0"``). callbacks: Optional mapping of command keys (e.g. ``"START"``, ``"STOP"``, ``"RESET"``) to callables registered on the device. + cloudxr_env_file: Optional path to a CloudXR ``.env`` file. When + provided and *auto_launch_cloudxr* is ``True``, the CloudXR + runtime and WSS proxy are launched automatically during session + start. When ``None``, no CloudXR runtime is launched. + auto_launch_cloudxr: Whether to auto-launch the CloudXR runtime + when *cloudxr_env_file* is set. Set to ``False`` to skip the + launch (e.g. when running the runtime externally). Ignored + when *cloudxr_env_file* is ``None``. Returns: A fully configured :class:`IsaacTeleopDevice` ready for use in a @@ -382,7 +451,11 @@ def create_isaac_teleop_device( cfg.sim_device = sim_device logger.info("Using IsaacTeleop stack for teleoperation") - device = IsaacTeleopDevice(cfg) + device = IsaacTeleopDevice( + cfg, + cloudxr_env_file=cloudxr_env_file, + auto_launch_cloudxr=auto_launch_cloudxr, + ) if callbacks is not None: for key, func in callbacks.items(): diff --git a/source/isaaclab_teleop/isaaclab_teleop/session_lifecycle.py b/source/isaaclab_teleop/isaaclab_teleop/session_lifecycle.py index 8620e9d85b87..fa5f36f658e0 100644 --- a/source/isaaclab_teleop/isaaclab_teleop/session_lifecycle.py +++ b/source/isaaclab_teleop/isaaclab_teleop/session_lifecycle.py @@ -8,6 +8,7 @@ from __future__ import annotations import logging +import os from collections.abc import Callable from typing import TYPE_CHECKING, Any, Protocol @@ -15,11 +16,15 @@ import torch if TYPE_CHECKING: + from isaacteleop.cloudxr import CloudXRLauncher from isaacteleop.oxr import OpenXRSessionHandles + from isaacteleop.retargeting_engine.interface.execution_events import ExecutionEvents from isaacteleop.retargeting_engine_ui import MultiRetargeterTuningUIImGui from isaacteleop.teleop_session_manager import TeleopSession +from .control_events import _NO_OP_EVENTS, ControlEvents from .isaac_teleop_cfg import IsaacTeleopCfg +from .teleop_message_processor import TeleopMessageProcessor class SupportsDLPack(Protocol): @@ -69,6 +74,19 @@ def _to_numpy_4x4(mat: np.ndarray | torch.Tensor | SupportsDLPack) -> np.ndarray return np.asarray(mat, dtype=np.float32) +def _execution_events_to_control(ee: ExecutionEvents) -> ControlEvents: + """Map TeleopCore :class:`ExecutionEvents` to the script-facing :class:`ControlEvents`.""" + from isaacteleop.retargeting_engine.interface.execution_events import ExecutionState + + if ee.execution_state == ExecutionState.RUNNING: + is_active: bool | None = True + elif ee.execution_state in (ExecutionState.PAUSED, ExecutionState.STOPPED): + is_active = False + else: + is_active = None + return ControlEvents(is_active=is_active, should_reset=ee.reset) + + class TeleopSessionLifecycle: """Manages the IsaacTeleop session lifecycle. @@ -76,11 +94,13 @@ class TeleopSessionLifecycle: 1. Building the retargeting pipeline from configuration 2. Adding a parallel ``ControllersSource`` for button-state access - 3. Acquiring OpenXR handles from Kit's XR bridge extension - 4. Creating, entering, and exiting the ``TeleopSession`` - 5. Building external inputs for pipeline leaf nodes (e.g. world-to-anchor transform) - 6. Stepping the session and extracting the flattened action tensor - 7. Managing the optional retargeting tuning UI + 3. Building the optional ``teleop_control_pipeline`` for headset-driven + start/stop/reset via a message channel + 4. Acquiring OpenXR handles from Kit's XR bridge extension + 5. Creating, entering, and exiting the ``TeleopSession`` + 6. Building external inputs for pipeline leaf nodes (e.g. world-to-anchor transform) + 7. Stepping the session and extracting the flattened action tensor + 8. Managing the optional retargeting tuning UI """ WORLD_T_ANCHOR_INPUT_NAME = "world_T_anchor" @@ -90,20 +110,41 @@ class TeleopSessionLifecycle: _CONTROLLER_RIGHT_KEY = "_controller_right" """Internal pipeline output key for the right controller ``TensorGroup``.""" - def __init__(self, cfg: IsaacTeleopCfg): + def __init__( + self, + cfg: IsaacTeleopCfg, + cloudxr_env_file: str | None = None, + auto_launch_cloudxr: bool = True, + ): """Initialize the session lifecycle manager. Args: cfg: Configuration for IsaacTeleop settings. + cloudxr_env_file: Optional path to a CloudXR ``.env`` file. + When provided, the CloudXR runtime is launched automatically + during :meth:`start` (unless *auto_launch_cloudxr* is + ``False``). When ``None``, no CloudXR runtime is launched. + auto_launch_cloudxr: Whether to auto-launch the CloudXR runtime + when *cloudxr_env_file* is set. Ignored when + *cloudxr_env_file* is ``None``. """ self._cfg = cfg self._device = torch.device(cfg.sim_device) + self._cloudxr_env_file = cloudxr_env_file + self._auto_launch_cloudxr = auto_launch_cloudxr # Session state (populated during start) self._session: TeleopSession | None = None self._pipeline = None + self._teleop_control_pipeline = None + self._message_processor: TeleopMessageProcessor | None = None self._last_right_controller = None self._session_start_deferred_logged = False + # Fallback for host-initiated resets when no control pipeline is configured + self._pending_reset = False + + # CloudXR runtime launcher (created in start if configured, stopped in stop) + self._cloudxr_launcher: CloudXRLauncher | None = None # Retargeting tuning UI (created in start, closed in stop) self._retargeting_ui_ctx: MultiRetargeterTuningUIImGui | None = None @@ -173,6 +214,48 @@ def last_right_controller(self): """ return self._last_right_controller + @property + def has_control_channel(self) -> bool: + """Whether a message-channel-based control pipeline is configured.""" + return self._message_processor is not None + + @property + def last_control_events(self) -> ControlEvents: + """Control events from the most recent :meth:`step`. + + When a ``teleop_control_pipeline`` is configured, derives + :class:`ControlEvents` from + ``session.last_context.execution_events``. Otherwise returns a + default (no-op) :class:`ControlEvents`. + """ + if self._message_processor is None: + return _NO_OP_EVENTS + if self._session is None: + return _NO_OP_EVENTS + ctx = self._session.last_context + if ctx is None: + return _NO_OP_EVENTS + return _execution_events_to_control(ctx.execution_events) + + def request_reset(self) -> None: + """Schedule a reset for the next pipeline step. + + When a control pipeline is configured, the reset flows through + :meth:`TeleopMessageProcessor.inject_reset` so + :class:`~isaacteleop.teleop_session_manager.DefaultTeleopStateManager` + processes it normally. Otherwise falls back to an + ``execution_events`` override on the next :meth:`step` call. + + If the control channel already processed a reset this frame, + this method is a no-op to avoid a redundant second reset pulse. + """ + if self.last_control_events.should_reset: + return + if self._message_processor is not None: + self._message_processor.inject_reset() + else: + self._pending_reset = True + # ------------------------------------------------------------------ # Lifecycle: start / stop # ------------------------------------------------------------------ @@ -180,15 +263,22 @@ def last_right_controller(self): def start(self) -> None: """Build the pipeline and attempt to start the session. + If a CloudXR env file was provided and auto-launch is enabled, + the CloudXR runtime and WSS proxy are launched first. + Builds the retargeting pipeline, wraps it with a parallel - ``ControllersSource`` for button-state access, attempts to acquire - OpenXR handles, and opens the retargeting tuning UI if retargeters - are configured. + ``ControllersSource`` for button-state access, builds the optional + ``teleop_control_pipeline`` for message-channel control, attempts + to acquire OpenXR handles, and opens the retargeting tuning UI if + retargeters are configured. If the OpenXR handles are not yet available (e.g. user hasn't clicked "Start AR"), session creation is deferred and will be retried on each :meth:`step` call. """ + if self._cloudxr_env_file is not None: + self._ensure_cloudxr_runtime() + from isaacteleop.retargeting_engine.deviceio_source_nodes import ControllersSource from isaacteleop.retargeting_engine.interface import OutputCombiner @@ -197,12 +287,19 @@ def start(self) -> None: self._last_right_controller = None button_controllers = ControllersSource("_button_controllers") - self._pipeline = OutputCombiner( - { - "action": user_pipeline.output("action"), - self._CONTROLLER_RIGHT_KEY: button_controllers.output(ControllersSource.RIGHT), - } - ) + pipeline_outputs: dict[str, Any] = { + "action": user_pipeline.output("action"), + self._CONTROLLER_RIGHT_KEY: button_controllers.output(ControllersSource.RIGHT), + } + self._pipeline = OutputCombiner(pipeline_outputs) + + # Build optional teleop_control_pipeline for message-channel control + self._teleop_control_pipeline = None + self._message_processor = None + if self._cfg.control_channel_uuid is not None: + self._teleop_control_pipeline, self._message_processor = self._build_control_pipeline( + self._cfg.control_channel_uuid + ) # Try to start the session now; it may be deferred self._try_start_session() @@ -244,21 +341,86 @@ def stop(self, exc_type=None, exc_val=None, exc_tb=None) -> None: # expected and safe to suppress. logger.debug(f"Suppressed error during IsaacTeleop session cleanup: {e}") self._session = None - self._pipeline = None + + # Always clear pipeline state (session may never have been created if + # OpenXR handles were never available). + self._pipeline = None + self._teleop_control_pipeline = None + self._message_processor = None + + if self._cloudxr_launcher is not None: + try: + self._cloudxr_launcher.stop() + except RuntimeError: + logger.warning("CloudXR runtime process could not be terminated; handle retained for atexit cleanup") + else: + self._cloudxr_launcher = None + logger.info("CloudXR runtime stopped") + logger.info("IsaacTeleop session ended") + # ------------------------------------------------------------------ + # Control pipeline construction + # ------------------------------------------------------------------ + + @staticmethod + def _build_control_pipeline(channel_uuid: bytes) -> tuple[Any, TeleopMessageProcessor]: + """Build a ``teleop_control_pipeline`` from a message channel UUID. + + Wires ``MessageChannelSource`` -> :class:`TeleopMessageProcessor` + -> :class:`~isaacteleop.teleop_session_manager.DefaultTeleopStateManager`. + + Args: + channel_uuid: 16-byte UUID for the OpenXR opaque data channel. + + Returns: + A ``(teleop_control_pipeline, message_processor)`` tuple. + """ + from isaacteleop.retargeting_engine.deviceio_source_nodes import message_channel_config + from isaacteleop.teleop_session_manager import DefaultTeleopStateManager + + source, _sink = message_channel_config( + name="_teleop_control", + channel_uuid=channel_uuid, + ) + + processor = TeleopMessageProcessor(name="_teleop_msg_processor") + processor_graph = processor.connect({processor.INPUT_MESSAGES: source.output("messages_tracked")}) + + state_manager = DefaultTeleopStateManager(name="_teleop_state") + teleop_control_pipeline = state_manager.connect( + { + state_manager.INPUT_KILL: processor_graph.output("kill"), + state_manager.INPUT_RUN_TOGGLE: processor_graph.output("run_toggle"), + state_manager.INPUT_RESET: processor_graph.output("reset"), + } + ) + + return teleop_control_pipeline, processor + + # ------------------------------------------------------------------ + # Extension / XR lifecycle callbacks + # ------------------------------------------------------------------ + def _on_request_required_extensions(self) -> list[str]: """Callback for required extensions subscription. + Inspects both the main pipeline and the ``teleop_control_pipeline`` + (if configured) so that extensions required by the control channel + (e.g. ``XR_NV_opaque_data_channel``) are included. + Returns: A list of required extensions. """ from isaacteleop.teleop_session_manager.helpers import get_required_oxr_extensions_from_pipeline - required_extensions = ( - get_required_oxr_extensions_from_pipeline(self._pipeline) if self._pipeline is not None else [] - ) + required_extensions: list[str] = [] + if self._pipeline is not None: + required_extensions.extend(get_required_oxr_extensions_from_pipeline(self._pipeline)) + if self._teleop_control_pipeline is not None: + required_extensions.extend(get_required_oxr_extensions_from_pipeline(self._teleop_control_pipeline)) + required_extensions = sorted(set(required_extensions)) logger.info(f"Required extensions: {required_extensions}") return required_extensions @@ -272,10 +434,16 @@ def _on_xr_enabled_changed(self, item, event_type): self._teardown_dead_session() def _on_pre_shutdown(self, _event): - """Called when Kit is closing; run full cleanup since the app is exiting.""" + """Called when Kit is closing; tear down the session but leave the + pipeline intact so the main loop can exit via its own control flow + (``simulation_app.is_running()`` will go ``False``). + + Full resource cleanup happens later when the context manager's + ``__exit__`` calls :meth:`stop`. + """ logger.info("Shutting down IsaacTeleop session due to Kit close") self._pre_shutdown_subscription = None - self.stop() + self._teardown_dead_session() # ------------------------------------------------------------------ # Deferred session creation @@ -306,11 +474,6 @@ def _try_start_session(self) -> bool: if self._session is not None: return True - # In headless mode the AR profile setting is deliberately omitted - # from the .kit file so that all extensions (including the teleop - # bridge and its BridgeComponent) can load and register before Kit - # creates the OpenXR instance. We enable it here, after extensions - # are loaded; Kit will process the change on the next event-loop tick. self._ensure_xr_ar_profile_enabled() from isaacteleop.oxr import OpenXRSessionHandles @@ -336,6 +499,7 @@ def _try_start_session(self) -> bool: app_name=self._cfg.app_name, trackers=[], pipeline=self._pipeline, + teleop_control_pipeline=self._teleop_control_pipeline, plugins=self._cfg.plugins, oxr_handles=oxr_handles, ) @@ -401,6 +565,15 @@ def step( # pipeline contains ValueInput leaf nodes. external_inputs = self._build_external_inputs(anchor_world_matrix_fn, target_T_world) + # When no control pipeline is configured, host-initiated resets use + # the execution_events override as a fallback path. + execution_events = None + if self._pending_reset: + from isaacteleop.retargeting_engine.interface.execution_events import ExecutionEvents, ExecutionState + + execution_events = ExecutionEvents(reset=True, execution_state=ExecutionState.RUNNING) + self._pending_reset = False + # Execute one step of the teleop session. # If the underlying OpenXR session was destroyed externally (e.g. # user clicked "Stop AR"), the step call will fail. We catch the @@ -408,7 +581,10 @@ def step( # can continue rendering (or wait for the session to restart). assert self._session is not None # guaranteed by _try_start_session above try: - result = self._session.step(external_inputs=external_inputs) + result = self._session.step( + external_inputs=external_inputs, + execution_events=execution_events, + ) except Exception as e: logger.warning(f"IsaacTeleop session step failed (XR session likely torn down): {e}") self._teardown_dead_session() @@ -507,6 +683,44 @@ def _build_external_inputs( return external_inputs if external_inputs else None + # ------------------------------------------------------------------ + # CloudXR runtime auto-launch + # ------------------------------------------------------------------ + + def _ensure_cloudxr_runtime(self) -> None: + """Launch the CloudXR runtime and WSS proxy if configured. + + Uses :class:`~isaacteleop.cloudxr.CloudXRLauncher` to set up the + environment, spawn the native runtime process, and start the WSS + TLS proxy in a background thread. The launcher is stored in + ``self._cloudxr_launcher`` and shut down in :meth:`stop`. + + Auto-launch is skipped when ``auto_launch_cloudxr`` is ``False`` + or the ``ISAACLAB_CXR_SKIP_AUTOLAUNCH=1`` environment variable is + set (the env var takes precedence). + """ + if self._cloudxr_launcher is not None: + return + + if os.environ.get("ISAACLAB_CXR_SKIP_AUTOLAUNCH", "").strip() == "1": + logger.info("CloudXR auto-launch skipped (ISAACLAB_CXR_SKIP_AUTOLAUNCH=1)") + return + + if not self._auto_launch_cloudxr: + logger.info("CloudXR auto-launch disabled (auto_launch_cloudxr=False)") + return + + from pathlib import Path + + from isaacteleop.cloudxr import CloudXRLauncher as _CloudXRLauncher + + self._cloudxr_launcher = _CloudXRLauncher( + install_dir=str(Path.home() / ".cloudxr"), + env_config=self._cloudxr_env_file, + accept_eula=False, + ) + logger.info("CloudXR runtime auto-launched") + # ------------------------------------------------------------------ # OpenXR handle acquisition # ------------------------------------------------------------------ diff --git a/source/isaaclab_teleop/isaaclab_teleop/teleop_message_processor.py b/source/isaaclab_teleop/isaaclab_teleop/teleop_message_processor.py new file mode 100644 index 000000000000..1844925c4d0c --- /dev/null +++ b/source/isaaclab_teleop/isaaclab_teleop/teleop_message_processor.py @@ -0,0 +1,232 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Message-channel payload parser for TeleopCore's teleop_control_pipeline. + +Provides :class:`TeleopMessageProcessor`, a lightweight +:class:`~isaacteleop.retargeting_engine.interface.BaseRetargeter` that +converts message-channel payloads into boolean pulse signals suitable for +:class:`~isaacteleop.teleop_session_manager.DefaultTeleopStateManager`. +""" + +from __future__ import annotations + +import json +import re +from typing import TYPE_CHECKING + +from isaacteleop.retargeting_engine.interface import BaseRetargeter, RetargeterIOType + +if TYPE_CHECKING: + from isaacteleop.retargeting_engine.interface.retargeter_core_types import ComputeContext, RetargeterIO + +_COMMAND_PATTERNS: list[tuple[re.Pattern[str], str]] = [ + (re.compile(r"\breset\b", re.IGNORECASE), "reset"), + (re.compile(r"\bstop\b", re.IGNORECASE), "stop"), + (re.compile(r"\bstart\b", re.IGNORECASE), "start"), +] +"""Ordered patterns for classifying a command string. + +``reset`` is checked first so that a hypothetical payload containing +both "reset" and "start" is treated as a reset (the more destructive +operation wins). ``stop`` precedes ``start`` for the same reason. +""" + +# Shadow states mirroring DefaultTeleopStateManager's ExecutionState. +_STOPPED = "stopped" +_PAUSED = "paused" +_RUNNING = "running" + +# DefaultTeleopStateManager cycles states on run_toggle rising edges: +# STOPPED -> PAUSED -> RUNNING -> PAUSED -> RUNNING -> ... +# To map imperative "start" (= go to RUNNING) and "stop" (= go to PAUSED) +# we emit the right number of toggle edges based on predicted state. +_START_TOGGLE_SEQUENCES: dict[str, list[bool]] = { + _STOPPED: [True, False, True], # 2 edges: STOPPED -> PAUSED -> RUNNING + _PAUSED: [True], # 1 edge: PAUSED -> RUNNING + _RUNNING: [], # already running +} +_STOP_TOGGLE_SEQUENCES: dict[str, list[bool]] = { + _RUNNING: [True], # 1 edge: RUNNING -> PAUSED + _PAUSED: [], # already paused + _STOPPED: [], # already stopped +} +# Shadow state advances on each rising edge (True after False). +_TOGGLE_TRANSITIONS: dict[str, str] = { + _STOPPED: _PAUSED, + _PAUSED: _RUNNING, + _RUNNING: _PAUSED, +} + + +class TeleopMessageProcessor(BaseRetargeter): + """Parse message-channel payloads into boolean control signals. + + Consumes the ``messages_tracked`` output of a + :class:`~isaacteleop.retargeting_engine.deviceio_source_nodes.MessageChannelSource` + and produces three boolean pulse outputs that drive + :class:`~isaacteleop.teleop_session_manager.DefaultTeleopStateManager`: + + * ``run_toggle`` -- pulsed ``True`` on rising edges; the number of + edges depends on the target state (e.g. ``"start"`` from STOPPED + emits two edges over three frames: STOPPED -> PAUSED -> RUNNING). + * ``kill`` -- always ``False`` (reserved for fail-safe; ``"stop"`` + uses ``run_toggle`` to reach PAUSED instead of STOPPED). + * ``reset`` -- pulsed ``True`` for one frame on ``"reset"``. + + The processor maintains a *shadow state* that mirrors + ``DefaultTeleopStateManager``'s internal state so it can emit the + correct toggle sequence for imperative commands. + + Payload formats supported: + + 1. **JSON (Quest client format)**:: + + {"type": "teleop_command", "message": {"command": "start teleop"}} + + 2. **Plain text (fallback)**: raw UTF-8 string matched by word boundary + (``"start"``, ``"stop"``, ``"reset"``). + + Host-initiated resets (e.g. environment success) are injected via + :meth:`inject_reset`, which sets the ``reset`` output ``True`` on the + next compute call without requiring a message-channel payload. + """ + + INPUT_MESSAGES = "messages_tracked" + + def __init__(self, name: str) -> None: + self._inject_reset_pending = False + self._shadow_state = _STOPPED + self._run_toggle_queue: list[bool] = [] + self._prev_toggle_output = False + super().__init__(name=name) + + def inject_reset(self) -> None: + """Schedule a reset pulse on the next pipeline step. + + The ``reset`` output will be ``True`` for exactly one frame, then + automatically cleared. + """ + self._inject_reset_pending = True + + def _make_toggle_sequence(self, base_sequence: list[bool]) -> list[bool]: + """Prepend a ``False`` frame if needed to guarantee a clean rising edge. + + ``DefaultTeleopStateManager`` uses edge detection + (``pressed and not prev_pressed``), so emitting ``True`` when the + previous output was already ``True`` would not trigger a state + transition. This method prepends ``False`` when necessary. + """ + if not base_sequence: + return [] + seq = list(base_sequence) + if self._prev_toggle_output: + seq.insert(0, False) + return seq + + def input_spec(self) -> RetargeterIOType: + from isaacteleop.retargeting_engine.deviceio_source_nodes.deviceio_tensor_types import ( + MessageChannelMessagesTrackedGroup, + ) + + return {self.INPUT_MESSAGES: MessageChannelMessagesTrackedGroup()} + + def output_spec(self) -> RetargeterIOType: + from isaacteleop.teleop_session_manager.teleop_state_manager_types import bool_signal + + return { + "run_toggle": bool_signal("run_toggle"), + "kill": bool_signal("kill"), + "reset": bool_signal("reset"), + } + + def _compute_fn( + self, + inputs: RetargeterIO, + outputs: RetargeterIO, + context: ComputeContext, + ) -> None: + del context + + reset = self._inject_reset_pending + self._inject_reset_pending = False + + # Parse incoming messages and enqueue toggle sequences. + messages_tracked = inputs[self.INPUT_MESSAGES][0] + data = getattr(messages_tracked, "data", None) + if data: + for message in data: + payload = getattr(message, "payload", None) + if payload is None: + continue + try: + text = bytes(payload).decode("utf-8") + except (UnicodeDecodeError, TypeError): + continue + + command = _extract_command(text) + if command is None: + continue + + kind = _classify_command(command) + if kind == "start" and not self._run_toggle_queue: + self._run_toggle_queue = self._make_toggle_sequence(_START_TOGGLE_SEQUENCES[self._shadow_state]) + elif kind == "stop" and not self._run_toggle_queue: + self._run_toggle_queue = self._make_toggle_sequence(_STOP_TOGGLE_SEQUENCES[self._shadow_state]) + elif kind == "reset": + reset = True + + # Drain the toggle queue (one value per frame). + if self._run_toggle_queue: + run_toggle = self._run_toggle_queue.pop(0) + else: + run_toggle = False + + # Advance shadow state on rising edges (matches DefaultTeleopStateManager's + # edge detection: ``pressed and not prev_pressed``). + if run_toggle and not self._prev_toggle_output: + self._shadow_state = _TOGGLE_TRANSITIONS[self._shadow_state] + self._prev_toggle_output = run_toggle + + outputs["run_toggle"][0] = run_toggle + outputs["kill"][0] = False + outputs["reset"][0] = reset + + +def _classify_command(text: str) -> str | None: + """Return ``"start"``, ``"stop"``, ``"reset"``, or ``None``. + + Uses word-boundary matching so that e.g. ``"stop_and_restart"`` + matches ``"stop"`` (not ``"start"``). + """ + for pattern, label in _COMMAND_PATTERNS: + if pattern.search(text): + return label + return None + + +def _extract_command(text: str) -> str | None: + """Extract the command string from a JSON or plain-text payload. + + Tries JSON parsing first (Quest client format) and falls back to the + raw text for plain-string payloads. Non-string JSON scalars (numbers, + arrays, booleans) are discarded. + """ + try: + obj = json.loads(text) + except (json.JSONDecodeError, TypeError): + return text + + if not isinstance(obj, dict): + return None + if obj.get("type") != "teleop_command": + return None + + msg = obj.get("message") + if isinstance(msg, dict): + return msg.get("command", "") + if isinstance(msg, str): + return msg + return None diff --git a/source/isaaclab_teleop/isaaclab_teleop/xr_anchor_manager.py b/source/isaaclab_teleop/isaaclab_teleop/xr_anchor_manager.py index a225b7f6297f..d39cdcbe84ad 100644 --- a/source/isaaclab_teleop/isaaclab_teleop/xr_anchor_manager.py +++ b/source/isaaclab_teleop/isaaclab_teleop/xr_anchor_manager.py @@ -24,8 +24,7 @@ with contextlib.suppress(ModuleNotFoundError): from omni.kit.xr.core import XRCore, XRCoreEventType -with contextlib.suppress(ModuleNotFoundError): - from isaacsim.core.prims import SingleXFormPrim +from isaaclab.sim.utils.prims import create_prim as _create_prim logger = logging.getLogger(__name__) @@ -77,14 +76,12 @@ def __init__(self, xr_cfg: XrCfg): self._xr_anchor_headset_path = "/World/XRAnchor" # Create the XR anchor prim in USD. - # XrCfg.anchor_rot is xyzw; SingleXFormPrim expects wxyz. + # XrCfg.anchor_rot is xyzw; create_prim orientation expects xyzw. x, y, z, w = self._xr_cfg.anchor_rot try: - _ = SingleXFormPrim( - self._xr_anchor_headset_path, - position=self._xr_cfg.anchor_pos, - orientation=np.array([w, x, y, z], dtype=np.float64), - ) + pos = np.asarray(self._xr_cfg.anchor_pos, dtype=np.float64) + quat_xyzw = np.asarray([x, y, z, w], dtype=np.float64) + _create_prim(self._xr_anchor_headset_path, prim_type="Xform", position=pos, orientation=quat_xyzw) except Exception as e: logger.warning(f"Failed to create XR anchor prim: {e}") diff --git a/source/isaaclab_teleop/isaaclab_teleop/xr_anchor_utils.py b/source/isaaclab_teleop/isaaclab_teleop/xr_anchor_utils.py index 035630959fb8..196de3ce56b9 100644 --- a/source/isaaclab_teleop/isaaclab_teleop/xr_anchor_utils.py +++ b/source/isaaclab_teleop/isaaclab_teleop/xr_anchor_utils.py @@ -17,7 +17,7 @@ logger = logging.getLogger(__name__) from isaaclab.sim import SimulationContext -from isaaclab.sim.utils.stage import get_current_stage_id +from isaaclab.sim.utils.stage import get_current_stage, get_current_stage_id from .xr_cfg import XrAnchorRotationMode @@ -51,8 +51,6 @@ def __init__(self, xr_core: Any, xr_cfg: Any, xr_anchor_headset_path: str): # Resolve USD layer identifier of the anchor for updates try: - from isaacsim.core.utils.stage import get_current_stage - stage = get_current_stage() xr_anchor_headset_prim = stage.GetPrimAtPath(self._xr_anchor_headset_path) prim_stack = xr_anchor_headset_prim.GetPrimStack() if xr_anchor_headset_prim is not None else None diff --git a/source/isaaclab_teleop/setup.py b/source/isaaclab_teleop/setup.py index bc80dd556066..7ecec8340abb 100644 --- a/source/isaaclab_teleop/setup.py +++ b/source/isaaclab_teleop/setup.py @@ -6,7 +6,6 @@ """Installation script for the 'isaaclab_teleop' python package.""" import os -import platform import toml from setuptools import find_packages, setup @@ -16,12 +15,15 @@ # 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 = [] +SUPPORTED_ARCHS = "platform_machine in 'x86_64,AMD64'" -# nvidia-srl-usd-to-urdf depends on usd-core which has no aarch64 wheels -if platform.machine() != "aarch64": - INSTALL_REQUIRES.append("nvidia-srl-usd-to-urdf") +# Minimum dependencies required prior to installation +INSTALL_REQUIRES = [ + # IsaacTeleop is only available on Linux x86_64 + f"isaacteleop[retargeters,ui,cloudxr]~=1.2.0 ; platform_system == 'Linux' and ({SUPPORTED_ARCHS})", + # required by isaaclab.devices.openxr.retargeters.humanoid.fourier.gr1_t2_dex_retargeting_utils + f"dex-retargeting==0.5.0 ; platform_system == 'Linux' and ({SUPPORTED_ARCHS})", +] # Installation operation setup( @@ -33,19 +35,13 @@ description=EXTENSION_TOML_DATA["package"]["description"], keywords=EXTENSION_TOML_DATA["package"]["keywords"], include_package_data=True, - package_data={"": ["*.pyi"]}, - python_requires=">=3.10", + package_data={"": ["*.pyi", "*.env"]}, + python_requires=">=3.12", install_requires=INSTALL_REQUIRES, - extras_require={ - "teleop": ["isaacteleop"], - }, packages=find_packages(), classifiers=[ "Natural Language :: English", - "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", - "Isaac Sim :: 5.0.0", - "Isaac Sim :: 5.1.0", "Isaac Sim :: 6.0.0", ], zip_safe=False, diff --git a/source/isaaclab_teleop/test/test_cloudxr_lifecycle.py b/source/isaaclab_teleop/test/test_cloudxr_lifecycle.py new file mode 100644 index 000000000000..43131f70cfc3 --- /dev/null +++ b/source/isaaclab_teleop/test/test_cloudxr_lifecycle.py @@ -0,0 +1,341 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +# pyright: reportPrivateUsage=none + +"""Tests for CloudXR runtime auto-launch lifecycle. + +These tests exercise the CloudXR auto-launch logic in +:class:`~isaaclab_teleop.session_lifecycle.TeleopSessionLifecycle` without +requiring the Omniverse/Isaac Sim stack or a real CloudXR installation. + +All heavy dependencies (isaacteleop, carb, omni.kit, isaacsim) are +stubbed out via ``sys.modules`` and ``unittest.mock`` so these tests run +in a plain Python environment. +""" + +from __future__ import annotations + +import os +import sys +from pathlib import Path +from types import ModuleType +from unittest.mock import MagicMock, patch + +import pytest + +# --------------------------------------------------------------------------- +# Stub out isaacteleop and Kit modules before any isaaclab_teleop imports. +# TeleopSessionLifecycle.__init__ tries to import several Kit/XR modules; +# we inject stubs so the constructor can complete without Omniverse. +# --------------------------------------------------------------------------- + +_MODULES_TO_STUB = [ + "isaacteleop", + "isaacteleop.cloudxr", + "isaacteleop.oxr", + "isaacteleop.retargeting_engine", + "isaacteleop.retargeting_engine.interface", + "isaacteleop.retargeting_engine.interface.execution_events", + "isaacteleop.retargeting_engine.interface.retargeter_core_types", + "isaacteleop.retargeting_engine.interface.tensor_group_type", + "isaacteleop.retargeting_engine.deviceio_source_nodes", + "isaacteleop.retargeting_engine.deviceio_source_nodes.deviceio_tensor_types", + "isaacteleop.retargeting_engine_ui", + "isaacteleop.teleop_session_manager", + "isaacteleop.teleop_session_manager.teleop_state_manager_retargeter", + "isaacteleop.teleop_session_manager.teleop_state_manager_types", + "isaacsim", + "isaacsim.kit", + "isaacsim.kit.xr", + "isaacsim.kit.xr.teleop", + "isaacsim.kit.xr.teleop.bridge", + "carb", + "carb.settings", + "carb.eventdispatcher", + "omni", + "omni.kit", + "omni.kit.app", + "omni.kit.xr", + "omni.kit.xr.system", + "omni.kit.xr.system.openxr", +] + +_stubs_installed: dict[str, ModuleType | MagicMock] = {} + + +def _install_stubs(): + """Insert MagicMock modules for all heavy dependencies.""" + for name in _MODULES_TO_STUB: + if name not in sys.modules: + _stubs_installed[name] = MagicMock() + sys.modules[name] = _stubs_installed[name] + + +_install_stubs() + +from isaaclab_teleop.isaac_teleop_cfg import ( # noqa: E402 + CLOUDXR_AVP_ENV, + CLOUDXR_JS_ENV, + IsaacTeleopCfg, +) +from isaaclab_teleop.session_lifecycle import TeleopSessionLifecycle # noqa: E402 + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + + +def _make_cfg() -> IsaacTeleopCfg: + """Build a minimal IsaacTeleopCfg with a dummy pipeline_builder.""" + return IsaacTeleopCfg( + pipeline_builder=lambda: MagicMock(), + control_channel_uuid=None, + ) + + +def _make_lifecycle( + cloudxr_env_file: str | None = None, + auto_launch_cloudxr: bool = True, +) -> TeleopSessionLifecycle: + """Create a TeleopSessionLifecycle with Kit dependencies safely stubbed.""" + cfg = _make_cfg() + return TeleopSessionLifecycle( + cfg, + cloudxr_env_file=cloudxr_env_file, + auto_launch_cloudxr=auto_launch_cloudxr, + ) + + +# ============================================================================ +# Shipped .env profile paths +# ============================================================================ + + +class TestEnvProfilePaths: + """Tests for the shipped .env profile path constants.""" + + def test_avp_env_is_absolute_path(self): + assert os.path.isabs(CLOUDXR_AVP_ENV) + + def test_js_env_is_absolute_path(self): + assert os.path.isabs(CLOUDXR_JS_ENV) + + def test_avp_env_file_exists(self): + assert Path(CLOUDXR_AVP_ENV).is_file(), f"Missing: {CLOUDXR_AVP_ENV}" + + def test_js_env_file_exists(self): + assert Path(CLOUDXR_JS_ENV).is_file(), f"Missing: {CLOUDXR_JS_ENV}" + + def test_avp_env_filename(self): + assert Path(CLOUDXR_AVP_ENV).name == "avp-cloudxr.env" + + def test_js_env_filename(self): + assert Path(CLOUDXR_JS_ENV).name == "cloudxrjs-cloudxr.env" + + def test_profiles_are_in_same_directory(self): + assert Path(CLOUDXR_AVP_ENV).parent == Path(CLOUDXR_JS_ENV).parent + + +# ============================================================================ +# _ensure_cloudxr_runtime +# ============================================================================ + + +class TestEnsureCloudXRRuntime: + """Tests for the ``_ensure_cloudxr_runtime`` method on TeleopSessionLifecycle.""" + + def test_skip_when_env_var_set(self): + """ISAACLAB_CXR_SKIP_AUTOLAUNCH=1 skips the launch entirely.""" + lifecycle = _make_lifecycle(cloudxr_env_file="/tmp/test.env") + + with patch.dict(os.environ, {"ISAACLAB_CXR_SKIP_AUTOLAUNCH": "1"}): + lifecycle._ensure_cloudxr_runtime() + + assert lifecycle._cloudxr_launcher is None + + def test_skip_when_env_var_set_with_whitespace(self): + """Whitespace around the env var value is stripped before comparison.""" + lifecycle = _make_lifecycle(cloudxr_env_file="/tmp/test.env") + + with patch.dict(os.environ, {"ISAACLAB_CXR_SKIP_AUTOLAUNCH": " 1 "}): + lifecycle._ensure_cloudxr_runtime() + + assert lifecycle._cloudxr_launcher is None + + def test_no_skip_when_env_var_zero(self): + """ISAACLAB_CXR_SKIP_AUTOLAUNCH=0 does NOT skip the launch.""" + mock_cls = MagicMock() + fake_module = MagicMock() + fake_module.CloudXRLauncher = mock_cls + + lifecycle = _make_lifecycle(cloudxr_env_file="/tmp/test.env") + + with ( + patch.dict(os.environ, {"ISAACLAB_CXR_SKIP_AUTOLAUNCH": "0"}), + patch.dict(sys.modules, {"isaacteleop.cloudxr": fake_module}), + ): + lifecycle._ensure_cloudxr_runtime() + + assert lifecycle._cloudxr_launcher is not None + + def test_skip_when_auto_launch_false(self): + """auto_launch_cloudxr=False skips the launch.""" + lifecycle = _make_lifecycle( + cloudxr_env_file="/tmp/test.env", + auto_launch_cloudxr=False, + ) + + with patch.dict(os.environ, {}, clear=False): + os.environ.pop("ISAACLAB_CXR_SKIP_AUTOLAUNCH", None) + lifecycle._ensure_cloudxr_runtime() + + assert lifecycle._cloudxr_launcher is None + + def test_idempotency(self): + """Calling _ensure_cloudxr_runtime twice does not create a second launcher.""" + sentinel = MagicMock() + lifecycle = _make_lifecycle(cloudxr_env_file="/tmp/test.env") + lifecycle._cloudxr_launcher = sentinel + + lifecycle._ensure_cloudxr_runtime() + + assert lifecycle._cloudxr_launcher is sentinel + + def test_launches_with_correct_args(self): + """CloudXRLauncher is constructed with hardcoded install_dir/accept_eula and the env file.""" + mock_cls = MagicMock() + lifecycle = _make_lifecycle(cloudxr_env_file="/etc/cxr.env") + + fake_module = MagicMock() + fake_module.CloudXRLauncher = mock_cls + + with ( + patch.dict(os.environ, {}, clear=False), + patch.dict(sys.modules, {"isaacteleop.cloudxr": fake_module}), + ): + os.environ.pop("ISAACLAB_CXR_SKIP_AUTOLAUNCH", None) + lifecycle._ensure_cloudxr_runtime() + + mock_cls.assert_called_once_with( + install_dir=str(Path.home() / ".cloudxr"), + env_config="/etc/cxr.env", + accept_eula=False, + ) + assert lifecycle._cloudxr_launcher is mock_cls.return_value + + def test_env_var_takes_precedence_over_auto_launch(self): + """ISAACLAB_CXR_SKIP_AUTOLAUNCH=1 overrides auto_launch_cloudxr=True.""" + lifecycle = _make_lifecycle( + cloudxr_env_file="/tmp/test.env", + auto_launch_cloudxr=True, + ) + + with patch.dict(os.environ, {"ISAACLAB_CXR_SKIP_AUTOLAUNCH": "1"}): + lifecycle._ensure_cloudxr_runtime() + + assert lifecycle._cloudxr_launcher is None + + +# ============================================================================ +# Lifecycle start/stop integration with CloudXR +# ============================================================================ + + +class TestLifecycleCloudXRIntegration: + """Tests for CloudXR launch/shutdown within the start()/stop() lifecycle.""" + + def _make_started_lifecycle(self) -> tuple[TeleopSessionLifecycle, MagicMock]: + """Build a lifecycle whose start() has been called with a mock launcher.""" + mock_cls = MagicMock() + lifecycle = _make_lifecycle(cloudxr_env_file="/tmp/test.env") + + fake_cxr_module = MagicMock() + fake_cxr_module.CloudXRLauncher = mock_cls + + fake_teleop_modules = { + "isaacteleop.cloudxr": fake_cxr_module, + "isaacteleop.retargeting_engine.deviceio_source_nodes": MagicMock(), + "isaacteleop.retargeting_engine.interface": MagicMock(), + } + + with ( + patch.dict(os.environ, {}, clear=False), + patch.dict(sys.modules, fake_teleop_modules), + ): + os.environ.pop("ISAACLAB_CXR_SKIP_AUTOLAUNCH", None) + lifecycle.start() + + return lifecycle, mock_cls.return_value + + def test_start_launches_runtime(self): + """start() invokes _ensure_cloudxr_runtime when cloudxr_env_file is set.""" + lifecycle, mock_launcher = self._make_started_lifecycle() + assert lifecycle._cloudxr_launcher is mock_launcher + + def test_stop_calls_launcher_stop(self): + """stop() calls CloudXRLauncher.stop().""" + lifecycle, mock_launcher = self._make_started_lifecycle() + lifecycle.stop() + mock_launcher.stop.assert_called_once() + + def test_stop_clears_launcher_on_success(self): + """After a successful stop(), _cloudxr_launcher is set to None.""" + lifecycle, mock_launcher = self._make_started_lifecycle() + lifecycle.stop() + assert lifecycle._cloudxr_launcher is None + + def test_stop_retains_launcher_on_runtime_error(self): + """When CloudXRLauncher.stop() raises RuntimeError, the launcher is retained for atexit.""" + lifecycle, mock_launcher = self._make_started_lifecycle() + mock_launcher.stop.side_effect = RuntimeError("process not found") + + lifecycle.stop() + + assert lifecycle._cloudxr_launcher is mock_launcher + + def test_start_without_cloudxr_env_file(self): + """start() works normally when no cloudxr_env_file is provided.""" + lifecycle = _make_lifecycle(cloudxr_env_file=None) + + fake_teleop_modules = { + "isaacteleop.retargeting_engine.deviceio_source_nodes": MagicMock(), + "isaacteleop.retargeting_engine.interface": MagicMock(), + } + + with patch.dict(sys.modules, fake_teleop_modules): + lifecycle.start() + + assert lifecycle._cloudxr_launcher is None + + def test_start_with_auto_launch_disabled(self): + """start() skips CloudXR launch when auto_launch_cloudxr=False.""" + lifecycle = _make_lifecycle( + cloudxr_env_file="/tmp/test.env", + auto_launch_cloudxr=False, + ) + + fake_teleop_modules = { + "isaacteleop.retargeting_engine.deviceio_source_nodes": MagicMock(), + "isaacteleop.retargeting_engine.interface": MagicMock(), + } + + with ( + patch.dict(os.environ, {}, clear=False), + patch.dict(sys.modules, fake_teleop_modules), + ): + os.environ.pop("ISAACLAB_CXR_SKIP_AUTOLAUNCH", None) + lifecycle.start() + + assert lifecycle._cloudxr_launcher is None + + def test_stop_without_cloudxr_env_file(self): + """stop() does not error when no CloudXR launcher was created.""" + lifecycle = _make_lifecycle(cloudxr_env_file=None) + lifecycle.stop() + + +if __name__ == "__main__": + pytest.main([__file__, "-v"]) diff --git a/source/isaaclab_teleop/test/test_control_events.py b/source/isaaclab_teleop/test/test_control_events.py new file mode 100644 index 000000000000..8bc05d3f957c --- /dev/null +++ b/source/isaaclab_teleop/test/test_control_events.py @@ -0,0 +1,586 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +# pyright: reportPrivateUsage=none + +"""Tests for TeleopMessageProcessor, _classify_command, _extract_command, +and poll_control_events. + +These tests exercise pure logic (no Omniverse/Isaac Sim stack required). +The message processor is tested by calling its ``_compute_fn`` method +directly with fake pipeline I/O, mirroring how TeleopCore's +``teleop_control_pipeline`` mechanism invokes it. +""" + +from __future__ import annotations + +import dataclasses +import json +import sys +from types import ModuleType +from unittest.mock import MagicMock + +import pytest + +# --------------------------------------------------------------------------- +# Stub out isaacteleop modules before any isaaclab_teleop imports so the +# tests can run in a plain Python environment without Omniverse. +# --------------------------------------------------------------------------- + +_MODULES_TO_STUB = [ + "isaacteleop", + "isaacteleop.deviceio", + "isaacteleop.deviceio_trackers", + "isaacteleop.retargeting_engine", + "isaacteleop.retargeting_engine.deviceio_source_nodes", + "isaacteleop.retargeting_engine.deviceio_source_nodes.deviceio_tensor_types", + "isaacteleop.retargeting_engine.interface", + "isaacteleop.retargeting_engine.interface.retargeter_core_types", + "isaacteleop.retargeting_engine.interface.tensor_group_type", + "isaacteleop.retargeting_engine_ui", + "isaacteleop.schema", + "isaacteleop.teleop_session_manager", + "isaacteleop.teleop_session_manager.teleop_state_manager_retargeter", + "isaacteleop.teleop_session_manager.teleop_state_manager_types", +] + +_stubs: dict[str, ModuleType | MagicMock] = {} + + +def _install_stubs(): + for name in _MODULES_TO_STUB: + if name not in sys.modules: + _stubs[name] = MagicMock() + sys.modules[name] = _stubs[name] + + from enum import Enum + + class ExecutionState(str, Enum): + UNKNOWN = "unknown" + STOPPED = "stopped" + PAUSED = "paused" + RUNNING = "running" + + @dataclasses.dataclass + class ExecutionEvents: + reset: bool = False + execution_state: ExecutionState = ExecutionState.UNKNOWN + + ee_mod = sys.modules["isaacteleop.retargeting_engine.interface.execution_events"] = ModuleType( + "isaacteleop.retargeting_engine.interface.execution_events" + ) + ee_mod.ExecutionState = ExecutionState # type: ignore[attr-defined] + ee_mod.ExecutionEvents = ExecutionEvents # type: ignore[attr-defined] + + iface = sys.modules["isaacteleop.retargeting_engine.interface"] + iface.ExecutionState = ExecutionState # type: ignore[attr-defined] + iface.ExecutionEvents = ExecutionEvents # type: ignore[attr-defined] + iface.RetargeterIOType = dict # type: ignore[attr-defined] + + class FakeBaseRetargeter: + def __init__(self, name: str) -> None: + self.name = name + + iface.BaseRetargeter = FakeBaseRetargeter # type: ignore[attr-defined] + + tsm_types = sys.modules["isaacteleop.teleop_session_manager.teleop_state_manager_types"] + tsm_types.bool_signal = MagicMock # type: ignore[attr-defined] + + dt_mod = sys.modules["isaacteleop.retargeting_engine.deviceio_source_nodes.deviceio_tensor_types"] + dt_mod.MessageChannelMessagesTrackedGroup = MagicMock # type: ignore[attr-defined] + + +_install_stubs() + +from isaaclab_teleop.control_events import ControlEvents, poll_control_events # noqa: E402 +from isaaclab_teleop.teleop_message_processor import ( # noqa: E402 + TeleopMessageProcessor, + _classify_command, + _extract_command, +) + +# --------------------------------------------------------------------------- +# Test doubles for MessageChannelMessagesTrackedT +# --------------------------------------------------------------------------- + + +@dataclasses.dataclass +class _FakePayload: + payload: bytes + + +@dataclasses.dataclass +class _FakeTracked: + data: list[_FakePayload] | None = None + + +def _tracked(*payloads: bytes) -> _FakeTracked: + """Build a lightweight stand-in for ``MessageChannelMessagesTrackedT``.""" + return _FakeTracked(data=[_FakePayload(p) for p in payloads]) + + +def _empty_tracked() -> _FakeTracked: + return _FakeTracked(data=[]) + + +def _null_tracked() -> _FakeTracked: + return _FakeTracked(data=None) + + +def _make_inputs(messages_tracked): + """Build a fake RetargeterIO dict for the processor.""" + tg = MagicMock() + tg.__getitem__ = MagicMock(return_value=messages_tracked) + return {TeleopMessageProcessor.INPUT_MESSAGES: tg} + + +class _FakeOutputSlot: + """Captures ``outputs["key"][0] = value`` assignments.""" + + def __init__(self): + self.value = None + + def __setitem__(self, idx, val): + self.value = val + + def __getitem__(self, idx): + return self.value + + +def _make_outputs(): + """Build a fake outputs dict with capturable slots.""" + return {"run_toggle": _FakeOutputSlot(), "kill": _FakeOutputSlot(), "reset": _FakeOutputSlot()} + + +def _step(proc, messages_tracked) -> dict: + """Run the processor's _compute_fn and return captured outputs.""" + inputs = _make_inputs(messages_tracked) + outputs = _make_outputs() + proc._compute_fn(inputs, outputs, context=None) + return {k: v.value for k, v in outputs.items()} + + +# =========================================================================== +# TeleopMessageProcessor: basic command parsing +# =========================================================================== + + +class TestStartCommand: + def test_start_sets_run_toggle(self): + proc = TeleopMessageProcessor(name="test") + result = _step(proc, _tracked(b"start")) + assert result["run_toggle"] is True + assert result["kill"] is False + assert result["reset"] is False + + def test_start_does_not_set_reset(self): + proc = TeleopMessageProcessor(name="test") + result = _step(proc, _tracked(b"start")) + assert result["reset"] is False + + +class TestStopCommand: + def test_stop_from_stopped_is_noop(self): + proc = TeleopMessageProcessor(name="test") + result = _step(proc, _tracked(b"stop")) + assert result["run_toggle"] is False + assert result["kill"] is False + + +class TestResetCommand: + def test_reset_sets_reset_flag(self): + proc = TeleopMessageProcessor(name="test") + result = _step(proc, _tracked(b"reset")) + assert result["reset"] is True + assert result["run_toggle"] is False + assert result["kill"] is False + + +class TestResetPulseBehaviour: + def test_reset_clears_on_next_step(self): + proc = TeleopMessageProcessor(name="test") + result = _step(proc, _tracked(b"reset")) + assert result["reset"] is True + + result = _step(proc, _empty_tracked()) + assert result["reset"] is False + + +class TestKillAlwaysFalse: + def test_kill_is_always_false(self): + proc = TeleopMessageProcessor(name="test") + for payload in [b"start", b"stop", b"reset", b"hello"]: + result = _step(proc, _tracked(payload)) + assert result["kill"] is False + + +# =========================================================================== +# Shadow state and toggle sequences +# =========================================================================== + + +class TestStartFromStopped: + """``start`` from STOPPED needs 2 toggle edges over 3 frames.""" + + def test_full_sequence_reaches_running(self): + proc = TeleopMessageProcessor(name="test") + # Frame 0: "start" received, first toggle edge queued + r0 = _step(proc, _tracked(b"start")) + assert r0["run_toggle"] is True # edge 1: STOPPED -> PAUSED + + # Frame 1: queue drains False (prev resets) + r1 = _step(proc, _empty_tracked()) + assert r1["run_toggle"] is False + + # Frame 2: queue drains True (second edge) + r2 = _step(proc, _empty_tracked()) + assert r2["run_toggle"] is True # edge 2: PAUSED -> RUNNING + + # Frame 3: queue empty, back to idle + r3 = _step(proc, _empty_tracked()) + assert r3["run_toggle"] is False + + def test_shadow_state_is_running_after_sequence(self): + proc = TeleopMessageProcessor(name="test") + _step(proc, _tracked(b"start")) + _step(proc, _empty_tracked()) + _step(proc, _empty_tracked()) + assert proc._shadow_state == "running" + + +class TestStartFromPaused: + """``start`` from PAUSED needs 1 toggle edge.""" + + def test_single_edge_reaches_running(self): + proc = TeleopMessageProcessor(name="test") + # Drive to RUNNING: start sequence plays 3 frames + _step(proc, _tracked(b"start")) + _step(proc, _empty_tracked()) + _step(proc, _empty_tracked()) + assert proc._shadow_state == "running" + + # Stop to reach PAUSED (prev_toggle is True from start sequence, + # so a False is prepended before the toggle edge) + _step(proc, _tracked(b"stop")) # drains False (prepended) + r_stop_edge = _step(proc, _empty_tracked()) # drains True (edge) + assert r_stop_edge["run_toggle"] is True + assert proc._shadow_state == "paused" + + # Start from PAUSED: prev_toggle is True, so False prepended + _step(proc, _tracked(b"start")) # drains False (prepended) + r_start_edge = _step(proc, _empty_tracked()) # drains True (edge) + assert r_start_edge["run_toggle"] is True + assert proc._shadow_state == "running" + + +class TestStartFromRunning: + """``start`` when already RUNNING is a no-op.""" + + def test_start_from_running_noop(self): + proc = TeleopMessageProcessor(name="test") + _step(proc, _tracked(b"start")) + _step(proc, _empty_tracked()) + _step(proc, _empty_tracked()) + assert proc._shadow_state == "running" + + result = _step(proc, _tracked(b"start")) + assert result["run_toggle"] is False + + +class TestStopFromRunning: + """``stop`` from RUNNING uses one toggle edge to reach PAUSED.""" + + def test_stop_pauses(self): + proc = TeleopMessageProcessor(name="test") + _step(proc, _tracked(b"start")) + _step(proc, _empty_tracked()) + _step(proc, _empty_tracked()) + assert proc._shadow_state == "running" + + # prev_toggle is True, so stop prepends False before the edge + r0 = _step(proc, _tracked(b"stop")) + assert r0["run_toggle"] is False # prepended False + r1 = _step(proc, _empty_tracked()) + assert r1["run_toggle"] is True # edge: RUNNING -> PAUSED + assert proc._shadow_state == "paused" + + +class TestStopFromPaused: + """``stop`` when already PAUSED is a no-op.""" + + def test_stop_from_paused_noop(self): + proc = TeleopMessageProcessor(name="test") + _step(proc, _tracked(b"start")) + _step(proc, _empty_tracked()) + _step(proc, _empty_tracked()) + # Stop to PAUSED + _step(proc, _tracked(b"stop")) + _step(proc, _empty_tracked()) + assert proc._shadow_state == "paused" + + result = _step(proc, _tracked(b"stop")) + assert result["run_toggle"] is False + + +class TestCommandDuringToggleSequence: + """Commands received while a toggle sequence is in progress are ignored.""" + + def test_second_start_during_sequence_ignored(self): + proc = TeleopMessageProcessor(name="test") + _step(proc, _tracked(b"start")) # starts the 3-frame sequence + # Second start during the sequence should not restart it + r1 = _step(proc, _tracked(b"start")) + assert r1["run_toggle"] is False # draining the False from queue + + r2 = _step(proc, _empty_tracked()) + assert r2["run_toggle"] is True # second edge fires normally + + +# =========================================================================== +# inject_reset +# =========================================================================== + + +class TestInjectReset: + def test_inject_reset_produces_pulse(self): + proc = TeleopMessageProcessor(name="test") + proc.inject_reset() + result = _step(proc, _empty_tracked()) + assert result["reset"] is True + + def test_inject_reset_clears_after_one_step(self): + proc = TeleopMessageProcessor(name="test") + proc.inject_reset() + _step(proc, _empty_tracked()) + result = _step(proc, _empty_tracked()) + assert result["reset"] is False + + def test_inject_reset_combines_with_message_reset(self): + proc = TeleopMessageProcessor(name="test") + proc.inject_reset() + result = _step(proc, _tracked(b"reset")) + assert result["reset"] is True + + def test_inject_reset_independent_of_toggle(self): + proc = TeleopMessageProcessor(name="test") + proc.inject_reset() + result = _step(proc, _tracked(b"start")) + assert result["run_toggle"] is True + assert result["reset"] is True + + +# =========================================================================== +# Word boundary matching +# =========================================================================== + + +class TestWordBoundaryMatching: + @pytest.mark.parametrize("payload", [b"teleop start", b"xr start session", b"start now"]) + def test_start_word(self, payload: bytes): + proc = TeleopMessageProcessor(name="test") + result = _step(proc, _tracked(payload)) + assert result["run_toggle"] is True + + @pytest.mark.parametrize("payload", [b"teleop reset", b"env reset"]) + def test_reset_word(self, payload: bytes): + proc = TeleopMessageProcessor(name="test") + result = _step(proc, _tracked(payload)) + assert result["reset"] is True + + +class TestAmbiguousPayloads: + def test_reset_wins_over_start(self): + proc = TeleopMessageProcessor(name="test") + result = _step(proc, _tracked(b"reset and start")) + assert result["reset"] is True + assert result["run_toggle"] is False + + +# =========================================================================== +# Empty, null, and malformed batches +# =========================================================================== + + +class TestEmptyAndNullBatches: + def test_empty_data_list(self): + proc = TeleopMessageProcessor(name="test") + result = _step(proc, _empty_tracked()) + assert result["run_toggle"] is False + assert result["kill"] is False + assert result["reset"] is False + + def test_null_data(self): + proc = TeleopMessageProcessor(name="test") + result = _step(proc, _null_tracked()) + assert result["run_toggle"] is False + + def test_none_input(self): + proc = TeleopMessageProcessor(name="test") + result = _step(proc, None) + assert result["run_toggle"] is False + + +class TestMultipleMessagesInBatch: + def test_start_then_reset_in_one_batch(self): + proc = TeleopMessageProcessor(name="test") + result = _step(proc, _tracked(b"start", b"reset")) + assert result["run_toggle"] is True + assert result["reset"] is True + + +class TestMalformedPayloads: + def test_invalid_utf8(self): + proc = TeleopMessageProcessor(name="test") + result = _step(proc, _tracked(b"\xff\xfe")) + assert result["run_toggle"] is False + assert result["kill"] is False + assert result["reset"] is False + + def test_none_payload(self): + proc = TeleopMessageProcessor(name="test") + tracked = _FakeTracked(data=[_FakePayload(payload=None)]) # type: ignore[arg-type] + result = _step(proc, tracked) + assert result["run_toggle"] is False + + +# =========================================================================== +# JSON format tests (Quest client sends JSON teleop_command messages) +# =========================================================================== + + +def _json_command(command: str) -> bytes: + """Build a Quest-style JSON teleop_command payload.""" + return json.dumps({"type": "teleop_command", "message": {"command": command}}).encode("utf-8") + + +class TestJsonFormat: + def test_json_start_teleop(self): + proc = TeleopMessageProcessor(name="test") + result = _step(proc, _tracked(_json_command("start teleop"))) + assert result["run_toggle"] is True + + def test_json_stop_teleop_from_stopped_noop(self): + proc = TeleopMessageProcessor(name="test") + result = _step(proc, _tracked(_json_command("stop teleop"))) + assert result["run_toggle"] is False + + def test_json_reset_teleop(self): + proc = TeleopMessageProcessor(name="test") + result = _step(proc, _tracked(_json_command("reset teleop"))) + assert result["reset"] is True + + def test_json_wrong_type_ignored(self): + payload = json.dumps({"type": "other_event", "message": {"command": "start"}}).encode("utf-8") + proc = TeleopMessageProcessor(name="test") + result = _step(proc, _tracked(payload)) + assert result["run_toggle"] is False + + def test_json_message_as_string(self): + payload = json.dumps({"type": "teleop_command", "message": "start teleop"}).encode("utf-8") + proc = TeleopMessageProcessor(name="test") + result = _step(proc, _tracked(payload)) + assert result["run_toggle"] is True + + +# =========================================================================== +# _extract_command unit tests +# =========================================================================== + + +class TestExtractCommand: + def test_plain_text(self): + assert _extract_command("start teleop") == "start teleop" + + def test_json_teleop_command(self): + text = json.dumps({"type": "teleop_command", "message": {"command": "stop"}}) + assert _extract_command(text) == "stop" + + def test_json_wrong_type(self): + text = json.dumps({"type": "other", "message": {"command": "start"}}) + assert _extract_command(text) is None + + def test_json_no_message_key(self): + text = json.dumps({"type": "teleop_command"}) + assert _extract_command(text) is None + + def test_json_non_dict_value_returns_none(self): + assert _extract_command("42") is None + assert _extract_command("[1, 2, 3]") is None + assert _extract_command("true") is None + + +# =========================================================================== +# _classify_command unit tests +# =========================================================================== + + +class TestClassifyCommand: + def test_exact_words(self): + assert _classify_command("start") == "start" + assert _classify_command("stop") == "stop" + assert _classify_command("reset") == "reset" + + def test_word_boundary_prevents_false_match(self): + assert _classify_command("upstart") is None + assert _classify_command("nonstop") is None + assert _classify_command("unreset") is None + + def test_reset_beats_start(self): + assert _classify_command("reset and start") == "reset" + + def test_stop_beats_start(self): + assert _classify_command("stop and start") == "stop" + + def test_unrecognized_text(self): + assert _classify_command("hello world") is None + + def test_case_insensitive(self): + assert _classify_command("START") == "start" + assert _classify_command("Stop Teleop") == "stop" + assert _classify_command("RESET NOW") == "reset" + + +# =========================================================================== +# poll_control_events tests +# =========================================================================== + + +class TestPollControlEvents: + def test_plain_object_returns_default(self): + result = poll_control_events(object()) + assert result.is_active is None + assert result.should_reset is False + + def test_device_with_control_events(self): + class FakeDevice: + @property + def last_control_events(self): + return ControlEvents(is_active=True, should_reset=True) + + result = poll_control_events(FakeDevice()) + assert result.is_active is True + assert result.should_reset is True + + def test_device_with_none_events(self): + class FakeDevice: + last_control_events = None + + result = poll_control_events(FakeDevice()) + assert result.is_active is None + assert result.should_reset is False + + def test_duck_typed_snapshot(self): + class FakeSnapshot: + is_active = False + should_reset = True + + class FakeDevice: + @property + def last_control_events(self): + return FakeSnapshot() + + result = poll_control_events(FakeDevice()) + assert result.is_active is False + assert result.should_reset is True diff --git a/source/isaaclab_teleop/test/test_oxr_device.py b/source/isaaclab_teleop/test/test_oxr_device.py index 2d2ed8444969..be2a604a6489 100644 --- a/source/isaaclab_teleop/test/test_oxr_device.py +++ b/source/isaaclab_teleop/test/test_oxr_device.py @@ -179,13 +179,13 @@ def test_xr_anchor(empty_env, mock_xrcore): device = OpenXRDevice(OpenXRDeviceCfg(xr_cfg=env_cfg.xr)) # Check that the xr anchor prim is created with the correct pose - xr_anchor_view = sim_utils.XformPrimView("/World/XRAnchor") + xr_anchor_view = sim_utils.FrameView("/World/XRAnchor") assert xr_anchor_view.count == 1 position, orientation = xr_anchor_view.get_world_poses() - np.testing.assert_almost_equal(position.numpy(), [[1, 2, 3]]) - # XformPrimView returns quaternion in xyzw format, identity is [0, 0, 0, 1] - np.testing.assert_almost_equal(orientation.numpy(), [[0, 0, 0, 1]]) + np.testing.assert_almost_equal(position.torch.numpy(), [[1, 2, 3]]) + # FrameView returns quaternion in xyzw format, identity is [0, 0, 0, 1] + np.testing.assert_almost_equal(orientation.torch.numpy(), [[0, 0, 0, 1]]) # Check that xr anchor mode and custom anchor are set correctly assert carb.settings.get_settings().get("/persistent/xr/anchorMode") == "custom anchor" @@ -202,12 +202,12 @@ def test_xr_anchor_default(empty_env, mock_xrcore): device = OpenXRDevice(OpenXRDeviceCfg()) # Check that the xr anchor prim is created with the correct default pose - xr_anchor_view = sim_utils.XformPrimView("/World/XRAnchor") + xr_anchor_view = sim_utils.FrameView("/World/XRAnchor") assert xr_anchor_view.count == 1 position, orientation = xr_anchor_view.get_world_poses() - np.testing.assert_almost_equal(position.numpy().tolist(), [[0, 0, 0]]) - np.testing.assert_almost_equal(orientation.numpy().tolist(), [[0, 0, 0, 1]]) + np.testing.assert_almost_equal(position.torch.numpy().tolist(), [[0, 0, 0]]) + np.testing.assert_almost_equal(orientation.torch.numpy().tolist(), [[0, 0, 0, 1]]) # Check that xr anchor mode and custom anchor are set correctly assert carb.settings.get_settings().get("/persistent/xr/anchorMode") == "custom anchor" @@ -225,12 +225,12 @@ def test_xr_anchor_multiple_devices(empty_env, mock_xrcore): device_2 = OpenXRDevice(OpenXRDeviceCfg()) # Check that the xr anchor prim is created with the correct default pose - xr_anchor_view = sim_utils.XformPrimView("/World/XRAnchor") + xr_anchor_view = sim_utils.FrameView("/World/XRAnchor") assert xr_anchor_view.count == 1 position, orientation = xr_anchor_view.get_world_poses() - np.testing.assert_almost_equal(position.numpy().tolist(), [[0, 0, 0]]) - np.testing.assert_almost_equal(orientation.numpy().tolist(), [[0, 0, 0, 1]]) + np.testing.assert_almost_equal(position.torch.numpy().tolist(), [[0, 0, 0]]) + np.testing.assert_almost_equal(orientation.torch.numpy().tolist(), [[0, 0, 0, 1]]) # Check that xr anchor mode and custom anchor are set correctly assert carb.settings.get_settings().get("/persistent/xr/anchorMode") == "custom anchor" diff --git a/source/isaaclab_visualizers/isaaclab_visualizers/kit/kit_visualizer.py b/source/isaaclab_visualizers/isaaclab_visualizers/kit/kit_visualizer.py index 6b1b5c2077dc..ced2935897ae 100644 --- a/source/isaaclab_visualizers/isaaclab_visualizers/kit/kit_visualizer.py +++ b/source/isaaclab_visualizers/isaaclab_visualizers/kit/kit_visualizer.py @@ -11,10 +11,13 @@ import logging from typing import TYPE_CHECKING -from pxr import UsdGeom +from pxr import Gf, Usd, UsdGeom, Vt +from isaaclab.app.settings_manager import get_settings_manager from isaaclab.visualizers.base_visualizer import BaseVisualizer +from isaaclab_visualizers.newton_adapter import resolve_visible_env_indices + from .kit_visualizer_cfg import KitVisualizerCfg logger = logging.getLogger(__name__) @@ -22,6 +25,8 @@ if TYPE_CHECKING: from isaaclab.physics import BaseSceneDataProvider +_DEFAULT_VIEWPORT_NAME = "Visualizer Viewport" + class KitVisualizer(BaseVisualizer): """Kit visualizer using Isaac Sim viewport.""" @@ -42,10 +47,11 @@ def __init__(self, cfg: KitVisualizerCfg): self._sim_time = 0.0 self._step_counter = 0 self._hidden_env_visibilities: dict[str, str] = {} - # Camera prim path that set_camera_view() writes to. Pinned at initialization so that - # user-switching the GUI viewport to a sensor camera does not corrupt the sensor's prim. - self._controlled_camera_path: str | None = None + # PointInstancer prim path -> (had authored invisibleIds, previous value) for partial viz restore. + self._point_instancer_invisible_ids_backup: dict[str, tuple[bool, object]] = {} self._runtime_headless = bool(cfg.headless) + # USD path for the viewport's active camera, refreshed after setup (used by CI/tests). + self._controlled_camera_path: str | None = None # ---- Lifecycle ------------------------------------------------------------------------ @@ -68,22 +74,29 @@ def initialize(self, scene_data_provider: BaseSceneDataProvider) -> None: metadata = scene_data_provider.get_metadata() self._ensure_simulation_app() - self._setup_viewport(usd_stage) + self._setup_viewport() self._env_ids = self._compute_visualized_env_ids() - if self._env_ids: + num_envs_meta = int(metadata.get("num_envs", 0)) + self._resolved_visible_env_ids = resolve_visible_env_indices( + self._env_ids, self.cfg.max_visible_envs, num_envs_meta + ) + if self._resolved_visible_env_ids is not None: logger.warning( - "[KitVisualizer] env_filter_ids filtering is cosmetic only (no perf gain) in OV; hiding other envs." + "[KitVisualizer] Partial visualization in Kit uses visibility only; unselected env prims are hidden." ) - self._apply_env_visibility(usd_stage, metadata) - num_visualized_envs = len(self._env_ids) if self._env_ids is not None else int(metadata.get("num_envs", 0)) + self._apply_env_visibility(usd_stage, metadata, self._resolved_visible_env_ids) + num_visualized_envs = ( + len(self._resolved_visible_env_ids) if self._resolved_visible_env_ids is not None else num_envs_meta + ) self._log_initialization_table( logger=logger, title="KitVisualizer Configuration", rows=[ - ("camera_position", self.cfg.camera_position), - ("camera_target", self.cfg.camera_target), - ("camera_source", self.cfg.camera_source), + ("eye", self.cfg.eye), + ("lookat", self.cfg.lookat), + ("cam_source", self.cfg.cam_source), + ("max_visible_envs", self.cfg.max_visible_envs), ("num_visualized_envs", num_visualized_envs), ("create_viewport", self.cfg.create_viewport), ("headless", self._runtime_headless), @@ -105,18 +118,19 @@ def step(self, dt: float) -> None: try: import omni.kit.app - from isaaclab.app.settings_manager import get_settings_manager - app = omni.kit.app.get_app() if app is not None and app.is_running(): - # Keep app pumping for viewport/UI updates only. - # Simulation stepping is owned by SimulationContext. + # Keep app pumping for viewport/UI updates only; physics is owned by SimulationContext. + # Disable playSimulations around app.update() so Kit does not advance its own physics here. settings = get_settings_manager() settings.set_bool("/app/player/playSimulations", False) app.update() settings.set_bool("/app/player/playSimulations", True) except (ImportError, AttributeError) as exc: logger.debug("[KitVisualizer] App update skipped: %s", exc) + # Markers (VisualizationMarkers) are often created or resized to num_envs only after the first + # simulation / debug-vis step; re-apply PointInstancer invisibleIds each step when partial viz is on. + self._refresh_partial_viz_point_instancers_if_needed() def close(self) -> None: """Close viewport resources and restore temporary state.""" @@ -150,8 +164,6 @@ def is_running(self) -> bool: def is_training_paused(self) -> bool: """Return whether simulation play flag is paused in Kit settings.""" try: - from isaaclab.app.settings_manager import get_settings_manager - settings = get_settings_manager() play_flag = settings.get("/app/player/playSimulations") return play_flag is False @@ -179,10 +191,17 @@ def set_camera_view( ) -> None: """Set active viewport camera eye/target. + When :attr:`self.cfg.cam_source` is ``"cfg"``, this is a no-op: the pose comes only from + :attr:`self.cfg.eye` / :attr:`self.cfg.lookat` (applied in :meth:`_setup_viewport`). Otherwise + :class:`~isaaclab.sim.simulation_context.SimulationContext` and :class:`ViewportCameraController` + would overwrite that pose with :class:`~isaaclab.envs.common.ViewerCfg`-driven views. + Args: eye: Camera eye position. target: Camera look-at target. """ + if self.cfg.cam_source == "cfg": + return if not self._is_initialized: logger.debug("[KitVisualizer] set_camera_view() ignored because visualizer is not initialized.") return @@ -215,22 +234,33 @@ def _ensure_simulation_app(self) -> None: except ImportError: pass - def _setup_viewport(self, usd_stage) -> None: - """Create/resolve viewport and configure initial camera. - - Args: - usd_stage: USD stage used for camera prim setup. - """ + def _setup_viewport(self) -> None: + """Create/resolve viewport and configure initial camera.""" import omni.kit.viewport.utility as vp_utils from omni.ui import DockPosition if self._runtime_headless: - # In headless mode we keep the visualizer active but skip viewport/window setup. + # Headless: no viewport window; apply cfg pose to the default perspective camera path. self._viewport_window = None self._viewport_api = None + if self.cfg.cam_source == "prim_path": + logger.warning( + "[KitVisualizer] cam_source='prim_path' has limited support in headless mode; " + "using eye/lookat from cfg instead." + ) + self._apply_cfg_camera_pose_if_configured() + self._refresh_controlled_camera_path() return - if self.cfg.create_viewport and self.cfg.viewport_name: + effective_viewport_name = ( + self.cfg.viewport_name if self.cfg.viewport_name is not None else _DEFAULT_VIEWPORT_NAME + ) + + if self.cfg.create_viewport: + if not str(effective_viewport_name).strip(): + raise RuntimeError( + "[KitVisualizer] viewport_name must be a non-empty string when create_viewport=True." + ) dock_position_name = self.cfg.dock_position.upper() dock_position_map = { "LEFT": DockPosition.LEFT, @@ -241,7 +271,7 @@ def _setup_viewport(self, usd_stage) -> None: dock_pos = dock_position_map.get(dock_position_name, DockPosition.SAME) self._viewport_window = vp_utils.create_viewport_window( - name=self.cfg.viewport_name, + name=effective_viewport_name, width=self.cfg.window_width, height=self.cfg.window_height, position_x=50, @@ -249,28 +279,33 @@ def _setup_viewport(self, usd_stage) -> None: docked=True, ) - asyncio.ensure_future(self._dock_viewport_async(self.cfg.viewport_name, dock_pos)) - self._create_and_assign_camera(usd_stage) + asyncio.ensure_future(self._dock_viewport_async(effective_viewport_name, dock_pos)) else: self._viewport_window = vp_utils.get_active_viewport_window() if self._viewport_window is None: logger.warning("[KitVisualizer] No active viewport window found.") self._viewport_api = None + self._refresh_controlled_camera_path() return self._viewport_api = self._viewport_window.viewport_api - # Pin the camera path we will write to, using the active camera at init time. - # This must happen before any _set_viewport_camera() call so the path is known. - self._controlled_camera_path = self._viewport_api.get_active_camera() or "/OmniverseKit_Persp" - if self.cfg.camera_source == "usd_path": - if not self._set_active_camera_path(self.cfg.camera_usd_path): - logger.warning( - "[KitVisualizer] camera_usd_path '%s' not found; using configured camera.", - self.cfg.camera_usd_path, + if self.cfg.cam_source == "prim_path": + if not self._set_active_camera_path(self.cfg.cam_prim_path): + raise RuntimeError( + "[KitVisualizer] cam_source='prim_path' requires a valid cam_prim_path. " + f"Camera prim not found: '{self.cfg.cam_prim_path}'." ) - self._set_viewport_camera(self.cfg.camera_position, self.cfg.camera_target) else: - self._set_viewport_camera(self.cfg.camera_position, self.cfg.camera_target) + self._apply_cfg_camera_pose_if_configured() + self._refresh_controlled_camera_path() + + def _refresh_controlled_camera_path(self) -> None: + """Cache :attr:`_controlled_camera_path` from the active viewport (or default persp).""" + if self._viewport_api is not None: + path = self._viewport_api.get_active_camera() + self._controlled_camera_path = path if path else "/OmniverseKit_Persp" + else: + self._controlled_camera_path = "/OmniverseKit_Persp" async def _dock_viewport_async(self, viewport_name: str, dock_position) -> None: """Dock a created viewport window relative to main viewport.""" @@ -303,35 +338,28 @@ async def _dock_viewport_async(self, viewport_name: str, dock_position) -> None: await omni.kit.app.get_app().next_update_async() viewport_window.focus() - def _create_and_assign_camera(self, usd_stage) -> None: - """Create viewport camera prim (if needed) and set it active.""" - camera_path = f"/World/Cameras/{self.cfg.viewport_name}_Camera".replace(" ", "_") - - camera_prim = usd_stage.GetPrimAtPath(camera_path) - if not camera_prim.IsValid(): - UsdGeom.Camera.Define(usd_stage, camera_path) - - if self._viewport_api: - self._viewport_api.set_active_camera(camera_path) - self._controlled_camera_path = camera_path - def _set_viewport_camera(self, position: tuple[float, float, float], target: tuple[float, float, float]) -> None: """Apply eye/target camera view to the active viewport.""" - import isaacsim.core.utils.viewports as isaacsim_viewports - if self._viewport_api is None: return - # Use the camera path pinned at initialization. This prevents user-switching the GUI - # viewport to a sensor camera from corrupting the sensor's USD prim transform. - camera_path = self._controlled_camera_path - if not camera_path: - camera_path = self._viewport_api.get_active_camera() if self._viewport_api else None + + try: + from omni.kit.viewport.utility.camera_state import ViewportCameraState + except ImportError as exc: + logger.warning("[KitVisualizer] Viewport camera update skipped: %s", exc) + return + + camera_path = self._viewport_api.get_active_camera() if not camera_path: camera_path = "/OmniverseKit_Persp" - isaacsim_viewports.set_camera_view( - eye=list(position), target=list(target), camera_prim_path=camera_path, viewport_api=self._viewport_api - ) + camera_state = ViewportCameraState(camera_path, self._viewport_api) + camera_state.set_position_world(Gf.Vec3d(float(position[0]), float(position[1]), float(position[2])), True) + camera_state.set_target_world(Gf.Vec3d(float(target[0]), float(target[1]), float(target[2])), True) + + def _apply_cfg_camera_pose_if_configured(self) -> None: + """Apply configured camera pose from eye/lookat.""" + self._set_viewport_camera(self.cfg.eye, self.cfg.lookat) def _set_active_camera_path(self, camera_path: str) -> bool: """Set active camera path for viewport if the prim exists. @@ -348,17 +376,14 @@ def _set_active_camera_path(self, camera_path: str) -> bool: if not camera_prim.IsValid(): return False self._viewport_api.set_active_camera(camera_path) - self._controlled_camera_path = camera_path return True - def _apply_env_visibility(self, usd_stage, metadata: dict) -> None: - """Hide non-selected environments for cosmetic env filtering.""" - if not self._env_ids: - return + def _apply_env_visibility(self, usd_stage, metadata: dict, visible_env_ids: list[int]) -> None: + """Hide environments not listed in ``visible_env_ids`` (cosmetic partial visualization).""" num_envs = int(metadata.get("num_envs", 0)) if num_envs <= 0: return - visible = set(self._env_ids) + visible = set(visible_env_ids) for env_id in range(num_envs): if env_id in visible: continue @@ -375,10 +400,63 @@ def _apply_env_visibility(self, usd_stage, metadata: dict) -> None: self._hidden_env_visibilities[env_path] = prev attr.Set(UsdGeom.Tokens.invisible) - def _restore_env_visibility(self) -> None: - """Restore environment visibilities modified by env filtering.""" - if not self._hidden_env_visibilities: + self._apply_visual_point_instancer_visibility(usd_stage, num_envs, visible) + + def _refresh_partial_viz_point_instancers_if_needed(self) -> None: + """Re-apply ``invisibleIds`` for env-scaled `/Visuals` instancers (handles lazy marker creation).""" + if self._resolved_visible_env_ids is None or self._scene_data_provider is None: return + usd_stage = self._scene_data_provider.get_usd_stage() + if usd_stage is None: + return + num_envs = int(self._scene_data_provider.get_metadata().get("num_envs", 0)) + if num_envs <= 0: + return + self._apply_visual_point_instancer_visibility(usd_stage, num_envs, set(self._resolved_visible_env_ids)) + + def _apply_visual_point_instancer_visibility(self, usd_stage, num_envs: int, visible_env_ids: set[int]) -> None: + """Set ``PointInstancer.invisibleIds`` for per-env `/Visuals` markers (e.g. velocity arrows).""" + hidden = [i for i in range(num_envs) if i not in visible_env_ids] + vt_hidden = Vt.Int64Array([int(i) for i in hidden]) + for root_path in ("/Visuals", "/World/Visuals"): + root_prim = usd_stage.GetPrimAtPath(root_path) + if not root_prim.IsValid(): + continue + for prim in Usd.PrimRange(root_prim): + if not prim.IsA(UsdGeom.PointInstancer): + continue + pi = UsdGeom.PointInstancer(prim) + n = self._point_instancer_instance_count(pi) + if n is None or n != num_envs: + continue + path_str = prim.GetPath().pathString + inv_attr = pi.GetInvisibleIdsAttr() + # Record original authorship/value once per instancer for :meth:`_restore_env_visibility`. + if path_str not in self._point_instancer_invisible_ids_backup: + was_authored = inv_attr.HasAuthoredValue() + prev = inv_attr.Get() if was_authored else None + self._point_instancer_invisible_ids_backup[path_str] = (was_authored, prev) + inv_attr.Set(vt_hidden) + + @staticmethod + def _point_instancer_instance_count(pi: UsdGeom.PointInstancer) -> int | None: + """Return instance count from the first authored per-instance array, if any.""" + for attr in ( + pi.GetPositionsAttr(), + pi.GetScalesAttr(), + pi.GetOrientationsAttr(), + pi.GetProtoIndicesAttr(), + ): + if not attr.HasAuthoredValue(): + continue + val = attr.Get() + if val is None: + continue + return len(val) + return None + + def _restore_env_visibility(self) -> None: + """Restore environment visibilities and PointInstancer ``invisibleIds`` from partial viz.""" usd_stage = self._scene_data_provider.get_usd_stage() if self._scene_data_provider else None if usd_stage is None: return @@ -391,3 +469,14 @@ def _restore_env_visibility(self) -> None: continue imageable.GetVisibilityAttr().Set(prev) self._hidden_env_visibilities.clear() + + for path_str, (was_authored, prev) in self._point_instancer_invisible_ids_backup.items(): + prim = usd_stage.GetPrimAtPath(path_str) + if not prim.IsValid() or not prim.IsA(UsdGeom.PointInstancer): + continue + inv_attr = UsdGeom.PointInstancer(prim).GetInvisibleIdsAttr() + if not was_authored: + inv_attr.Clear() + else: + inv_attr.Set(prev) + self._point_instancer_invisible_ids_backup.clear() diff --git a/source/isaaclab_visualizers/isaaclab_visualizers/kit/kit_visualizer_cfg.py b/source/isaaclab_visualizers/isaaclab_visualizers/kit/kit_visualizer_cfg.py index 88112a6f20b4..342be3fc2c6f 100644 --- a/source/isaaclab_visualizers/isaaclab_visualizers/kit/kit_visualizer_cfg.py +++ b/source/isaaclab_visualizers/isaaclab_visualizers/kit/kit_visualizer_cfg.py @@ -5,6 +5,8 @@ """Configuration for Kit-based visualizer.""" +from __future__ import annotations + from isaaclab.utils import configclass from isaaclab.visualizers.visualizer_cfg import VisualizerCfg @@ -16,20 +18,23 @@ class KitVisualizerCfg(VisualizerCfg): visualizer_type: str = "kit" """Type identifier for Kit visualizer.""" - viewport_name: str | None = "Visualizer Viewport" - """Viewport name to use. If None, uses active viewport.""" + viewport_name: str | None = None + """Name for a new viewport window when :attr:`create_viewport` is ``True``. + + If ``None``, a default name (``"Visualizer Viewport"``) is used. + """ create_viewport: bool = False - """Create new viewport with specified name and camera pose.""" + """If ``True``, create a new viewport window; if ``False``, use the active viewport window.""" headless: bool = False """Run without creating viewport windows when supported by the app.""" dock_position: str = "SAME" - """Dock position for new viewport. Options: 'LEFT', 'RIGHT', 'BOTTOM', 'SAME'.""" + """Dock position for a new viewport. Options: 'LEFT', 'RIGHT', 'BOTTOM', 'SAME'.""" window_width: int = 1280 - """Viewport width in pixels.""" + """Viewport width in pixels (when :attr:`create_viewport` is ``True``).""" window_height: int = 720 - """Viewport height in pixels.""" + """Viewport height in pixels (when :attr:`create_viewport` is ``True``).""" diff --git a/source/isaaclab_visualizers/isaaclab_visualizers/newton/newton_visualizer.py b/source/isaaclab_visualizers/isaaclab_visualizers/newton/newton_visualizer.py index 70d44d1956f7..8c8bb0bed9d8 100644 --- a/source/isaaclab_visualizers/isaaclab_visualizers/newton/newton_visualizer.py +++ b/source/isaaclab_visualizers/isaaclab_visualizers/newton/newton_visualizer.py @@ -16,6 +16,8 @@ from isaaclab.visualizers.base_visualizer import BaseVisualizer +from isaaclab_visualizers.newton_adapter import apply_viewer_visible_worlds, resolve_visible_env_indices + from .newton_visualizer_cfg import NewtonVisualizerCfg logger = logging.getLogger(__name__) @@ -56,7 +58,7 @@ def __init__( self._fallback_draw_controls = True def is_training_paused(self) -> bool: - """Return whether training is paused by viewer controls.""" + """Return whether simulation is paused by viewer controls.""" return self._paused_training def is_rendering_paused(self) -> bool: @@ -68,7 +70,7 @@ def _render_training_controls(self, imgui): imgui.separator() imgui.text("IsaacLab Controls") - pause_label = "Resume Training" if self._paused_training else "Pause Training" + pause_label = "Resume Simulation" if self._paused_training else "Pause Simulation" if imgui.button(pause_label): self._paused_training = not self._paused_training @@ -110,7 +112,7 @@ def _render_ui(self): imgui.set_next_window_pos(imgui.ImVec2(320, 10)) flags = 0 - if imgui.begin("Training Controls", flags=flags): + if imgui.begin("Simulation Controls", flags=flags): self._render_training_controls(imgui) imgui.end() return None @@ -190,9 +192,15 @@ def _render_left_panel(self): show_contacts = self.show_contacts changed, self.show_contacts = imgui.checkbox("Show Contacts", show_contacts) + show_collision = self.show_collision + changed, self.show_collision = imgui.checkbox("Show Collision", show_collision) + show_springs = self.show_springs changed, self.show_springs = imgui.checkbox("Show Springs", show_springs) + show_inertia_boxes = self.show_inertia_boxes + changed, self.show_inertia_boxes = imgui.checkbox("Show Inertia Boxes", show_inertia_boxes) + show_com = self.show_com changed, self.show_com = imgui.checkbox("Show Center of Mass", show_com) @@ -275,40 +283,37 @@ def initialize(self, scene_data_provider: BaseSceneDataProvider) -> None: self._scene_data_provider = scene_data_provider metadata = scene_data_provider.get_metadata() + num_envs = int(metadata.get("num_envs", 0)) self._env_ids = self._compute_visualized_env_ids() - if self._env_ids: - get_filtered_model = getattr(scene_data_provider, "get_newton_model_for_env_ids", None) - if callable(get_filtered_model): - self._model = get_filtered_model(self._env_ids) - else: - self._model = scene_data_provider.get_newton_model() - else: - self._model = scene_data_provider.get_newton_model() - self._state = scene_data_provider.get_newton_state(self._env_ids) - - try: - self._viewer = NewtonViewerGL( - width=self.cfg.window_width, - height=self.cfg.window_height, - headless=self.cfg.headless, - metadata=metadata, - update_frequency=self.cfg.update_frequency, - ) - except Exception as exc: - if not self.cfg.headless: - raise - self._viewer = None - self._headless_no_viewer = True - logger.info( - "[NewtonVisualizer] Headless fallback enabled (ViewerGL unavailable in this environment): %s", - exc, - ) + self._model = scene_data_provider.get_newton_model() + self._state = scene_data_provider.get_newton_state() + + # Use pyglet's EGL headless backend when requested. Must run before the first + # ``pyglet.window`` import so ``Window`` resolves to :class:`~pyglet.window.headless.HeadlessWindow`. + if self.cfg.headless: + import pyglet + + pyglet.options["headless"] = True + + self._viewer = NewtonViewerGL( + width=self.cfg.window_width, + height=self.cfg.window_height, + headless=self.cfg.headless, + metadata=metadata, + update_frequency=self.cfg.update_frequency, + ) if self._viewer is not None: - max_worlds = self.cfg.max_worlds - self._viewer.set_model(self._model, max_worlds=max_worlds) + self._viewer.set_model(self._model) + apply_viewer_visible_worlds( + self._viewer, + env_ids=self._env_ids, + max_visible_envs=self.cfg.max_visible_envs, + num_envs=num_envs, + ) self._viewer.set_world_offsets((0.0, 0.0, 0.0)) - self._apply_camera_pose(self._resolve_initial_camera_pose()) + initial_pose = self._resolve_initial_camera_pose() + self._apply_camera_pose(initial_pose) self._viewer.up_axis = 2 # Z-up self._viewer.scaling = 1.0 @@ -316,7 +321,9 @@ def initialize(self, scene_data_provider: BaseSceneDataProvider) -> None: self._viewer.show_joints = self.cfg.show_joints self._viewer.show_contacts = self.cfg.show_contacts + self._viewer.show_collision = self.cfg.show_collision self._viewer.show_springs = self.cfg.show_springs + self._viewer.show_inertia_boxes = self.cfg.show_inertia_boxes self._viewer.show_com = self.cfg.show_com self._viewer.renderer.draw_shadows = self.cfg.enable_shadows @@ -328,19 +335,18 @@ def initialize(self, scene_data_provider: BaseSceneDataProvider) -> None: self._viewer.renderer.sky_lower = self._viewer._coerce_color3(self.cfg.sky_lower_color) self._viewer.renderer._light_color = self._viewer._coerce_color3(self.cfg.light_color) - num_visualized_envs = len(self._env_ids) if self._env_ids is not None else int(metadata.get("num_envs", 0)) + _resolved = resolve_visible_env_indices(self._env_ids, self.cfg.max_visible_envs, num_envs) + num_visualized_envs = len(_resolved) if _resolved is not None else num_envs self._log_initialization_table( logger=logger, title="NewtonVisualizer Configuration", rows=[ ( - "camera_position", - tuple(float(x) for x in self._viewer.camera.pos) - if self._viewer is not None - else self.cfg.camera_position, + "eye", + tuple(float(x) for x in self._viewer.camera.pos) if self._viewer is not None else self.cfg.eye, ), - ("camera_target", self._last_camera_pose[1] if self._last_camera_pose else self.cfg.camera_target), - ("camera_source", self.cfg.camera_source), + ("lookat", self._last_camera_pose[1] if self._last_camera_pose else self.cfg.lookat), + ("cam_source", self.cfg.cam_source), ("num_visualized_envs", num_visualized_envs), ("headless", self.cfg.headless), ], @@ -361,13 +367,13 @@ def step(self, dt: float) -> None: if self._viewer is None: if self._scene_data_provider is not None: - self._state = self._scene_data_provider.get_newton_state(self._env_ids) + self._state = self._scene_data_provider.get_newton_state() return - if self.cfg.camera_source == "usd_path": + if self.cfg.cam_source == "prim_path": self._update_camera_from_usd_path() - self._state = self._scene_data_provider.get_newton_state(self._env_ids) + self._state = self._scene_data_provider.get_newton_state() contacts = None if self._viewer.show_contacts: @@ -429,15 +435,15 @@ def _resolve_initial_camera_pose(self) -> tuple[tuple[float, float, float], tupl Returns: Camera eye and target tuples. """ - if self.cfg.camera_source == "usd_path": - pose = self._resolve_camera_pose_from_usd_path(self.cfg.camera_usd_path) + if self.cfg.cam_source == "prim_path": + pose = self._resolve_camera_pose_from_usd_path(self.cfg.cam_prim_path) if pose is not None: return pose - logger.warning( - "[NewtonVisualizer] camera_usd_path '%s' not found; using configured camera.", - self.cfg.camera_usd_path, + raise RuntimeError( + "[NewtonVisualizer] cam_source='prim_path' requires a resolvable camera prim path, " + f"but no camera pose was found for '{self.cfg.cam_prim_path}'." ) - return self.cfg.camera_position, self.cfg.camera_target + return self._resolve_cfg_camera_pose("NewtonVisualizer") def _apply_camera_pose(self, pose: tuple[tuple[float, float, float], tuple[float, float, float]]) -> None: """Apply camera eye/target pose to the Newton viewer. @@ -461,7 +467,7 @@ def _apply_camera_pose(self, pose: tuple[tuple[float, float, float], tuple[float def _update_camera_from_usd_path(self) -> None: """Refresh camera pose from configured USD camera path when it changes.""" - pose = self._resolve_camera_pose_from_usd_path(self.cfg.camera_usd_path) + pose = self._resolve_camera_pose_from_usd_path(self.cfg.cam_prim_path) if pose is None: return if self._last_camera_pose == pose: diff --git a/source/isaaclab_visualizers/isaaclab_visualizers/newton/newton_visualizer_cfg.py b/source/isaaclab_visualizers/isaaclab_visualizers/newton/newton_visualizer_cfg.py index 2449db73b5e3..711e86e03b31 100644 --- a/source/isaaclab_visualizers/isaaclab_visualizers/newton/newton_visualizer_cfg.py +++ b/source/isaaclab_visualizers/isaaclab_visualizers/newton/newton_visualizer_cfg.py @@ -25,12 +25,6 @@ class NewtonVisualizerCfg(VisualizerCfg): headless: bool = False """Run the Newton viewer without requiring a display server.""" - max_worlds: int | None = None - """Maximum number of worlds/environments rendered by the viewer. - - Set to ``None`` to leave this option disabled. - """ - update_frequency: int = 1 """Visualizer update frequency (updates every N frames).""" @@ -40,9 +34,15 @@ class NewtonVisualizerCfg(VisualizerCfg): show_contacts: bool = False """Show contact visualization.""" + show_collision: bool = False + """Show collision visualization.""" + show_springs: bool = False """Show spring visualization.""" + show_inertia_boxes: bool = False + """Show inertia box visualization.""" + show_com: bool = False """Show center of mass visualization.""" diff --git a/source/isaaclab_visualizers/isaaclab_visualizers/newton_adapter.py b/source/isaaclab_visualizers/isaaclab_visualizers/newton_adapter.py new file mode 100644 index 000000000000..6bc3d5a2b4f1 --- /dev/null +++ b/source/isaaclab_visualizers/isaaclab_visualizers/newton_adapter.py @@ -0,0 +1,63 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Shared helpers for viewer env selection (Newton viewers and Kit partial USD visibility).""" + +from __future__ import annotations + + +def resolve_visible_env_indices( + env_ids: list[int] | None, + max_visible_envs: int | None, + num_envs: int, +) -> list[int] | None: + """Resolve which env indices stay visible (same rules as :func:`apply_viewer_visible_worlds`). + + * Cap-only path (``env_ids`` is ``None``): contiguous ``0 .. min(cap, num_envs) - 1`` when ``max_visible_envs`` + is set; otherwise ``None`` (viewer shows all worlds). (Random cap-only selection is applied earlier by + turning it into explicit ``env_ids``.) + * Explicit path (``env_ids`` is a list): if ``max_visible_envs`` is set, keep only the first *cap* indices + (truncate from the end); if ``None``, use the full list. + + Returns: + Selected indices, or ``None`` when all environments should be visible (cap-only, no limit). + """ + if env_ids is not None: + out = list(env_ids) + if max_visible_envs is not None: + out = out[: max(0, int(max_visible_envs))] + return out + if max_visible_envs is not None and num_envs > 0: + n = min(int(max_visible_envs), num_envs) + return list(range(n)) + return None + + +def apply_viewer_visible_worlds( + viewer, + *, + env_ids: list[int] | None, + max_visible_envs: int | None, + num_envs: int, +) -> None: + """Select which simulation worlds are visualized; no-op if the viewer does not support it. + + Prefer this over ``set_model(..., max_worlds=...)`` (deprecated in Newton). + + Args: + viewer: Newton viewer (ViewerGL, ViewerRerun, ViewerViser, etc.). + env_ids: Env indices from ``visible_env_indices`` (after validation), or ``None`` for the cap-only + contiguous path (see ``VisualizerCfg``). + max_visible_envs: When ``env_ids`` is ``None``, caps the contiguous count; otherwise truncates the list to + the first *N* indices. + num_envs: Total environment count from scene metadata. + """ + if not hasattr(viewer, "set_visible_worlds"): + return + resolved = resolve_visible_env_indices(env_ids, max_visible_envs, num_envs) + if resolved is None: + viewer.set_visible_worlds(None) + else: + viewer.set_visible_worlds(resolved) diff --git a/source/isaaclab_visualizers/isaaclab_visualizers/rerun/rerun_visualizer.py b/source/isaaclab_visualizers/isaaclab_visualizers/rerun/rerun_visualizer.py index ab2ed723223f..5390802df69d 100644 --- a/source/isaaclab_visualizers/isaaclab_visualizers/rerun/rerun_visualizer.py +++ b/source/isaaclab_visualizers/isaaclab_visualizers/rerun/rerun_visualizer.py @@ -20,6 +20,8 @@ from isaaclab.visualizers.base_visualizer import BaseVisualizer +from isaaclab_visualizers.newton_adapter import apply_viewer_visible_worlds, resolve_visible_env_indices + from .rerun_visualizer_cfg import RerunVisualizerCfg if TYPE_CHECKING: @@ -145,16 +147,10 @@ def initialize(self, scene_data_provider: BaseSceneDataProvider) -> None: self._scene_data_provider = scene_data_provider metadata = scene_data_provider.get_metadata() + num_envs = int(metadata.get("num_envs", 0)) self._env_ids = self._compute_visualized_env_ids() - if self._env_ids: - get_filtered_model = getattr(scene_data_provider, "get_newton_model_for_env_ids", None) - if callable(get_filtered_model): - self._model = get_filtered_model(self._env_ids) - else: - self._model = scene_data_provider.get_newton_model() - else: - self._model = scene_data_provider.get_newton_model() - self._state = scene_data_provider.get_newton_state(self._env_ids) + self._model = scene_data_provider.get_newton_model() + self._state = scene_data_provider.get_newton_state() grpc_port = int(self.cfg.grpc_port) web_port = int(self.cfg.web_port) @@ -185,22 +181,30 @@ def initialize(self, scene_data_provider: BaseSceneDataProvider) -> None: viewer_url = _rerun_web_viewer_url(viewer_host, web_port, rerun_address) if self.cfg.open_browser and not start_server_in_viewer: _open_rerun_web_viewer(viewer_host, web_port, rerun_address) - self._viewer.set_model(self._model, max_worlds=self.cfg.max_worlds) + self._viewer.set_model(self._model) + apply_viewer_visible_worlds( + self._viewer, + env_ids=self._env_ids, + max_visible_envs=self.cfg.max_visible_envs, + num_envs=num_envs, + ) # Preserve simulation world positions (env_spacing) rather than adding viewer-side offsets. self._viewer.set_world_offsets((0.0, 0.0, 0.0)) - self._apply_camera_pose(self._resolve_initial_camera_pose()) + initial_pose = self._resolve_initial_camera_pose() + self._apply_camera_pose(initial_pose) self._viewer.up_axis = 2 self._viewer.scaling = 1.0 self._viewer._paused = False - num_visualized_envs = len(self._env_ids) if self._env_ids is not None else int(metadata.get("num_envs", 0)) + _resolved = resolve_visible_env_indices(self._env_ids, self.cfg.max_visible_envs, num_envs) + num_visualized_envs = len(_resolved) if _resolved is not None else num_envs self._log_initialization_table( logger=logger, title="RerunVisualizer Configuration", rows=[ - ("camera_position", self.cfg.camera_position), - ("camera_target", self.cfg.camera_target), - ("camera_source", self.cfg.camera_source), + ("eye", self.cfg.eye), + ("lookat", self.cfg.lookat), + ("cam_source", self.cfg.cam_source), ("num_visualized_envs", num_visualized_envs), ("endpoint", f"http://{viewer_host}:{web_port}"), ("viewer_url", viewer_url), @@ -227,10 +231,10 @@ def step(self, dt: float) -> None: self._sim_time += dt self._step_counter += 1 - if self.cfg.camera_source == "usd_path": + if self.cfg.cam_source == "prim_path": self._update_camera_from_usd_path() - self._state = self._scene_data_provider.get_newton_state(self._env_ids) + self._state = self._scene_data_provider.get_newton_state() if not self._viewer.is_paused(): self._viewer.begin_frame(self._sim_time) @@ -275,11 +279,15 @@ def is_running(self) -> bool: def _resolve_initial_camera_pose(self) -> tuple[tuple[float, float, float], tuple[float, float, float]]: """Resolve initial camera pose from config or USD camera path.""" - if self.cfg.camera_source == "usd_path": - pose = self._resolve_camera_pose_from_usd_path(self.cfg.camera_usd_path) + if self.cfg.cam_source == "prim_path": + pose = self._resolve_camera_pose_from_usd_path(self.cfg.cam_prim_path) if pose is not None: return pose - return self.cfg.camera_position, self.cfg.camera_target + raise RuntimeError( + "[RerunVisualizer] cam_source='prim_path' requires a resolvable camera prim path, " + f"but no camera pose was found for '{self.cfg.cam_prim_path}'." + ) + return self._resolve_cfg_camera_pose("RerunVisualizer") def _apply_camera_pose(self, pose: tuple[tuple[float, float, float], tuple[float, float, float]]) -> None: """Apply camera pose to rerun's 3D view controls. @@ -307,7 +315,7 @@ def _apply_camera_pose(self, pose: tuple[tuple[float, float, float], tuple[float def _update_camera_from_usd_path(self) -> None: """Refresh camera pose from configured USD camera path when it changes.""" - pose = self._resolve_camera_pose_from_usd_path(self.cfg.camera_usd_path) + pose = self._resolve_camera_pose_from_usd_path(self.cfg.cam_prim_path) if pose is None: return if self._last_camera_pose == pose: diff --git a/source/isaaclab_visualizers/isaaclab_visualizers/rerun/rerun_visualizer_cfg.py b/source/isaaclab_visualizers/isaaclab_visualizers/rerun/rerun_visualizer_cfg.py index 5edd918929de..780b346f802b 100644 --- a/source/isaaclab_visualizers/isaaclab_visualizers/rerun/rerun_visualizer_cfg.py +++ b/source/isaaclab_visualizers/isaaclab_visualizers/rerun/rerun_visualizer_cfg.py @@ -47,9 +47,3 @@ class RerunVisualizerCfg(VisualizerCfg): record_to_rrd: str | None = None """Path to save .rrd recording file. None = no recording.""" - - max_worlds: int | None = None - """Maximum number of worlds/environments rendered by the viewer. - - Set to ``None`` to leave this option disabled. - """ diff --git a/source/isaaclab_visualizers/isaaclab_visualizers/viser/viser_visualizer.py b/source/isaaclab_visualizers/isaaclab_visualizers/viser/viser_visualizer.py index c20bfcd85a9f..a629ab8b2fed 100644 --- a/source/isaaclab_visualizers/isaaclab_visualizers/viser/viser_visualizer.py +++ b/source/isaaclab_visualizers/isaaclab_visualizers/viser/viser_visualizer.py @@ -19,6 +19,8 @@ from isaaclab.visualizers.base_visualizer import BaseVisualizer +from isaaclab_visualizers.newton_adapter import apply_viewer_visible_worlds, resolve_visible_env_indices + from .viser_visualizer_cfg import ViserVisualizerCfg logger = logging.getLogger(__name__) @@ -143,28 +145,22 @@ def initialize(self, scene_data_provider: BaseSceneDataProvider) -> None: self._scene_data_provider = scene_data_provider metadata = scene_data_provider.get_metadata() self._env_ids = self._compute_visualized_env_ids() - if self._env_ids: - get_filtered_model = getattr(scene_data_provider, "get_newton_model_for_env_ids", None) - self._model = ( - get_filtered_model(self._env_ids) - if callable(get_filtered_model) - else scene_data_provider.get_newton_model() - ) - else: - self._model = scene_data_provider.get_newton_model() - self._state = scene_data_provider.get_newton_state(self._env_ids) + self._model = scene_data_provider.get_newton_model() + self._state = scene_data_provider.get_newton_state() self._active_record_path = self.cfg.record_to_viser self._create_viewer(record_to_viser=self.cfg.record_to_viser, metadata=metadata) - num_visualized_envs = len(self._env_ids) if self._env_ids is not None else int(metadata.get("num_envs", 0)) + num_envs_meta = int(metadata.get("num_envs", 0)) + _resolved = resolve_visible_env_indices(self._env_ids, self.cfg.max_visible_envs, num_envs_meta) + num_visualized_envs = len(_resolved) if _resolved is not None else num_envs_meta viewer_url = _viser_web_viewer_url(self.cfg.port) self._log_initialization_table( logger=logger, title="ViserVisualizer Configuration", rows=[ - ("camera_position", self.cfg.camera_position), - ("camera_target", self.cfg.camera_target), - ("camera_source", self.cfg.camera_source), + ("eye", self.cfg.eye), + ("lookat", self.cfg.lookat), + ("cam_source", self.cfg.cam_source), ("num_visualized_envs", num_visualized_envs), ("port", self.cfg.port), ("viewer_url", viewer_url), @@ -182,11 +178,11 @@ def step(self, dt: float) -> None: if not self._is_initialized or self._viewer is None or self._scene_data_provider is None: return - if self.cfg.camera_source == "usd_path": + if self.cfg.cam_source == "prim_path": self._update_camera_from_usd_path() self._apply_pending_camera_pose() - self._state = self._scene_data_provider.get_newton_state(self._env_ids) + self._state = self._scene_data_provider.get_newton_state() self._sim_time += dt self._viewer.begin_frame(self._sim_time) self._viewer.log_state(self._state) @@ -253,13 +249,20 @@ def _create_viewer(self, record_to_viser: str | None, metadata: dict | None = No record_to_viser=record_to_viser, metadata=metadata or {}, ) - max_worlds = self.cfg.max_worlds - self._viewer.set_model(self._model, max_worlds=max_worlds) + num_envs = int((metadata or {}).get("num_envs", 0)) + self._viewer.set_model(self._model) + apply_viewer_visible_worlds( + self._viewer, + env_ids=self._env_ids, + max_visible_envs=self.cfg.max_visible_envs, + num_envs=num_envs, + ) # Preserve simulation world positions (env_spacing) rather than adding viewer-side offsets. self._viewer.set_world_offsets((0.0, 0.0, 0.0)) if self.cfg.open_browser: _open_viser_web_viewer(self.cfg.port) - self._set_viser_camera_view(self._resolve_initial_camera_pose()) + initial_pose = self._resolve_initial_camera_pose() + self._set_viser_camera_view(initial_pose) self._sim_time = 0.0 def _close_viewer(self, finalize_viser: bool = False) -> None: @@ -277,15 +280,15 @@ def _close_viewer(self, finalize_viser: bool = False) -> None: def _resolve_initial_camera_pose(self) -> tuple[tuple[float, float, float], tuple[float, float, float]]: """Resolve initial camera pose from config or USD camera path.""" - if self.cfg.camera_source == "usd_path": - pose = self._resolve_camera_pose_from_usd_path(self.cfg.camera_usd_path) + if self.cfg.cam_source == "prim_path": + pose = self._resolve_camera_pose_from_usd_path(self.cfg.cam_prim_path) if pose is not None: return pose - logger.warning( - "[ViserVisualizer] camera_usd_path '%s' not found; using configured camera.", - self.cfg.camera_usd_path, + raise RuntimeError( + "[ViserVisualizer] cam_source='prim_path' requires a resolvable camera prim path, " + f"but no camera pose was found for '{self.cfg.cam_prim_path}'." ) - return self.cfg.camera_position, self.cfg.camera_target + return self._resolve_cfg_camera_pose("ViserVisualizer") def _try_apply_viser_camera_view(self, pose: tuple[tuple[float, float, float], tuple[float, float, float]]) -> bool: """Try applying camera pose to active viser clients. @@ -341,7 +344,7 @@ def _apply_pending_camera_pose(self) -> None: def _update_camera_from_usd_path(self) -> None: """Refresh camera pose from configured USD camera path when it changes.""" - pose = self._resolve_camera_pose_from_usd_path(self.cfg.camera_usd_path) + pose = self._resolve_camera_pose_from_usd_path(self.cfg.cam_prim_path) if pose is None: return if self._last_camera_pose == pose or self._pending_camera_pose == pose: diff --git a/source/isaaclab_visualizers/isaaclab_visualizers/viser/viser_visualizer_cfg.py b/source/isaaclab_visualizers/isaaclab_visualizers/viser/viser_visualizer_cfg.py index c2400c7ee1e6..f3f2aa39b0c2 100644 --- a/source/isaaclab_visualizers/isaaclab_visualizers/viser/viser_visualizer_cfg.py +++ b/source/isaaclab_visualizers/isaaclab_visualizers/viser/viser_visualizer_cfg.py @@ -35,9 +35,3 @@ class ViserVisualizerCfg(VisualizerCfg): record_to_viser: str | None = None """Path to save a .viser recording file. None = no recording.""" - - max_worlds: int | None = None - """Maximum number of worlds/environments rendered by the viewer. - - Set to ``None`` to leave this option disabled. - """ diff --git a/source/isaaclab_visualizers/setup.py b/source/isaaclab_visualizers/setup.py index 5b0c24cffa6c..fc120619787b 100644 --- a/source/isaaclab_visualizers/setup.py +++ b/source/isaaclab_visualizers/setup.py @@ -17,16 +17,16 @@ "kit": [], "newton": [ "warp-lang", - "newton @ git+https://github.com/newton-physics/newton.git@2684d75bfa4bb8b058a93b81c458a74b7701c997", + "newton @ git+https://github.com/newton-physics/newton.git@a27277ed49d6f307b8a1e4c394be7e1d14965a62", "PyOpenGL-accelerate", "imgui-bundle>=1.92.5", ], "rerun": [ - "newton @ git+https://github.com/newton-physics/newton.git@2684d75bfa4bb8b058a93b81c458a74b7701c997", + "newton @ git+https://github.com/newton-physics/newton.git@a27277ed49d6f307b8a1e4c394be7e1d14965a62", "rerun-sdk>=0.29.0", ], "viser": [ - "newton @ git+https://github.com/newton-physics/newton.git@2684d75bfa4bb8b058a93b81c458a74b7701c997", + "newton @ git+https://github.com/newton-physics/newton.git@a27277ed49d6f307b8a1e4c394be7e1d14965a62", "viser>=1.0.16", ], } @@ -44,16 +44,13 @@ license="BSD-3-Clause", include_package_data=True, package_data={"": ["*.pyi"]}, - python_requires=">=3.11", + python_requires=">=3.12", install_requires=INSTALL_REQUIRES, extras_require=EXTRAS_REQUIRE, packages=["isaaclab_visualizers"], classifiers=[ "Natural Language :: English", - "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", - "Isaac Sim :: 5.0.0", - "Isaac Sim :: 5.1.0", "Isaac Sim :: 6.0.0", ], zip_safe=False, diff --git a/source/isaaclab_visualizers/test/test_newton_adapter.py b/source/isaaclab_visualizers/test/test_newton_adapter.py new file mode 100644 index 000000000000..3c020a8d10ee --- /dev/null +++ b/source/isaaclab_visualizers/test/test_newton_adapter.py @@ -0,0 +1,49 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Unit tests for viewer env resolution helpers.""" + +from __future__ import annotations + +from isaaclab_visualizers.newton_adapter import apply_viewer_visible_worlds, resolve_visible_env_indices + + +def test_resolve_visible_env_indices_truncates_explicit_list(): + assert resolve_visible_env_indices([1, 3, 5], 2, 10) == [1, 3] + assert resolve_visible_env_indices([1, 3], 1, 10) == [1] + + +def test_resolve_visible_env_indices_explicit_full_list_when_no_cap(): + assert resolve_visible_env_indices([1, 3], None, 10) == [1, 3] + + +def test_resolve_visible_env_indices_cap_when_no_filter(): + # When _compute_visualized_env_ids is None, cap is max_visible_envs. + assert resolve_visible_env_indices(None, 3, 10) == [0, 1, 2] + + +def test_resolve_visible_env_indices_all_when_no_cap(): + assert resolve_visible_env_indices(None, None, 10) is None + + +def test_resolve_visible_env_indices_num_envs_zero_falls_through_like_newton(): + assert resolve_visible_env_indices(None, 5, 0) is None + + +def test_apply_viewer_visible_worlds_delegates_to_resolved(): + calls: list = [] + + class _V: + def set_visible_worlds(self, worlds): + calls.append(worlds) + + apply_viewer_visible_worlds(_V(), env_ids=None, max_visible_envs=2, num_envs=5) + assert calls == [[0, 1]] + + apply_viewer_visible_worlds(_V(), env_ids=[2], max_visible_envs=99, num_envs=5) + assert calls[-1] == [2] + + apply_viewer_visible_worlds(_V(), env_ids=None, max_visible_envs=None, num_envs=3) + assert calls[-1] is None diff --git a/source/isaaclab_visualizers/test/test_visualizer_cartpole_integration.py b/source/isaaclab_visualizers/test/test_visualizer_cartpole_integration.py new file mode 100644 index 000000000000..42d1368dcebf --- /dev/null +++ b/source/isaaclab_visualizers/test/test_visualizer_cartpole_integration.py @@ -0,0 +1,608 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Integration tests: cartpole env + per-backend visualizers (Kit Replicator, tiled camera, GL, Rerun, Viser). + +Visualizer packages use ``logging.getLogger(__name__)``, so loggers are named like +``isaaclab_visualizers.kit.kit_visualizer`` and ``isaaclab.visualizers.base_visualizer``. +:class:`~isaaclab.sim.simulation_context.SimulationContext` uses +``logging.getLogger(__name__)`` → ``isaaclab.sim.simulation_context``. + +We filter :class:`~pytest.LogCaptureFixture` records with :data:`_VIS_LOGGER_PREFIXES` +so only those namespaces count (not Omniverse, PhysX, or unrelated warnings). + +Set :data:`ASSERT_VISUALIZER_WARNINGS` to ``True`` locally or in CI if you want tests to +fail on WARNING-level records from those loggers; by default only ERROR+ fails. +""" + +from __future__ import annotations + +# Pyglet must use HeadlessWindow (EGL) before ``pyglet.window`` is imported so Newton +# ViewerGL can construct without an X11 display (matches ``headless=True`` on NewtonVisualizerCfg). +import pyglet + +pyglet.options["headless"] = True + +from isaaclab.app import AppLauncher + +# launch Kit app +simulation_app = AppLauncher(headless=True, enable_cameras=True).app + +import contextlib +import copy +import logging +import socket + +import numpy as np +import pytest +import torch +import warp as wp +from isaaclab_visualizers.kit import KitVisualizer, KitVisualizerCfg +from isaaclab_visualizers.newton import NewtonVisualizer, NewtonVisualizerCfg +from isaaclab_visualizers.rerun import RerunVisualizer, RerunVisualizerCfg +from isaaclab_visualizers.viser import ViserVisualizer, ViserVisualizerCfg + +import isaaclab.sim as sim_utils +from isaaclab.sim import SimulationContext + +from isaaclab_tasks.direct.cartpole.cartpole_camera_env import CartpoleCameraEnv +from isaaclab_tasks.direct.cartpole.cartpole_camera_presets_env_cfg import CartpoleCameraPresetsEnvCfg +from isaaclab_tasks.manager_based.classic.cartpole.cartpole_env_cfg import CartpolePhysicsCfg + +# When True, tests also fail on WARNING-level records from visualizer-related loggers. +ASSERT_VISUALIZER_WARNINGS = False + +_MAX_NON_BLACK_STEPS = 8 +"""Steps for tiled camera / Rerun / Viser smoke tests (early exit ok when non-black).""" + +_CARTPOLE_INTEGRATION_NUM_ENVS = 1 +"""Vectorized env count for cartpole + visualizer integration tests.""" + +_CARTPOLE_INTEGRATION_VISUALIZER_EYE: tuple[float, float, float] = (3.0, 3.0, 3.0) +"""Passed to :class:`~isaaclab.visualizers.visualizer_cfg.VisualizerCfg` subclasses (``eye``).""" + +_CARTPOLE_INTEGRATION_VISUALIZER_LOOKAT: tuple[float, float, float] = (-4.0, -4.0, 0.0) +"""Passed to visualizer cfgs (``lookat``); also applied to :class:`~isaaclab.envs.common.ViewerCfg` for the env.""" + +# Resolution overrides for this test module (cartpole preset defaults: tiled camera 100×100; Kit helper was 320×240). +_CARTPOLE_KIT_INTEGRATION_RENDER_RESOLUTION: tuple[int, int] = (600, 600) +"""Kit: Replicator ``render_product`` (width, height) for viewport RGB in the motion check.""" + +_CARTPOLE_NEWTON_INTEGRATION_WINDOW_SIZE: tuple[int, int] = (600, 600) +"""Newton: ``NewtonVisualizerCfg`` framebuffer (window_width × window_height) for ``get_frame()``.""" + +_CARTPOLE_TILED_CAMERA_INTEGRATION_WH: tuple[int, int] = (600, 600) +"""Tiled camera per-env tile width/height (preset default is 100×100); keeps ``observation_space`` consistent.""" + +_VIS_FRAME_TEST_STEPS = 60 +"""Steps for Kit / Newton frame capture: no early exit.""" + +# Motion check compares the 2nd vs last captured frame (e.g. 2nd vs 60th when *_STEPS* is 60). +_MOTION_FRAME_EARLY_IDX = 1 +"""0-based index of the *early* frame (2nd capture).""" + +_MOTION_FRAME_LATE_IDX = _VIS_FRAME_TEST_STEPS - 1 +"""0-based index of the *late* frame (e.g. 60th capture when :data:`_VIS_FRAME_TEST_STEPS` is 60).""" + +# Early vs late frame motion: void background stays similar; only count *strongly* differing pixels. +_FRAME_MOTION_CHANNEL_DIFF_THRESHOLD = 50 +"""A pixel counts as differing if max(|ΔR|, |ΔG|, |ΔB|) >= this (0–255 space).""" + +_FRAME_MOTION_MIN_DIFFERING_PIXELS = 100 +"""Minimum number of such pixels between early and late frames (stale/frozen viz should be near zero).""" + +_VIS_LOGGER_PREFIXES = ( + "isaaclab.visualizers", + "isaaclab_visualizers", + "isaaclab.sim.simulation_context", +) + + +def _logger_name_matches_visualizer_scope(logger_name: str) -> bool: + """Return True if *logger_name* is a visualizer / SimulationContext visualizer path.""" + return any(logger_name.startswith(prefix) for prefix in _VIS_LOGGER_PREFIXES) + + +def _assert_no_visualizer_log_issues(caplog: pytest.LogCaptureFixture, *, fail_on_warnings: bool | None = None) -> None: + """Fail if captured records include ERROR/CRITICAL (always) or WARNING (if *fail_on_warnings*). + + *fail_on_warnings* defaults to :data:`ASSERT_VISUALIZER_WARNINGS`. + """ + if fail_on_warnings is None: + fail_on_warnings = ASSERT_VISUALIZER_WARNINGS + + error_logs = [ + r for r in caplog.records if r.levelno >= logging.ERROR and _logger_name_matches_visualizer_scope(r.name) + ] + assert not error_logs, "Visualizer-related error logs: " + "; ".join( + f"{r.name}: {r.getMessage()}" for r in error_logs + ) + + if fail_on_warnings: + warning_logs = [ + r for r in caplog.records if r.levelno == logging.WARNING and _logger_name_matches_visualizer_scope(r.name) + ] + assert not warning_logs, "Visualizer-related warning logs: " + "; ".join( + f"{r.name}: {r.getMessage()}" for r in warning_logs + ) + + +def _configure_sim_for_visualizer_test(env: CartpoleCameraEnv) -> None: + """Settings used by the previous smoke tests; keep RTX sensors enabled for camera paths.""" + env.sim.set_setting("/isaaclab/render/rtx_sensors", True) + env.sim._app_control_on_stop_handle = None # type: ignore[attr-defined] + + +def _find_free_tcp_port(host: str = "127.0.0.1") -> int: + """Ask OS for a currently free local TCP port.""" + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: + sock.bind((host, 0)) + return int(sock.getsockname()[1]) + + +def _allocate_rerun_test_ports(host: str = "127.0.0.1") -> tuple[int, int]: + """Allocate distinct free ports for rerun web and gRPC endpoints.""" + grpc_port = _find_free_tcp_port(host) + web_port = _find_free_tcp_port(host) + while web_port == grpc_port: + web_port = _find_free_tcp_port(host) + return web_port, grpc_port + + +def _cartpole_integration_visualizer_camera_kwargs() -> dict[str, tuple[float, float, float]]: + """Eye/lookat for all :class:`~isaaclab.visualizers.visualizer_cfg.VisualizerCfg` subclasses in these tests.""" + return { + "eye": _CARTPOLE_INTEGRATION_VISUALIZER_EYE, + "lookat": _CARTPOLE_INTEGRATION_VISUALIZER_LOOKAT, + } + + +def _get_visualizer_cfg(visualizer_kind: str): + """Return (visualizer_cfg, expected_visualizer_cls) for the given visualizer kind.""" + cam = _cartpole_integration_visualizer_camera_kwargs() + if visualizer_kind == "newton": + __import__("newton") + nw, nh = _CARTPOLE_NEWTON_INTEGRATION_WINDOW_SIZE + return ( + NewtonVisualizerCfg( + headless=True, + window_width=nw, + window_height=nh, + randomly_sample_visible_envs=False, + **cam, + ), + NewtonVisualizer, + ) + if visualizer_kind == "viser": + __import__("newton") + __import__("viser") + port = _find_free_tcp_port(host="127.0.0.1") + return ( + ViserVisualizerCfg(open_browser=False, port=port, randomly_sample_visible_envs=False, **cam), + ViserVisualizer, + ) + if visualizer_kind == "rerun": + __import__("newton") + __import__("rerun") + web_port, grpc_port = _allocate_rerun_test_ports(host="127.0.0.1") + return ( + RerunVisualizerCfg( + bind_address="127.0.0.1", + open_browser=False, + web_port=web_port, + grpc_port=grpc_port, + randomly_sample_visible_envs=False, + **cam, + ), + RerunVisualizer, + ) + return KitVisualizerCfg(randomly_sample_visible_envs=False, **cam), KitVisualizer + + +def _get_physics_cfg(backend_kind: str): + """Return physics config and expected backend substring for the given backend kind.""" + if backend_kind == "physx": + __import__("isaaclab_physx") + preset = CartpolePhysicsCfg() + physics_cfg = getattr(preset, "physx", None) + if physics_cfg is None: + from isaaclab_physx.physics import PhysxCfg + + physics_cfg = PhysxCfg() + return physics_cfg, "physx" + if backend_kind == "newton": + __import__("newton") + __import__("isaaclab_newton") + preset = CartpolePhysicsCfg() + physics_cfg = getattr(preset, "newton_mjwarp", None) + if physics_cfg is None: + from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg + + physics_cfg = NewtonCfg( + solver_cfg=MJWarpSolverCfg( + njmax=5, + nconmax=3, + cone="pyramidal", + impratio=1, + integrator="implicitfast", + ), + num_substeps=1, + debug_mode=False, + use_cuda_graph=True, + ) + return physics_cfg, "newton" + raise ValueError(f"Unknown backend: {backend_kind!r}") + + +def _assert_non_black_tensor(image_tensor: torch.Tensor, *, min_nonzero_pixels: int = 1) -> None: + """Assert camera-like tensor contains non-black pixels.""" + assert isinstance(image_tensor, torch.Tensor), f"Expected torch.Tensor, got {type(image_tensor)!r}" + assert image_tensor.numel() > 0, "Image tensor is empty." + finite_tensor = torch.where(torch.isfinite(image_tensor), image_tensor, torch.zeros_like(image_tensor)) + if finite_tensor.dtype.is_floating_point: + nonzero = torch.count_nonzero(torch.abs(finite_tensor) > 1e-6).item() + else: + nonzero = torch.count_nonzero(finite_tensor > 0).item() + assert nonzero >= min_nonzero_pixels, "Rendered frame appears black (no non-zero pixels)." + + +def _frame_to_numpy(frame) -> np.ndarray: + """Convert viewer ``get_frame()`` output (numpy, torch, or Warp array) to host ``numpy.ndarray``. + + ``np.asarray(wp.array)`` is unsafe: NumPy can trigger Warp indexing that raises at dimension edges. + """ + if isinstance(frame, np.ndarray): + return frame + if isinstance(frame, torch.Tensor): + return frame.detach().cpu().numpy() + if isinstance(frame, wp.array): + return wp.to_torch(frame).detach().cpu().numpy() + return np.asarray(frame) + + +def _assert_non_black_frame_array(frame) -> None: + """Assert viewer-captured frame has visible, non-black content.""" + frame_arr = _frame_to_numpy(frame) + assert frame_arr.size > 0, "Viewer returned an empty frame." + if frame_arr.ndim == 2: + color = frame_arr + else: + assert frame_arr.shape[-1] >= 3, f"Expected at least 3 channels, got shape {frame_arr.shape}." + color = frame_arr[..., :3] + finite = np.where(np.isfinite(color), color, 0) + assert np.count_nonzero(finite) > 0, "Viewer frame appears fully black." + + +def _frame_rgb_255_space(frame) -> np.ndarray: + """Return HxWx3 float in ~0–255 space for per-channel differencing.""" + arr = _frame_to_numpy(frame) + if arr.ndim == 2: + rgb = np.stack([arr, arr, arr], axis=-1) + else: + rgb = arr[..., :3] + rgb = np.asarray(rgb, dtype=np.float64) + # Normalized HDR buffers: scale so threshold matches (0,255) semantics. + if rgb.size > 0 and float(np.nanmax(rgb)) <= 1.0 + 1e-6: + rgb = rgb * 255.0 + return rgb + + +def _count_significantly_differing_pixels( + frame_a, + frame_b, + *, + channel_diff_threshold: float = _FRAME_MOTION_CHANNEL_DIFF_THRESHOLD, +) -> int: + """Count pixels where max(|ΔR|, |ΔG|, |ΔB|) >= *channel_diff_threshold* (0–255 space).""" + a = _frame_rgb_255_space(frame_a) + b = _frame_rgb_255_space(frame_b) + assert a.shape == b.shape, f"Frame shape mismatch for motion check: {a.shape} vs {b.shape}." + per_pixel_max = np.max(np.abs(a - b), axis=-1) + return int(np.count_nonzero(per_pixel_max >= channel_diff_threshold)) + + +def _assert_early_and_late_motion_frames_differ( + frames: list, + *, + channel_diff_threshold: float = _FRAME_MOTION_CHANNEL_DIFF_THRESHOLD, + min_differing_pixels: int = _FRAME_MOTION_MIN_DIFFERING_PIXELS, +) -> None: + """Fail if early vs late frames lack enough strongly differing pixels (stale/frozen bodies). + + Compares :data:`_MOTION_FRAME_EARLY_IDX` vs :data:`_MOTION_FRAME_LATE_IDX` (e.g. 2nd vs 60th capture). + + Voids/background stay near-identical; we only count pixels that change by at least + *channel_diff_threshold* on some channel (0–255). + """ + assert len(frames) >= _VIS_FRAME_TEST_STEPS, ( + f"Need at least {_VIS_FRAME_TEST_STEPS} frames for motion check, got {len(frames)}." + ) + i_early = _MOTION_FRAME_EARLY_IDX + i_late = _MOTION_FRAME_LATE_IDX + early_1 = i_early + 1 + late_1 = i_late + 1 + n_diff = _count_significantly_differing_pixels( + frames[i_early], frames[i_late], channel_diff_threshold=channel_diff_threshold + ) + assert n_diff >= min_differing_pixels, ( + f"Viewport captures #{early_1} and #{late_1} have too few strongly differing pixels " + f"({n_diff} < {min_differing_pixels}; threshold per channel={channel_diff_threshold} in 0–255 space). " + "Possible frozen or stale robot visualization." + ) + + +def _step_until_non_black_camera(env, actions: torch.Tensor, *, max_steps: int = _MAX_NON_BLACK_STEPS) -> None: + """Step env until the env's tiled camera RGB tensor is non-black, bounded by *max_steps*.""" + last_rgb = None + for _ in range(max_steps): + env.step(action=actions) + rgb = env._tiled_camera.data.output.get("rgb") + if rgb is None: + rgb = env._tiled_camera.data.output[env.cfg.tiled_camera.data_types[0]] + last_rgb = rgb + try: + _assert_non_black_tensor(rgb) + return + except AssertionError: + continue + _assert_non_black_tensor(last_rgb) + + +def _run_newton_viewer_frame_motion_test( + viewer, + *, + step_hook, + physics_kind: str, + viz_kind: str = "newton", +) -> None: + """Exactly ``_VIS_FRAME_TEST_STEPS`` sim steps; last frame non-black; early vs late motion check.""" + frames: list = [] + for _ in range(_VIS_FRAME_TEST_STEPS): + step_hook() + frames.append(viewer.get_frame()) + _assert_non_black_frame_array(frames[-1]) + _assert_early_and_late_motion_frames_differ(frames) + + +def _step_env_without_frame_check(env, actions: torch.Tensor, *, max_steps: int = _MAX_NON_BLACK_STEPS) -> None: + """Step the env to exercise visualizers that do not implement ``get_frame`` (e.g. Rerun, Viser).""" + for _ in range(max_steps): + env.step(action=actions) + + +def _build_rgb_annotator_for_camera( + camera_path: str, + *, + resolution: tuple[int, int] | None = None, +): + """Create CPU RGB annotator attached to a camera render product.""" + import omni.replicator.core as rep + + if resolution is None: + resolution = _CARTPOLE_KIT_INTEGRATION_RENDER_RESOLUTION + render_product = rep.create.render_product(camera_path, resolution=resolution) + annotator = rep.AnnotatorRegistry.get_annotator("rgb", device="cpu") + annotator.attach([render_product]) + return annotator, render_product + + +def _annotator_rgb_to_numpy(rgb_data) -> np.ndarray: + """Convert replicator annotator output to HxWx3 uint8 numpy array.""" + rgb_array = np.frombuffer(rgb_data, dtype=np.uint8).reshape(*rgb_data.shape) + if rgb_array.size == 0: + return np.zeros((1, 1, 3), dtype=np.uint8) + return rgb_array[:, :, :3] + + +def _run_kit_viewport_frame_motion_test( + env, + kit_visualizer: KitVisualizer, + *, + physics_kind: str, + viz_kind: str = "kit", +) -> None: + """Exactly ``_VIS_FRAME_TEST_STEPS`` env steps; last Replicator frame non-black; early vs late motion check.""" + camera_path = getattr(kit_visualizer, "_controlled_camera_path", None) + assert camera_path, "Kit visualizer does not expose a controlled viewport camera path." + + annotator = None + render_product = None + try: + annotator, render_product = _build_rgb_annotator_for_camera(camera_path) + actions = torch.zeros((env.num_envs, env.action_space.shape[-1]), device=env.device) + frames: list = [] + for _ in range(_VIS_FRAME_TEST_STEPS): + env.step(action=actions) + rgb_data = annotator.get_data() + frames.append(_annotator_rgb_to_numpy(rgb_data)) + _assert_non_black_frame_array(frames[-1]) + _assert_early_and_late_motion_frames_differ(frames) + finally: + if annotator is not None and render_product is not None: + with contextlib.suppress(Exception): + annotator.detach([render_product]) + + +def _make_cartpole_camera_env(visualizer_kind: str, backend_kind: str) -> CartpoleCameraEnv: + """Create cartpole camera env configured with selected visualizer and physics backend.""" + env_cfg_root = CartpoleCameraPresetsEnvCfg() + env_cfg = getattr(env_cfg_root, "default", None) + if env_cfg is None: + env_cfg = getattr(type(env_cfg_root), "default", None) + if env_cfg is None: + raise RuntimeError( + "CartpoleCameraPresetsEnvCfg does not expose a 'default' preset config. " + f"Available attributes: {sorted(vars(env_cfg_root).keys())}" + ) + env_cfg = copy.deepcopy(env_cfg) + env_cfg.scene.num_envs = _CARTPOLE_INTEGRATION_NUM_ENVS + env_cfg.viewer.eye = _CARTPOLE_INTEGRATION_VISUALIZER_EYE + env_cfg.viewer.lookat = _CARTPOLE_INTEGRATION_VISUALIZER_LOOKAT + tw, th = _CARTPOLE_TILED_CAMERA_INTEGRATION_WH + env_cfg.tiled_camera.width = tw + env_cfg.tiled_camera.height = th + if isinstance(env_cfg.observation_space, list) and len(env_cfg.observation_space) >= 3: + env_cfg.observation_space = [th, tw, env_cfg.observation_space[2]] + env_cfg.seed = None + env_cfg.sim.physics, _ = _get_physics_cfg(backend_kind) + visualizer_cfg, _ = _get_visualizer_cfg(visualizer_kind) + env_cfg.sim.visualizer_cfgs = visualizer_cfg + return CartpoleCameraEnv(env_cfg) + + +@pytest.mark.isaacsim_ci +@pytest.mark.parametrize( + "backend_kind", + [ + # xfail: Kit visualizer + PhysX only (Newton backend uses skip below — separate CUDA issue). + pytest.param( + "physx", + marks=pytest.mark.xfail( + reason=("Kit visualizer + PhysX: TODO remove xfail when stale Fabric transforms bug in Kit is fixed"), + strict=False, + ), + ), + pytest.param( + "newton", + marks=pytest.mark.skip( + reason=( + "TODO: Kit visualizer + Newton physics + Isaac RTX tiled camera can hit CUDA illegal access " + "or bad GPU state. Repro: rl_games train Isaac-Cartpole-Camera-Presets-Direct-v0 " + "--enable_cameras presets=newton_mjwarp --viz kit. Re-enable when fixed." + ) + ), + ), + ], +) +def test_cartpole_kit_visualizer_replicator_viewport_rgb_motion( + backend_kind: str, caplog: pytest.LogCaptureFixture +) -> None: + """Kit + cartpole: Replicator RGB on viewport camera; last frame non-black; early vs late frame differ; logs.""" + env = None + try: + sim_utils.create_new_stage() + env = _make_cartpole_camera_env(visualizer_kind="kit", backend_kind=backend_kind) + _configure_sim_for_visualizer_test(env) + with caplog.at_level(logging.WARNING): + env.reset() + kit_visualizers = [viz for viz in env.sim.visualizers if isinstance(viz, KitVisualizer)] + assert kit_visualizers, "Expected an initialized Kit visualizer." + _run_kit_viewport_frame_motion_test(env, kit_visualizers[0], physics_kind=backend_kind) + _assert_no_visualizer_log_issues(caplog) + finally: + if env is not None: + env.close() + else: + SimulationContext.clear_instance() + + +@pytest.mark.isaacsim_ci +@pytest.mark.parametrize("backend_kind", ["physx", "newton"]) +def test_cartpole_newton_visualizer_tiled_camera_rgb_non_black( + backend_kind: str, caplog: pytest.LogCaptureFixture +) -> None: + """Newton visualizer + cartpole: env tiled-camera RGB becomes non-black within a few steps; clean logs.""" + env = None + try: + sim_utils.create_new_stage() + env = _make_cartpole_camera_env(visualizer_kind="newton", backend_kind=backend_kind) + _configure_sim_for_visualizer_test(env) + with caplog.at_level(logging.WARNING): + env.reset() + actions = torch.zeros((env.num_envs, env.action_space.shape[-1]), device=env.device) + _step_until_non_black_camera(env, actions, max_steps=_MAX_NON_BLACK_STEPS) + _assert_no_visualizer_log_issues(caplog) + finally: + if env is not None: + env.close() + else: + SimulationContext.clear_instance() + + +@pytest.mark.isaacsim_ci +@pytest.mark.parametrize("backend_kind", ["physx", "newton"]) +def test_cartpole_newton_visualizer_viewergl_rgb_motion(backend_kind: str, caplog: pytest.LogCaptureFixture) -> None: + """Newton GL (``ViewerGL.get_frame``): full motion steps, last frame non-black; early vs late differ; logs.""" + env = None + try: + sim_utils.create_new_stage() + env = _make_cartpole_camera_env(visualizer_kind="newton", backend_kind=backend_kind) + _configure_sim_for_visualizer_test(env) + with caplog.at_level(logging.WARNING): + env.reset() + actions = torch.zeros((env.num_envs, env.action_space.shape[-1]), device=env.device) + newton_visualizers = [viz for viz in env.sim.visualizers if isinstance(viz, NewtonVisualizer)] + assert newton_visualizers, "Expected an initialized Newton visualizer." + viewer = getattr(newton_visualizers[0], "_viewer", None) + assert viewer is not None, "Newton viewer was not created." + + def _step_env() -> None: + env.step(action=actions) + + _run_newton_viewer_frame_motion_test(viewer, step_hook=_step_env, physics_kind=backend_kind) + _assert_no_visualizer_log_issues(caplog) + finally: + if env is not None: + env.close() + else: + SimulationContext.clear_instance() + + +@pytest.mark.isaacsim_ci +@pytest.mark.parametrize("backend_kind", ["physx", "newton"]) +def test_cartpole_rerun_visualizer_smoke_steps_and_logs(backend_kind: str, caplog: pytest.LogCaptureFixture) -> None: + """Rerun + cartpole: visualizer and viewer initialize; env steps exercise the pipeline; clean logs. + + Rerun does not expose a per-frame RGB API like ``get_frame``, so we do not assert pixel content. + """ + env = None + try: + sim_utils.create_new_stage() + env = _make_cartpole_camera_env(visualizer_kind="rerun", backend_kind=backend_kind) + _configure_sim_for_visualizer_test(env) + with caplog.at_level(logging.WARNING): + env.reset() + actions = torch.zeros((env.num_envs, env.action_space.shape[-1]), device=env.device) + rerun_visualizers = [viz for viz in env.sim.visualizers if isinstance(viz, RerunVisualizer)] + assert rerun_visualizers, "Expected an initialized Rerun visualizer." + assert getattr(rerun_visualizers[0], "_viewer", None) is not None, "Rerun viewer was not created." + _step_env_without_frame_check(env, actions, max_steps=_MAX_NON_BLACK_STEPS) + _assert_no_visualizer_log_issues(caplog) + finally: + if env is not None: + env.close() + else: + SimulationContext.clear_instance() + + +@pytest.mark.isaacsim_ci +@pytest.mark.parametrize("backend_kind", ["physx", "newton"]) +def test_cartpole_viser_visualizer_smoke_steps_and_logs(backend_kind: str, caplog: pytest.LogCaptureFixture) -> None: + """Viser + cartpole: visualizer and viewer initialize; env steps exercise the pipeline; clean logs. + + No per-frame RGB assertion (Viser does not mirror the Newton ``get_frame`` path used elsewhere). + """ + env = None + try: + sim_utils.create_new_stage() + env = _make_cartpole_camera_env(visualizer_kind="viser", backend_kind=backend_kind) + _configure_sim_for_visualizer_test(env) + with caplog.at_level(logging.WARNING): + env.reset() + actions = torch.zeros((env.num_envs, env.action_space.shape[-1]), device=env.device) + viser_visualizers = [viz for viz in env.sim.visualizers if isinstance(viz, ViserVisualizer)] + assert viser_visualizers, "Expected an initialized Viser visualizer." + assert getattr(viser_visualizers[0], "_viewer", None) is not None, "Viser viewer was not created." + _step_env_without_frame_check(env, actions, max_steps=_MAX_NON_BLACK_STEPS) + _assert_no_visualizer_log_issues(caplog) + finally: + if env is not None: + env.close() + else: + SimulationContext.clear_instance() + + +if __name__ == "__main__": + pytest.main([__file__, "-v", "--maxfail=1"]) diff --git a/source/isaaclab_visualizers/test/test_visualizer_smoke_logs.py b/source/isaaclab_visualizers/test/test_visualizer_smoke_logs.py deleted file mode 100644 index 22f620fb02a8..000000000000 --- a/source/isaaclab_visualizers/test/test_visualizer_smoke_logs.py +++ /dev/null @@ -1,228 +0,0 @@ -# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). -# All rights reserved. -# -# SPDX-License-Identifier: BSD-3-Clause - -"""Smoke test visualizer stepping and error logging.""" - -from isaaclab.app import AppLauncher - -# launch Kit app -simulation_app = AppLauncher(headless=True, enable_cameras=True).app - -import logging -import socket - -import pytest -import torch -from isaaclab_visualizers.kit import KitVisualizer, KitVisualizerCfg -from isaaclab_visualizers.newton import NewtonVisualizer, NewtonVisualizerCfg -from isaaclab_visualizers.rerun import RerunVisualizer, RerunVisualizerCfg -from isaaclab_visualizers.viser import ViserVisualizer, ViserVisualizerCfg - -import isaaclab.sim as sim_utils -from isaaclab.envs import DirectRLEnv, DirectRLEnvCfg -from isaaclab.scene import InteractiveSceneCfg -from isaaclab.sim import SimulationCfg, SimulationContext -from isaaclab.utils import configclass - -from isaaclab_tasks.manager_based.classic.cartpole.cartpole_env_cfg import ( - CartpolePhysicsCfg, - CartpoleSceneCfg, -) - -# Set to False to only fail on visualizer errors; when True, also fail on warnings. -ASSERT_VISUALIZER_WARNINGS = True - -_SMOKE_STEPS = 4 -_VIS_LOGGER_PREFIXES = ( - "isaaclab.visualizers", - "isaaclab_visualizers", - "isaaclab.sim.simulation_context", -) - - -def _find_free_tcp_port(host: str = "127.0.0.1") -> int: - """Ask OS for a currently free local TCP port.""" - with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: - sock.bind((host, 0)) - return int(sock.getsockname()[1]) - - -def _allocate_rerun_test_ports(host: str = "127.0.0.1") -> tuple[int, int]: - """Allocate distinct free ports for rerun web and gRPC endpoints.""" - grpc_port = _find_free_tcp_port(host) - web_port = _find_free_tcp_port(host) - while web_port == grpc_port: - web_port = _find_free_tcp_port(host) - return web_port, grpc_port - - -@configclass -class _SmokeEnvCfg(DirectRLEnvCfg): - decimation: int = 2 - action_space: int = 0 - observation_space: int = 0 - episode_length_s: float = 5.0 - sim: SimulationCfg = SimulationCfg(dt=0.005, render_interval=2, visualizer_cfgs=KitVisualizerCfg()) - scene: InteractiveSceneCfg = InteractiveSceneCfg(num_envs=1, env_spacing=1.0) - - -class _SmokeEnv(DirectRLEnv): - def _pre_physics_step(self, actions): - return - - def _apply_action(self): - return - - def _get_observations(self): - return {} - - def _get_rewards(self): - return {} - - def _get_dones(self): - return torch.zeros(1, dtype=torch.bool), torch.zeros(1, dtype=torch.bool) - - -def _get_visualizer_cfg(visualizer_kind: str): - """Return (visualizer_cfg, expected_visualizer_cls) for the given visualizer kind.""" - if visualizer_kind == "newton": - __import__("newton") - return NewtonVisualizerCfg(headless=True), NewtonVisualizer - if visualizer_kind == "viser": - __import__("newton") - __import__("viser") - return ViserVisualizerCfg(open_browser=False), ViserVisualizer - if visualizer_kind == "rerun": - __import__("newton") - __import__("rerun") - web_port, grpc_port = _allocate_rerun_test_ports(host="127.0.0.1") - # Use dynamically allocated non-default ports in smoke tests to avoid collisions. - # TODO: Consider supporting cleanup/termination of stale rerun processes when ports are occupied. - return ( - RerunVisualizerCfg( - bind_address="127.0.0.1", - open_browser=False, - web_port=web_port, - grpc_port=grpc_port, - ), - RerunVisualizer, - ) - return KitVisualizerCfg(), KitVisualizer - - -def _get_physics_cfg(backend_kind: str): - """Return physics config and expected backend substring for the given backend kind. - - Uses cartpole preset instance so we work whether presets are class or instance attributes. - Fallback: build PhysxCfg/NewtonCfg in-test if preset does not expose that backend. - """ - if backend_kind == "physx": - __import__("isaaclab_physx") - preset = CartpolePhysicsCfg() - physics_cfg = getattr(preset, "physx", None) - if physics_cfg is None: - from isaaclab_physx.physics import PhysxCfg - - physics_cfg = PhysxCfg() - return physics_cfg, "physx" - if backend_kind == "newton": - __import__("newton") - __import__("isaaclab_newton") - preset = CartpolePhysicsCfg() - physics_cfg = getattr(preset, "newton", None) - if physics_cfg is None: - from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg - - physics_cfg = NewtonCfg( - solver_cfg=MJWarpSolverCfg( - njmax=5, - nconmax=3, - cone="pyramidal", - impratio=1, - integrator="implicitfast", - ), - num_substeps=1, - debug_mode=False, - use_cuda_graph=True, - ) - return physics_cfg, "newton" - raise ValueError(f"Unknown backend: {backend_kind!r}") - - -def _resolve_case(visualizer_kind: str, backend_kind: str): - """Resolve (env_cfg, expected_visualizer_cls, expected_backend_substring) for one smoke test. - - Uses cartpole scene for all combinations (works with both PhysX and Newton). - """ - scene_cfg = CartpoleSceneCfg(num_envs=1, env_spacing=1.0) - viz_cfg, expected_viz_cls = _get_visualizer_cfg(visualizer_kind) - physics_cfg, expected_backend = _get_physics_cfg(backend_kind) - - cfg = _SmokeEnvCfg() - cfg.scene = scene_cfg - cfg.sim = SimulationCfg( - dt=0.005, - render_interval=2, - visualizer_cfgs=viz_cfg, - physics=physics_cfg, - ) - return cfg, expected_viz_cls, expected_backend - - -def _run_smoke_test(cfg, expected_visualizer_cls, expected_backend: str, caplog) -> None: - """Run smoke steps and assert no visualizer errors; optionally no warnings (see ASSERT_VISUALIZER_WARNINGS).""" - env = None - try: - sim_utils.create_new_stage() - env = _SmokeEnv(cfg=cfg) - backend_name = env.sim.physics_manager.__name__.lower() - assert expected_backend in backend_name, ( - f"Expected physics backend containing {expected_backend!r}, got {backend_name!r}" - ) - env.sim.set_setting("/isaaclab/render/rtx_sensors", True) - env.sim._app_control_on_stop_handle = None # type: ignore[attr-defined] - - actions = torch.zeros((env.num_envs, 0), device=env.device) - with caplog.at_level(logging.WARNING): - env.reset() - assert env.sim.visualizers - assert isinstance(env.sim.visualizers[0], expected_visualizer_cls) - for _ in range(_SMOKE_STEPS): - env.step(action=actions) - - # Always fail on errors - error_logs = [ - r for r in caplog.records if r.levelno >= logging.ERROR and r.name.startswith(_VIS_LOGGER_PREFIXES) - ] - assert not error_logs, "Visualizer emitted error logs during smoke stepping: " + "; ".join( - f"{r.name}: {r.message}" for r in error_logs - ) - - # Optionally fail on warnings - if ASSERT_VISUALIZER_WARNINGS: - warning_logs = [ - r for r in caplog.records if r.levelno >= logging.WARNING and r.name.startswith(_VIS_LOGGER_PREFIXES) - ] - assert not warning_logs, "Visualizer emitted warning logs during smoke stepping: " + "; ".join( - f"{r.name}: {r.message}" for r in warning_logs - ) - finally: - if env is not None: - env.close() - else: - SimulationContext.clear_instance() - - -@pytest.mark.isaacsim_ci -@pytest.mark.parametrize("visualizer_kind", ["kit", "newton", "rerun", "viser"]) -@pytest.mark.parametrize("backend_kind", ["physx", "newton"]) -def test_visualizer_backend_smoke(visualizer_kind: str, backend_kind: str, caplog): - """Smoke test each (visualizer, backend) pair; assert no errors (optionally no warnings).""" - cfg, expected_viz_cls, expected_backend = _resolve_case(visualizer_kind, backend_kind) - _run_smoke_test(cfg, expected_viz_cls, expected_backend, caplog) - - -if __name__ == "__main__": - pytest.main([__file__, "-v", "--maxfail=1"]) diff --git a/tools/changelog/cli.py b/tools/changelog/cli.py new file mode 100644 index 000000000000..16ad551b4ca3 --- /dev/null +++ b/tools/changelog/cli.py @@ -0,0 +1,1009 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Manage changelog fragments — single entry point with two subcommands. + +Each PR drops a fragment under ``source//changelog.d/.rst``. +The slug is any short, unique name — the contributor's branch name (with +``/`` replaced by ``-``) is the recommended default. The file mirrors +the RST that will appear in the changelog — one or more section headings +(``Added``, ``Changed``, ``Deprecated``, ``Removed``, ``Fixed``) each +underlined with ``^``. The **filename suffix** declares the bump tier: + +- ``.rst`` — patch bump. +- ``.minor.rst`` — minor bump. +- ``.major.rst`` — major bump. +- ``.skip`` — no entry, no bump. + +When a batch compiles together, the highest declared bump wins for the +package (one ``.major.rst`` anywhere → major). + +Subcommands: + + check PR gate. Verifies every modified package has a valid fragment. + compile Roll accumulated fragments into ``CHANGELOG.rst`` and bump + ``extension.toml``. Run by the nightly workflow + (``.github/workflows/nightly-changelog.yml``) on a cron and + by maintainers manually when cutting a release. + +Usage: + + # ── check ───────────────────────────────────────────────────── + # CI invocation on every pull_request: + cli.py check + + # ── compile ─────────────────────────────────────────────────── + # Normal release-time invocation — bump every managed package + # from accumulated fragments, write entries, delete fragments: + cli.py compile --all + + # Preview only (no writes, no deletes): + cli.py compile --all --dry-run + + # Pin one package to a specific version (single-package only — + # each managed package has its own version trajectory): + cli.py compile --package isaaclab --version 4.7.0 + + # Preview against a worked example without touching real packages: + cli.py compile --package isaaclab --dry-run \\ + --fragments-dir tools/changelog/test/integration/02_minor_bump/fragments + +For big version jumps (e.g. ``2.1`` → ``4.7``) edit +``source//config/extension.toml`` and prepend a manual entry to +``source//docs/CHANGELOG.rst``. The compiler is for fragment-driven +incremental bumps, not for jumps. +""" + +from __future__ import annotations + +import argparse +import re +import subprocess +import sys +from dataclasses import dataclass, field +from datetime import date +from functools import cached_property +from pathlib import Path +from typing import ClassVar + +# Walk three levels up: tools/changelog/cli.py -> tools/changelog/ -> tools/ -> repo root. +REPO_ROOT = Path(__file__).parent.parent.parent +PACKAGES_ROOT = REPO_ROOT / "source" + +# Recognised fragment filename patterns. ```` is any short identifier +# the contributor chose — typically their branch name with ``/`` replaced by +# ``-``. The slug must not contain ``.`` (reserved for the tier suffix) or +# ``/`` (path separator), but otherwise mirrors what git allows in a ref name. +# These regexes live at module level because Fragment, FragmentBatch, and +# PRDiff all match against them — they are the wire-format contract between +# contributors and the gate. +FRAGMENT_RE = re.compile(r"^(?P[^./][^./]*)(?:\.(?Pminor|major))?\.rst$") +SKIP_RE = re.compile(r"^(?P[^./][^./]*)\.skip$") + + +def _display_path(p: Path) -> str: + """Pretty-print a Path. Strips ``REPO_ROOT`` if ``p`` is inside the repo, + falls back to the absolute path otherwise (``--fragments-dir`` may + legitimately point at an external directory like ``/tmp/...``). + + Lives at module level because both :class:`Package` (writing on-disk + paths) and :class:`FragmentBatch` (warning about external fragment + paths) use it. + """ + try: + return str(p.relative_to(REPO_ROOT)) + except ValueError: + return str(p) + + +# --------------------------------------------------------------------------- +# Domain objects +# --------------------------------------------------------------------------- + + +@dataclass(frozen=True) +class Version: + """A semver-style version string ``X.Y.Z`` (optionally suffixed with ``.devN``). + + Models a version as a value object: immutable, comparable by its text, + knows how to produce a bumped successor. PEP 440 ``.devN`` suffixes + are tolerated on the way *in* (stripped before bumping) but never + written back out — :meth:`bumped` always returns a clean ``X.Y.Z``. + + Construction validates the format up front so that an invalid + ``--version`` flag from the CLI fails fast instead of silently writing + a malformed entry to ``CHANGELOG.rst``. + """ + + # ``X.Y.Z`` with an optional PEP 440 ``.devN`` suffix. The suffix is + # tolerated on the way *in* (e.g. when reading a stale dev version out + # of an existing ``extension.toml``) but :meth:`bumped` always strips + # it before producing a successor. + _SEMVER_RE: ClassVar[re.Pattern[str]] = re.compile(r"^\d+\.\d+\.\d+(\.dev\d+)?$") + + text: str + + def __post_init__(self) -> None: + if not self._SEMVER_RE.match(self.text): + raise ValueError(f"Invalid version {self.text!r}; expected X.Y.Z (optionally suffixed with .devN)") + + def bumped(self, tier: str) -> Version: + """Return a new Version one tier ahead of this one. + + ``tier`` is ``'major'``, ``'minor'``, or ``'patch'``. Major zeros + the minor and patch components; minor zeros patch. Any ``.devN`` + suffix on the current version is stripped before bumping. + """ + # __post_init__ guarantees the format, so this split is safe. + parts = self.text.split(".dev")[0].split(".") + if tier == "major": + return Version(f"{int(parts[0]) + 1}.0.0") + if tier == "minor": + return Version(f"{parts[0]}.{int(parts[1]) + 1}.0") + return Version(f"{parts[0]}.{parts[1]}.{int(parts[2]) + 1}") + + def __str__(self) -> str: + return self.text + + +@dataclass(frozen=True) +class Fragment: + """One fragment file in a package's ``changelog.d/`` (or an examples dir). + + A :class:`Fragment` instance is just a path plus methods that interpret + it as a changelog fragment. ``.gitkeep`` and ``*.skip`` files should + not be wrapped — only files matching :data:`FRAGMENT_RE`. + """ + + path: Path + + @property + def name(self) -> str: + return self.path.name + + @cached_property + def _match(self) -> re.Match[str] | None: + return FRAGMENT_RE.match(self.name) + + @property + def is_valid_filename(self) -> bool: + return self._match is not None + + @property + def bump(self) -> str: + """Bump tier declared by the filename suffix (defaults to ``'patch'``).""" + if self._match and self._match.group("bump"): + return self._match.group("bump") + return "patch" + + def parse(self) -> dict[str, list[str]]: + """Return ``{section: [lines]}`` from this fragment's content. + + Lines are kept as-is (including trailing newlines) so the compiled + output is byte-for-byte identical to what the contributor wrote. A + section heading is a non-empty line followed by ``^`` underline of + equal-or-greater length. + """ + text = self.path.read_text(encoding="utf-8") + lines = text.splitlines(keepends=True) + sections: dict[str, list[str]] = {} + current: str | None = None + buf: list[str] = [] + + i = 0 + while i < len(lines): + raw = lines[i] + stripped = raw.rstrip("\n") + if ( + i + 1 < len(lines) + and stripped + and re.fullmatch(r"\^+", lines[i + 1].rstrip("\n")) + and len(lines[i + 1].rstrip("\n")) >= len(stripped) + ): + if current is not None: + sections[current] = self._strip_trailing_blank(buf) + current = stripped + buf = [] + i += 2 # skip heading + underline + if i < len(lines) and not lines[i].strip(): + i += 1 + continue + if current is not None: + buf.append(raw) + i += 1 + + if current is not None: + sections[current] = self._strip_trailing_blank(buf) + + return sections + + @staticmethod + def _strip_trailing_blank(lines: list[str]) -> list[str]: + """Drop trailing blank lines from a section's raw line buffer.""" + while lines and not lines[-1].strip(): + lines.pop() + return lines + + @staticmethod + def parse_slug(filename: str) -> str | None: + """Return the slug declared by a fragment / skip filename, or ``None``. + + Used by :class:`PRDiff` to detect collisions between an added + fragment's slug and an existing fragment in the same directory, + without needing to materialise a :class:`Fragment` (the diff entry + may not exist on disk yet during a gate run). + """ + m = FRAGMENT_RE.match(filename) or SKIP_RE.match(filename) + return m.group("slug") if m else None + + def merge_time(self) -> int: + """Unix timestamp of the merge commit that introduced this fragment. + + Uses ``git log --diff-filter=A --first-parent`` to follow develop's + first-parent history, so the timestamp reflects when the PR's merge + commit landed (not the feature-branch commit that originally added + the file). Falls back to the file's most recent commit time when + not yet in first-parent history (e.g. local dry-runs on a feature + branch), and ultimately to ``0`` if git is unavailable. + """ + for cmd in ( + ["git", "log", "--diff-filter=A", "--first-parent", "-1", "--format=%ct", "--", str(self.path)], + ["git", "log", "-1", "--format=%ct", "--", str(self.path)], + ): + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True, cwd=REPO_ROOT) + ts = result.stdout.strip() + if ts: + return int(ts) + except (subprocess.CalledProcessError, ValueError): + continue + return 0 + + def validate(self) -> str | None: + """Return a human-readable error string if malformed, else ``None``. + + Filename rules: must match :data:`FRAGMENT_RE` (``.gitkeep`` and + ``*.skip`` files are filtered out at :meth:`FragmentBatch.from_dir` + level and never reach this method). Content rules (for ``*.rst`` + fragments only): non-empty file with at least one valid section + heading and at least one bullet point. + """ + if not self.is_valid_filename: + return ( + "invalid filename — must be .rst, .minor.rst, " + ".major.rst, or .skip (slug = your branch name " + "with `/` replaced by `-`, no dots)" + ) + if not self.path.exists(): + # Deleted fragments don't need validating (consumed by a previous compile). + return None + text = self.path.read_text(encoding="utf-8") + if not text.strip(): + return "fragment is empty" + sections = self.parse() + if not sections: + return ( + "no recognised section headings (expected one or more of " + "Added / Changed / Deprecated / Removed / Fixed, each underlined " + "with carets ``^`` of equal-or-greater length)" + ) + # Every declared section must carry at least one bullet — otherwise + # the compiled output emits a heading with no body, which is both + # ugly and almost certainly a contributor authoring mistake (typed + # the heading, forgot the bullet). + empty = [s for s, lines in sections.items() if not any(line.lstrip().startswith("*") for line in lines)] + if empty: + return ( + f"section(s) {', '.join(repr(s) for s in empty)} have no bullet entries — " + "use ``* `` to start each entry, or remove the heading" + ) + return None + + +@dataclass(frozen=True) +class FragmentBatch: + """A collection of fragments collected from a directory. + + ``valid`` are :class:`Fragment` instances sorted by merge time + (oldest first). ``invalid`` are paths that don't match any recognised + filename pattern — surfaced so the caller can warn or fail. ``.skip`` + and ``.gitkeep`` files are tolerated but excluded from both lists. + + Holds the pure-data class methods that turn a batch (or a synthetic + list of bumps / sections) into a compiled changelog entry. The + instance methods (:meth:`aggregate_bump`, :meth:`merged_sections`, + :meth:`compile_to_entry`) read the batch's own state; the + underscore-prefixed static methods (:meth:`_aggregate`, etc.) are + the underlying pure transformations and are used directly by tests + that exercise edge cases without a real fragments directory. + """ + + # Canonical ordering of section headings in compiled output. Anything + # not listed here keeps insertion order *after* these. + _SECTION_ORDER: ClassVar[list[str]] = ["Added", "Changed", "Deprecated", "Removed", "Fixed"] + + # Strict ordering of bump tiers (``major`` strictly outranks ``minor`` + # outranks ``patch``). Unrecognised tiers sort below ``patch``. + _BUMP_RANK: ClassVar[dict[str, int]] = {"patch": 0, "minor": 1, "major": 2} + + valid: list[Fragment] + invalid: list[Path] + skip_paths: list[Path] = field(default_factory=list) + + # ---- Construction -------------------------------------------------- + + @classmethod + def from_dir(cls, fragment_dir: Path) -> FragmentBatch: + if not fragment_dir.is_dir(): + return cls([], []) + valid: list[Fragment] = [] + invalid: list[Path] = [] + skips: list[Path] = [] + for p in fragment_dir.iterdir(): + if p.is_dir() or p.name == ".gitkeep": + continue + if SKIP_RE.match(p.name): + skips.append(p) + continue + f = Fragment(p) + if f.is_valid_filename: + valid.append(f) + else: + invalid.append(p) + # Sort by merge time, breaking ties on filename so the compiled output + # is deterministic when fragments share a merge commit (or when none + # are in git history yet — e.g. a local dry-run against test fixtures). + valid.sort(key=lambda f: (f.merge_time(), f.name)) + return cls(valid, invalid, skips) + + # ---- Queries against this batch's state --------------------------- + + def aggregate_bump(self) -> str: + """Highest bump tier declared by fragments that parsed to content. + + Empty fragments (which the compiler warns about and skips) are + excluded so they don't influence the version. Defaults to + ``patch`` if nothing parsed. + """ + return self._aggregate([f.bump for f, _ in self.parsed()]) + + def parsed(self) -> list[tuple[Fragment, dict[str, list[str]]]]: + """Return ``(fragment, sections)`` pairs, dropping fragments that parse empty.""" + return [(f, s) for f, s in ((f, f.parse()) for f in self.valid) if s] + + def merged_sections(self) -> dict[str, list[str]]: + """Cross-fragment merged section map for this batch.""" + return self._merge_sections([s for _, s in self.parsed()]) + + def compile_to_entry( + self, + current_version: Version, + *, + explicit_version: Version | None = None, + ) -> tuple[Version, str, str]: + """Return ``(new_version, bump_label, entry_text)`` for this batch. + + ``new_version`` is either ``explicit_version`` verbatim or the + result of bumping ``current_version`` by the aggregated tier. + ``bump_label`` is a human-readable suffix like ``" (bump: minor)"`` + for log lines (empty when ``explicit_version`` is used). + ``entry_text`` is the rendered RST block ready to prepend to a + ``CHANGELOG.rst``. Pure computation — no I/O. + """ + if explicit_version is not None: + new_version = explicit_version + bump_label = "" + else: + chosen_bump = self.aggregate_bump() + new_version = current_version.bumped(chosen_bump) + bump_label = f" (bump: {chosen_bump})" + entry = self._format_entry(new_version.text, self.merged_sections()) + return new_version, bump_label, entry + + # ---- Cleanup ------------------------------------------------------- + + def delete_all(self) -> tuple[int, int]: + """Delete every consumed fragment + skip file. Returns ``(n_frag, n_skip)``.""" + n_frag = self.delete_valid() + n_skip = self.delete_skips() + return n_frag, n_skip + + def delete_valid(self) -> int: + for f in self.valid: + f.path.unlink() + return len(self.valid) + + def delete_skips(self) -> int: + for p in self.skip_paths: + p.unlink() + return len(self.skip_paths) + + # ---- Pure transformations (the data class methods) ---------------- + # Static so callers and tests can exercise them with synthetic + # primitives — no FragmentBatch instance needed when the question + # is "given these tiers, which wins?" or "how do these dicts merge?" + + @classmethod + def _aggregate(cls, bumps: list[str]) -> str: + """Highest-ranked bump from ``bumps`` (``major > minor > patch``). + + An empty list defaults to ``'patch'``. + """ + if not bumps: + return "patch" + return max(bumps, key=lambda b: cls._BUMP_RANK.get(b, -1)) + + @staticmethod + def _merge_sections(fragments: list[dict[str, list[str]]]) -> dict[str, list[str]]: + """Merge multiple parsed fragments into a single section map. + + Bullets from different fragments that share a section heading are + concatenated directly (no blank line between them) to match the + dominant style in IsaacLab's existing ``CHANGELOG.rst`` files. + """ + merged: dict[str, list[str]] = {} + for frag in fragments: + for section, lines in frag.items(): + if section not in merged: + merged[section] = list(lines) + else: + merged[section].extend(lines) + return merged + + @classmethod + def _format_entry(cls, version: str, sections: dict[str, list[str]]) -> str: + """Return a complete RST version entry, ready to prepend to ``CHANGELOG.rst``. + + Sections appear in :attr:`_SECTION_ORDER` (Added, Changed, + Deprecated, Removed, Fixed). Anything else keeps insertion order + *after* the canonical ones. + """ + today = date.today().strftime("%Y-%m-%d") + heading = f"{version} ({today})" + out = [heading, "~" * len(heading), ""] + + ordered = [s for s in cls._SECTION_ORDER if s in sections] + extras = [s for s in sections if s not in cls._SECTION_ORDER] + + for section in ordered + extras: + out.append(section) + out.append("^" * len(section)) + out.append("") + for line in sections[section]: + out.append(line.rstrip("\n")) + out.append("") + + return "\n".join(out) + "\n" + + +@dataclass(frozen=True) +class Package: + """A source// directory the changelog tool can manage. + + A package is "managed" if it has both a ``config/extension.toml`` (the + version file the compiler bumps) and a ``docs/CHANGELOG.rst`` (the + file the compiler updates). :meth:`discover` returns only managed + packages; instances created directly may not be managed (use + :attr:`is_managed`). + """ + + root: Path + + @property + def name(self) -> str: + return self.root.name + + @property + def changelog_path(self) -> Path: + return self.root / "docs" / "CHANGELOG.rst" + + @property + def toml_path(self) -> Path: + return self.root / "config" / "extension.toml" + + @property + def default_fragment_dir(self) -> Path: + return self.root / "changelog.d" + + @property + def is_managed(self) -> bool: + return self.toml_path.is_file() and self.changelog_path.is_file() + + def current_version(self) -> Version: + for line in self.toml_path.read_text(encoding="utf-8").splitlines(): + m = re.match(r'^version\s*=\s*"([^"]+)"', line) + if m: + return Version(m.group(1)) + raise ValueError(f"No version field found in {self.toml_path}") + + def write_changelog_entry(self, entry: str, *, dry_run: bool) -> None: + text = self.changelog_path.read_text(encoding="utf-8") + m = re.search(r"^Changelog\n-+\s*\n\s*\n", text, re.MULTILINE) + if not m: + raise ValueError(f"Could not locate changelog header in {self.changelog_path}") + updated = text[: m.end()] + entry + "\n" + text[m.end() :] + if dry_run: + print(f"\n{'=' * 60}") + print(f"DRY RUN — would write to {_display_path(self.changelog_path)}") + print(f"{'=' * 60}") + print(entry) + else: + self.changelog_path.write_text(updated, encoding="utf-8") + + def write_version(self, new_version: Version, *, dry_run: bool) -> None: + text = self.toml_path.read_text(encoding="utf-8") + updated = re.sub(r'^version\s*=\s*"[^"]+"', f'version = "{new_version}"', text, flags=re.MULTILINE) + if dry_run: + print(f'DRY RUN — would set version = "{new_version}" in {_display_path(self.toml_path)}') + else: + self.toml_path.write_text(updated, encoding="utf-8") + + @classmethod + def from_name(cls, name: str, packages_root: Path = PACKAGES_ROOT) -> Package: + return cls(packages_root / name) + + @classmethod + def discover(cls, packages_root: Path = PACKAGES_ROOT) -> list[Package]: + """Return all managed packages under ``packages_root``, sorted by name.""" + if not packages_root.is_dir(): + return [] + return sorted( + (cls(child) for child in packages_root.iterdir() if child.is_dir() and cls(child).is_managed), + key=lambda p: p.name, + ) + + def compile( + self, + *, + fragments_dir: Path | None = None, + explicit_version: Version | None = None, + dry_run: bool = False, + ) -> bool: + """Compile fragments for this package. Returns True if any were compiled. + + There are exactly two modes: ``dry_run=True`` previews and writes + nothing; ``dry_run=False`` writes the new entry, bumps the version, + **and** deletes the consumed fragments. There is deliberately no + third "write but keep fragments" mode — leaving fragments in place + after a real compile is a footgun (the next compile would re-emit + them as a duplicate version block). + + Args: + fragments_dir: Read fragments from here instead of + :attr:`default_fragment_dir`. Useful for previewing against + example fixtures. + explicit_version: Pin the new version to this string (skips the + per-fragment bump inference). + dry_run: Preview only — no files are written or deleted. + """ + batch = FragmentBatch.from_dir(self._resolve_fragments_dir(fragments_dir)) + + for p in batch.invalid: + print( + f" WARNING: {_display_path(p)} does not match any recognised fragment " + "pattern (.rst, .minor.rst, .major.rst, .skip) — skipping.", + file=sys.stderr, + ) + + if not batch.valid: + if batch.skip_paths: + n = len(batch.skip_paths) + if dry_run: + print(f" {self.name}: would clean {n} stale skip file(s).") + else: + batch.delete_skips() + print(f" {self.name}: cleaned {n} stale skip file(s).") + else: + print(f" {self.name}: no fragments, skipping.") + return False + + # Apply the same content-validation rules the PR gate uses, so a + # malformed fragment that somehow reached this package (e.g. a + # stale fragment that predates a content-rule tightening, or a + # locally-edited file) doesn't silently produce a half-empty + # version block. Runs every fragment that survived filename + # validation in ``from_dir``. + validation_errors = [(f, err) for f in batch.valid if (err := f.validate()) is not None] + if validation_errors: + for f, err in validation_errors: + print(f" ERROR: {_display_path(f.path)}: {err}", file=sys.stderr) + raise ValueError( + f"{self.name}: {len(validation_errors)} fragment(s) failed content validation; " + "fix or remove them before compiling." + ) + + parsed_pairs = batch.parsed() + if not parsed_pairs: + print(f" {self.name}: all fragments empty after parsing, skipping.") + return False + + new_version, bump_label, entry = batch.compile_to_entry( + self.current_version(), explicit_version=explicit_version + ) + print(f" {self.name}: {len(parsed_pairs)} fragment(s) → version {new_version}{bump_label}") + + if not self.changelog_path.exists(): + # Should never happen with managed packages discovered via + # ``Package.discover()`` — defensive check for callers that + # construct a ``Package`` directly with an unmanaged root. + raise ValueError( + f"{_display_path(self.changelog_path)} does not exist; " + f"package {self.name!r} is not managed (missing CHANGELOG.rst)." + ) + self.write_changelog_entry(entry, dry_run=dry_run) + self.write_version(new_version, dry_run=dry_run) + + if not dry_run: + n_frag, n_skip = batch.delete_all() + msg = f" {self.name}: deleted {n_frag} fragment(s)" + if n_skip: + msg += f" and {n_skip} skip file(s)" + print(msg + ".") + + return True + + def _resolve_fragments_dir(self, override: Path | None) -> Path: + """Pick the directory ``compile`` should read fragments from. + + ``None`` means "use this package's own ``changelog.d/``"; an + absolute path is used as-is; a relative path is resolved against + ``REPO_ROOT`` so callers can pass things like + ``tools/changelog/test/integration/01_patch_bump/fragments`` without + worrying about the cwd. + """ + if override is None: + return self.default_fragment_dir + return override if override.is_absolute() else (REPO_ROOT / override).resolve() + + +@dataclass(frozen=True) +class PRDiff: + """A snapshot of "what this PR changed against its base branch." + + Wraps two views from the same git diff: ``changed`` (any file modified + or added) and ``added`` (the strict subset that's new on this branch). + Tests construct ``PRDiff`` directly with synthetic sets; + :meth:`from_git` runs the real ``git diff`` for production use. + """ + + changed: set[str] + added: set[str] + + @classmethod + def from_git(cls, base_ref: str) -> PRDiff: + """Run ``git diff`` against ``origin/...HEAD`` to populate the diff.""" + + def _diff(extra_args: list[str]) -> set[str]: + result = subprocess.run( + ["git", "diff", "--name-only", *extra_args, f"origin/{base_ref}...HEAD"], + capture_output=True, + text=True, + check=True, + cwd=REPO_ROOT, + ) + return {f for f in result.stdout.splitlines() if f} + + return cls(changed=_diff([]), added=_diff(["--diff-filter=A"])) + + def evaluate( + self, + packages: list[Package], + ) -> tuple[list[str], list[tuple[str, str]]]: + """Apply the PR-gate rules and return ``(missing_packages, invalid_fragments)``. + + Rules: + + 1. **Immutability** — every fragment file in the diff must be in + ``added`` (added on this branch). Modifying or renaming an existing + fragment is rejected with a hint to add a new one instead. + + 2. **Content validity** — every added ``*.rst`` fragment must parse + (recognised section headings + at least one bullet). ``.skip`` and + ``.gitkeep`` are exempt. + + 3. **Slug uniqueness** — within a package's ``changelog.d/``, no two + fragments may share the same slug. If an added fragment's slug + collides with an existing or co-added fragment, fail with a hint + to rename (e.g. append ``-2``). + + 4. **Required fragment per touched package** — for each managed + package the PR touches in ``source/`` (outside ``changelog.d/``), + the PR must *add* at least one valid fragment to that package's + ``changelog.d/``. Chained PRs (parent PR's fragment shows up in + the child's diff) naturally satisfy this — slug uniqueness is + the only constraint that matters. + """ + missing: list[str] = [] + invalid_fragments: list[tuple[str, str]] = [] + + for pkg in packages: + pkg_prefix = f"source/{pkg.name}/" + changelog_dir = f"source/{pkg.name}/changelog.d/" + + source_changed = [f for f in self.changed if f.startswith(pkg_prefix) and not f.startswith(changelog_dir)] + fragment_changes = [f for f in self.changed if f.startswith(changelog_dir)] + + # Map *pre-existing* fragments in the package's changelog.d/ by slug, + # for the uniqueness check below. The CI checkout contains both + # base-branch fragments and the PR's additions side by side, so we + # must explicitly exclude added files — otherwise an added file can + # overwrite the entry for a colliding pre-existing fragment with + # the same slug, hiding the very collision we're trying to detect. + # Skip ``.gitkeep`` and unrecognised filenames — they can't collide. + added_basenames = {Path(f).name for f in self.added if f.startswith(changelog_dir)} + existing_slugs: dict[str, str] = {} + existing_dir = pkg.default_fragment_dir + if existing_dir.is_dir(): + for p in existing_dir.iterdir(): + if p.is_dir() or p.name == ".gitkeep" or p.name in added_basenames: + continue + slug = Fragment.parse_slug(p.name) + if slug is not None: + existing_slugs[slug] = p.name + + added_slugs: dict[str, str] = {} + for f in fragment_changes: + path = Path(f) + if path.name == ".gitkeep": + continue + + # Rule 1: immutability — modifying an existing fragment is forbidden. + if f not in self.added: + invalid_fragments.append( + ( + f, + "fragments are immutable — add a new fragment with a different slug " + "instead of editing an existing one", + ) + ) + continue + + # Rule 2: content validity (only for *.rst, not *.skip). + if not SKIP_RE.match(path.name): + err = Fragment(REPO_ROOT / f).validate() + if err: + invalid_fragments.append((f, err)) + continue + + # Rule 3: slug uniqueness within the package's changelog.d/. + slug = Fragment.parse_slug(path.name) + if slug is None: + # Filename validation already flagged this above for *.rst, + # but a malformed *.skip would slip through. Surface it. + invalid_fragments.append( + (f, "invalid filename — must be .rst, .minor.rst, .major.rst, or .skip") + ) + continue + if slug in existing_slugs and existing_slugs[slug] != path.name: + invalid_fragments.append( + ( + f, + f"slug {slug!r} collides with existing fragment " + f"{existing_slugs[slug]!r} — rename to {slug}-2 (or any unused slug)", + ) + ) + continue + if slug in added_slugs and added_slugs[slug] != path.name: + invalid_fragments.append( + ( + f, + f"slug {slug!r} collides with another added fragment " + f"{added_slugs[slug]!r} — rename one to {slug}-2 (or any unused slug)", + ) + ) + continue + added_slugs[slug] = path.name + + if not source_changed: + continue + + # Rule 4: this PR must add at least one valid fragment for the package. + owned = [ + f + for f in fragment_changes + if f in self.added and (FRAGMENT_RE.match(Path(f).name) or SKIP_RE.match(Path(f).name)) + ] + if not owned: + missing.append(pkg.name) + + return missing, invalid_fragments + + +# --------------------------------------------------------------------------- +# Subcommand handlers +# --------------------------------------------------------------------------- + + +def cmd_compile(args: argparse.Namespace, parser: argparse.ArgumentParser) -> int: + if args.fragments_dir is not None and args.all: + parser.error("--fragments-dir requires --package (it cannot apply to all packages at once)") + if args.version is not None and args.all: + parser.error( + "--version requires --package (each managed package has its own version trajectory; " + "pin one with --package )" + ) + # Validate ``--version`` shape up front so a typo like ``--version 4.7`` + # fails at argument parsing instead of silently writing ``4.7`` into + # ``CHANGELOG.rst`` and ``extension.toml``. + explicit_version: Version | None = None + if args.version is not None: + try: + explicit_version = Version(args.version) + except ValueError as e: + parser.error(f"--version: {e}") + + if args.package: + pkg = Package.from_name(args.package) + if not pkg.root.is_dir(): + parser.error(f"--package {args.package!r}: directory not found at {pkg.root}") + if not pkg.is_managed: + parser.error( + f"--package {args.package!r} is not managed: missing config/extension.toml or " + f"docs/CHANGELOG.rst at {pkg.root}. Run with --all to see the discovered list." + ) + packages = [pkg] + else: + packages = Package.discover() + + any_compiled = False + for pkg in packages: + try: + compiled = pkg.compile( + fragments_dir=args.fragments_dir, + explicit_version=explicit_version, + dry_run=args.dry_run, + ) + except (FileNotFoundError, ValueError) as e: + print(f" ERROR: {e}", file=sys.stderr) + return 1 + any_compiled = any_compiled or compiled + + if not any_compiled: + print("No fragments found in any package.") + return 0 + + +def cmd_check(args: argparse.Namespace, _parser: argparse.ArgumentParser) -> int: + try: + diff = PRDiff.from_git(args.base_ref) + except subprocess.CalledProcessError as e: + print(f"ERROR: git diff failed: {e.stderr}", file=sys.stderr) + return 1 + + missing, invalid_fragments = diff.evaluate(Package.discover()) + + if invalid_fragments: + print("::error::Invalid changelog fragment(s) in this PR:") + for path, reason in invalid_fragments: + print(f" • {path}") + print(f" → {reason}") + print() + + if missing: + print("::error::Missing changelog fragments for the following packages:") + for pkg_name in missing: + print(f" • {pkg_name}") + print(f" → add source/{pkg_name}/changelog.d/.rst (patch bump)") + print(f" → or source/{pkg_name}/changelog.d/.minor.rst (minor bump)") + print(f" → or source/{pkg_name}/changelog.d/.major.rst (major bump)") + print(f" → or source/{pkg_name}/changelog.d/.skip (no entry, no bump)") + print() + print("Slug = your branch name with `/` replaced by `-` (or any short, unique name).") + print() + print("Fragment format (source//changelog.d/[.minor|.major].rst):") + print() + print(" Added") + print(" ^^^^^") + print() + print(" * Added :class:`~pkg.Foo` for feature X.") + print() + print(" Fixed") + print(" ^^^^^") + print() + print(" * Fixed edge case in :meth:`~pkg.Foo.bar`.") + print() + print("See AGENTS.md ## Changelog for full guidance.") + + if invalid_fragments or missing: + return 1 + + print("✓ All modified packages have valid changelog fragments.") + return 0 + + +# --------------------------------------------------------------------------- +# CLI entry point +# --------------------------------------------------------------------------- + + +def _build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser( + # The module docstring carries the full usage walkthrough — surfacing + # it as the parser description means ``cli.py --help`` shows the same + # guidance someone reading the source would see. + description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter, + ) + sub = parser.add_subparsers(dest="cmd", required=True, metavar="{compile,check}") + + p_compile = sub.add_parser( + "compile", + help="Compile fragments into CHANGELOG.rst (maintainer release-time tool).", + description="Compile accumulated fragments into per-package CHANGELOG.rst entries and bump extension.toml.", + formatter_class=argparse.RawDescriptionHelpFormatter, + ) + p_compile.set_defaults(func=cmd_compile) + + # ── Target: which packages to compile (required, mutually exclusive) ── + target = p_compile.add_argument_group("target", "Which package(s) to compile (required, mutually exclusive)") + target_group = target.add_mutually_exclusive_group(required=True) + target_group.add_argument("--package", metavar="NAME", help="Compile a single package.") + target_group.add_argument("--all", action="store_true", help="Compile all managed packages.") + + # ── Version source: by default inferred from filename suffixes ──────── + version_group = p_compile.add_argument_group( + "version (optional)", + "By default the new version is inferred from the filename suffixes of the consumed fragments.", + ) + version_group.add_argument( + "--version", + metavar="X.Y.Z", + help=( + "Pin the package to an explicit version, skipping the per-fragment bump inference. " + "Requires --package — each managed package has its own version trajectory and " + "applying a single version to all of them would corrupt their independent histories." + ), + ) + + # ── Execution mode: preview vs apply, where to read fragments from ──── + exec_group = p_compile.add_argument_group("execution") + exec_group.add_argument( + "--dry-run", + action="store_true", + help=( + "Preview only — no files are written or deleted. Without this flag, " + "the compile writes the new entry, bumps the version, and deletes " + "the consumed fragments." + ), + ) + exec_group.add_argument( + "--fragments-dir", + type=Path, + default=None, + metavar="PATH", + help=( + "Override the directory to read fragments from " + "(default: source//changelog.d/). " + "Useful for previewing against example fragments without touching real ones. " + "Only valid with --package." + ), + ) + + p_check = sub.add_parser( + "check", + help="Verify each modified package has a valid fragment (PR gate).", + description="Verify each modified package has a valid changelog fragment.", + formatter_class=argparse.RawDescriptionHelpFormatter, + ) + p_check.set_defaults(func=cmd_check) + p_check.add_argument( + "base_ref", + help=( + "Base branch to diff against (e.g. 'main' or 'develop'). " + "The diff is taken against ``origin/...HEAD``." + ), + ) + + return parser + + +def main() -> None: + parser = _build_parser() + args = parser.parse_args() + sys.exit(args.func(args, parser)) + + +if __name__ == "__main__": + main() diff --git a/tools/changelog/pyproject.toml b/tools/changelog/pyproject.toml new file mode 100644 index 000000000000..6033f35f178c --- /dev/null +++ b/tools/changelog/pyproject.toml @@ -0,0 +1,13 @@ +# Scopes pytest to this self-contained tool: the ``[tool.pytest.ini_options]`` +# section makes pytest treat ``tools/changelog/`` as its rootdir, so: +# +# 1. ``pythonpath = ["."]`` adds ``tools/changelog/`` to ``sys.path``, +# making ``import cli`` work from the test files without any shim. +# 2. ``tools/conftest.py`` (a session-takeover hook for the IsaacLab +# source/ test suite) sits *above* rootdir and is therefore not +# loaded — no ``--noconftest`` flag required. +# +# Run with: ``./isaaclab.sh -p -m pytest tools/changelog/`` +[tool.pytest.ini_options] +pythonpath = ["."] +testpaths = ["test"] diff --git a/tools/changelog/test/integration/01_patch_bump/changelog_after.rst b/tools/changelog/test/integration/01_patch_bump/changelog_after.rst new file mode 100644 index 000000000000..199771149d62 --- /dev/null +++ b/tools/changelog/test/integration/01_patch_bump/changelog_after.rst @@ -0,0 +1,25 @@ +Changelog +--------- + +1.2.4 (2026-04-30) +~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Tightened error message in :class:`~example.Foo` when a required argument is missing. + +Fixed +^^^^^ + +* Fixed missing GPU sync in :func:`~example.refresh_buffers` that occasionally returned stale data. +* Fixed off-by-one in :meth:`~example.Foo.bar` when the input list was empty. + + +1.2.3 (2026-01-15) +~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :class:`~example.OldThing` for an earlier feature. diff --git a/tools/changelog/test/integration/01_patch_bump/changelog_before.rst b/tools/changelog/test/integration/01_patch_bump/changelog_before.rst new file mode 100644 index 000000000000..81dc30f240c3 --- /dev/null +++ b/tools/changelog/test/integration/01_patch_bump/changelog_before.rst @@ -0,0 +1,10 @@ +Changelog +--------- + +1.2.3 (2026-01-15) +~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :class:`~example.OldThing` for an earlier feature. diff --git a/tools/changelog/test/integration/01_patch_bump/fragments/asmith-fix-collision-margin.rst b/tools/changelog/test/integration/01_patch_bump/fragments/asmith-fix-collision-margin.rst new file mode 100644 index 000000000000..2f4c9e39a432 --- /dev/null +++ b/tools/changelog/test/integration/01_patch_bump/fragments/asmith-fix-collision-margin.rst @@ -0,0 +1,9 @@ +Fixed +^^^^^ + +* Fixed missing GPU sync in :func:`~example.refresh_buffers` that occasionally returned stale data. + +Changed +^^^^^^^ + +* Tightened error message in :class:`~example.Foo` when a required argument is missing. diff --git a/tools/changelog/test/integration/01_patch_bump/fragments/jdoe-fix-mass-units.rst b/tools/changelog/test/integration/01_patch_bump/fragments/jdoe-fix-mass-units.rst new file mode 100644 index 000000000000..f3a7a66a215a --- /dev/null +++ b/tools/changelog/test/integration/01_patch_bump/fragments/jdoe-fix-mass-units.rst @@ -0,0 +1,4 @@ +Fixed +^^^^^ + +* Fixed off-by-one in :meth:`~example.Foo.bar` when the input list was empty. diff --git a/tools/changelog/test/integration/02_minor_bump/changelog_after.rst b/tools/changelog/test/integration/02_minor_bump/changelog_after.rst new file mode 100644 index 000000000000..bc5a3fee0e35 --- /dev/null +++ b/tools/changelog/test/integration/02_minor_bump/changelog_after.rst @@ -0,0 +1,30 @@ +Changelog +--------- + +1.3.0 (2026-04-30) +~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :class:`~example.NewSensor` for IMU-based proprioception. +* Added :func:`~example.helper` utility for batched coordinate transforms. + +Changed +^^^^^^^ + +* Documented thread-safety guarantees for :class:`~example.Worker`. + +Fixed +^^^^^ + +* Fixed a NaN propagation in :meth:`~example.Sensor.update`. + + +1.2.3 (2026-01-15) +~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :class:`~example.OldThing` for an earlier feature. diff --git a/tools/changelog/test/integration/02_minor_bump/changelog_before.rst b/tools/changelog/test/integration/02_minor_bump/changelog_before.rst new file mode 100644 index 000000000000..81dc30f240c3 --- /dev/null +++ b/tools/changelog/test/integration/02_minor_bump/changelog_before.rst @@ -0,0 +1,10 @@ +Changelog +--------- + +1.2.3 (2026-01-15) +~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :class:`~example.OldThing` for an earlier feature. diff --git a/tools/changelog/test/integration/02_minor_bump/fragments/asmith-add-multi-asset-spawner.minor.rst b/tools/changelog/test/integration/02_minor_bump/fragments/asmith-add-multi-asset-spawner.minor.rst new file mode 100644 index 000000000000..5f623cf02ad5 --- /dev/null +++ b/tools/changelog/test/integration/02_minor_bump/fragments/asmith-add-multi-asset-spawner.minor.rst @@ -0,0 +1,4 @@ +Added +^^^^^ + +* Added :class:`~example.NewSensor` for IMU-based proprioception. diff --git a/tools/changelog/test/integration/02_minor_bump/fragments/blee-add-camera-output-contract.minor.rst b/tools/changelog/test/integration/02_minor_bump/fragments/blee-add-camera-output-contract.minor.rst new file mode 100644 index 000000000000..a3feda328623 --- /dev/null +++ b/tools/changelog/test/integration/02_minor_bump/fragments/blee-add-camera-output-contract.minor.rst @@ -0,0 +1,9 @@ +Added +^^^^^ + +* Added :func:`~example.helper` utility for batched coordinate transforms. + +Changed +^^^^^^^ + +* Documented thread-safety guarantees for :class:`~example.Worker`. diff --git a/tools/changelog/test/integration/02_minor_bump/fragments/jdoe-fix-rotation-frame.rst b/tools/changelog/test/integration/02_minor_bump/fragments/jdoe-fix-rotation-frame.rst new file mode 100644 index 000000000000..e103861d0d98 --- /dev/null +++ b/tools/changelog/test/integration/02_minor_bump/fragments/jdoe-fix-rotation-frame.rst @@ -0,0 +1,4 @@ +Fixed +^^^^^ + +* Fixed a NaN propagation in :meth:`~example.Sensor.update`. diff --git a/tools/changelog/test/integration/03_major_bump/changelog_after.rst b/tools/changelog/test/integration/03_major_bump/changelog_after.rst new file mode 100644 index 000000000000..cec9e3221263 --- /dev/null +++ b/tools/changelog/test/integration/03_major_bump/changelog_after.rst @@ -0,0 +1,34 @@ +Changelog +--------- + +2.0.0 (2026-04-30) +~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :class:`~example.AnotherSensor` for proximity detection. + +Changed +^^^^^^^ + +* **Breaking:** :meth:`~example.Foo.bar` now returns a tuple ``(value, error)`` instead of raising. + +Removed +^^^^^^^ + +* Removed deprecated module ``example.old_api`` (use :mod:`~example.api` instead). + +Fixed +^^^^^ + +* Fixed a deadlock in :class:`~example.Pool` under high concurrency. + + +1.2.3 (2026-01-15) +~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :class:`~example.OldThing` for an earlier feature. diff --git a/tools/changelog/test/integration/03_major_bump/changelog_before.rst b/tools/changelog/test/integration/03_major_bump/changelog_before.rst new file mode 100644 index 000000000000..81dc30f240c3 --- /dev/null +++ b/tools/changelog/test/integration/03_major_bump/changelog_before.rst @@ -0,0 +1,10 @@ +Changelog +--------- + +1.2.3 (2026-01-15) +~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :class:`~example.OldThing` for an earlier feature. diff --git a/tools/changelog/test/integration/03_major_bump/fragments/asmith-add-warp-contact-stream.minor.rst b/tools/changelog/test/integration/03_major_bump/fragments/asmith-add-warp-contact-stream.minor.rst new file mode 100644 index 000000000000..864d48ce0cef --- /dev/null +++ b/tools/changelog/test/integration/03_major_bump/fragments/asmith-add-warp-contact-stream.minor.rst @@ -0,0 +1,4 @@ +Added +^^^^^ + +* Added :class:`~example.AnotherSensor` for proximity detection. diff --git a/tools/changelog/test/integration/03_major_bump/fragments/blee-rename-articulation-api.major.rst b/tools/changelog/test/integration/03_major_bump/fragments/blee-rename-articulation-api.major.rst new file mode 100644 index 000000000000..d392bcd339c2 --- /dev/null +++ b/tools/changelog/test/integration/03_major_bump/fragments/blee-rename-articulation-api.major.rst @@ -0,0 +1,9 @@ +Removed +^^^^^^^ + +* Removed deprecated module ``example.old_api`` (use :mod:`~example.api` instead). + +Changed +^^^^^^^ + +* **Breaking:** :meth:`~example.Foo.bar` now returns a tuple ``(value, error)`` instead of raising. diff --git a/tools/changelog/test/integration/03_major_bump/fragments/jdoe-fix-articulation-state.rst b/tools/changelog/test/integration/03_major_bump/fragments/jdoe-fix-articulation-state.rst new file mode 100644 index 000000000000..b184ab45c6e2 --- /dev/null +++ b/tools/changelog/test/integration/03_major_bump/fragments/jdoe-fix-articulation-state.rst @@ -0,0 +1,4 @@ +Fixed +^^^^^ + +* Fixed a deadlock in :class:`~example.Pool` under high concurrency. diff --git a/tools/changelog/test/integration/README.md b/tools/changelog/test/integration/README.md new file mode 100644 index 000000000000..1f55d0438705 --- /dev/null +++ b/tools/changelog/test/integration/README.md @@ -0,0 +1,35 @@ +# Changelog integration fixtures + +End-to-end test fixtures for `tools/changelog/cli.py compile`. Each +subdirectory holds a worked example: input fragments, the starting +`CHANGELOG.rst`, and the expected compiled output. + +`tools/changelog/test/test_integration.py` runs the compiler +against each one and asserts the output matches `changelog_after.rst`. +The fixtures double as human-readable demos — read alongside the PR +description to see how the system handles patch / minor / major bumps +and cross-fragment section merges. + +## Layout + +| Demo | Fragments | Bump | Resulting version | +|---|---|---|---| +| `01_patch_bump/` | 2 × `.rst` | patch | `1.2.3 → 1.2.4` | +| `02_minor_bump/` | 1 × `.rst` + 2 × `.minor.rst` | minor | `1.2.3 → 1.3.0` | +| `03_major_bump/` | 1 × `.rst` + 1 × `.minor.rst` + 1 × `.major.rst` | major | `1.2.3 → 2.0.0` | + +Each demo includes a `changelog_before.rst` (initial state) and a +`changelog_after.rst` (expected post-compile state). The bump tier is the +**max** of every fragment's filename suffix in the batch. + +## Run the compiler against a demo + +```bash +./isaaclab.sh -p tools/changelog/cli.py compile --package isaaclab \ + --fragments-dir tools/changelog/test/integration/02_minor_bump/fragments \ + --dry-run +``` + +`--dry-run` prevents the compile from consuming (deleting) the fixture +fragments. The output should match `02_minor_bump/changelog_after.rst` +modulo today's date. diff --git a/tools/changelog/test/invalid_content/3001.rst b/tools/changelog/test/invalid_content/3001.rst new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/tools/changelog/test/invalid_content/3002.rst b/tools/changelog/test/invalid_content/3002.rst new file mode 100644 index 000000000000..190621a3aaf3 --- /dev/null +++ b/tools/changelog/test/invalid_content/3002.rst @@ -0,0 +1 @@ +Just a free-form note with no section headings. diff --git a/tools/changelog/test/invalid_content/3003.rst b/tools/changelog/test/invalid_content/3003.rst new file mode 100644 index 000000000000..4470915bae8e --- /dev/null +++ b/tools/changelog/test/invalid_content/3003.rst @@ -0,0 +1,2 @@ +Added +^^^^^ diff --git a/tools/changelog/test/invalid_filenames/1234.notabump.rst b/tools/changelog/test/invalid_filenames/1234.notabump.rst new file mode 100644 index 000000000000..f70a86344dc6 --- /dev/null +++ b/tools/changelog/test/invalid_filenames/1234.notabump.rst @@ -0,0 +1,4 @@ +Added +^^^^^ + +* This file has an unrecognised bump tier and should be rejected. diff --git a/tools/changelog/test/invalid_filenames/multi.dot.slug.rst b/tools/changelog/test/invalid_filenames/multi.dot.slug.rst new file mode 100644 index 000000000000..c9ea00434158 --- /dev/null +++ b/tools/changelog/test/invalid_filenames/multi.dot.slug.rst @@ -0,0 +1,4 @@ +Added +^^^^^ + +* This file's slug contains dots (reserved for the tier suffix) and should be rejected. diff --git a/tools/changelog/test/test_bump_suffix.py b/tools/changelog/test/test_bump_suffix.py new file mode 100644 index 000000000000..1c191c6b33d9 --- /dev/null +++ b/tools/changelog/test/test_bump_suffix.py @@ -0,0 +1,135 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Bump-tier inference: filename suffix → bump, and aggregating across a batch. + +These tests use the worked examples under :file:`tools/changelog/examples/` +as fixtures so the same files double as human-readable demos and as +inputs the test suite verifies. +""" + +from __future__ import annotations + +from pathlib import Path + +import cli +import pytest + +EXAMPLES = Path(__file__).parent / "integration" + + +# --------------------------------------------------------------------------- +# Filename → bump tier (one demo per tier, tested separately) +# --------------------------------------------------------------------------- + + +def test_patch_bump_demo_aggregates_to_patch(): + """``examples/01_patch_bump/`` has two ``.rst`` files (no suffix) → patch.""" + batch = cli.FragmentBatch.from_dir(EXAMPLES / "01_patch_bump" / "fragments") + assert batch.invalid == [] + assert {f.name for f in batch.valid} == { + "jdoe-fix-mass-units.rst", + "asmith-fix-collision-margin.rst", + } + assert all(f.bump == "patch" for f in batch.valid) + assert batch.aggregate_bump() == "patch" + + +def test_minor_bump_demo_aggregates_to_minor(): + """``examples/02_minor_bump/`` mixes patch + minor fragments → minor wins.""" + batch = cli.FragmentBatch.from_dir(EXAMPLES / "02_minor_bump" / "fragments") + assert batch.invalid == [] + assert {f.name for f in batch.valid} == { + "jdoe-fix-rotation-frame.rst", + "asmith-add-multi-asset-spawner.minor.rst", + "blee-add-camera-output-contract.minor.rst", + } + bumps = sorted(f.bump for f in batch.valid) + assert bumps == ["minor", "minor", "patch"] + assert batch.aggregate_bump() == "minor" + + +def test_major_bump_demo_aggregates_to_major(): + """``examples/03_major_bump/`` mixes patch + minor + major → major wins.""" + batch = cli.FragmentBatch.from_dir(EXAMPLES / "03_major_bump" / "fragments") + assert batch.invalid == [] + assert {f.name for f in batch.valid} == { + "jdoe-fix-articulation-state.rst", + "asmith-add-warp-contact-stream.minor.rst", + "blee-rename-articulation-api.major.rst", + } + bumps = sorted(f.bump for f in batch.valid) + assert bumps == ["major", "minor", "patch"] + assert batch.aggregate_bump() == "major" + + +# --------------------------------------------------------------------------- +# Pure aggregation logic (no filesystem) +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + "bumps,expected", + [ + ([], "patch"), + (["patch"], "patch"), + (["patch", "patch"], "patch"), + (["patch", "minor"], "minor"), + (["minor", "patch", "minor"], "minor"), + (["patch", "minor", "major"], "major"), + (["major", "patch"], "major"), + ], +) +def test_aggregate_bump_logic(bumps, expected): + assert cli.FragmentBatch._aggregate(bumps) == expected + + +# --------------------------------------------------------------------------- +# Filename regex — what the gate and compiler agree to accept +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + "name,is_fragment,is_skip", + [ + ("1234.rst", True, False), + ("1234.minor.rst", True, False), + ("1234.major.rst", True, False), + ("1234.skip", False, True), + ("jdoe-fix-bug.rst", True, False), + ("jdoe-add-feature.minor.rst", True, False), + ("jdoe-rename-api.major.rst", True, False), + ("jdoe-ci-only.skip", False, True), + (".gitkeep", False, False), + ("README.md", False, False), + ("1234.patch.rst", False, False), # only minor/major are recognised tiers + ("foo.bar.rst", False, False), # extra dots in slug are reserved for tier suffix + ("1234.minor", False, False), # missing .rst extension + ("1234.rst.bak", False, False), + ], +) +def test_fragment_filename_regexes(name, is_fragment, is_skip): + assert bool(cli.FRAGMENT_RE.match(name)) is is_fragment + assert bool(cli.SKIP_RE.match(name)) is is_skip + + +# --------------------------------------------------------------------------- +# Fragment.parse_slug — derived from filename for collision detection +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + "name,expected_slug", + [ + ("1234.rst", "1234"), + ("jdoe-add-feature.minor.rst", "jdoe-add-feature"), + ("blee-rename-api.major.rst", "blee-rename-api"), + ("ci-only.skip", "ci-only"), + ("README.md", None), + (".gitkeep", None), + ], +) +def test_parse_slug_for_filenames(name, expected_slug): + assert cli.Fragment.parse_slug(name) == expected_slug diff --git a/tools/changelog/test/test_format.py b/tools/changelog/test/test_format.py new file mode 100644 index 000000000000..24a249992f7b --- /dev/null +++ b/tools/changelog/test/test_format.py @@ -0,0 +1,94 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""FragmentBatch._merge_sections + ._format_entry + Version.bumped — the rendering pipeline.""" + +from __future__ import annotations + +import cli +import pytest + +# --------------------------------------------------------------------------- +# merge_fragments — collapses bullets across fragments under the same section +# --------------------------------------------------------------------------- + + +def test_merge_fragments_collapses_same_section_across_fragments(): + f1 = {"Added": ["* a1\n"]} + f2 = {"Added": ["* a2\n"], "Fixed": ["* f1\n"]} + merged = cli.FragmentBatch._merge_sections([f1, f2]) + # Bullets from separate fragments concatenate with no blank line in between + # (matching IsaacLab's repo convention, where successive bullets are run-on). + assert merged["Added"] == ["* a1\n", "* a2\n"] + assert merged["Fixed"] == ["* f1\n"] + + +# --------------------------------------------------------------------------- +# format_entry — section ordering + version heading +# --------------------------------------------------------------------------- + + +def test_format_entry_orders_canonical_sections(): + sections = { + "Fixed": ["* f1\n"], + "Added": ["* a1\n"], + "Removed": ["* r1\n"], + } + out = cli.FragmentBatch._format_entry("1.2.4", sections) + # Canonical order is Added, Changed, Deprecated, Removed, Fixed. + a_pos = out.index("Added") + r_pos = out.index("Removed") + f_pos = out.index("Fixed") + assert a_pos < r_pos < f_pos + + +def test_format_entry_includes_version_heading(): + out = cli.FragmentBatch._format_entry("9.9.9", {"Added": ["* x\n"]}) + assert "9.9.9 (" in out + assert "~~~~~~" in out # tilde underline + + +def test_format_entry_unknown_sections_appear_after_canonical(): + sections = {"Performance": ["* p1\n"], "Added": ["* a1\n"]} + out = cli.FragmentBatch._format_entry("1.0.0", sections) + assert out.index("Added") < out.index("Performance") + + +# --------------------------------------------------------------------------- +# bump_version — semver maths +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + "current,part,expected", + [ + ("1.2.3", "patch", "1.2.4"), + ("1.2.3", "minor", "1.3.0"), # minor bump zeros patch + ("1.2.3", "major", "2.0.0"), # major bump zeros minor and patch + ("4.6.21", "patch", "4.6.22"), + ("4.6.21.dev20260301", "patch", "4.6.22"), # dev suffix stripped + ], +) +def test_version_bumped(current, part, expected): + assert cli.Version(current).bumped(part).text == expected + assert str(cli.Version(current).bumped(part)) == expected + + +def test_version_bumped_rejects_non_semver(): + # Construction itself rejects malformed input — fail-fast for bad ``--version``. + with pytest.raises(ValueError): + cli.Version("1.2") + with pytest.raises(ValueError): + cli.Version("not-semver") + with pytest.raises(ValueError): + cli.Version("1.2.3.4.5") + + +def test_version_accepts_dev_suffix(): + """PEP 440 ``.devN`` suffixes are tolerated on construction (they appear in + real ``extension.toml`` files between releases) and stripped on bump.""" + v = cli.Version("4.6.21.dev20260301") + assert v.text == "4.6.21.dev20260301" + assert v.bumped("patch").text == "4.6.22" diff --git a/tools/changelog/test/test_integration.py b/tools/changelog/test/test_integration.py new file mode 100644 index 000000000000..0e48e4a874aa --- /dev/null +++ b/tools/changelog/test/test_integration.py @@ -0,0 +1,69 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""End-to-end checks: run the compiler against each worked example and verify +the resulting changelog matches the checked-in :file:`changelog_after.rst`. + +This is what makes the examples *living docs* — if anything in the compile +pipeline drifts, an example's ``changelog_after.rst`` stops matching and +the corresponding test fails immediately. +""" + +from __future__ import annotations + +import re +import shutil +from pathlib import Path + +import cli +import pytest + +EXAMPLES = Path(__file__).parent / "integration" + +# Strip the ``(YYYY-MM-DD)`` suffix from version headings so the fixed example +# files don't drift when the compiler stamps today's date. +_DATE_RE = re.compile(r"\(\d{4}-\d{2}-\d{2}\)") + + +def _normalize(text: str) -> str: + return _DATE_RE.sub("(YYYY-MM-DD)", text) + + +@pytest.mark.parametrize( + "demo,expected_version", + [ + ("01_patch_bump", "1.2.4"), + ("02_minor_bump", "1.3.0"), + ("03_major_bump", "2.0.0"), + ], +) +def test_demo_compile_matches_changelog_after(tmp_path, demo, expected_version): + """Stage a fake package whose CHANGELOG.rst matches the demo's ``before``, + run the compiler against the demo's fragments, and verify the file ends + up byte-equal to the demo's ``after`` (modulo today's date).""" + demo_dir = EXAMPLES / demo + + # Build a minimal package layout the compiler will accept. + pkg_root = tmp_path / "demo_pkg" + (pkg_root / "config").mkdir(parents=True) + (pkg_root / "docs").mkdir(parents=True) + (pkg_root / "config" / "extension.toml").write_text('version = "1.2.3"\n', encoding="utf-8") + shutil.copy(demo_dir / "changelog_before.rst", pkg_root / "docs" / "CHANGELOG.rst") + + # Copy fragments into tmp_path so the compile's auto-clean doesn't + # delete the live checked-in examples directory. + fragments_tmp = tmp_path / "fragments" + shutil.copytree(demo_dir / "fragments", fragments_tmp) + + # Run the compiler against the (copied) fragments. + pkg = cli.Package(pkg_root) + pkg.compile(fragments_dir=fragments_tmp) + + actual = (pkg_root / "docs" / "CHANGELOG.rst").read_text(encoding="utf-8") + expected = (demo_dir / "changelog_after.rst").read_text(encoding="utf-8") + assert _normalize(actual) == _normalize(expected) + + # Version should have bumped exactly as the demo name suggests. + assert str(pkg.current_version()) == expected_version diff --git a/tools/changelog/test/test_parse.py b/tools/changelog/test/test_parse.py new file mode 100644 index 000000000000..fe8123c2f14c --- /dev/null +++ b/tools/changelog/test/test_parse.py @@ -0,0 +1,143 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Fragment.parse + FragmentBatch.from_dir + Package.discover — directory scanning.""" + +from __future__ import annotations + +from pathlib import Path + +import cli + +FIXTURES = Path(__file__).parent + + +def _write(path: Path, body: str) -> Path: + path.write_text(body, encoding="utf-8") + return path + + +# --------------------------------------------------------------------------- +# parse_fragment — section header detection (pure function) +# --------------------------------------------------------------------------- + + +def test_parse_fragment_single_section(tmp_path): + p = _write(tmp_path / "1.rst", "Added\n^^^^^\n\n* Added :class:`~pkg.Foo`.\n") + sections = cli.Fragment(p).parse() + assert list(sections.keys()) == ["Added"] + assert sections["Added"] == ["* Added :class:`~pkg.Foo`.\n"] + + +def test_parse_fragment_multiple_sections_preserves_dict_order(tmp_path): + p = _write(tmp_path / "1.rst", "Added\n^^^^^\n\n* a1\n\nFixed\n^^^^^\n\n* f1\n* f2\n") + sections = cli.Fragment(p).parse() + assert list(sections.keys()) == ["Added", "Fixed"] + assert sections["Added"] == ["* a1\n"] + assert sections["Fixed"] == ["* f1\n", "* f2\n"] + + +def test_parse_fragment_underline_must_be_at_least_heading_length(tmp_path): + """Heading 'Added' (5 chars) needs >=5 carets; '^^' must not match.""" + p = _write(tmp_path / "1.rst", "Added\n^^\n\n* a1\n") + assert cli.Fragment(p).parse() == {} + + +def test_parse_fragment_empty_file(tmp_path): + p = _write(tmp_path / "1.rst", "") + assert cli.Fragment(p).parse() == {} + + +def test_parse_fragment_no_section_headings(tmp_path): + p = _write(tmp_path / "1.rst", "Just a free-form note with no headings.\n") + assert cli.Fragment(p).parse() == {} + + +# --------------------------------------------------------------------------- +# Fragment.parse — same logic, exposed as a method on the wrapper +# --------------------------------------------------------------------------- + + +# --------------------------------------------------------------------------- +# FragmentBatch.from_dir — separates valid filenames from the rest +# --------------------------------------------------------------------------- + + +def test_fragment_batch_flags_invalid_filenames_from_fixture(): + """Files with dotted slugs or unknown bump tiers go in ``invalid``.""" + batch = cli.FragmentBatch.from_dir(FIXTURES / "invalid_filenames") + assert batch.valid == [] + assert {p.name for p in batch.invalid} == {"multi.dot.slug.rst", "1234.notabump.rst"} + + +def test_fragment_batch_missing_directory(tmp_path): + """A non-existent directory is treated as empty, not an error.""" + batch = cli.FragmentBatch.from_dir(tmp_path / "does-not-exist") + assert batch.valid == [] + assert batch.invalid == [] + assert batch.skip_paths == [] + + +def test_fragment_batch_collects_skip_files_separately(tmp_path): + """``.skip`` files are tolerated — exposed via ``skip_paths``, not ``valid``.""" + (tmp_path / "1234.skip").write_text("", encoding="utf-8") + (tmp_path / "1235.rst").write_text("Added\n^^^^^\n\n* x\n", encoding="utf-8") + batch = cli.FragmentBatch.from_dir(tmp_path) + assert {f.name for f in batch.valid} == {"1235.rst"} + assert {p.name for p in batch.skip_paths} == {"1234.skip"} + + +# --------------------------------------------------------------------------- +# Package.discover — a package is "managed" iff it has both +# config/extension.toml and docs/CHANGELOG.rst +# --------------------------------------------------------------------------- + + +def _make_pkg(root: Path, name: str, *, has_ext: bool = True, has_changelog: bool = True) -> None: + pkg = root / name + if has_ext: + (pkg / "config").mkdir(parents=True, exist_ok=True) + (pkg / "config" / "extension.toml").write_text('version = "0.0.0"\n', encoding="utf-8") + if has_changelog: + (pkg / "docs").mkdir(parents=True, exist_ok=True) + (pkg / "docs" / "CHANGELOG.rst").write_text("Changelog\n---------\n\n", encoding="utf-8") + + +def test_package_discover_includes_complete_packages(tmp_path): + _make_pkg(tmp_path, "complete_a") + _make_pkg(tmp_path, "complete_b") + pkgs = cli.Package.discover(tmp_path) + assert [p.name for p in pkgs] == ["complete_a", "complete_b"] + assert all(p.is_managed for p in pkgs) + + +def test_package_discover_excludes_packages_missing_changelog(tmp_path): + _make_pkg(tmp_path, "complete") + _make_pkg(tmp_path, "no_changelog", has_changelog=False) + assert [p.name for p in cli.Package.discover(tmp_path)] == ["complete"] + + +def test_package_discover_excludes_packages_missing_extension_toml(tmp_path): + _make_pkg(tmp_path, "complete") + _make_pkg(tmp_path, "no_extension", has_ext=False) + assert [p.name for p in cli.Package.discover(tmp_path)] == ["complete"] + + +def test_package_discover_returns_sorted_alphabetically(tmp_path): + _make_pkg(tmp_path, "zebra") + _make_pkg(tmp_path, "alpha") + _make_pkg(tmp_path, "mango") + assert [p.name for p in cli.Package.discover(tmp_path)] == ["alpha", "mango", "zebra"] + + +def test_package_discover_missing_root_returns_empty(tmp_path): + assert cli.Package.discover(tmp_path / "does-not-exist") == [] + + +def test_package_is_managed_property(tmp_path): + _make_pkg(tmp_path, "complete") + _make_pkg(tmp_path, "no_changelog", has_changelog=False) + assert cli.Package(tmp_path / "complete").is_managed is True + assert cli.Package(tmp_path / "no_changelog").is_managed is False diff --git a/tools/changelog/test/test_validate.py b/tools/changelog/test/test_validate.py new file mode 100644 index 000000000000..e02e1b95e990 --- /dev/null +++ b/tools/changelog/test/test_validate.py @@ -0,0 +1,323 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Fragment.validate — PR-gate filename + content rules.""" + +from __future__ import annotations + +from pathlib import Path + +import cli +import pytest + +FIXTURES = Path(__file__).parent + + +def _write(path: Path, body: str) -> Path: + path.write_text(body, encoding="utf-8") + return path + + +# --------------------------------------------------------------------------- +# Acceptance — well-formed fragments +# --------------------------------------------------------------------------- + + +def test_validate_accepts_well_formed(tmp_path): + p = _write(tmp_path / "1234.rst", "Added\n^^^^^\n\n* Added X.\n") + assert cli.Fragment(p).validate() is None + + +def test_validate_accepts_minor_suffix(tmp_path): + p = _write(tmp_path / "1234.minor.rst", "Added\n^^^^^\n\n* Added X.\n") + assert cli.Fragment(p).validate() is None + + +def test_validate_accepts_major_suffix(tmp_path): + p = _write(tmp_path / "1234.major.rst", "Removed\n^^^^^^^\n\n* Removed X.\n") + assert cli.Fragment(p).validate() is None + + +# --------------------------------------------------------------------------- +# Rejection — uses checked-in fixtures so the malformed inputs are reviewable +# --------------------------------------------------------------------------- + + +def test_validate_rejects_unknown_filename_from_fixture(): + err = cli.Fragment(FIXTURES / "invalid_filenames" / "multi.dot.slug.rst").validate() + assert err is not None and "invalid filename" in err + + +def test_validate_rejects_unknown_bump_tier_from_fixture(): + err = cli.Fragment(FIXTURES / "invalid_filenames" / "1234.notabump.rst").validate() + assert err is not None and "invalid filename" in err + + +def test_validate_rejects_empty_file_from_fixture(): + err = cli.Fragment(FIXTURES / "invalid_content" / "3001.rst").validate() + assert err is not None and "empty" in err + + +def test_validate_rejects_missing_section_heading_from_fixture(): + err = cli.Fragment(FIXTURES / "invalid_content" / "3002.rst").validate() + assert err is not None and "section" in err.lower() + + +def test_validate_rejects_section_without_bullets_from_fixture(): + err = cli.Fragment(FIXTURES / "invalid_content" / "3003.rst").validate() + assert err is not None and "bullet" in err.lower() + + +# --------------------------------------------------------------------------- +# check_fragments — gate orchestration: immutability, slug uniqueness, and +# the "PR must add at least one fragment per touched package" rule +# --------------------------------------------------------------------------- + + +def _pkg_under(tmp_path: Path, name: str) -> cli.Package: + """Build a managed-looking Package rooted at ``tmp_path/source/``.""" + root = tmp_path / "source" / name + (root / "config").mkdir(parents=True) + (root / "docs").mkdir(parents=True) + (root / "config" / "extension.toml").write_text('version = "0.0.0"\n', encoding="utf-8") + (root / "docs" / "CHANGELOG.rst").write_text("Changelog\n---------\n\n", encoding="utf-8") + return cli.Package(root) + + +def test_check_fragments_immutability_rejects_modified_fragment(tmp_path): + """Modifying an existing fragment is forbidden — must add a new one instead.""" + pkg = _pkg_under(tmp_path, "isaaclab") + changed = {"source/isaaclab/code.py", "source/isaaclab/changelog.d/jdoe-fix-bug.rst"} + added = {"source/isaaclab/code.py"} # fragment exists already; the PR only modified it + missing, invalid = cli.PRDiff(changed=changed, added=added).evaluate([pkg]) + assert missing == ["isaaclab"] + invalid_map = dict(invalid) + assert "source/isaaclab/changelog.d/jdoe-fix-bug.rst" in invalid_map + assert "immutable" in invalid_map["source/isaaclab/changelog.d/jdoe-fix-bug.rst"] + + +def test_check_fragments_chain_allows_other_pr_fragment(tmp_path): + """A chained PR (B based on A's branch, A still open) sees A's fragment in + its diff. That should pass — both fragments have distinct slugs and B + contributes its own fragment for the touched package.""" + pkg = _pkg_under(tmp_path, "isaaclab") + (pkg.root / "changelog.d").mkdir() + (pkg.root / "changelog.d" / "alice-feature-a.rst").write_text("Fixed\n^^^^^\n\n* x\n", encoding="utf-8") + (pkg.root / "changelog.d" / "bob-feature-b.rst").write_text("Added\n^^^^^\n\n* y\n", encoding="utf-8") + changed = { + "source/isaaclab/code.py", + "source/isaaclab/changelog.d/alice-feature-a.rst", # parent PR's fragment + "source/isaaclab/changelog.d/bob-feature-b.rst", # this PR's own fragment + } + added = changed + missing, invalid = cli.PRDiff(changed=changed, added=added).evaluate([pkg]) + assert missing == [] + assert invalid == [] + + +def test_check_fragments_slug_collision_with_existing(tmp_path): + """Adding a fragment whose slug collides with one already in changelog.d/ fails.""" + pkg = _pkg_under(tmp_path, "isaaclab") + (pkg.root / "changelog.d").mkdir() + # Pre-existing fragment on develop with the same slug as the one this PR adds. + (pkg.root / "changelog.d" / "jdoe-fix-bug.rst").write_text("Fixed\n^^^^^\n\n* x\n", encoding="utf-8") + # PR adds a fresh fragment whose slug collides — different tier, same slug. + (pkg.root / "changelog.d" / "jdoe-fix-bug.minor.rst").write_text("Added\n^^^^^\n\n* y\n", encoding="utf-8") + changed = {"source/isaaclab/code.py", "source/isaaclab/changelog.d/jdoe-fix-bug.minor.rst"} + added = changed + missing, invalid = cli.PRDiff(changed=changed, added=added).evaluate([pkg]) + invalid_map = dict(invalid) + assert "source/isaaclab/changelog.d/jdoe-fix-bug.minor.rst" in invalid_map + assert "collides" in invalid_map["source/isaaclab/changelog.d/jdoe-fix-bug.minor.rst"] + + +def test_check_fragments_collision_independent_of_iterdir_order(tmp_path, monkeypatch): + """Regression: an added file must not be allowed to *replace* a colliding + pre-existing fragment in the existing-slug map. The CI checkout contains + both, and depending on filesystem iteration order the added file could + end up as the "existing" entry, hiding the collision.""" + pkg = _pkg_under(tmp_path, "isaaclab") + (pkg.root / "changelog.d").mkdir() + (pkg.root / "changelog.d" / "jdoe-foo.rst").write_text("Fixed\n^^^^^\n\n* x\n", encoding="utf-8") + (pkg.root / "changelog.d" / "jdoe-foo.minor.rst").write_text("Added\n^^^^^\n\n* y\n", encoding="utf-8") + changed = {"source/isaaclab/code.py", "source/isaaclab/changelog.d/jdoe-foo.minor.rst"} + added = changed + + # Force iterdir() to return the added file *last* so it would overwrite + # the pre-existing entry in a buggy implementation. Sort with the added + # file ranked highest, so it lands at the tail regardless of natural + # alphabetical order. + real_iterdir = Path.iterdir + added_name = "jdoe-foo.minor.rst" + + def ordered_iterdir(self): + if self == pkg.root / "changelog.d": + return iter(sorted(real_iterdir(self), key=lambda p: (p.name == added_name, p.name))) + return real_iterdir(self) + + monkeypatch.setattr(Path, "iterdir", ordered_iterdir) + + missing, invalid = cli.PRDiff(changed=changed, added=added).evaluate([pkg]) + invalid_map = dict(invalid) + assert "source/isaaclab/changelog.d/jdoe-foo.minor.rst" in invalid_map + assert "collides" in invalid_map["source/isaaclab/changelog.d/jdoe-foo.minor.rst"] + + +def test_check_fragments_slug_collision_within_pr(tmp_path): + """Two added fragments in the same PR that share a slug (e.g. across tiers) fail.""" + pkg = _pkg_under(tmp_path, "isaaclab") + (pkg.root / "changelog.d").mkdir() + (pkg.root / "changelog.d" / "jdoe-fix.rst").write_text("Fixed\n^^^^^\n\n* x\n", encoding="utf-8") + (pkg.root / "changelog.d" / "jdoe-fix.minor.rst").write_text("Added\n^^^^^\n\n* y\n", encoding="utf-8") + changed = { + "source/isaaclab/code.py", + "source/isaaclab/changelog.d/jdoe-fix.rst", + "source/isaaclab/changelog.d/jdoe-fix.minor.rst", + } + added = changed + missing, invalid = cli.PRDiff(changed=changed, added=added).evaluate([pkg]) + # One of the two is the offender; the other is the first-seen "winner". + invalid_paths = [p for p, _ in invalid] + assert any("jdoe-fix" in p for p in invalid_paths) + assert any("collides" in r for _, r in invalid) + + +def test_check_fragments_skip_file_satisfies_requirement(tmp_path): + """A ``.skip`` opt-out is a valid form of "PR owns a fragment for this pkg".""" + pkg = _pkg_under(tmp_path, "isaaclab") + (pkg.root / "changelog.d").mkdir() + (pkg.root / "changelog.d" / "ci-only.skip").write_text("", encoding="utf-8") + changed = {"source/isaaclab/code.py", "source/isaaclab/changelog.d/ci-only.skip"} + added = changed + missing, invalid = cli.PRDiff(changed=changed, added=added).evaluate([pkg]) + assert missing == [] + assert invalid == [] + + +def test_check_fragments_no_source_changes_means_no_required_fragment(tmp_path): + """Pure docs / CI / changelog-tooling PRs don't trigger the requirement.""" + pkg = _pkg_under(tmp_path, "isaaclab") + changed = {"docs/something.rst"} # not under source/isaaclab/ + added = changed + missing, invalid = cli.PRDiff(changed=changed, added=added).evaluate([pkg]) + assert missing == [] + assert invalid == [] + + +def test_check_fragments_missing_when_source_touched_without_fragment(tmp_path): + """If the PR touches a package's source but adds no fragment, the package is missing.""" + pkg = _pkg_under(tmp_path, "isaaclab") + changed = {"source/isaaclab/code.py"} + added = changed + missing, invalid = cli.PRDiff(changed=changed, added=added).evaluate([pkg]) + assert missing == ["isaaclab"] + assert invalid == [] + + +# --------------------------------------------------------------------------- +# _display_path — handles paths inside *and* outside REPO_ROOT +# --------------------------------------------------------------------------- + + +def test_display_path_strips_repo_root_for_internal_paths(): + """Inside-repo paths are shown relative for terse log lines.""" + p = cli.REPO_ROOT / "tools" / "changelog" / "cli.py" + assert cli._display_path(p) == "tools/changelog/cli.py" + + +def test_display_path_falls_back_to_absolute_for_external(tmp_path): + """External paths (e.g. ``--fragments-dir /tmp/foo`` outside the repo) + used to crash on ``relative_to(REPO_ROOT)``; the helper now returns the + absolute path in that case.""" + external = tmp_path / "external_fragments" / "1234.rst" + external.parent.mkdir(parents=True) + external.write_text("", encoding="utf-8") + assert cli._display_path(external) == str(external) + + +# --------------------------------------------------------------------------- +# Package.compile bails on unmanaged packages instead of silently warning +# --------------------------------------------------------------------------- + + +def test_compile_raises_on_package_missing_changelog(tmp_path): + """Constructing a Package directly at an unmanaged root and calling + ``compile()`` must raise (not silently warn-and-write a stale toml).""" + pkg_root = tmp_path / "pkg" + (pkg_root / "config").mkdir(parents=True) + (pkg_root / "config" / "extension.toml").write_text('version = "1.2.3"\n', encoding="utf-8") + # No docs/CHANGELOG.rst — package is not managed. + pkg = cli.Package(pkg_root) + assert pkg.is_managed is False + + fragments = tmp_path / "fragments" + fragments.mkdir() + (fragments / "1234.rst").write_text("Fixed\n^^^^^\n\n* x\n", encoding="utf-8") + + with pytest.raises(ValueError, match="not managed"): + pkg.compile(fragments_dir=fragments, dry_run=True) + + +# --------------------------------------------------------------------------- +# cmd_compile parser guards — argparse-level errors fire as SystemExit +# --------------------------------------------------------------------------- + + +def _parse_compile(argv: list[str]): + """Build the parser and parse a compile invocation. Returns (parser, args).""" + parser = cli._build_parser() + return parser, parser.parse_args(argv) + + +def test_compile_guard_version_with_all_errors(): + """``--version`` with ``--all`` is meaningless — each package has its own version.""" + parser, args = _parse_compile(["compile", "--all", "--version", "1.2.3"]) + with pytest.raises(SystemExit): + cli.cmd_compile(args, parser) + + +def test_compile_guard_fragments_dir_with_all_errors(): + """``--fragments-dir`` with ``--all`` is meaningless — different dirs per package.""" + parser, args = _parse_compile(["compile", "--all", "--fragments-dir", "/tmp/x"]) + with pytest.raises(SystemExit): + cli.cmd_compile(args, parser) + + +def test_compile_guard_malformed_version_errors(): + """A garbage ``--version`` value fails before any file is touched.""" + parser, args = _parse_compile(["compile", "--package", "isaaclab", "--version", "not-semver"]) + with pytest.raises(SystemExit): + cli.cmd_compile(args, parser) + + +def test_compile_guard_nonexistent_package_errors(): + """A ``--package`` that doesn't exist on disk fails fast.""" + parser, args = _parse_compile(["compile", "--package", "definitely_not_a_real_package_xyz"]) + with pytest.raises(SystemExit): + cli.cmd_compile(args, parser) + + +def test_compile_rejects_fragments_that_check_would_reject(tmp_path): + """``compile`` must enforce the same content rules as ``check``. + + Regression: a fragment with a section heading but no bullet body + used to slip past compile (parsed to ``{"Added": []}``, emitted an + empty Added section), while check correctly rejected it. The two + paths must agree on what a valid fragment looks like. + """ + pkg_root = tmp_path / "pkg" + (pkg_root / "config").mkdir(parents=True) + (pkg_root / "docs").mkdir(parents=True) + (pkg_root / "config" / "extension.toml").write_text('version = "1.2.3"\n', encoding="utf-8") + (pkg_root / "docs" / "CHANGELOG.rst").write_text("Changelog\n---------\n\n", encoding="utf-8") + pkg = cli.Package(pkg_root) + + fragments = tmp_path / "fragments" + fragments.mkdir() + # Header but no bullets — same shape as fixtures/invalid_content/3003.rst. + (fragments / "1234.rst").write_text("Added\n^^^^^\n\n", encoding="utf-8") + + with pytest.raises(ValueError, match="failed content validation"): + pkg.compile(fragments_dir=fragments, dry_run=True) diff --git a/tools/conftest.py b/tools/conftest.py index 2a123fe62d2a..bf92d62f6c46 100644 --- a/tools/conftest.py +++ b/tools/conftest.py @@ -48,6 +48,9 @@ def pytest_ignore_collect(collection_path, config): STARTUP_HANG_RETRIES = 2 """Number of times to retry a test that hangs during startup before giving up.""" +TIMEOUT_RETRIES = 2 +"""Number of times to retry a test that reaches its hard timeout before giving up.""" + SHUTDOWN_GRACE_PERIOD = 30 """Seconds to wait for clean exit after the JUnit XML report file appears. @@ -352,10 +355,12 @@ def run_individual_tests(test_files, workspace_root, isaacsim_ci): report_file = f"tests/test-reports-{str(file_name)}.xml" - # -- Run with retry on startup hang -------------------------------- + # -- Run with retry on startup hang or hard timeout ----------------- returncode, stdout_data, stderr_data, kill_reason = -1, b"", b"", "" wall_time, pre_kill_diag = 0.0, "" - for attempt in range(STARTUP_HANG_RETRIES + 1): + startup_hang_attempts = 0 + timeout_attempts = 0 + while True: with contextlib.suppress(FileNotFoundError): os.remove(report_file) @@ -365,11 +370,32 @@ def run_individual_tests(test_files, workspace_root, isaacsim_ci): ) ) - if kill_reason == "startup_hang" and attempt < STARTUP_HANG_RETRIES: + has_report = os.path.exists(report_file) + + if kill_reason == "startup_hang" and startup_hang_attempts < STARTUP_HANG_RETRIES: + startup_hang_attempts += 1 print( f"⚠️ {test_file}: startup hang detected after {startup_deadline}s" - f" (attempt {attempt + 1}/{STARTUP_HANG_RETRIES + 1}), retrying..." + f" (attempt {startup_hang_attempts}/{STARTUP_HANG_RETRIES + 1}), retrying..." + ) + if stderr_data: + print("=== STDERR (last 5000 chars) ===") + print(stderr_data.decode("utf-8", errors="replace")[-5000:]) + diag = pre_kill_diag or _capture_system_diagnostics() + if len(diag) > 10000: + diag = diag[:10000] + "\n... (truncated)" + print(diag) + continue + + if kill_reason == "timeout" and not has_report and timeout_attempts < TIMEOUT_RETRIES: + timeout_attempts += 1 + print( + f"⚠️ {test_file}: timeout detected after {timeout}s" + f" (attempt {timeout_attempts}/{TIMEOUT_RETRIES + 1}), retrying..." ) + if stdout_data: + print("=== STDOUT (last 5000 chars) ===") + print(stdout_data.decode("utf-8", errors="replace")[-5000:]) if stderr_data: print("=== STDERR (last 5000 chars) ===") print(stderr_data.decode("utf-8", errors="replace")[-5000:]) @@ -417,7 +443,7 @@ def run_individual_tests(test_files, workspace_root, isaacsim_ci): print(f"Test {test_file} timed out after {timeout} seconds...") print(diag) - msg = f"Timeout after {timeout} seconds" + msg = f"Timeout after {timeout} seconds (retried {timeout_attempts} time(s))" details = f"{msg}\n\n=== SYSTEM DIAGNOSTICS ===\n{diag}\n\n" if stdout_data: details += "=== STDOUT (last 5000 chars) ===\n" diff --git a/tools/run_install_ci.py b/tools/run_install_ci.py new file mode 100755 index 000000000000..ba2dedd1fe60 --- /dev/null +++ b/tools/run_install_ci.py @@ -0,0 +1,364 @@ +#!/usr/bin/env python3 +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Unified runner for Isaac Lab installation CI tests. + +Modes + +``docker`` + Build a clean-room Docker container and execute pytest inside it. +``native`` + Run pytest directly on the host (no Docker). + +Examples + +.. code-block:: bash + + # Run all tests inside Docker (Ubuntu 24.04) + tools/run_install_ci.py docker + + # Run only pip tests with a custom base image + tools/run_install_ci.py docker --base-image ubuntu:22.04 -- -vs -k "testname" + + # Run with GPU support (passes --gpus all to Docker) + tools/run_install_ci.py docker --gpu + + # Filter by marker (e.g. only uv tests, only slow tests) + tools/run_install_ci.py docker -- -m uv + tools/run_install_ci.py docker --gpu -- -m "slow and gpu" + + # Filter by bug ID (dashes become underscores) + tools/run_install_ci.py docker --gpu -- -m nvbugs_5968136 + + # Drop into a shell for debugging + tools/run_install_ci.py docker --shell + + # Run natively (no Docker) + tools/run_install_ci.py native -- -vs + + # Pass a pre-built wheel + tools/run_install_ci.py docker --wheel /tmp/isaaclab-3.0.0-py3-none-any.whl +""" + +from __future__ import annotations + +import argparse +import os +import shutil +import subprocess +import sys +import time +from pathlib import Path + +_DIM = "\033[2m" +_MAGENTA = "\033[95m" +_RESET = "\033[0m" + +# Controls whether run_cmd() streams output by default. +stream_output: bool = False + + +def run_cmd( + args: list[str], + *, + cwd: str | Path | None = None, + env: dict[str, str] | None = None, + timeout: int = 600, + check: bool = True, + stream: bool | None = None, +) -> subprocess.CompletedProcess: + """Run a command, merging *env* into the current environment. + + Args: + args: Command and arguments to run. + cwd: Working directory for the subprocess. + env: Extra environment variables merged into the current environment. + timeout: Timeout in seconds. + check: Raise CalledProcessError on non-zero exit. + stream: When True, stream stdout/stderr to the console in + real time instead of capturing them. + + Returns: + The CompletedProcess; raises CalledProcessError when *check* is + True and return code != 0. + """ + if stream is None: + stream = stream_output + merged_env = {**os.environ, **(env or {})} + cmd_str = " ".join(str(a) for a in args) + if stream: + sys.stdout.write(f"{_MAGENTA}[COMMAND] {cmd_str}{_RESET}\n") + sys.stdout.flush() + t0 = time.monotonic() + proc = subprocess.Popen( + [str(a) for a in args], + cwd=str(cwd) if cwd else None, + env=merged_env, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + text=True, + ) + lines: list[str] = [] + try: + for line in proc.stdout: + lines.append(line) + sys.stdout.write(f"{_DIM}{line}{_RESET}") + sys.stdout.flush() + except Exception: + proc.kill() + raise + try: + proc.wait(timeout=timeout) + except subprocess.TimeoutExpired: + proc.kill() + proc.wait() + raise + elapsed = time.monotonic() - t0 + sys.stdout.write(f"{_MAGENTA}[{elapsed:.1f}s]{_RESET}\n") + sys.stdout.flush() + result = subprocess.CompletedProcess( + args=proc.args, + returncode=proc.returncode, + stdout="".join(lines), + stderr="", + ) + if check and result.returncode != 0: + raise subprocess.CalledProcessError(result.returncode, result.args, result.stdout, result.stderr) + return result + return subprocess.run( + [str(a) for a in args], + cwd=str(cwd) if cwd else None, + env=merged_env, + capture_output=True, + text=True, + timeout=timeout, + check=check, + ) + + +def _find_repo_root() -> Path: + """Walk up from CWD or this file to find the repo root.""" + for anchor in [Path.cwd(), Path(__file__).resolve().parent]: + for parent in [anchor] + list(anchor.parents): + if (parent / "isaaclab.sh").exists(): + return parent + raise FileNotFoundError("Could not locate IsaacLab repository root") + + +# Docker mode + + +def _cmd_docker(args: argparse.Namespace) -> int: + """Build the Docker image and run tests inside the container based on *args*.""" + + repo_root = _find_repo_root() + dockerfile = repo_root / "docker" / "Dockerfile.installci" + image_tag = f"isaaclab-installci:{args.base_image.replace(':', '-').replace('/', '-')}" + + # Build the Docker image + build_cmd = [ + "docker", + "build", + "--build-arg", + f"BASE_IMAGE={args.base_image}", + "-f", + str(dockerfile), + "-t", + image_tag, + "--progress=plain", + ] + + if args.no_cache: + build_cmd.append("--no-cache") + + build_cmd.append(str(repo_root)) + + result = run_cmd(build_cmd, check=False, stream=True) + if result.returncode != 0: + print(f"Docker build failed (exit {result.returncode})") + return result.returncode + + print(f"Docker image built successfully: {image_tag}") + + # Run + docker_run_cmd: list[str] = [ + "docker", + "run", + "--rm", + "--network=host", + ] + + if args.gpu: + docker_run_cmd.extend(["--gpus", "all"]) + + # Persist pip and uv caches across runs via named Docker volumes + if not args.no_pip_cache: + docker_run_cmd.extend(["-v", "isaaclab-installci-pip-cache:/root/.cache/pip"]) + if not args.no_uv_cache: + docker_run_cmd.extend(["-v", "isaaclab-installci-uv-cache:/root/.cache/uv"]) + + # Pass environment variables + docker_run_cmd.extend(["-e", "OMNI_KIT_ACCEPT_EULA=Y"]) + docker_run_cmd.extend(["-e", "ACCEPT_EULA=Y"]) + + if args.results_dir: + results_abs = Path(args.results_dir).resolve() + results_abs.mkdir(parents=True, exist_ok=True) + docker_run_cmd.extend(["-v", f"{results_abs}:/tmp/results"]) + + if args.wheel: + wheel_abs = Path(args.wheel).resolve() + container_wheel = f"/tmp/wheels/{wheel_abs.name}" + docker_run_cmd.extend(["-v", f"{wheel_abs}:{container_wheel}:ro"]) + docker_run_cmd.extend(["-e", f"ISAACLAB_WHEEL={container_wheel}"]) + + if args.shell: + # Interactive debugging mode + docker_run_cmd.extend(["-it", "--entrypoint", "bash", image_tag]) + else: + # Test execution mode + pytest_args = args.pytest_args or ["--tb=short"] + if args.results_dir: + pytest_args = ["--junitxml=/tmp/results/results.xml"] + pytest_args + docker_run_cmd.extend([image_tag] + pytest_args) + + print(f"{_MAGENTA}[COMMAND] {' '.join(docker_run_cmd)}{_RESET}") + + t0 = time.monotonic() + try: + ret = subprocess.call(docker_run_cmd, timeout=5400) + except subprocess.TimeoutExpired: + print("Docker run timed out after 90 minutes", file=sys.stderr) + ret = 124 + elapsed = time.monotonic() - t0 + print(f"{_MAGENTA}[{elapsed:.1f}s]{_RESET}") + return ret + + +# Native mode + + +def _cmd_native(args: argparse.Namespace) -> int: + """Run tests directly on the host OS.""" + + repo_root = _find_repo_root() + test_dir = repo_root / "source" / "isaaclab" / "test" / "install_ci" + + env = os.environ.copy() + if args.wheel: + env["ISAACLAB_WHEEL"] = str(Path(args.wheel).resolve()) + + pytest_args = args.pytest_args or ["--tb=short"] + cmd = [sys.executable, "-m", "pytest"] + pytest_args + + print(f"{_MAGENTA}[COMMAND] {' '.join(cmd)}{_RESET}") + + t0 = time.monotonic() + ret = subprocess.call(cmd, cwd=str(test_dir), env=env) + elapsed = time.monotonic() - t0 + print(f"{_MAGENTA}[{elapsed:.1f}s]{_RESET}") + return ret + + +# CLI + + +def main() -> int: + """Parse CLI arguments and dispatch to the docker or native test runner. + + Returns: + Exit code: 0 on success, non-zero on failure. + """ + parser = argparse.ArgumentParser( + description="Isaac Lab Installation CI test runner", + formatter_class=argparse.RawDescriptionHelpFormatter, + epilog="""\ +docker options: + --base-image IMAGE Docker base image (default: ubuntu:24.04) + --gpu Pass --gpus all to docker run + --shell Drop into interactive bash instead of running tests + --no-cache Build Docker image without layer cache + --no-pip-cache Disable persistent pip cache volume + --no-uv-cache Disable persistent uv cache volume + --results-dir DIR Host directory for test results (auto-adds --junitxml) + --wheel PATH Path to pre-built isaaclab wheel file + +native options: + --wheel PATH Path to pre-built isaaclab wheel file + +pytest arguments: + Pass pytest options after '--'. Without '--', defaults to '-sv --tb=short'. + + examples: + %(prog)s docker # run all tests in Docker + %(prog)s docker --base-image ubuntu:22.04 -- -vs -k "testname" # custom base image + %(prog)s docker --gpu # GPU support (--gpus all) + %(prog)s docker -- -m uv # filter by marker + %(prog)s docker --gpu -- -m "slow and gpu" # combine markers with GPU + %(prog)s docker --gpu -- -m nvbugs_5968136 # filter by bug ID + %(prog)s docker --shell # drop into shell for debugging + %(prog)s native -- -vs # run natively (no Docker) + %(prog)s docker --wheel /tmp/isaaclab.whl # pass a pre-built wheel + %(prog)s docker -- --collect-only # list tests without running +""", + ) + sub = parser.add_subparsers(dest="mode") + + # docker subcommand + docker_p = sub.add_parser("docker", help="Build container and run tests inside Docker") + docker_p.add_argument( + "--base-image", + default="ubuntu:24.04", + help="Docker base image (default: ubuntu:24.04)", + ) + docker_p.add_argument("--gpu", action="store_true", help="Pass --gpus all to docker run") + docker_p.add_argument( + "--shell", action="store_true", help="Drop into an interactive bash shell instead of running tests" + ) + docker_p.add_argument("--no-cache", action="store_true", help="Build Docker image without cache") + docker_p.add_argument("--no-pip-cache", action="store_true", help="Disable persistent pip cache volume") + docker_p.add_argument("--no-uv-cache", action="store_true", help="Disable persistent uv cache volume") + docker_p.add_argument( + "--results-dir", type=str, default=None, help="Host directory for test results (auto-adds --junitxml)" + ) + docker_p.add_argument("--wheel", type=str, default=None, help="Path to pre-built isaaclab wheel file") + docker_p.add_argument("pytest_args", nargs="*", help="Arguments forwarded to pytest (use -- to separate)") + + # native subcommand + native_p = sub.add_parser("native", help="Run tests directly on the host OS") + native_p.add_argument("--wheel", type=str, default=None, help="Path to pre-built isaaclab wheel file") + native_p.add_argument("pytest_args", nargs="*", help="Arguments forwarded to pytest (use -- to separate)") + + # If '--' is in sys.argv, split there so pytest args are captured correctly + argv = sys.argv[1:] + if "--" in argv: + split_idx = argv.index("--") + our_args = argv[:split_idx] + pytest_extra = argv[split_idx + 1 :] + else: + our_args = argv + pytest_extra = [] + + args = parser.parse_args(our_args) + + # Merge any args after '--' into pytest_args + if pytest_extra: + args.pytest_args = (args.pytest_args or []) + pytest_extra + + if args.mode == "docker": + if not shutil.which("docker"): + print("Error: docker is not available on PATH", file=sys.stderr) + return 1 + return _cmd_docker(args) + elif args.mode == "native": + return _cmd_native(args) + else: + parser.print_help() + return 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/template/templates/extension/setup.py b/tools/template/templates/extension/setup.py index 4eb164f37378..4c7dcc237e70 100644 --- a/tools/template/templates/extension/setup.py +++ b/tools/template/templates/extension/setup.py @@ -34,13 +34,10 @@ install_requires=INSTALL_REQUIRES, license="Apache-2.0", include_package_data=True, - python_requires=">=3.10", + python_requires=">=3.12", classifiers=[ "Natural Language :: English", - "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", - "Isaac Sim :: 5.0.0", - "Isaac Sim :: 5.1.0", "Isaac Sim :: 6.0.0", ], zip_safe=False, diff --git a/tools/test_settings.py b/tools/test_settings.py index 12d4bf5bcf97..66832541e5cc 100644 --- a/tools/test_settings.py +++ b/tools/test_settings.py @@ -17,7 +17,7 @@ PER_TEST_TIMEOUTS = { - "test_articulation.py": 1000, + "test_articulation.py": 1500, "test_stage_in_memory.py": 1000, "test_imu.py": 1000, "test_environments.py": 10000, # This test runs through all the environments for 100 steps each @@ -28,7 +28,11 @@ "test_pickplace_stack_environments.py": 10000, # This test runs through PickPlace and Stack environments "test_factory_environments.py": 1000, # This test runs through Factory environments for 100 steps each "test_multi_agent_environments.py": 800, # This test runs through multi-agent environments for 100 steps each - "test_generate_dataset.py": 1000, # This test runs annotation for 10 demos and generation until one succeeds + "test_generate_dataset_franka_state.py": 10000, # This test runs annotation for 10 demos and generation for 1 demo + "test_generate_dataset_franka_visuomotor.py": 10000, # This test runs generation until one succeeds + "test_generate_dataset_gr1t2_nutpour.py": 10000, # This test runs generation until one succeeds + "test_generate_dataset_gr1t2_pickplace.py": 10000, # This test runs generation until one succeeds + "test_generate_dataset_skillgen.py": 10000, # This test runs generation for skillgen "test_pink_ik.py": 1000, # This test runs through all the pink IK environments through various motions "test_environments_training.py": ( 10000 @@ -43,6 +47,7 @@ "test_operational_space.py": 1000, "test_non_headless_launch.py": 1000, # This test launches the app in non-headless mode and starts simulation "test_rl_games_wrapper.py": 1000, + "test_rsl_rl_export_flow.py": 4000, "test_rsl_rl_wrapper.py": 1000, "test_sb3_wrapper.py": 1000, "test_skrl_wrapper.py": 1000, @@ -56,6 +61,7 @@ "test_multirotor.py": 1000, "test_shadow_hand_vision_presets.py": 5000, "test_environments_newton.py": 5000, + "test_surface_gripper.py": 3000, } """A dictionary of tests and their timeouts in seconds. diff --git a/tools/wheel_builder/.gitignore b/tools/wheel_builder/.gitignore new file mode 100644 index 000000000000..a007feab071f --- /dev/null +++ b/tools/wheel_builder/.gitignore @@ -0,0 +1 @@ +build/* diff --git a/tools/wheel_builder/build.sh b/tools/wheel_builder/build.sh new file mode 100755 index 000000000000..12e6a00e3abc --- /dev/null +++ b/tools/wheel_builder/build.sh @@ -0,0 +1,105 @@ +#!/bin/bash +set -e + +SELF_DIR="$(dirname "$(realpath "$0")")" +cd "$SELF_DIR/../.." + +VERSION=$(cat VERSION) +BUILD_DIR=$SELF_DIR/build/stage +DIST_DIR=$SELF_DIR/build/dist + +# Compose a PEP 440 local version when CI metadata is provided so the wheel is +# traceable to a specific build and commit. With both env vars set the version +# becomes e.g. "3.0.0+build123.abc1234" (build number is monotonic, sha slug +# pins the source). If either is missing, fall back to the plain VERSION so +# local dev builds stay simple. +WHEEL_BUILD_NUMBER="${WHEEL_BUILD_NUMBER:-}" +WHEEL_SHA="${WHEEL_SHA:-}" +if [ -n "$WHEEL_BUILD_NUMBER" ] && [ -n "$WHEEL_SHA" ]; then + SHA_SLUG="${WHEEL_SHA:0:7}" + WHEEL_VERSION="${VERSION}+build${WHEEL_BUILD_NUMBER}.${SHA_SLUG}" +else + WHEEL_VERSION="${VERSION}" +fi +echo "[WHEEL VERSION] $WHEEL_VERSION" + +# Platform tags matching the official IsaacLab wheel +PYTHON_TAG="${PYTHON_TAG:-cp312}" +ABI_TAG="${ABI_TAG:-cp312}" +# Auto-detect platform +ARCH=$(uname -m) +case "$ARCH" in + x86_64|AMD64) PLATFORM_TAG="${PLATFORM_TAG:-manylinux_2_35_x86_64}" ;; + aarch64|arm64) PLATFORM_TAG="${PLATFORM_TAG:-manylinux_2_35_aarch64}" ;; + *) PLATFORM_TAG="${PLATFORM_TAG:-linux_$ARCH}" ;; +esac + +rm -rf "$BUILD_DIR" "$DIST_DIR" +mkdir -p "$BUILD_DIR/src/isaaclab" + +# 1. Copy inventory (same as python_packages.toml inventory.includes.all) +cp -r apps "$BUILD_DIR/src/isaaclab/" +cp -r source "$BUILD_DIR/src/isaaclab/" + +# Ensure apps/ is discovered as a Python sub-package (it has no __init__.py) +find "$BUILD_DIR/src/isaaclab/apps" -type d -exec touch {}/__init__.py \; + +# Promote sub-packages (isaaclab_assets, isaaclab_rl, etc.) to top-level +# so they are importable as e.g. `import isaaclab_assets`. +# Each extension has the structure: source/isaaclab_FOO/isaaclab_FOO/ (Python pkg) +# plus sibling dirs like config/, data/. The __init__.py references ../config etc. +# We copy the inner Python package to src/ and also copy sibling resource dirs +# (config, data) into it so the relative-path lookups in __init__.py work. +for ext_dir in "$BUILD_DIR"/src/isaaclab/source/isaaclab_*; do + pkg=$(basename "$ext_dir") + inner="$ext_dir/$pkg" + if [ -d "$inner" ] && [ -f "$inner/__init__.py" ]; then + cp -r "$inner" "$BUILD_DIR/src/$pkg" + # Copy resource dirs (config/, data/) into the Python package + for res_dir in config data; do + if [ -d "$ext_dir/$res_dir" ]; then + cp -r "$ext_dir/$res_dir" "$BUILD_DIR/src/$pkg/$res_dir" + fi + done + # Patch EXT_DIR: change '../' to '.' so __init__.py finds config/ inside + # the package dir rather than one level up. + sed -i 's|os\.path\.join(os\.path\.dirname(__file__), "\.\./"|os.path.join(os.path.dirname(__file__), ""|g' \ + "$BUILD_DIR/src/$pkg/__init__.py" + # Remove the original from inside the isaaclab bundle to avoid duplication + rm -rf "$ext_dir" + fi +done + +# Clean build artifacts that shouldn't be in the wheel +find "$BUILD_DIR/src" -type d -name "__pycache__" -exec rm -rf {} + 2>/dev/null || true +find "$BUILD_DIR/src" -type d -name "*.egg-info" -exec rm -rf {} + 2>/dev/null || true +find "$BUILD_DIR/src" -name "*.pyc" -delete 2>/dev/null || true + +# 2. Copy the custom res __init__.py and __main__.py +cp "$SELF_DIR/res/__init__.py" "$BUILD_DIR/src/isaaclab/" +cp "$SELF_DIR/res/__main__.py" "$BUILD_DIR/src/isaaclab/" + +# 3. Generate pyproject.toml with dependencies from python_packages.toml +python3 "$SELF_DIR/gen_pyproject.py" "$SELF_DIR/res/python_packages.toml" "$BUILD_DIR/pyproject.toml" "$WHEEL_VERSION" + +# 4. Build the wheel +cd "$BUILD_DIR" +# Prefer --user to avoid polluting system Python; fall back to --break-system-packages +# for environments where --user is unsupported (e.g. Docker, ephemeral CI runners). +python3 -m pip install --user build wheel 2>/dev/null || python3 -m pip install --break-system-packages build wheel +python3 -m build --wheel --outdir "$DIST_DIR/" + +# 5. Retag the wheel to match official platform tags +# cd "$DIST_DIR" +# GENERIC_WHL=$(ls isaaclab-*.whl) +# echo "Retagging $GENERIC_WHL -> $PYTHON_TAG-$ABI_TAG-$PLATFORM_TAG" +# python3 -m wheel tags --python-tag "$PYTHON_TAG" --abi-tag "$ABI_TAG" --platform-tag "$PLATFORM_TAG" "$GENERIC_WHL" +# # Remove the generic wheel (wheel tags creates a new file) +# TAGGED_WHL=$(ls isaaclab-*"$PLATFORM_TAG"*.whl 2>/dev/null) +# if [ "$GENERIC_WHL" != "$TAGGED_WHL" ] && [ -n "$TAGGED_WHL" ]; then +# rm -f "$GENERIC_WHL" +# fi + +echo "" +echo "[WHEEL BUILT]" +ls -lh $DIST_DIR/isaaclab-*.whl diff --git a/tools/wheel_builder/gen_pyproject.py b/tools/wheel_builder/gen_pyproject.py new file mode 100644 index 000000000000..a8cf3fdd8d5d --- /dev/null +++ b/tools/wheel_builder/gen_pyproject.py @@ -0,0 +1,82 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Generate pyproject.toml for the isaaclab wheel from python_packages.toml.""" + +import sys + +import tomllib + +if len(sys.argv) != 4: + print(f"Usage: {sys.argv[0]} ", file=sys.stderr) + sys.exit(1) + +packages_toml_path = sys.argv[1] +output_path = sys.argv[2] +version = sys.argv[3] + +with open(packages_toml_path, "rb") as f: + data = tomllib.load(f) +pkg = data["isaaclab"] + +# Collect dependencies (deduplicated, preserving order) +raw_deps = pkg["pyproject"]["dependencies"]["all"] +seen = set() +deps = [] +for d in raw_deps: + # Normalize for dedup: lowercase package name (before any version specifier) + key = d.split(">")[0].split("<")[0].split("=")[0].split("!")[0].split("[")[0].strip().lower() + if key not in seen: + seen.add(key) + deps.append(d) + +# Collect optional dependencies +opt_deps = {} +for entry in pkg["pyproject"]["optional-dependencies"]["all"]: + # Each entry is a dict like {"name": ["dep1", "dep2"]} + for name, dep_list in entry.items(): + opt_deps[name] = dep_list + +# Write pyproject.toml +lines = [] +lines.append("[build-system]") +lines.append('requires = ["setuptools >= 70.0, < 82.0.0"]') +lines.append('build-backend = "setuptools.build_meta"') +lines.append("") +lines.append("[tool.setuptools]") +lines.append("include-package-data = true") +lines.append('package-dir = {"" = "src"}') +lines.append("") +lines.append("[tool.setuptools.packages.find]") +lines.append('where = ["src"]') +lines.append("") +lines.append("# Include all non-.py files (kit apps, toml configs, usd, yaml, etc.)") +lines.append("[tool.setuptools.package-data]") +lines.append('"*" = ["**/*"]') +lines.append("") +lines.append("[project]") +lines.append('name = "isaaclab"') +lines.append(f'version = "{version}"') +lines.append('requires-python = ">=3.12"') +lines.append('description = "Isaac Lab"') +lines.append('license = {text = "BSD-3-Clause"}') +lines.append("dependencies = [") +for d in deps: + lines.append(f' "{d}",') +lines.append("]") +lines.append("") +lines.append("[project.scripts]") +lines.append('isaaclab = "isaaclab:main"') +lines.append("") +lines.append("[project.optional-dependencies]") +for name, dep_list in opt_deps.items(): + formatted = ", ".join(f'"{d}"' for d in dep_list) + lines.append(f"{name} = [{formatted}]") +lines.append("") + +with open(output_path, "w") as f: + f.write("\n".join(lines) + "\n") + +print(f"Generated {output_path} with {len(deps)} dependencies and {len(opt_deps)} optional groups") diff --git a/tools/wheel_builder/res/__init__.py b/tools/wheel_builder/res/__init__.py new file mode 100644 index 000000000000..bd162c1edd6c --- /dev/null +++ b/tools/wheel_builder/res/__init__.py @@ -0,0 +1,42 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +import os +import sys +from importlib.metadata import version +from importlib.util import find_spec + +__version__ = version("isaaclab") + +# Extend the package search path so subpackages (app/, envs/, etc.) in the +# nested source tree are importable as isaaclab.app, isaaclab.envs, etc. +__path__.append(os.path.join(os.path.dirname(__file__), "source", "isaaclab", "isaaclab")) + +# TODO(myurasov-nv): bootstrap_kernel() is ported from the internal GitLab wheel builder +# for backwards compatibility. It is not called currently, but may be needed if Isaac Sim +# requires explicit kernel bootstrapping before use. Remove once confirmed unnecessary. +def bootstrap_kernel(): + # Isaac Lab path + isaaclab_path = os.path.dirname(os.path.abspath(os.path.realpath(__file__))) + + # bootstrap kernel via Isaac Sim + if find_spec("isaacsim") is not None: + import isaacsim + + # log info + if find_spec("carb") is not None: + import carb + carb.log_info(f"Isaac Lab path: {isaaclab_path}") + +def main(): + """Entry point for the ``isaaclab`` console script (python -m isaaclab).""" + from isaaclab.__main__ import main as _main + + sys.exit(_main()) + + +if __name__ == "__main__": + bootstrap_kernel() + main() diff --git a/tools/wheel_builder/res/__main__.py b/tools/wheel_builder/res/__main__.py new file mode 100644 index 000000000000..1bf1917d3012 --- /dev/null +++ b/tools/wheel_builder/res/__main__.py @@ -0,0 +1,155 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +import argparse +import os +import re +import sys +import textwrap + +import tomllib + +VSCODE_SETTINGS_TEMPLATE = """ +{ + "editor.rulers": [120], + + // Enables python language server (seems to work slightly better than jedi) + "python.languageServer": "Pylance", + "python.jediEnabled": false, + + // Those paths are automatically filled by isaaclab (see: 'python -m isaaclab --help') + "python.defaultInterpreterPath": "PYTHON.DEFAULTINTERPRETERPATH", + "python.analysis.extraPaths": [ + PYTHON.ANALYSIS.EXTRAPATHS + ], + + // Use "black" as a formatter + "python.formatting.provider": "black", + "python.formatting.blackArgs": ["--line-length", "120"], + + // Use "flake8" for linting + "python.linting.pylintEnabled": false, + "python.linting.flake8Enabled": true, +} +""" + + +def generate_vscode_settings(): + def _mock_python_modules(ext_path: str, ext_name: str) -> None: + # parse config/extension.toml + cprint(f" |-- Parsing extension config ({ext_path})") + config_path = os.path.join(ext_path, "config", "extension.toml") + try: + with open(config_path, "rb") as f: + config = tomllib.load(f) + except Exception as e: + cprint(f" | |-- [Warning] {e}") + return + # get python modules + for item in config.get("python", {}).get("module", []): + if list(item.keys()) == ["name"]: + # skip tests + if item.get("name", "").endswith(".tests"): + continue + # mock __init__.py for each submodule (if not exists) + submodule_path = ext_path + for submodule in item.get("name", "").split("."): + init_path = os.path.join(submodule_path, "__init__.py") + if not os.path.isfile(init_path): + try: + cprint(f" |-- Mocking {init_path}") + with open(init_path, "w") as f: + f.write("# Generated by 'isaaclab' package") + except Exception as e: + cprint(f" | |-- [Warning] {e}") + continue + submodule_path = os.path.join(submodule_path, submodule) + + def _get_paths(base_path: str, mock_python_modules: bool = False) -> list[str]: + paths = [] + if os.path.isdir(base_path): + for folder in os.listdir(base_path): + folder_path = os.path.join(base_path, folder) + if os.path.isdir(folder_path): + paths.append(folder_path) + cprint(f"Registering extension: {folder_path}") + if mock_python_modules: + _mock_python_modules(folder_path, re.split(r"-\d+", folder)[0]) + return paths + + try: + import omni.kit_app # importing 'omni.kit_app' will bootstrap kernel + + kit_path = os.path.dirname(os.path.abspath(os.path.realpath(omni.kit_app.__file__))) + except ModuleNotFoundError: + print("Unable to find 'omniverse-kit' package") + # exit() + try: + import isaacsim + + isaacsim_path = os.path.dirname(os.path.abspath(os.path.realpath(isaacsim.__file__))) + except ModuleNotFoundError: + print("Unable to find 'isaacsim' package") + # exit() + + cwd = os.getcwd() + vscode_settings_path = os.path.join(cwd, ".vscode", "settings.json") + # check if .vscode/settings.json exists + if os.path.exists(vscode_settings_path): + print(f"VS Code settings already exists: {vscode_settings_path}") + if input("Overwrite? (y/N): ").lower() not in ["y", "yes"]: + print("Cancelled: VS Code settings not overwritten") + return + + # get extensions paths + extensions_paths = [] + # - omniverse-kit + folder_path = os.path.join(kit_path, "kernel", "py") + if os.path.isdir(folder_path): + extensions_paths.append(folder_path) + for folder in ["exts", "extscore"]: + extensions_paths.extend(_get_paths(os.path.join(kit_path, folder), mock_python_modules=True)) + # - isaacsim + for folder in ["exts", "extscache", "extsDeprecated", "extsUser"]: + extensions_paths.extend(_get_paths(os.path.join(isaacsim_path, folder), mock_python_modules=True)) + # - isaaclab + isaaclab_path = os.path.dirname(os.path.abspath(os.path.realpath(__file__))) + for folder in ["source"]: + extensions_paths.extend(_get_paths(os.path.join(isaaclab_path, folder), mock_python_modules=True)) + + # update 'python.defaultInterpreterPath' + template = VSCODE_SETTINGS_TEMPLATE[:] + template = template.replace("PYTHON.DEFAULTINTERPRETERPATH", sys.executable) + + # update 'python.analysis.extraPaths' + content = "\n".join([f'"{path}",' for path in extensions_paths]) + content = textwrap.indent(content, prefix=" " * 8)[8:] + template = template.replace("PYTHON.ANALYSIS.EXTRAPATHS", content) + + # create .vscode/settings.json + os.makedirs(os.path.join(cwd, ".vscode"), exist_ok=True) + with open(vscode_settings_path, "w") as f: + f.write(template) + print("VS Code settings generated at", vscode_settings_path) + + +def main(): + """Entry point for ``isaaclab`` console script and ``python -m isaaclab``.""" + parser = argparse.ArgumentParser() + parser.add_argument( + "--generate-vscode-settings", default=False, action="store_true", help="Generate VS Code settings." + ) + parser.add_argument("--verbose", default=False, action="store_true", help="Verbose output.") + args, _ = parser.parse_known_args() + + global cprint + cprint = print if args.verbose else lambda *args, **kwargs: None + + if args.generate_vscode_settings: + generate_vscode_settings() + + +if __name__ == "__main__": + main() diff --git a/tools/wheel_builder/res/python_packages.toml b/tools/wheel_builder/res/python_packages.toml new file mode 100644 index 000000000000..1676fdc8f905 --- /dev/null +++ b/tools/wheel_builder/res/python_packages.toml @@ -0,0 +1,120 @@ +[isaaclab] +# pyproject.toml +pyproject.description = "Isaac Lab" +pyproject.keywords = ["nvidia", "omniverse", "isaacsim", "isaaclab"] +pyproject.dependencies.all = [ + # ================================================================================ + # https://github.com/isaac-sim/IsaacLab/blob/main/source/isaaclab/setup.py + # ================================================================================ + # generic + "numpy>=2", + "torch>=2.10", + "onnx>=1.18.0", # 1.16.2 throws access violation on Windows + "prettytable==3.3.0", + "toml", + # devices + "hidapi==0.14.0.post2", + # reinforcement learning + "gymnasium==1.2.0", + # procedural-generation + "trimesh", + "pyglet>=2.1.6", + # image processing + "transformers==4.57.6", + "einops", # needed for transformers, doesn't always auto-install + "warp-lang==1.12.0", + "matplotlib>=3.10.3", + # make sure this is consistent with isaac sim version + "pillow==12.1.1", + "botocore", + # livestream + "starlette==0.49.1", # TODO: update starlette once Isaac Lab be released with Isaac Sim 6.0.0 + "omniverseclient==2.71.1.7015", + # testing + "pytest", + "pytest-mock", + "junitparser", + "flatdict==4.0.0", + "flaky", + "packaging", + # visualizers + "imgui-bundle==1.92.4", + "rerun-sdk>=0.29.0", + "viser>=1.0.16", + "typing_extensions==4.12.2", + "lazy_loader>=0.4", + "pin ; platform_system == 'Linux'", + "pin-pink>=2.3.6 ; platform_system == 'Linux'", + # ================================================================================ + # https://github.com/isaac-sim/IsaacLab/blob/main/source/isaaclab_rl/setup.py + # ================================================================================ + # generic + "numpy>=2", + "torch>=2.10", + "torchvision>=0.25.0", # ensure compatibility with torch 2.10 + "protobuf>=4.25.8,!=5.26.0", + # configuration management + "hydra-core", + # data collection + "h5py", + # basic logger + "tensorboard", + # video recording + "moviepy", + "packaging<24", + "tqdm==4.67.1", + # ================================================================================ + # https://github.com/isaac-sim/IsaacLab/blob/main/source/isaaclab_tasks/setup.py + # ================================================================================ + # generic + "numpy>=2", + "torch>=2.10", + "torchvision>=0.25.0", # ensure compatibility with torch 2.10 + "protobuf>=4.25.8,!=5.26.0", + # basic logger + "tensorboard", + "numba>=0.63.1", +] +pyproject.optional-dependencies.all = [ + # Isaac Sim + { "isaacsim" = ["isaacsim[all,extscache]==6.0.0.*"] }, + # ================================================================================ + # https://github.com/isaac-sim/IsaacLab/blob/main/source/isaaclab_newton/setup.py + # ================================================================================ + { "newton" = [ + "warp-lang==1.12.0", + "mujoco==3.6.0", + "mujoco-warp==3.6.0", + "newton @ git+https://github.com/newton-physics/newton.git@a27277ed49d6f307b8a1e4c394be7e1d14965a62", + "PyOpenGL-accelerate==3.1.10" + ] }, + # ================================================================================ + # https://github.com/isaac-sim/IsaacLab/blob/main/source/isaaclab_rl/setup.py + # ================================================================================ + # RL libraries + { "sb3" = ["stable-baselines3>=2.6", "tqdm", "rich"] }, + { "skrl" = ["skrl>=1.4.3"] }, + # { "rl-games" = ["rl-games==1.6.1"] }, # TODO: re-enable when rl-games Python package supports Python 3.11 + # { "rl_games" = ["rl-games==1.6.1"] }, # TODO: re-enable when rl-games Python package supports Python 3.11 + { "rsl-rl" = ["rsl-rl-lib==3.1.2", "onnxscript>=0.5"] }, + { "rsl_rl" = ["rsl-rl-lib==3.1.2", "onnxscript>=0.5"] }, + # RL libraries (all) + { "all" = [ + "stable-baselines3>=2.6", + "tqdm", + "rich", + "skrl>=1.4.3", + # "rl-games==1.6.1", # TODO: re-enable when rl-games Python package supports Python 3.11 + "rsl-rl-lib==3.1.2", + "onnxscript>=0.5", + ] }, +] +# inventory (relative to the `source_folder` config) +inventory.includes.all = [ + # Isaac Lab + "apps", + "source", + # python package/module + [ "../source/python_packages/isaaclab/__init__.py", "." ], + [ "../source/python_packages/isaaclab/__main__.py", "." ], +]